focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String getGeneratedResourceString(GeneratedResource generatedResource) throws JsonProcessingException {
return objectMapper.writeValueAsString(generatedResource);
} | @Test
void getGeneratedResourceString() throws JsonProcessingException {
String fullClassName = "full.class.Name";
GeneratedResource generatedResource = new GeneratedClassResource(fullClassName);
String expected = String.format("{\"step-type\":\"class\",\"fullClassName\":\"%s\"}", fullClassN... |
public TaskRunScheduler getTaskRunScheduler() {
return taskRunScheduler;
} | @Test
public void testTaskRunNotMerge() {
TaskRunManager taskRunManager = new TaskRunManager();
Task task = new Task("test");
task.setDefinition("select 1");
long taskId = 1;
TaskRun taskRun1 = TaskRunBuilder
.newBuilder(task)
.setExecuteOpt... |
@Override
public void triggerForProject(String projectUuid) {
try (DbSession dbSession = dbClient.openSession(false)) {
// remove already existing indexing task, if any
removeExistingIndexationTasksForProject(dbSession, projectUuid);
dbClient.branchDao().updateAllNeedIssueSyncForProject(dbSess... | @Test
public void triggerForProject() {
ProjectDto projectDto = dbTester.components().insertPrivateProject().getProjectDto();
BranchDto dto = new BranchDto()
.setBranchType(BRANCH)
.setKey("branchName")
.setUuid("branch_uuid")
.setProjectUuid(projectDto.getUuid())
.setIsMain(true... |
public void refreshLogRetentionSettings() throws IOException {
if (getServiceState() == STATE.STARTED) {
Configuration conf = createConf();
setConfig(conf);
stopRMClient();
stopTimer();
scheduleLogDeletionTasks();
} else {
LOG.warn("Failed to execute refreshLogRetentionSettin... | @Test
void testRefreshLogRetentionSettings() throws Exception {
long now = System.currentTimeMillis();
long before2000Secs = now - (2000 * 1000);
long before50Secs = now - (50 * 1000);
int checkIntervalSeconds = 2;
int checkIntervalMilliSeconds = checkIntervalSeconds * 1000;
Configuration con... |
public static boolean isLong(String s) {
if (StrUtil.isBlank(s)) {
return false;
}
try {
Long.parseLong(s);
} catch (NumberFormatException e) {
return false;
}
return true;
} | @Test
public void isLongTest() {
assertTrue(NumberUtil.isLong("-12"));
assertTrue(NumberUtil.isLong("256"));
assertTrue(NumberUtil.isLong("0256"));
assertTrue(NumberUtil.isLong("0"));
assertFalse(NumberUtil.isLong("23.4"));
assertFalse(NumberUtil.isLong(null));
assertFalse(NumberUtil.isLong(""));
asser... |
@Override
public synchronized InetSocketAddress getConfAddress() throws UnavailableException {
return mMasterSelectionPolicy.getPrimaryMasterAddressCached(mMasterInquireClient);
} | @Test
public void specificMaster() throws UnavailableException {
int masterIndex = 2;
AbstractMasterClient client = new TestAbstractClient(
mMockMasterClientContext,
MasterSelectionPolicy.Factory.specifiedMaster(mAddress.get(masterIndex))
);
Assert.assertEquals(mAddress.get(masterIndex... |
public static <FnT extends DoFn<?, ?>> DoFnSignature signatureForDoFn(FnT fn) {
return getSignature(fn.getClass());
} | @Test
public void testSimpleStateIdNamedDoFn() throws Exception {
class DoFnForTestSimpleStateIdNamedDoFn extends DoFn<KV<String, Integer>, Long> {
@StateId("foo")
private final StateSpec<ValueState<Integer>> bizzle = StateSpecs.value(VarIntCoder.of());
@ProcessElement
public void foo(Pr... |
public Set<Device> getDevicesFromPath(String path) throws IOException {
MutableInt counter = new MutableInt(0);
try (Stream<Path> stream = Files.walk(Paths.get(path), 1)) {
return stream.filter(p -> p.toFile().getName().startsWith("veslot"))
.map(p -> toDevice(p, counter))
.collect... | @Test
public void testDetectSingleOnlineDevice() throws IOException {
createVeSlotFile(0);
createOsStateFile(0);
when(mockCommandExecutor.getOutput())
.thenReturn("8:1:character special file");
when(udevUtil.getSysPath(anyInt(), anyChar())).thenReturn(testFolder);
Set<Device> devices = disc... |
@Override
public Long clusterCountKeysInSlot(int slot) {
RedisClusterNode node = clusterGetNodeForSlot(slot);
MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(new InetSocketAddress(node.getHost(), node.getPort()));
RFuture<Long> f = executorService.readAsync(entry, St... | @Test
public void testClusterCountKeysInSlot() {
Long t = connection.clusterCountKeysInSlot(1);
assertThat(t).isZero();
} |
@Override
public ConfigInfoStateWrapper findConfigInfoState(final String dataId, final String group, final String tenant) {
final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceT... | @Test
void testFindConfigInfoState() {
String dataId = "dataId1324";
String group = "group23546";
String tenant = "tenant13245";
//mock select config state
ConfigInfoStateWrapper mockedConfig = new ConfigInfoStateWrapper();
mockedConfig.setLastModifi... |
@Override
public String getUrl() {
return String.format("/%sartifact/%s", run.getUrl(), artifact.getHref());
} | @Test
public void findUniqueArtifactsWithSameName() throws IllegalAccessException, NoSuchFieldException {
//mock artifacts
assumeTrue("TODO in Java 12+ final cannot be removed", Runtime.version().feature() < 12);
FieldUtils.removeFinalModifier(Run.Artifact.class.getField("relativePath"));
... |
public Chapter readChapter(@NonNull FrameHeader frameHeader) throws IOException, ID3ReaderException {
int chapterStartedPosition = getPosition();
String elementId = readIsoStringNullTerminated(100);
long startTime = readInt();
skipBytes(12); // Ignore end time, start offset, end offset
... | @Test
public void testReadChapterWithoutSubframes() throws IOException, ID3ReaderException {
FrameHeader header = new FrameHeader(ChapterReader.FRAME_ID_CHAPTER,
CHAPTER_WITHOUT_SUBFRAME.length, (short) 0);
CountingInputStream inputStream = new CountingInputStream(new ByteArrayInputS... |
public String getChineseMonth() {
return getChineseMonth(false);
} | @Test
public void getChineseMonthTest(){
ChineseDate chineseDate = new ChineseDate(2020,6,15);
assertEquals("2020-08-04 00:00:00", chineseDate.getGregorianDate().toString());
assertEquals("六月", chineseDate.getChineseMonth());
chineseDate = new ChineseDate(2020,4,15);
assertEquals("2020-06-06 00:00:00", chin... |
@Override
public int hashCode() {
return Objects.hash(mInstantCreated, mWorkers);
} | @Test
public void hashCodeImpl() {
WorkerIdentity worker1 = WorkerIdentityTestUtils.ofLegacyId(1);
WorkerIdentity worker2 = WorkerIdentityTestUtils.ofLegacyId(2);
WorkerIdentity worker3 = WorkerIdentityTestUtils.ofLegacyId(3);
List<WorkerInfo> workers = ImmutableList.of(
new WorkerInfo().setId... |
@Override
public Stream<HoodieInstant> getCandidateInstants(HoodieTableMetaClient metaClient, HoodieInstant currentInstant,
Option<HoodieInstant> lastSuccessfulInstant) {
HoodieActiveTimeline activeTimeline = metaClient.getActiveTimeline();
// To find which ... | @Test
public void testNoConcurrentWrites() throws Exception {
String newInstantTime = HoodieTestTable.makeNewCommitTime();
createCommit(newInstantTime, metaClient);
// consider commits before this are all successful
Option<HoodieInstant> lastSuccessfulInstant = metaClient.getCommitsTimeline().filterC... |
public void putWorkerMetrics(String source, List<Metric> metrics) {
if (metrics.isEmpty() || source == null) {
return;
}
try (LockResource r = new LockResource(mLock.readLock())) {
putReportedMetrics(InstanceType.WORKER, metrics);
}
LOG.debug("Put {} metrics of worker {}", metrics.size()... | @Test
public void putWorkerUfsMetrics() {
String readBytes = MetricKey.WORKER_BYTES_READ_UFS.getName();
String writtenBytes = MetricKey.WORKER_BYTES_WRITTEN_UFS.getName();
String ufsName1 = MetricsSystem.escape(new AlluxioURI("/my/local/folder"));
String readBytesUfs1 = Metric.getMetricNameWithTags(r... |
public abstract HttpHeaders set(String name, Object value); | @Test
public void testSetNullHeaderValueNotValidate() {
final HttpHeaders headers = new DefaultHttpHeaders(false);
assertThrows(NullPointerException.class, new Executable() {
@Override
public void execute() {
headers.set(of("test"), (CharSequence) null);
... |
@Override
public URL getResource(String name) {
ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name);
log.trace("Received request to load resource '{}'", name);
for (ClassLoadingStrategy.Source classLoadingSource : loadingStrategy.getSources()) {
URL url = null;
... | @Test
void parentFirstGetResourceNonExisting() {
assertNull(parentFirstPluginClassLoader.getResource("META-INF/non-existing-file"));
} |
public static ElasticSearchLogCollectClient getElasticSearchLogCollectClient() {
return ELASTICSEARCH_LOG_COLLECT_CLIENT;
} | @Test
public void testGetRocketMqLogCollectClient() {
Assertions.assertEquals(LoggingElasticSearchPluginDataHandler.getElasticSearchLogCollectClient().getClass(), ElasticSearchLogCollectClient.class);
} |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldHandleSelectStructAllOnNestedStruct() {
// Given:
final SingleStatementContext stmt =
givenQuery("SELECT NESTED_ORDER_COL->ITEMINFO->* FROM NESTED_STREAM;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
assertThat(result.getSele... |
public List<PhotoAlbum> split(int numberOfNewAlbums) {
return IntStream.range(1, numberOfNewAlbums + 1)
.mapToObj(
i ->
new PhotoAlbum(
String.format("%s-pt%d", id, i),
String.format("%s (%d/%d)", id, i, numberOfNewAlbums),
... | @Test
public void splitSimple() {
PhotoAlbum originalAlbum = new PhotoAlbum("123", "MyAlbum", DESCRIPTION);
List<PhotoAlbum> actual = originalAlbum.split(3);
Truth.assertThat(actual)
.containsExactly(
new PhotoAlbum("123-pt1", "123 (1/3)", DESCRIPTION),
new PhotoAlbum("123-... |
public static Properties parseKeyValueArgs(List<String> args) {
return parseKeyValueArgs(args, true);
} | @Test
public void testParseEmptyArg() {
List<String> argArray = Arrays.asList("my.empty.property=");
assertThrows(IllegalArgumentException.class, () -> CommandLineUtils.parseKeyValueArgs(argArray, false));
} |
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) {
SinkConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!existingC... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Subscription Name cannot be altered")
public void testMergeDifferentSubname() {
SinkConfig sinkConfig = createSinkConfig();
SinkConfig newSinkConfig = createUpdatedSinkConfig("sourceSubscriptionName", "Diff... |
public static List<String> getErrorMessages(final Throwable e) {
return getThrowables(e).stream()
.map(ErrorMessageUtil::getErrorMessage)
.collect(Collectors.toList());
} | @Test
public void shouldBuildErrorMessageChain() {
// Given:
final Throwable e = new Exception("root", new Exception("cause"));
// Then:
assertThat(getErrorMessages(e), equalTo(ImmutableList.of("root", "cause")));
} |
public void clear(long index) {
assert index >= 0;
int prefix = (int) (index >>> Integer.SIZE);
if (prefix == lastPrefix) {
if (lastStorage.clear((int) index)) {
lastPrefix = -1;
lastStorage = null;
// cleanup the empty storage
... | @Test
public void testClear() {
// try to clear empty array
actual.clear();
verify();
// at the beginning
for (long i = 0; i < 1000; ++i) {
set(i);
}
for (long i = 0; i < 1000 + 100; ++i) {
clear(i);
verify();
/... |
@Override
public void handleTenantMenu(TenantMenuHandler handler) {
// 如果禁用,则不执行逻辑
if (isTenantDisable()) {
return;
}
// 获得租户,然后获得菜单
TenantDO tenant = getTenant(TenantContextHolder.getRequiredTenantId());
Set<Long> menuIds;
if (isSystemTenant(tenan... | @Test
public void testHandleTenantMenu_disable() {
// 准备参数
TenantMenuHandler handler = mock(TenantMenuHandler.class);
// mock 禁用
when(tenantProperties.getEnable()).thenReturn(false);
// 调用
tenantService.handleTenantMenu(handler);
// 断言
verify(handler,... |
public static ShenyuAdminResult error(final String msg) {
return error(CommonErrorCode.ERROR, msg);
} | @Test
public void testError() {
final ShenyuAdminResult result = ShenyuAdminResult.error("msg");
assertEquals(CommonErrorCode.ERROR, result.getCode().intValue());
assertEquals("msg", result.getMessage());
assertNull(result.getData());
assertEquals(3871218, result.hashCode());... |
public static boolean isComplete(Object obj) throws IllegalArgumentException {
requireNonNull(obj);
Field[] fields = obj.getClass().getDeclaredFields();
StringBuilder error = new StringBuilder();
for (Field field : fields) {
if (field.isAnnotationPresent(FieldContext.class)) ... | @Test
public void testComplete() throws Exception {
TestCompleteObject complete = new TestCompleteObject();
assertTrue(isComplete(complete));
} |
@Override
public Map<SubClusterId, List<ResourceRequest>> splitResourceRequests(
List<ResourceRequest> resourceRequests,
Set<SubClusterId> timedOutSubClusters) throws YarnException {
// object used to accumulate statistics about the answer, initialize with
// active subclusters. Create a new inst... | @Test
public void testCancelWithLocalizedResource() throws YarnException {
// Configure policy to be 100% headroom based
getPolicyInfo().setHeadroomAlpha(1.0f);
initializePolicy();
List<ResourceRequest> resourceRequests = new ArrayList<>();
// Initialize the headroom map
prepPolicyWithHeadro... |
public static void handleUncaughtException(
CompletableFuture<?> completableFuture,
Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
handleUncaughtException(
completableFuture, uncaughtExceptionHandler, FatalExitExceptionHandler.INSTANCE);
} | @Test
void testHandleUncaughtExceptionWithExceptionallyCompletion() {
final CompletableFuture<String> future = new CompletableFuture<>();
final TestingUncaughtExceptionHandler uncaughtExceptionHandler =
new TestingUncaughtExceptionHandler();
FutureUtils.handleUncaughtExcept... |
@Override
public void pluginUnLoaded(GoPluginDescriptor descriptor) {
PluggableTaskConfigStore.store().removePreferenceFor(descriptor.id());
} | @Test
public void shouldRemoveConfigForTheTaskCorrespondingToGivenPluginId() throws Exception {
final GoPluginDescriptor descriptor = mock(GoPluginDescriptor.class);
String pluginId = "test-plugin-id";
when(descriptor.id()).thenReturn(pluginId);
final Task task = mock(Task.class);
... |
public static String findANummer(List<Container> categorieList){
return findValue(categorieList, CATEGORIE_IDENTIFICATIENUMMERS, ELEMENT_A_NUMMER);
} | @Test
public void testFindAnummer() {
assertThat(CategorieUtil.findANummer(createFullCategories()), is("a-nummer"));
} |
public static MetadataExtractor create(String metadataClassName) {
String metadataExtractorClassName = metadataClassName;
try {
LOGGER.info("Instantiating MetadataExtractor class {}", metadataExtractorClassName);
MetadataExtractor metadataExtractor = (MetadataExtractor) Class.forName(metadataExtract... | @Test
public void testConfiguredMetadataProvider() {
Assert.assertTrue(
MetadataExtractorFactory.create(DefaultMetadataExtractor.class.getName()) instanceof DefaultMetadataExtractor);
} |
public Certificate add(X509Certificate cert) {
final Certificate db;
try {
db = Certificate.from(cert);
} catch (CertificateEncodingException e) {
logger.error("Encoding error in certificate", e);
throw new RuntimeException("Encoding error in certificate", e);... | @Test
public void shouldDisallowToAddCRLIfNotNewer() throws Exception {
certificateRepo.saveAndFlush(loadCertificate("rdw/02.cer", true));
crlRepo.saveAndFlush(loadCRL("rdw/02.crl"));
Exception exception = assertThrows(BadRequestException.class, () -> {
service.add(readCRL("rdw/0... |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException {
try {
final StoregateApiClient client = session.getClient();
final MoveFileRequest move = new Mov... | @Test
public void testMoveToDifferentParentAndRename() throws Exception {
final StoregateIdProvider nodeid = new StoregateIdProvider(session);
final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir(
new Path(String.format("/My files/%s", new AlphanumericRandomStringServic... |
@Override
public DdlCommand create(
final String sqlExpression,
final DdlStatement ddlStatement,
final SessionConfig config
) {
return FACTORIES
.getOrDefault(ddlStatement.getClass(), (statement, cf, ci) -> {
throw new KsqlException(
"Unable to find ddl command ... | @Test
public void shouldCreateCommandForCreateStream() {
// Given:
final CreateStream statement = new CreateStream(SOME_NAME, SOME_ELEMENTS, false, true, withProperties, false);
// When:
final DdlCommand result = commandFactories
.create(sqlExpression, statement, SessionConfig.of(ksqlConfig, ... |
public static Config fromHocon(ConfigOrigin origin, com.typesafe.config.Config config) {
var object = config.root();
var path = ConfigValuePath.root();
var value = toObject(origin, object, path);
return new SimpleConfig(origin, value);
} | @Test
void testFromHocon() {
var hocon = ConfigFactory.parseString("""
testObject {
f1 = "test1"
}
test {
f1 = "test1"
f2 = prefix_${testObject.f1}_suffix
f3 = 10
f4 = 15... |
public String process(final Expression expression) {
return formatExpression(expression);
} | @Test
public void shouldGenerateCorrectCodeForTimestampStringEQ() {
// Given:
final ComparisonExpression compExp = new ComparisonExpression(
Type.EQUAL,
TIMESTAMPCOL,
new StringLiteral("2020-01-01T00:00:00")
);
// When:
final String java = sqlToJavaVisitor.process(compExp)... |
static PrintStream create(
Handler handler, String loggerName, Level messageLevel, Charset charset) {
try {
return new JulHandlerPrintStream(handler, loggerName, messageLevel, charset);
} catch (UnsupportedEncodingException exc) {
throw new RuntimeException("Encoding not supported: " + charset... | @Test
public void testLogRecordMetadata() {
PrintStream printStream =
JulHandlerPrintStreamAdapterFactory.create(
handler, "fooLogger", Level.WARNING, StandardCharsets.UTF_8);
printStream.println("anyMessage");
assertThat(handler.getLogs(), not(empty()));
LogRecord log = Iterables... |
@Override
public void handle(final ClassicHttpResponse response) {
final int statusCode = response.getCode();
try {
if (statusCode == HttpStatus.SC_OK && response.getEntity().getContent() != null) {
final String content = EntityUtils.toString(response.getEntity());
if (content.length() ... | @Test
public void testHandle() throws IOException {
// Given
final ClassicHttpResponse response = mock(ClassicHttpResponse.class);
final HttpEntity entity = mock(HttpEntity.class);
final Logger log = mock(Logger.class);
expect(response.getCode()).andReturn(HttpStatus.SC_OK).once();
expect(resp... |
@Override
public boolean processLine(String line) throws IOException {
BugPatternInstance pattern = new Gson().fromJson(line, BugPatternInstance.class);
pattern.severity = severityRemapper.apply(pattern);
result.add(pattern);
// replace spaces in filename with underscores
Path checkPath = Paths.g... | @Test
public void regressionTest_frontmatter_pygments() throws Exception {
BugPatternFileGenerator generator =
new BugPatternFileGenerator(
wikiDir, explanationDirBase, true, null, input -> input.severity);
generator.processLine(BUGPATTERN_LINE);
String expected =
CharStreams.t... |
@Override
public void putAll(Map<? extends K, ? extends Writable> t) {
for (Map.Entry<? extends K, ? extends Writable> e:
t.entrySet()) {
put(e.getKey(), e.getValue());
}
} | @Test(timeout = 10000)
public void testPutAll() {
SortedMapWritable<Text> map1 = new SortedMapWritable<Text>();
SortedMapWritable<Text> map2 = new SortedMapWritable<Text>();
map1.put(new Text("key"), new Text("value"));
map2.putAll(map1);
assertEquals("map1 entries don't match map2 entries", map1... |
@Override
public void run() {
try { // make sure we call afterRun() even on crashes
// and operate countdown latches, else we may hang the parallel runner
if (steps == null) {
beforeRun();
}
if (skipped) {
return;
}
... | @Test
void testCallKarateFeature() {
run(
"def b = 'bar'",
"def res = call read('called1.feature')"
);
matchVar("res", "{ a: 1, foo: { hello: 'world' } }");
run(
"def b = 'bar'",
"def res = call read('called1.feature') {... |
void start(Iterable<ShardCheckpoint> checkpoints) {
LOG.info(
"Pool {} - starting for stream {} consumer {}. Checkpoints = {}",
poolId,
read.getStreamName(),
consumerArn,
checkpoints);
for (ShardCheckpoint shardCheckpoint : checkpoints) {
checkState(
!stat... | @Test
public void poolReSubscribesAndReadsRecordsWithTrimHorizon() throws Exception {
kinesis = new EFOStubbedKinesisAsyncClient(10);
kinesis.stubSubscribeToShard("shard-000", eventWithRecords(3));
kinesis.stubSubscribeToShard("shard-001", eventWithRecords(11, 3));
KinesisReaderCheckpoint initialChec... |
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext,
final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon... | @Test
void assertNewInstanceForAlwaysFalse() {
SQLStatement sqlStatement = mock(SQLStatement.class);
when(sqlStatementContext.getSqlStatement()).thenReturn(sqlStatement);
QueryContext queryContext = new QueryContext(sqlStatementContext, "", Collections.emptyList(), new HintValueContext(), mo... |
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder();
protobuf.setName("System");
setAttribute(protobuf, "Server ID", server.getId());
setAttribute(protobuf, "Edition", sonarRuntime.getEdition().getLabel());
... | @Test
public void toProtobuf_whenInstanceIsManaged_shouldWriteItsProviderName() {
when(commonSystemInformation.getManagedInstanceProviderName()).thenReturn("Okta");
ProtobufSystemInfo.Section protobuf = underTest.toProtobuf();
assertThatAttributeIs(protobuf, "External Users and Groups Provisioning", "Okt... |
public void upgrade() {
viewService.streamAll().forEach(view -> {
final Optional<User> user = view.owner().map(userService::load);
if (user.isPresent() && !user.get().isLocalAdmin()) {
final GRNType grnType = ViewDTO.Type.DASHBOARD.equals(view.type()) ? GRNTypes.DASHBOARD... | @Test
@DisplayName("dont migrate admin owners")
void dontMigrateAdminOwners() {
final GRN testuserGRN = GRNTypes.USER.toGRN("testuser");
final GRN search = GRNTypes.SEARCH.toGRN("54e3deadbeefdeadbeef0001");
final User testuser = mock(User.class);
when(testuser.getName()).thenRe... |
@Override
public void preflight(final Path source, final Path target) throws BackgroundException {
if(!CteraTouchFeature.validate(target.getName())) {
throw new InvalidFilenameException(MessageFormat.format(LocaleFactory.localizedString("Cannot rename {0}", "Error"), source.getName())).withFile(... | @Test
public void testPreflightFileAccessGrantedCustomProps() throws Exception {
final Path source = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
source.setAttributes(source.attributes().withAcl(new Acl(new Acl.Ca... |
@Bean("EsClient")
public EsClient provide(Configuration config) {
Settings.Builder esSettings = Settings.builder();
// mandatory property defined by bootstrap process
esSettings.put("cluster.name", config.get(CLUSTER_NAME.getKey()).get());
boolean clusterEnabled = config.getBoolean(CLUSTER_ENABLED.g... | @Test
public void es_client_provider_must_throw_IAE_when_incorrect_port_is_used() {
settings.setProperty(CLUSTER_ENABLED.getKey(), true);
settings.setProperty(CLUSTER_NODE_TYPE.getKey(), "search");
settings.setProperty(SEARCH_HOST.getKey(), "localhost");
settings.setProperty(SEARCH_PORT.getKey(), "100... |
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
} | @Test
public void testStartNoPort() throws Exception {
receiver.setRemoteHost(TEST_HOST_NAME);
receiver.start();
assertFalse(receiver.isStarted());
int count = lc.getStatusManager().getCount();
Status status = lc.getStatusManager().getCopyOfStatusList().get(count - 1);
... |
public final void containsEntry(@Nullable Object key, @Nullable Object value) {
Map.Entry<@Nullable Object, @Nullable Object> entry = immutableEntry(key, value);
checkNotNull(actual);
if (!actual.entrySet().contains(entry)) {
List<@Nullable Object> keyList = singletonList(key);
List<@Nullable Ob... | @Test
public void failMapContainsKeyWithValue() {
ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
expectFailureWhenTestingThat(actual).containsEntry("a", "a");
assertFailureValue("value of", "map.get(a)");
assertFailureValue("expected", "a");
assertFailureValue("but was", "A");
... |
public static Future<Void> maybeUpdateMetadataVersion(
Reconciliation reconciliation,
Vertx vertx,
TlsPemIdentity coTlsPemIdentity,
AdminClientProvider adminClientProvider,
String desiredMetadataVersion,
KafkaStatus status
) {
String bo... | @Test
public void testSuccessfulMetadataVersionUpgrade(VertxTestContext context) {
// Mock the Admin client
Admin mockAdminClient = mock(Admin.class);
// Mock describing the current metadata version
mockDescribeVersion(mockAdminClient);
// Mock updating metadata version
... |
@Override
public List<String> choices() {
if (commandLine.getArguments() == null) {
return Collections.emptyList();
}
List<String> argList = Lists.newArrayList();
String argOne = null;
if (argList.size() > 1) {
argOne = argList.get(1);
}
... | @Test
public void testNameCompleter() {
VplsNameCompleter vplsNameCompleter = new VplsNameCompleter();
vplsNameCompleter.vpls = new TestVpls();
((TestVpls) vplsNameCompleter.vpls).initSampleData();
List<String> choices = vplsNameCompleter.choices();
List<String> expected = Im... |
@Override
public Clob getClob(final int columnIndex) throws SQLException {
return (Clob) mergeResultSet.getValue(columnIndex, Clob.class);
} | @Test
void assertGetClobWithColumnLabel() throws SQLException {
Clob clob = mock(Clob.class);
when(mergeResultSet.getValue(1, Clob.class)).thenReturn(clob);
assertThat(shardingSphereResultSet.getClob("label"), is(clob));
} |
@Override
public long read() {
return gaugeSource.read();
} | @Test
public void whenCreatedForDynamicDoubleMetricWithProvidedValue() {
SomeObject someObject = new SomeObject();
someObject.longField = 42;
metricsRegistry.registerDynamicMetricsProvider((tagger, context) -> context
.collect(tagger.withPrefix("foo"), "doubleField", INFO, BY... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void externalFunctionDefinition() {
String inputExpression = "{ trigonometric cosine : function( angle ) external {"
+ " java : {"
+ " class : \"java.lang.Math\","
+ " method signature : \"cos(double)\""
... |
@Override
void toHtml() throws IOException {
writeHtmlHeader();
htmlCoreReport.toHtml();
writeHtmlFooter();
} | @Test
public void testWithCollectorServer() throws IOException {
final CollectorServer collectorServer = new CollectorServer();
try {
final HtmlReport htmlReport = new HtmlReport(collector, collectorServer,
javaInformationsList, Period.TOUT, writer);
htmlReport.toHtml(null, null);
assertNotEmptyAndCl... |
public static List<String> getJavaOpts(Configuration conf) {
String adminOpts = conf.get(YarnConfiguration.NM_CONTAINER_LOCALIZER_ADMIN_JAVA_OPTS_KEY,
YarnConfiguration.NM_CONTAINER_LOCALIZER_ADMIN_JAVA_OPTS_DEFAULT);
String userOpts = conf.get(YarnConfiguration.NM_CONTAINER_LOCALIZER_JAVA_OPTS_KEY,
... | @Test
public void testAdminOptionsPrecedeUserDefinedJavaOptions() throws Exception {
ContainerLocalizerWrapper wrapper = new ContainerLocalizerWrapper();
ContainerLocalizer localizer = wrapper.setupContainerLocalizerForTest();
Configuration conf = new Configuration();
conf.setStrings(YarnConfiguratio... |
@Override
public boolean contains(Object objectToCheck) {
return contains(objectToCheck, objectToCheck.hashCode());
} | @Test(expected = NullPointerException.class)
public void testContainsNull() {
final OAHashSet<Integer> set = new OAHashSet<>(8);
set.contains(null);
} |
@Override
public Result apply(ApplyNode applyNode, Captures captures, Context context)
{
return Result.ofPlanNode(applyNode.getInput());
} | @Test
public void testEmptyAssignments()
{
tester().assertThat(new RemoveUnreferencedScalarApplyNodes())
.on(p -> p.apply(
Assignments.of(),
ImmutableList.of(),
p.values(p.variable("x")),
p.va... |
public static LookupDefaultMultiValue create(String valueString, LookupDefaultValue.Type valueType) {
requireNonNull(valueString, "valueString cannot be null");
requireNonNull(valueType, "valueType cannot be null");
Map<Object, Object> value;
try {
switch (valueType) {
... | @Test
public void createSingleBoolean() throws Exception {
expectedException.expect(IllegalArgumentException.class);
LookupDefaultMultiValue.create("true", LookupDefaultMultiValue.Type.BOOLEAN);
} |
public static DataList convertListRetainingNulls(List<?> input)
{
return convertList(input, true, false);
} | @Test
void testConvertListWithRetainingNull()
{
List<String> listWithNull = Arrays.asList("element1", null, "element2");
DataList dataList = DataComplexUtil.convertListRetainingNulls(listWithNull);
Assert.assertNotNull(dataList);
Assert.assertEquals(dataList.size(), 3);
Assert.assertEquals(data... |
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) {
if (statsEnabled) {
stats.log(deviceStateServiceMsg);
}
stateService.onQueueMsg(deviceStateServiceMsg, callback);
} | @Test
public void givenProcessingFailure_whenForwardingActivityMsgToStateService_thenOnFailureCallbackIsCalled() {
// GIVEN
var activityMsg = TransportProtos.DeviceActivityProto.newBuilder()
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(te... |
@Override
public SyntheticSourceReader createReader(PipelineOptions pipelineOptions) {
return new SyntheticSourceReader(this);
} | @Test
public void testRegressingProgress() throws Exception {
PipelineOptions options = PipelineOptionsFactory.create();
testSourceOptions.progressShape = ProgressShape.LINEAR_REGRESSING;
SyntheticBoundedSource source = new SyntheticBoundedSource(testSourceOptions);
BoundedSource.BoundedReader<KV<byte... |
@Override
public SchemaAndValue get(final ProcessingLogConfig config) {
final Struct struct = new Struct(ProcessingLogMessageSchema.PROCESSING_LOG_SCHEMA)
.put(ProcessingLogMessageSchema.TYPE, MessageType.SERIALIZATION_ERROR.getTypeId())
.put(ProcessingLogMessageSchema.SERIALIZATION_ERROR, seriali... | @Test
public void shouldBuildSerializationError() {
// Given:
final SerializationError<GenericRow> serError = new SerializationError<>(
ERROR,
Optional.of(RECORD),
TOPIC,
false
);
// When:
final SchemaAndValue msg = serError.get(LOGGING_CONFIG);
// Then:
f... |
@Override
public int offer(E e) {
@SuppressWarnings("deprecation")
long z = mix64(Thread.currentThread().getId());
int increment = ((int) (z >>> 32)) | 1;
int h = (int) z;
int mask;
int result;
Buffer<E> buffer;
boolean uncontended = true;
Buffer<E>[] buffers = table;
if ((buf... | @Test(dataProvider = "buffers")
public void init(FakeBuffer<Integer> buffer) {
assertThat(buffer.table).isNull();
var result = buffer.offer(ELEMENT);
assertThat(buffer.table).hasLength(1);
assertThat(result).isEqualTo(Buffer.SUCCESS);
} |
String getBcp47Locale(boolean canonicalize) {
StringBuilder str = new StringBuilder();
// This represents the "any" locale value, which has traditionally been
// represented by the empty string.
if (language[0] == '\0' && country[0] == '\0') {
return "";
}
if (language[0] != '\0') {
... | @Test
public void getBcp47Locale_philippines_shouldReturnFil() {
ResTable_config resTable_config = new ResTable_config();
resTable_config.language[0] = 't';
resTable_config.language[1] = 'l';
resTable_config.country[0] = 'p';
resTable_config.country[1] = 'h';
assertThat(resTable_config.getBcp... |
public static boolean isAnyNullOrEmpty(String... args) {
for (String arg : args)
if (StringUtil.isNullOrEmpty(arg))
return true;
return false;
} | @Test
void testIsAnyNullOrEmpty() {
assertTrue(StringUtil.isAnyNullOrEmpty("", "a", null));
assertTrue(StringUtil.isAnyNullOrEmpty("", "a"));
assertTrue(StringUtil.isAnyNullOrEmpty("a", null));
assertTrue(StringUtil.isAnyNullOrEmpty(""));
assertTrue(StringUtil.isAnyNullOrEmpty((String) null));
assertFalse(... |
public Map<Object, Double> getTopValues(int number) {
AssertUtil.isTrue(number > 0, "number must be positive");
metric.currentWindow();
List<CacheMap<Object, LongAdder>> buckets = metric.values();
Map<Object, Long> result = new HashMap<>(buckets.size());
for (CacheMap<Object, L... | @Test(expected = IllegalArgumentException.class)
public void testIllegalArgument() {
ClusterParamMetric metric = new ClusterParamMetric(5, 25, 100);
metric.getTopValues(-1);
} |
@Override
public void validTenant(Long id) {
TenantDO tenant = getTenant(id);
if (tenant == null) {
throw exception(TENANT_NOT_EXISTS);
}
if (tenant.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) {
throw exception(TENANT_DISABLE, tenant.getName());
... | @Test
public void testValidTenant_success() {
// mock 数据
TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus())
.setExpireTime(LocalDateTime.now().plusDays(1)));
tenantMapper.insert(tenant);
// 调用,并断言业务异常
... |
public static Pair<CloudObjectIncrCheckpoint, Option<Dataset<Row>>> filterAndGenerateCheckpointBasedOnSourceLimit(Dataset<Row> sourceData,
long sourceLimit, QueryInfo queryInfo,
... | @Test
void testEmptySource() {
StructType schema = new StructType();
Dataset<Row> emptyDataset = spark().createDataFrame(new ArrayList<Row>(), schema);
QueryInfo queryInfo = new QueryInfo(
QUERY_TYPE_INCREMENTAL_OPT_VAL(), "commit1", "commit1",
"commit2", "_hoodie_commit_time",
"s3... |
@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String,... | @Test
public void reportsTimerValues() throws Exception {
final Timer timer = mock(Timer.class);
when(timer.getCount()).thenReturn(1L);
when(timer.getMeanRate()).thenReturn(2.0);
when(timer.getOneMinuteRate()).thenReturn(3.0);
when(timer.getFiveMinuteRate()).thenReturn(4.0);
... |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void kGroupedStreamNamedMaterializedCountShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic")
.groupByKey()
.count(Materialized.<Object, Long, KeyValueStore<Bytes, byte[]>>as("count-store")
... |
public static String normalizeUri(String uri) throws URISyntaxException {
// try to parse using the simpler and faster Camel URI parser
String[] parts = CamelURIParser.fastParseUri(uri);
if (parts != null) {
// we optimized specially if an empty array is returned
if (part... | @Test
public void testNormalizeHttpEndpointUnicodedParameter() throws Exception {
String out = URISupport.normalizeUri("http://www.google.com?q=S\u00F8ren");
assertEquals("http://www.google.com?q=S%C3%B8ren", out);
} |
public List<ExpressionElement> getExpressionElements() {
return expressionElements;
} | @Test
public void getExpressionElementsWithoutClass_missingExpression() {
original = new FactMapping("FACT_ALIAS", FactIdentifier.create("FI_TEST", "com.test.Foo"), new ExpressionIdentifier("EI_TEST", GIVEN));
assertThatThrownBy(original::getExpressionElementsWithoutClass)
.... |
public void execute() throws DdlException {
Map<String, UserVariable> clonedUserVars = new ConcurrentHashMap<>();
boolean hasUserVar = stmt.getSetListItems().stream().anyMatch(var -> var instanceof UserVariable);
boolean executeSuccess = true;
if (hasUserVar) {
clonedUserVars... | @Test
public void testNormal() throws UserException {
List<SetListItem> vars = Lists.newArrayList();
vars.add(new SetPassVar(new UserIdentity("testUser", "%"),
"*88EEBA7D913688E7278E2AD071FDB5E76D76D34B"));
vars.add(new SetNamesVar("utf8"));
vars.add(new SystemVariabl... |
@Override
protected String createRegistryCacheKey(URL url) {
String namespace = url.getParameter(CONFIG_NAMESPACE_KEY);
url = URL.valueOf(url.toServiceStringWithoutResolving());
if (StringUtils.isNotEmpty(namespace)) {
url = url.addParameter(CONFIG_NAMESPACE_KEY, namespace);
... | @Test
void testCreateRegistryCacheKey() {
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":8080?nacos.check=false");
String registryCacheKey1 = nacosRegistryFactory.createRegistryCacheKey(url);
String registryCacheKey2 = nacosRegistryFactory.createRegistryCa... |
public NearCacheConfig setPreloaderConfig(NearCachePreloaderConfig preloaderConfig) {
this.preloaderConfig = checkNotNull(preloaderConfig, "NearCachePreloaderConfig cannot be null!");
return this;
} | @Test(expected = NullPointerException.class)
public void testSetNearCachePreloaderConfig_whenNull_thenThrowException() {
config.setPreloaderConfig(null);
} |
@Override
public void deleteTenantPackage(Long id) {
// 校验存在
validateTenantPackageExists(id);
// 校验正在使用
validateTenantUsed(id);
// 删除
tenantPackageMapper.deleteById(id);
} | @Test
public void testDeleteTenantPackage_used() {
// mock 数据
TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class);
tenantPackageMapper.insert(dbTenantPackage);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbTenantPackage.getId();
// mock 租户在使用该套餐
when... |
public CounterMessageFlyweight keyBuffer(final DirectBuffer keyBuffer, final int keyOffset, final int keyLength)
{
buffer.putInt(offset + KEY_LENGTH_OFFSET, keyLength);
if (null != keyBuffer && keyLength > 0)
{
buffer.putBytes(offset + KEY_BUFFER_OFFSET, keyBuffer, keyOffset, key... | @Test
void keyBuffer()
{
final int offset = 24;
buffer.setMemory(0, offset, (byte)15);
flyweight.wrap(buffer, offset);
flyweight.keyBuffer(newBuffer(16), 4, 8);
assertEquals(8, flyweight.keyBufferLength());
assertEquals(KEY_BUFFER_OFFSET, flyweight.keyBufferOffs... |
@Override
public State cancel() throws IOException {
// Enforce that a cancel() call on the job is done at most once - as
// a workaround for Dataflow service's current bugs with multiple
// cancellation, where it may sometimes return an error when cancelling
// a job that was already cancelled, but s... | @Test
public void testCancelUnterminatedJobThatSucceeds() throws IOException {
Dataflow.Projects.Locations.Jobs.Update update =
mock(Dataflow.Projects.Locations.Jobs.Update.class);
when(mockJobs.update(eq(PROJECT_ID), eq(REGION_ID), eq(JOB_ID), any(Job.class)))
.thenReturn(update);
when(up... |
public static <T extends PipelineOptions> T as(Class<T> klass) {
return new Builder().as(klass);
} | @Test
public void testAppNameIsSet() {
ApplicationNameOptions options = PipelineOptionsFactory.as(ApplicationNameOptions.class);
assertEquals(PipelineOptionsFactoryTest.class.getSimpleName(), options.getAppName());
} |
public void transitionTo(ClassicGroupState groupState) {
assertValidTransition(groupState);
previousState = state;
state = groupState;
currentStateTimestamp = Optional.of(time.milliseconds());
metrics.onClassicGroupStateTransition(previousState, state);
} | @Test
public void testPreparingRebalanceToStableIllegalTransition() {
group.transitionTo(PREPARING_REBALANCE);
assertThrows(IllegalStateException.class, () -> group.transitionTo(STABLE));
} |
public long getMappedMemorySize() {
long size = 0;
Object[] mfs = this.copyMappedFiles(0);
if (mfs != null) {
for (Object mf : mfs) {
if (((ReferenceResource) mf).isAvailable()) {
size += this.mappedFileSize;
}
}
... | @Test
public void testGetMappedMemorySize() {
final String fixedMsg = "abcd";
MappedFileQueue mappedFileQueue =
new MappedFileQueue(storePath + File.separator + "d/", 1024, null);
for (int i = 0; i < 1024; i++) {
MappedFile mappedFile = mappedFileQueue.getLastMapped... |
public static boolean isHostName(String hostName) {
return VALID_HOSTNAME_PATTERN.matcher(hostName).matches();
} | @Test
public void testValidHostname() {
assertTrue(DnsClient.isHostName("google.com"));
assertTrue(DnsClient.isHostName("api.graylog.com"));
assertFalse(DnsClient.isHostName("http://api.graylog.com")); // Prefix not allowed
assertFalse(DnsClient.isHostName("api.graylog.com/10")); //... |
@Deprecated
@Override public void toXML(Object obj, OutputStream out) {
super.toXML(obj, out);
} | @Issue("JENKINS-71139")
@Test
public void nullsWithoutEncodingDeclaration() throws Exception {
Bar b = new Bar();
b.s = "x\u0000y";
try {
new XStream2().toXML(b, new StringWriter());
fail("expected to fail fast; not supported to read either");
} catch (Run... |
String getLayerFilename(DescriptorDigest layerDiffId) {
return layerDiffId.getHash();
} | @Test
public void testGetLayerFilename() throws DigestException {
DescriptorDigest diffId =
DescriptorDigest.fromHash(
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
Assert.assertEquals(
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
... |
@Override
synchronized public void close() {
if (stream != null) {
IOUtils.cleanupWithLogger(LOG, stream);
stream = null;
}
} | @Test(timeout=120000)
public void testRandomFloat() throws Exception {
OsSecureRandom random = getOsSecureRandom();
float rand1 = random.nextFloat();
float rand2 = random.nextFloat();
while (rand1 == rand2) {
rand2 = random.nextFloat();
}
random.close();
} |
public final void containsEntry(@Nullable Object key, @Nullable Object value) {
Map.Entry<@Nullable Object, @Nullable Object> entry = immutableEntry(key, value);
checkNotNull(actual);
if (!actual.entrySet().contains(entry)) {
List<@Nullable Object> keyList = singletonList(key);
List<@Nullable Ob... | @Test
public void containsEntry() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
assertThat(actual).containsEntry("kurt", "kluever");
} |
public static String getPartitionRangeString(DynamicPartitionProperty property, ZonedDateTime current,
int offset, String format) {
String timeUnit = property.getTimeUnit();
if (timeUnit.equalsIgnoreCase(TimeUnit.HOUR.toString())) {
return get... | @Test
public void testGetPartitionRangeString() throws DateTimeException {
// TimeUnit: DAY
// 1. 2020-05-25, offset -7
DynamicPartitionProperty property = new DynamicPartitionProperty(getDynamProp("DAY", -3, 3, -1, -1));
String res = DynamicPartitionUtil.getPartitionRangeString(pro... |
public static void getSemanticPropsDualFromString(
DualInputSemanticProperties result,
String[] forwardedFirst,
String[] forwardedSecond,
String[] nonForwardedFirst,
String[] nonForwardedSecond,
String[] readFieldsFirst,
String[] readFi... | @Test
void testNonForwardedDualInvalidTypes1() {
String[] nonForwardedFieldsFirst = {"f1"};
DualInputSemanticProperties dsp = new DualInputSemanticProperties();
assertThatThrownBy(
() ->
SemanticPropUtil.getSemanticPropsDualFromString(... |
public static String createQueryString(Map<String, Object> options) {
final Set<String> keySet = options.keySet();
return createQueryString(keySet.toArray(new String[0]), options, true);
} | @Test
public void testPlusInQuery() {
Map<String, Object> map = new HashMap<>();
map.put("param1", "+447777111222");
String q = URISupport.createQueryString(map);
assertEquals("param1=%2B447777111222", q);
// will be double encoded however
map.put("param1", "%2B44777... |
public FEELFnResult<Boolean> invoke(@ParameterName("list") List list) {
if (list == null) {
return FEELFnResult.ofResult(true);
}
boolean result = true;
for (final Object element : list) {
if (element != null && !(element instanceof Boolean)) {
ret... | @Test
void invokeBooleanParamTrue() {
FunctionTestUtil.assertResult(nnAllFunction.invoke(true), true);
} |
@Override
public Optional<DevOpsProjectCreator> getDevOpsProjectCreator(DbSession dbSession, Map<String, String> characteristics) {
return Optional.empty();
} | @Test
void getDevOpsProjectCreator_whenAlmIsAzureDevOps_shouldReturnProjectCreator() {
AlmSettingDto almSettingDto = mock(AlmSettingDto.class);
when(almSettingDto.getAlm()).thenReturn(ALM.AZURE_DEVOPS);
DevOpsProjectDescriptor devOpsProjectDescriptor = new DevOpsProjectDescriptor(ALM.AZURE_DEVOPS, null, "... |
public static NormalKey createRandom(EncryptionAlgorithmPB algorithm) {
byte[] plainKey;
if (algorithm == EncryptionAlgorithmPB.AES_128) {
plainKey = EncryptionUtil.genRandomKey(16);
} else {
throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
... | @Test
public void testCreateRandom() {
NormalKey key = NormalKey.createRandom();
assertNotNull(key);
assertNotNull(key.getPlainKey());
assertEquals(EncryptionAlgorithmPB.AES_128, key.getAlgorithm());
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void getUpdates() {
GetUpdates getUpdates = new GetUpdates()
.offset(874227176)
.allowedUpdates("")
.timeout(0)
.limit(100);
assertEquals(100, getUpdates.getLimit());
GetUpdatesResponse response = bot.execute(getUpd... |
public float getProgress() {
return total > 0 ? (float) completed / total : 0;
} | @Test
public void testGetProgress() {
assertEquals(1.0f, new BackupTaskStatus(BackupTaskState.SUCCESS, 10, 10).getProgress(), 0.1);
assertEquals(0.5f, new BackupTaskStatus(BackupTaskState.SUCCESS, 5, 10).getProgress(), 0.1);
assertEquals(0.0f, new BackupTaskStatus(BackupTaskState.SUCCESS, 0,... |
public static Map<String, Map<String, String>> splitAll(Map<String, List<String>> list, String separator) {
if (list == null) {
return null;
}
Map<String, Map<String, String>> result = new HashMap<>();
for (Map.Entry<String, List<String>> entry : list.entrySet()) {
... | @Test
void testSplitAll() {
assertNull(CollectionUtils.splitAll(null, null));
assertNull(CollectionUtils.splitAll(null, "-"));
assertTrue(CollectionUtils.splitAll(new HashMap<String, List<String>>(), "-")
.isEmpty());
Map<String, List<String>> input = new HashMap<St... |
@VisibleForTesting
RegistryErrorException newRegistryErrorException(ResponseException responseException) {
RegistryErrorExceptionBuilder registryErrorExceptionBuilder =
new RegistryErrorExceptionBuilder(
registryEndpointProvider.getActionDescription(), responseException);
if (responseExcep... | @Test
public void testNewRegistryErrorException_noOutputFromRegistry() {
ResponseException httpException = Mockito.mock(ResponseException.class);
// Registry returning null error output
Mockito.when(httpException.getContent()).thenReturn(null);
Mockito.when(httpException.getStatusCode()).thenReturn(40... |
public static String getMD5Checksum(File file) throws IOException, NoSuchAlgorithmException {
return getChecksum(MD5, file);
} | @Test
public void testGetMD5Checksum_String() {
String text = "test string";
String expResult = "6f8db599de986fab7a21625b7916589c";
String result = Checksum.getMD5Checksum(text);
assertEquals(expResult, result);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.