focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public String getName() {
return name;
} | @Test
public void testEqualsAndHashCode() {
assumeDifferentHashCodes();
EqualsVerifier.forClass(MultiMapConfig.class)
.suppress(Warning.NONFINAL_FIELDS, Warning.NULL_FIELDS)
.withPrefabValues(MultiMapConfigReadOnly.class,
new MultiMapConfigRead... |
@Override
protected String defaultWarehouseLocation(TableIdentifier tableIdentifier) {
validateTableIdentifier(tableIdentifier);
GetItemResponse response =
dynamo.getItem(
GetItemRequest.builder()
.tableName(awsProperties.dynamoDbTableName())
.consistentRead... | @Test
public void testDefaultWarehouseLocationNoDbUri() {
Mockito.doReturn(GetItemResponse.builder().item(Maps.newHashMap()).build())
.when(dynamo)
.getItem(any(GetItemRequest.class));
String warehousePath = WAREHOUSE_PATH + "/db.db/table";
String defaultWarehouseLocation = dynamoCatalog.... |
public static UriTemplate create(String template, Charset charset) {
return new UriTemplate(template, true, charset);
} | @Test
void simpleTemplateMultipleExpressions() {
String template = "https://www.example.com/{foo}/{bar}/details";
UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8);
/* verify that the template has 2 variables names foo and bar */
List<String> uriTemplateVariables = uriTemplate.getVar... |
@VisibleForTesting
public static String getUserAgentString(String id, CommonUtils.ProcessType processType,
List<String> additionalInfo) {
List<String> info = new ArrayList<>();
info.add(id);
addUserAgentEnvironments(info);
info.addAll(additionalInfo);
info.add(String.format("processType:%s",... | @Test
public void userAgent() {
String userAgentString = UpdateCheckUtils.getUserAgentString("cluster1",
CommonUtils.ProcessType.MASTER, new ArrayList<>());
Pattern pattern = Pattern.compile(
String.format("Alluxio\\/%s \\(cluster1(?:.+)[^;]\\)", ProjectConstants.VERSION));
Matcher matcher... |
public CounterRequest getCounterRequest(CounterRequestContext context) {
return getCounterRequestByName(context.getRequestName(), false);
} | @Test
public void testGetCounterRequest() {
counter.unbindContext();
final String requestName = "get counter request";
counter.bindContext(requestName, "my context", null, -1, -1);
final CounterRequest counterRequest = counter
.getCounterRequest(counter.getOrderedRootCurrentContexts().get(0));
assertEqua... |
public static KubernetesJobManagerSpecification buildKubernetesJobManagerSpecification(
FlinkPod podTemplate, KubernetesJobManagerParameters kubernetesJobManagerParameters)
throws IOException {
FlinkPod flinkPod = Preconditions.checkNotNull(podTemplate).copy();
List<HasMetadata> ... | @Test
void testServices() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
final List<Service> resultServices =
this.kuberne... |
@Override
public void resetConfigStats(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_RESETSTAT);
syncFuture(f);
} | @Test
public void testResetConfigStats() {
RedisClusterNode master = getFirstMaster();
connection.resetConfigStats(master);
} |
@Override
public void readLine(String line) {
if (line.startsWith("%") || line.isEmpty()) {
return;
}
if(line.startsWith("descr") && this.organization == null) {
this.organization = lineValue(line);
}
// Some responses have an org-name. Let this alwa... | @Test
public void testRunDirectMatchWithShortResultFormat() throws Exception {
RIPENCCResponseParser parser = new RIPENCCResponseParser();
for (String line : MATCH_WITH_SHORT_RESULT.split("\n")) {
parser.readLine(line);
}
assertEquals("US", parser.getCountryCode());
... |
@Override
public CompletableFuture<JobMasterGateway> getJobMasterGatewayFuture() {
return jobMasterGatewayFuture;
} | @Test
void testJobMasterGatewayGetsForwarded() {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
TestingJobMasterGateway testingGateway = ... |
@Bean
public ShenyuPlugin globalPlugin(final ShenyuContextBuilder shenyuContextBuilder) {
return new GlobalPlugin(shenyuContextBuilder);
} | @Test
public void testGlobalPlugin() {
applicationContextRunner.run(context -> {
ShenyuPlugin plugin = context.getBean("globalPlugin", ShenyuPlugin.class);
assertNotNull(plugin);
}
);
} |
public ConnectionDetails getConnectionDetails( IMetaStore metaStore, String key, String name ) {
ConnectionProvider<? extends ConnectionDetails> connectionProvider = getConnectionProvider( key );
if ( connectionProvider != null ) {
Class<? extends ConnectionDetails> clazz = connectionProvider.getClassType... | @Test
public void testDefaultPropertiesNotNull() {
addOne();
TestConnectionWithBucketsDetails connectionDetails =
(TestConnectionWithBucketsDetails) connectionManager.getConnectionDetails( CONNECTION_NAME );
assertNotNull( connectionDetails );
assertNotNull( connectionDetails.getProperties() );
... |
public static void validateMaterializedViewPartitionColumns(
SemiTransactionalHiveMetastore metastore,
MetastoreContext metastoreContext,
Table viewTable,
MaterializedViewDefinition viewDefinition)
{
SchemaTableName viewName = new SchemaTableName(viewTable.get... | @Test
public void testValidateMaterializedViewPartitionColumnsTwoColumnMatchDifferentTable()
{
TestingSemiTransactionalHiveMetastore testMetastore = TestingSemiTransactionalHiveMetastore.create();
Column dsColumn = new Column("ds", HIVE_STRING, Optional.empty(), Optional.empty());
Colum... |
@Override
protected List<String> getArgs() {
TableMetadata tableMetadata = getMetadata();
RetentionConfig config = tablesClient.getTableRetention(tableMetadata).get();
String columnName = config.getColumnName();
List<String> jobArgs =
Stream.of(
"--tableName",
t... | @Test
void testRetentionJobArgsForTableWithPattern() {
TableRetentionTask tableRetentionTask =
new TableRetentionTask(jobsClient, tablesClient, tableMetadata);
String columnPattern = "yyyy-MM-DD";
String columnName = "testColumnName";
int count = 1;
Retention.GranularityEnum retentionGranu... |
@Override
public CompletableFuture<RegistrationResponse> registerTaskManager(
final JobID jobId,
final TaskManagerRegistrationInformation taskManagerRegistrationInformation,
final Time timeout) {
if (!jobGraph.getJobID().equals(jobId)) {
log.debug(
... | @Test
void testJobMasterDisconnectsOldTaskExecutorIfNewSessionIsSeen() throws Exception {
try (final JobMaster jobMaster =
new JobMasterBuilder(jobGraph, rpcService).createJobMaster()) {
final CompletableFuture<Void> firstTaskExecutorDisconnectedFuture =
new ... |
public static boolean isInventoryFinished(final int jobShardingCount, final Collection<TransmissionJobItemProgress> jobItemProgresses) {
return isAllProgressesFilled(jobShardingCount, jobItemProgresses) && isAllInventoryTasksCompleted(jobItemProgresses);
} | @Test
void assertIsInventoryFinishedWhenInventoryTaskProgressHasEmptyMap() {
JobItemInventoryTasksProgress jobItemInventoryTasksProgress = new JobItemInventoryTasksProgress(Collections.emptyMap());
TransmissionJobItemProgress transmissionJobItemProgress = new TransmissionJobItemProgress();
t... |
void fetchPluginSettingsMetaData(GoPluginDescriptor pluginDescriptor) {
String pluginId = pluginDescriptor.id();
List<ExtensionSettingsInfo> allMetadata = findSettingsAndViewOfAllExtensionsIn(pluginId);
List<ExtensionSettingsInfo> validMetadata = allSettingsAndViewPairsWhichAreValid(allMetadata)... | @Test
public void shouldNotFetchPluginSettingsMetadataForTaskPlugin() {
PluginSettingsConfiguration configuration = new PluginSettingsConfiguration();
configuration.add(new PluginSettingsProperty("k1").with(Property.REQUIRED, true).with(Property.SECURE, false));
GoPluginDescriptor pluginDes... |
public String getPath() {
return null == parentNode ? String.join("/", type) : String.join("/", parentNode, type);
} | @Test
void assertPathWithNullParentNode() {
UniqueRuleItemNodePath uniqueRuleItemNodePath = new UniqueRuleItemNodePath(new RuleRootNodePath("foo"), "test_path");
assertThat(uniqueRuleItemNodePath.getPath(), is("test_path"));
} |
@Override
public MapTileArea computeFromSource(final MapTileArea pSource, final MapTileArea pReuse) {
final MapTileArea out = pReuse != null ? pReuse : new MapTileArea();
if (pSource.size() == 0) {
out.reset();
return out;
}
final int left = pSource.getLeft() ... | @Test
public void testTwoContiguousPointsModulo() {
final MapTileArea source = new MapTileArea();
final MapTileArea dest = new MapTileArea();
final Set<Long> set = new HashSet<>();
final int border = 2;
final MapTileAreaBorderComputer computer = new MapTileAreaBorderComputer(... |
@Override
public SelBoolean assignOps(SelOp op, SelType rhs) {
if (op == SelOp.ASSIGN) {
SelTypeUtil.checkTypeMatch(this.type(), rhs.type());
this.val = ((SelBoolean) rhs).val; // direct assignment
return this;
}
throw new UnsupportedOperationException(
"boolean/Boolean DO NOT su... | @Test
public void testAssignOps() {
SelBoolean res = one.assignOps(SelOp.ASSIGN, another);
another.assignOps(SelOp.ASSIGN, SelBoolean.of(true));
assertEquals("BOOLEAN: false", one.type() + ": " + one);
assertEquals("BOOLEAN: true", another.type() + ": " + another);
} |
public static String hashpw(String password, String salt) throws IllegalArgumentException {
BCrypt B;
String real_salt;
byte passwordb[], saltb[], hashed[];
char minor = (char) 0;
int rounds, off = 0;
StringBuilder rs = new StringBuilder();
if (salt == null) {
... | @Test
public void testHashpwMissingSaltRounds() throws IllegalArgumentException {
thrown.expect(IllegalArgumentException.class);
BCrypt.hashpw("foo", "$2$a10$.....................");
} |
@Override
public <T extends GetWorkBudgetSpender> void distributeBudget(
ImmutableCollection<T> budgetOwners, GetWorkBudget getWorkBudget) {
if (budgetOwners.isEmpty()) {
LOG.debug("Cannot distribute budget to no owners.");
return;
}
if (getWorkBudget.equals(GetWorkBudget.noBudget())) {... | @Test
public void testDistributeBudget_doesNothingWithNoBudget() {
GetWorkBudgetSpender getWorkBudgetSpender =
spy(createGetWorkBudgetOwnerWithRemainingBudgetOf(GetWorkBudget.noBudget()));
createBudgetDistributor(1L)
.distributeBudget(ImmutableList.of(getWorkBudgetSpender), GetWorkBudget.noBud... |
@VisibleForTesting
void validateParentMenu(Long parentId, Long childId) {
if (parentId == null || ID_ROOT.equals(parentId)) {
return;
}
// 不能设置自己为父菜单
if (parentId.equals(childId)) {
throw exception(MENU_PARENT_ERROR);
}
MenuDO menu = menuMapper... | @Test
public void testValidateParentMenu_success() {
// mock 数据
MenuDO menuDO = buildMenuDO(MenuTypeEnum.MENU, "parent", 0L);
menuMapper.insert(menuDO);
// 准备参数
Long parentId = menuDO.getId();
// 调用,无需断言
menuService.validateParentMenu(parentId, null);
} |
public static Type beamTypeToSpannerType(Schema.FieldType beamType) {
switch (beamType.getTypeName()) {
case ARRAY:
case ITERABLE:
Schema.@Nullable FieldType elementType = beamType.getCollectionElementType();
if (elementType == null) {
throw new NullPointerException("Null eleme... | @Test
public void testBeamTypeToSpannerTypeTranslation() {
assertEquals(Type.int64(), beamTypeToSpannerType(Schema.FieldType.INT64));
assertEquals(Type.int64(), beamTypeToSpannerType(Schema.FieldType.INT32));
assertEquals(Type.int64(), beamTypeToSpannerType(Schema.FieldType.INT16));
assertEquals(Type.... |
public Plan validateReservationUpdateRequest(
ReservationSystem reservationSystem, ReservationUpdateRequest request)
throws YarnException {
ReservationId reservationId = request.getReservationId();
Plan plan = validateReservation(reservationSystem, reservationId,
AuditConstants.UPDATE_RESERV... | @Test
public void testUpdateReservationEmptyRR() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 0, 1, 5, 3);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e) {
... |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName = null... | @Test
public void testAggregateMultiStatsOnlySomeAvailableButUnmergeableBitVector() throws MetaException {
List<String> partitions = Arrays.asList("part1", "part2", "part3");
ColumnStatisticsData data1 = new ColStatsBuilder<>(double.class).numNulls(1).numDVs(3)
.low(1d).high(6d).fmSketch(1, 2, 6).bui... |
public static long calculateIntervalEnd(long startTs, IntervalType intervalType, ZoneId tzId) {
var startTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(startTs), tzId);
switch (intervalType) {
case WEEK:
return startTime.truncatedTo(ChronoUnit.DAYS).with(WeekFields.SUNDA... | @Test
void testWeekEnd() {
long ts = 1704899727000L; // Wednesday, January 10 15:15:27 GMT
assertThat(TimeUtils.calculateIntervalEnd(ts, IntervalType.WEEK, ZoneId.of("Europe/Kyiv"))).isEqualTo(1705183200000L); // Sunday, January 14, 2024 0:00:00 GMT+02:00
assertThat(TimeUtils.calculateInterv... |
public static List<URI> getPeerServerURIs(HelixManager helixManager, String tableNameWithType, String segmentName,
String downloadScheme) {
HelixAdmin helixAdmin = helixManager.getClusterManagmentTool();
String clusterName = helixManager.getClusterName();
List<URI> onlineServerURIs = new ArrayList<>()... | @Test
public void testSegmentFoundSuccessfully()
throws Exception {
// SEGMENT_1 has only 2 online replicas.
List<URI> httpServerURIs = PeerServerSegmentFinder.getPeerServerURIs(_helixManager, REALTIME_TABLE_NAME, SEGMENT_1,
CommonConstants.HTTP_PROTOCOL);
assertEquals(httpServerURIs.size(),... |
static void unregisterCommand(PrintStream stream, Admin adminClient, int id) throws Exception {
try {
adminClient.unregisterBroker(id).all().get();
stream.println("Broker " + id + " is no longer registered.");
} catch (ExecutionException ee) {
Throwable cause = ee.get... | @Test
public void testLegacyModeClusterCannotUnregisterBroker() throws Exception {
Admin adminClient = new MockAdminClient.Builder().numBrokers(3).
usingRaftController(false).
build();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ClusterTool.unr... |
public static ExpansionServer create(ExpansionService service, String host, int port)
throws IOException {
return new ExpansionServer(service, host, port);
} | @Test
public void testPassingPipelineArguments() {
String[] args = {
"--defaultEnvironmentType=PROCESS",
"--defaultEnvironmentConfig={\"command\": \"/opt/apache/beam/boot\"}"
};
ExpansionService service = new ExpansionService(args);
assertThat(
service
.createPipeline(P... |
public static Optional<PfxOptions> getPfxTrustStoreOptions(final Map<String, String> props) {
final String location = getTrustStoreLocation(props);
final String password = getTrustStorePassword(props);
if (!Strings.isNullOrEmpty(location)) {
return Optional.of(buildPfxOptions(location, password));
... | @Test
public void shouldBuildTrustStorePfxOptionsWithPathAndPassword() {
// When
final Optional<PfxOptions> pfxOptions = VertxSslOptionsFactory.getPfxTrustStoreOptions(
ImmutableMap.of(
SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG,
"path",
SslConfigs.SSL_TRUSTSTORE_PAS... |
static TimelineFilterList parseKVFilters(String expr, boolean valueAsString)
throws TimelineParseException {
return parseFilters(new TimelineParserForKVFilters(expr, valueAsString));
} | @Test
void testInfoFiltersParsing() throws Exception {
String expr = "(((key11 ne 234 AND key12 eq val12) AND " +
"(key13 ene val13 OR key14 eq 567)) OR (key21 eq val_21 OR key22 eq " +
"5.0))";
TimelineFilterList expectedList = new TimelineFilterList(
Operator.OR,
new Timeline... |
public synchronized ValuesAndExtrapolations aggregate(SortedSet<Long> windowIndices, MetricDef metricDef) {
return aggregate(windowIndices, metricDef, true);
} | @Test
public void testExtrapolationAdjacentAvgAtMiddle() {
RawMetricValues rawValues = new RawMetricValues(NUM_WINDOWS_TO_KEEP, MIN_SAMPLES_PER_WINDOW, NUM_RAW_METRICS);
prepareWindowMissingAtIndex(rawValues, 1);
ValuesAndExtrapolations valuesAndExtrapolations = aggregate(rawValues, allWindowIndices(0));
... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof EntityDto entityDto)) {
return false;
}
return Objects.equals(uuid, entityDto.uuid);
} | @Test
void equals_whenEmptyObjects_shouldReturnTrue() {
PortfolioDto p1 = new PortfolioDto();
PortfolioDto p2 = new PortfolioDto();
boolean equals = p1.equals(p2);
assertThat(equals).isTrue();
} |
@Override
public void getConfig(StorServerConfig.Builder builder) {
super.getConfig(builder);
provider.getConfig(builder);
} | @Test
void testGarbageCollectionOffByDefault() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <redundancy>3</redundancy>" +
" <documents>\n" +
" <document type=\"... |
public int run() throws IOException {
Set<MasterInfoField> masterInfoFilter = new HashSet<>(Arrays
.asList(MasterInfoField.LEADER_MASTER_ADDRESS, MasterInfoField.WEB_PORT,
MasterInfoField.RPC_PORT, MasterInfoField.START_TIME_MS,
MasterInfoField.UP_TIME_MS, MasterInfoField.VERSION,
... | @Test
public void RaftHaSummary() throws IOException {
MasterVersion primaryVersion = MasterVersion.newBuilder()
.setVersion(RuntimeConstants.VERSION).setState("Primary").setAddresses(
NetAddress.newBuilder().setHost("hostname1").setRpcPort(10000).build()
).build();
MasterVersion s... |
public Collection<V> remove(K key)
{
List<V> removed = data.remove(key);
if (removed != null) {
for (V val : removed) {
inverse.remove(val);
}
}
return removed;
} | @Test
public void testRemoveKey()
{
Collection<Integer> removed = map.remove(1L);
assertThat(removed, is(Collections.singletonList(42)));
assertSize(0);
} |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QueryEntry that = (QueryEntry) o;
if (!key.equals(that.key)) {
return false;
}
... | @Test(expected = NullPointerException.class)
@SuppressWarnings("ResultOfMethodCallIgnored")
public void test_equality_empty() {
QueryableEntry entryKeyLeft = createEntry();
QueryableEntry entryKeyRight = createEntry();
entryKeyLeft.equals(entryKeyRight);
} |
public void markAsUnchanged(DefaultInputFile file) {
if (isFeatureActive()) {
if (file.status() != InputFile.Status.SAME) {
LOG.error("File '{}' was marked as unchanged but its status is {}", file.getProjectRelativePath(), file.status());
} else {
LOG.debug("File '{}' marked as unchanged... | @Test
public void dont_mark_file_is_status_is_not_same() {
when(file.status()).thenReturn(InputFile.Status.CHANGED);
executingSensorContext.setSensorExecuting(new SensorId("cpp", "CFamily"));
UnchangedFilesHandler handler = new UnchangedFilesHandler(enabledConfig, defaultBranchConfig, executingSensorConte... |
public static ZombieUpstream transform(final CommonUpstream commonUpstream, final int zombieCheckTimes, final String selectorId) {
return ZombieUpstream.builder().commonUpstream(commonUpstream).zombieCheckTimes(zombieCheckTimes).selectorId(selectorId).build();
} | @Test
public void testTransform() {
ZombieUpstream upstream = ZombieUpstream.transform(new CommonUpstream(), 10, "id");
assertThat(upstream, is(notNullValue()));
} |
@Override
public PostScript readPostScript(byte[] data, int offset, int length)
throws IOException
{
long cpuStart = THREAD_MX_BEAN.getCurrentThreadCpuTime();
CodedInputStream input = CodedInputStream.newInstance(data, offset, length);
DwrfProto.PostScript postScript = DwrfPr... | @Test
public void testReadPostScriptMissingDwrfStripeCacheLength()
throws IOException
{
DwrfProto.PostScript protoPostScript = baseProtoPostScript.toBuilder()
.clearCacheSize()
.build();
byte[] data = protoPostScript.toByteArray();
PostScript ... |
public void notifyMessageArriving(final String topic, final int queueId, final long maxOffset) {
notifyMessageArriving(topic, queueId, maxOffset, null, 0, null, null);
} | @Test
public void notifyMessageArrivingTest() {
Assertions.assertThatCode(() -> pullRequestHoldService.notifyMessageArriving(TEST_TOPIC, DEFAULT_QUEUE_ID, MAX_OFFSET)).doesNotThrowAnyException();
Assertions.assertThatCode(() -> pullRequestHoldService.suspendPullRequest(TEST_TOPIC, DEFAULT_QUEUE_ID,... |
void notifyPendingReceivedCallback(final Message<T> message, Exception exception) {
if (pendingReceives.isEmpty()) {
return;
}
// fetch receivedCallback from queue
final CompletableFuture<Message<T>> receivedFuture = nextPendingReceive();
if (receivedFuture == null) ... | @Test(invocationTimeOut = 1000)
public void testNotifyPendingReceivedCallback_CompleteWithExceptionWhenMessageIsNull() {
CompletableFuture<Message<byte[]>> receiveFuture = new CompletableFuture<>();
consumer.pendingReceives.add(receiveFuture);
consumer.notifyPendingReceivedCallback(null, nul... |
public void check(Metadata metadata) throws AccessPermissionException {
if (!needToCheck) {
return;
}
if ("false".equals(metadata.get(AccessPermissions.EXTRACT_CONTENT))) {
if (allowExtractionForAccessibility) {
if ("true".equals(metadata.get(AccessPermiss... | @Test
public void testNoExtraction() {
Metadata m = null;
//allow nothing
AccessChecker checker = new AccessChecker(false);
boolean ex = false;
try {
m = getMetadata(false, false);
checker.check(m);
} catch (AccessPermissionException e) {
... |
@GetMapping(value = "/node/list")
@Secured(action = ActionTypes.READ, resource = "nacos/admin", signType = SignType.CONSOLE)
public Result<Collection<Member>> listNodes(@RequestParam(value = "address", required = false) String address,
@RequestParam(value = "state", required = false) String state) t... | @Test
void testListNodes() throws NacosException {
Member member1 = new Member();
member1.setIp("1.1.1.1");
member1.setPort(8848);
member1.setState(NodeState.DOWN);
Member member2 = new Member();
member2.setIp("2.2.2.2");
member2.setPort(8848);
... |
public void sendCouponNewsletter() {
try {
// Retrieve the list of contacts from the "weekly-coupons-newsletter" contact
// list
// snippet-start:[sesv2.java2.newsletter.ListContacts]
ListContactsRequest contactListRequest = ListContactsRequest.builder()
.contactListName(CONTACT_LI... | @Test
public void test_sendCouponNewsletter_error_contactListNotFound() {
// Mock the necessary AWS SDK calls and responses
CreateEmailTemplateResponse templateResponse = CreateEmailTemplateResponse.builder().build();
when(sesClient.createEmailTemplate(any(CreateEmailTemplateRequest.class))).thenReturn(te... |
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
return lessIsBetter ? criterionValue1.isLessThan(criterionValue2)
: criterionValue1.isGreaterThan(criterionValue2);
} | @Test
public void betterThanWithLessIsNotBetter() {
AnalysisCriterion criterion = getCriterion(new ProfitLossCriterion(), false);
assertTrue(criterion.betterThan(numOf(5000), numOf(4500)));
assertFalse(criterion.betterThan(numOf(4500), numOf(5000)));
} |
void checkSupportedCipherSuites() {
if (getSupportedCipherSuites() == null) {
setSupportedCipherSuites(Collections.singletonList(HTTP2_DEFAULT_CIPHER));
} else if (!getSupportedCipherSuites().contains(HTTP2_DEFAULT_CIPHER)) {
throw new IllegalArgumentException("HTTP/2 server conf... | @Test
void testSetDefaultHttp2Cipher() {
http2ConnectorFactory.checkSupportedCipherSuites();
assertThat(http2ConnectorFactory.getSupportedCipherSuites()).containsExactly(
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
} |
@Override
public String getFailureMessage() {
if (hasAccess()) {
return StringUtils.EMPTY;
}
List<String> failedTablesList = new ArrayList<>(_failedTables);
Collections.sort(failedTablesList); // Sort to make output deterministic
return "Authorization Failed for tables: " + failedTablesList... | @Test
public void testGetFailureMessage() {
TableAuthorizationResult result = new TableAuthorizationResult(Set.of("table1", "table2"));
Assert.assertEquals(result.getFailureMessage(), "Authorization Failed for tables: [table1, table2]");
} |
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
} | @Test
public void testOrder() {
Assert.assertEquals(Ordered.LOWEST_PRECEDENCE, instance.getOrder());
} |
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
for (String pool : POOLS) {
for (int i = 0; i < ATTRIBUTES.length; i++) {
final String attribute = ATTRIBUTES[i];
final String name = NAMES[i];
... | @Test
public void ignoresGaugesForObjectsWhichCannotBeFound() throws Exception {
when(mBeanServer.getMBeanInfo(mapped)).thenThrow(new InstanceNotFoundException());
assertThat(buffers.getMetrics().keySet())
.containsOnly("direct.count",
"direct.capacity",
... |
@Override
public void execute(Exchange exchange) throws SmppException {
SubmitMulti[] submitMulties = createSubmitMulti(exchange);
List<SubmitMultiResult> results = new ArrayList<>(submitMulties.length);
for (SubmitMulti submitMulti : submitMulties) {
SubmitMultiResult result;
... | @Test
public void singleDlrRequestOverridesDeliveryReceiptFlag() throws Exception {
String longSms = "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" +
"12345678901234567890123456789012345678901234567890123456789012345678901";
Exc... |
@Override
public void open() throws Exception {
windowSerializer = windowAssigner.getWindowSerializer(new ExecutionConfig());
internalTimerService = getInternalTimerService("window-timers", windowSerializer, this);
// The structure is: [type]|[normal record]|[timestamp]|[current watermark]|... | @Test
void testFinishBundleTriggeredByCount() throws Exception {
Configuration conf = new Configuration();
conf.set(PythonOptions.MAX_BUNDLE_SIZE, 4);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf);
long initialTime = 0L;
ConcurrentLin... |
@Override
public long checkAndGetApplicationLifetime(String queueName,
long lifetimeRequestedByApp) {
readLock.lock();
try {
CSQueue queue = getQueue(queueName);
if (!(queue instanceof AbstractLeafQueue)) {
return lifetimeRequestedByApp;
}
long defaultApplicationLifetime... | @Test(timeout = 30000)
public void testcheckAndGetApplicationLifetime() throws Exception {
long maxLifetime = 10;
long defaultLifetime = 5;
// positive integer value
CapacityScheduler cs = setUpCSQueue(maxLifetime, defaultLifetime);
Assert.assertEquals(maxLifetime,
cs.checkAndGetApplicatio... |
public boolean isUserAuthorized(List<String> userAndRoles) {
if (!option.permissionIsSet()) {
return true;
}
Set<String> intersection = new HashSet<>(userAndRoles);
intersection.retainAll(option.getOwners());
return !intersection.isEmpty();
} | @Test
void testIsUserAuthorized() {
List<String> userAndRoles = new ArrayList<>();
userAndRoles.add("User1");
userAndRoles.add("Role1");
userAndRoles.add("Role2");
List<String> owners;
InterpreterSetting interpreterSetting;
InterpreterOption interpreterOption;
// With ... |
public PrepareResult prepare(HostValidator hostValidator, DeployLogger logger, PrepareParams params,
Optional<ApplicationVersions> activeApplicationVersions, Instant now, File serverDbSessionDir,
ApplicationPackage applicationPackage, SessionZooKeeperCli... | @Test
public void require_that_application_is_prepared() throws Exception {
prepare(testApp);
assertTrue(curator.exists(sessionPath(1).append(ZKApplication.USERAPP_ZK_SUBPATH).append("services.xml")));
} |
@Bean
@ConditionalOnMissingBean(ConsulDataChangedListener.class)
public DataChangedListener consulDataChangedListener(final ConsulClient consulClient) {
return new ConsulDataChangedListener(consulClient);
} | @Test
public void testConsulDataChangedListener() {
ConsulSyncConfiguration consulListener = new ConsulSyncConfiguration();
ConsulClient consulClient = mock(ConsulClient.class);
assertNotNull(consulListener.consulDataChangedListener(consulClient));
} |
static long stringToSeconds(String time) throws NumberFormatException, DateTimeParseException
{
long duration = 0;
if (time.matches(INPUT_HMS_REGEX))
{
String textWithoutWhitespaces = time.replaceAll(WHITESPACE_REGEX, "");
//parse input using ISO-8601 Duration format (e.g. 'PT1h30m10s')
duration = Dura... | @Test
public void properIntuitiveTimeStringShouldReturnCorrectSeconds()
{
assertEquals(5, ClockPanel.stringToSeconds("5s"));
assertEquals(50, ClockPanel.stringToSeconds("50s"));
assertEquals(120, ClockPanel.stringToSeconds("2m"));
assertEquals(120, ClockPanel.stringToSeconds("120s"));
assertEquals(1200, Clo... |
protected static String getConfigStr(String name) {
if (cacheMap.containsKey(name)) {
return (String) cacheMap.get(name);
}
String val = getConfig(name);
if (StringUtils.isBlank(val)) {
return null;
}
cacheMap.put(name, val);
return val;... | @Test
public void testGetConfigStr() {
// clear cache
DashboardConfig.clearCache();
// if not set, return null
assertEquals(null, DashboardConfig.getConfigStr("a"));
// test property
System.setProperty("a", "111");
assertEquals("111", DashboardConfig.getConf... |
public LatencyProbe newProbe(String serviceName, String dataStructureName, String methodName) {
ServiceProbes serviceProbes = getOrPutIfAbsent(
metricsPerServiceMap, serviceName, metricsPerServiceConstructorFunction);
return serviceProbes.newProbe(dataStructureName, methodName);
} | @Test
public void testMaxMicros() {
LatencyProbeImpl probe = (LatencyProbeImpl) plugin.newProbe("foo", "queue", "somemethod");
probe.recordValue(MICROSECONDS.toNanos(10));
probe.recordValue(MICROSECONDS.toNanos(1000));
probe.recordValue(MICROSECONDS.toNanos(4));
assertEquals... |
@Override
public EntityStatementJWS establishIdpTrust(URI issuer) {
var trustedFederationStatement = fetchTrustedFederationStatement(issuer);
// the federation statement from the master will establish trust in the JWKS and the issuer URL
// of the idp,
// we still need to fetch the entity configurat... | @Test
void establishTrust() {
var client = new FederationMasterClientImpl(FEDERATION_MASTER, federationApiClient, clock);
var issuer = URI.create("https://idp-tk.example.com");
var federationFetchUrl = FEDERATION_MASTER.resolve("/fetch");
var fedmasterKeypair = ECKeyGenerator.example();
var fe... |
@Override
public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException {
try {
String partitionColumn = job.get(Constants.JDBC_PARTITION_COLUMN);
int numPartitions = job.getInt(Constants.JDBC_NUM_PARTITIONS, -1);
String lowerBound = job.get(Constants.JDBC_LOW_BOUND);
Strin... | @Test
public void testIntervalSplit_Double() throws HiveJdbcDatabaseAccessException, IOException {
JdbcInputFormat f = new JdbcInputFormat();
when(mockDatabaseAccessor.getColumnNames(any(Configuration.class))).thenReturn(Lists.newArrayList("a"));
List<TypeInfo> columnTypes = Collections.singletonList(Type... |
public Set<String> getKeySetToDownload(Set<String> blobStoreKeySet, Set<String> zookeeperKeySet) {
zookeeperKeySet.removeAll(blobStoreKeySet);
LOG.debug("Key list to download {}", zookeeperKeySet);
return zookeeperKeySet;
} | @Test
public void testBlobSynchronizerForKeysToDownload() {
BlobStore store = initLocalFs();
LocalFsBlobStoreSynchronizer sync = new LocalFsBlobStoreSynchronizer(store, conf);
// test for keylist to download
Set<String> zkSet = new HashSet<>();
zkSet.add("key1");
Set<String> blobStoreSet = new... |
@Override
public UnboundedReader<KinesisRecord> createReader(
PipelineOptions options, @Nullable KinesisReaderCheckpoint checkpointMark)
throws IOException {
KinesisReaderCheckpoint initCheckpoint;
if (checkpointMark != null) {
LOG.info("Got checkpoint mark {}", checkpointMark);
initCh... | @Test
public void testCreateReaderOfCorrectType() throws Exception {
KinesisIO.Read readSpec =
KinesisIO.read()
.withStreamName("stream-xxx")
.withInitialPositionInStream(InitialPositionInStream.TRIM_HORIZON);
KinesisIO.Read readSpecEFO =
KinesisIO.read()
.... |
public List<GetBucketListReply.BucketInfo> retrieveBucketList(BucketId bucketId, String bucketSpace) throws BucketStatsException {
GetBucketListMessage msg = new GetBucketListMessage(bucketId, bucketSpace);
GetBucketListReply bucketListReply = sendMessage(msg, GetBucketListReply.class);
return b... | @Test
void testRetrieveBucketList() throws BucketStatsException {
String bucketInfo = "I like turtles!";
BucketId bucketId = bucketIdFactory.getBucketId(new DocumentId("id:ns:type::another"));
GetBucketListReply reply = new GetBucketListReply();
reply.getBuckets().add(new GetBucketL... |
@Override
protected boolean isSecure(String key) {
AuthorizationPluginInfo pluginInfo = this.metadataStore().getPluginInfo(getPluginId());
if (pluginInfo == null
|| pluginInfo.getAuthConfigSettings() == null
|| pluginInfo.getAuthConfigSettings().getConfiguration(key)... | @Test
public void addConfiguration_shouldEncryptASecureVariable() throws Exception {
PluggableInstanceSettings profileSettings = new PluggableInstanceSettings(List.of(new PluginConfiguration("password", new Metadata(true, true))));
AuthorizationPluginInfo pluginInfo = new AuthorizationPluginInfo(plu... |
public Serde<GenericRow> buildValueSerde(
final FormatInfo format,
final PhysicalSchema schema,
final QueryContext queryContext
) {
final String loggerNamePrefix = QueryLoggerUtil.queryLoggerName(queryId, queryContext);
schemas.trackValueSerdeCreation(
loggerNamePrefix,
sche... | @Test
public void shouldBuildValueSerde() {
// Then:
runtimeBuildContext.buildValueSerde(
FORMAT_INFO,
PHYSICAL_SCHEMA,
queryContext
);
// Then:
verify(valueSerdeFactory).create(
FORMAT_INFO,
PHYSICAL_SCHEMA.valueSchema(),
ksqlConfig,
srClie... |
public static List<TimeSlot> split(TimeSlot timeSlot, SegmentInMinutes unit) {
TimeSlot normalizedSlot = normalizeToSegmentBoundaries(timeSlot, unit);
return new SlotToSegments().apply(normalizedSlot, unit);
} | @Test
void splittingIntoSegmentsJustNormalizesIfChosenSegmentLargerThanPassedSlot() {
//given
Instant start = Instant.parse("2023-09-09T00:10:00Z");
Instant end = Instant.parse("2023-09-09T01:00:00Z");
TimeSlot timeSlot = new TimeSlot(start, end);
//when
List<TimeSlo... |
@Override
public SocialUserDO getSocialUser(Long id) {
return socialUserMapper.selectById(id);
} | @Test
public void testGetSocialUser() {
// 准备参数
Integer userType = UserTypeEnum.ADMIN.getValue();
Integer type = SocialTypeEnum.GITEE.getType();
String code = "tudou";
String state = "yuanma";
// mock 社交用户
SocialUserDO socialUserDO = randomPojo(SocialUserDO.cl... |
public List<String> getLiveBrokers() {
List<String> brokerUrls = new ArrayList<>();
try {
byte[] brokerResourceNodeData = _zkClient.readData(BROKER_EXTERNAL_VIEW_PATH, true);
brokerResourceNodeData = unpackZnodeIfNecessary(brokerResourceNodeData);
JsonNode jsonObject = OBJECT_READER.readTree(g... | @Test
public void testGetBrokerListByInstanceConfig() {
configureData(_instanceConfigPlain, true);
final List<String> brokers = _externalViewReaderUnderTest.getLiveBrokers();
assertEquals(brokers, Arrays.asList("first.pug-pinot-broker-headless:8099"));
} |
public static Object newInstance(ClassLoader cl, Class<?>[] interfaces, InvocationHandler handler) {
return getProxy(cl, interfaces, handler).newInstance();
} | @Test
void testNewInstance() throws Throwable {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
InvokerInvocationHandler handler = Mockito.mock(InvokerInvocationHandler.class);
Object proxy = ByteBuddyProxy.newInstance(cl, new Class<?>[] {RemoteService.class}, handler);
... |
@Override
public boolean contains(Object o) {
QueryableEntry entry = (QueryableEntry) o;
if (index != null) {
return checkFromIndex(entry);
} else {
//todo: what is the point of this condition? Is it some kind of optimization?
if (resultSets.size() > 3) {
... | @Test
public void testContains_empty() {
assertThat(result.contains(entry(data()))).isFalse();
} |
public String getStringHeader(Message in, String header, String defaultValue) {
String headerValue = in.getHeader(header, String.class);
return ObjectHelper.isNotEmpty(headerValue) ? headerValue : defaultValue;
} | @Test
public void testGetStringHeader() {
when(in.getHeader(HEADER_METRIC_NAME, String.class)).thenReturn("A");
assertThat(okProducer.getStringHeader(in, HEADER_METRIC_NAME, "value"), is("A"));
inOrder.verify(in, times(1)).getHeader(HEADER_METRIC_NAME, String.class);
inOrder.verifyNo... |
@SuppressWarnings("unchecked")
protected Object newInstanceFromString(Class c, String s) {
return this.getReaderCache().newInstanceFromString(c, s);
} | @Test
void newInstanceFromString() {
final GenericDatumReader.ReaderCache cache = new GenericDatumReader.ReaderCache(this::findStringClass);
Object object = cache.newInstanceFromString(StringBuilder.class, "Hello");
assertEquals(StringBuilder.class, object.getClass());
StringBuilder builder = (String... |
public static AbsoluteUnixPath get(String unixPath) {
if (!unixPath.startsWith("/")) {
throw new IllegalArgumentException("Path does not start with forward slash (/): " + unixPath);
}
return new AbsoluteUnixPath(UnixPathParser.parse(unixPath));
} | @Test
public void testGet_notAbsolute() {
try {
AbsoluteUnixPath.get("not/absolute");
Assert.fail();
} catch (IllegalArgumentException ex) {
Assert.assertEquals(
"Path does not start with forward slash (/): not/absolute", ex.getMessage());
}
} |
public static Getter newMethodGetter(Object object, Getter parent, Method method, String modifier) throws Exception {
return newGetter(object, parent, modifier, method.getReturnType(), method::invoke,
(t, et) -> new MethodGetter(parent, method, modifier, t, et));
} | @Test
public void newMethodGetter_whenExtractingFromEmpty_Collection_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType()
throws Exception {
OuterObject object = new OuterObject("name", InnerObject.emptyInner("inner"));
Getter parentGetter = GetterFactory.newMethodGetter(object, nu... |
public static Getter newMethodGetter(Object object, Getter parent, Method method, String modifier) throws Exception {
return newGetter(object, parent, modifier, method.getReturnType(), method::invoke,
(t, et) -> new MethodGetter(parent, method, modifier, t, et));
} | @Test
public void newMethodGetter_whenExtractingFromNonEmpty_Collection_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType()
throws Exception {
OuterObject object = new OuterObject("name", new InnerObject("inner", 0, 1, 2, 3));
Getter parentGetter = GetterFactory.newMethodGetter(ob... |
@Override
public void process(Exchange exchange) throws Exception {
Object payload = exchange.getMessage().getBody();
if (payload == null) {
return;
}
AvroSchema answer = computeIfAbsent(exchange);
if (answer != null) {
exchange.setProperty(SchemaHel... | @Test
void shouldReadSchemaFromClasspathResource() throws Exception {
Exchange exchange = new DefaultExchange(camelContext);
exchange.setProperty(SchemaHelper.CONTENT_CLASS, Person.class.getName());
exchange.getMessage().setBody(person);
AvroSchemaResolver schemaResolver = new Avro... |
public KsqlEntityList execute(
final KsqlSecurityContext securityContext,
final List<ParsedStatement> statements,
final SessionProperties sessionProperties
) {
final KsqlEntityList entities = new KsqlEntityList();
for (final ParsedStatement parsed : statements) {
final PreparedStatemen... | @Test
public void shouldDistributeProperties() {
// Given
givenRequestHandler(ImmutableMap.of());
when(sessionProperties.getMutableScopedProperties()).thenReturn(ImmutableMap.of("x", "y"));
// When
final List<ParsedStatement> statements =
KSQL_PARSER.parse(SOME_STREAM_SQL);
final KsqlE... |
static public Entry buildMenuStructure(String xml) {
final Reader reader = new StringReader(xml);
return buildMenuStructure(reader);
} | @Test
public void givenXmlWithChildEntryWithTrue_createsBooleanObject() {
String xmlWithoutContent = "<FreeplaneUIEntries><Entry builderSpecificAttribute='true'/></FreeplaneUIEntries>";
Entry builtMenuStructure = XmlEntryStructureBuilder.buildMenuStructure(xmlWithoutContent);
Entry menuStructureWithChildEntry ... |
@Override
public void configure(Map<String, ?> props) {
final SimpleConfig config = new SimpleConfig(CONFIG_DEF, props);
casts = parseFieldTypes(config.getList(SPEC_CONFIG));
wholeValueCastType = casts.get(WHOLE_VALUE_CAST);
schemaUpdateCache = new SynchronizedCache<>(new LRUCache<>(... | @Test
public void testConfigInvalidMap() {
assertThrows(ConfigException.class, () -> xformKey.configure(Collections.singletonMap(Cast.SPEC_CONFIG, "foo:int8:extra")));
} |
public static String generateInstanceId(Instance instance) {
String instanceIdGeneratorType = instance.getInstanceIdGenerator();
if (StringUtils.isBlank(instanceIdGeneratorType)) {
instanceIdGeneratorType = Constants.DEFAULT_INSTANCE_ID_GENERATOR;
}
return INSTANCE.getInstanc... | @Test
void testGenerateSnowFlakeInstanceId() {
Instance instance = new Instance();
Map<String, String> metaData = new HashMap<>(1);
metaData.put(PreservedMetadataKeys.INSTANCE_ID_GENERATOR, SNOWFLAKE_INSTANCE_ID_GENERATOR);
instance.setMetadata(metaData);
instance.setServiceN... |
public static Status getSummaryStatus(Map<String, Status> statuses) {
Level level = Level.OK;
StringBuilder msg = new StringBuilder();
for (Map.Entry<String, Status> entry : statuses.entrySet()) {
String key = entry.getKey();
Status status = entry.getValue();
... | @Test
void testGetSummaryStatus1() throws Exception {
Status status1 = new Status(Status.Level.ERROR);
Status status2 = new Status(Status.Level.WARN);
Status status3 = new Status(Status.Level.OK);
Map<String, Status> statuses = new HashMap<String, Status>();
statuses.put("sta... |
public static YearsWindows years(int number) {
return new YearsWindows(number, 1, 1, DEFAULT_START_DATE, DateTimeZone.UTC);
} | @Test
public void testYears() throws Exception {
Map<IntervalWindow, Set<String>> expected = new HashMap<>();
final List<Long> timestamps =
Arrays.asList(
makeTimestamp(2000, 5, 5, 0, 0).getMillis(),
makeTimestamp(2010, 5, 4, 23, 59).getMillis(),
makeTimestamp(2010... |
@Override
public ByteBuf writeInt(int value) {
ensureWritable0(4);
_setInt(writerIndex, value);
writerIndex += 4;
return this;
} | @Test
public void testWriteIntAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().writeInt(1);
}
});
} |
public boolean startsWithTablePrefix(@NotNull String tableName) {
return this.tablePrefix.stream().anyMatch(tableName::startsWith);
} | @Test
void startsWithTablePrefixTest() {
StrategyConfig.Builder strategyConfigBuilder = GeneratorBuilder.strategyConfigBuilder();
Assertions.assertFalse(strategyConfigBuilder.build().startsWithTablePrefix("t_name"));
strategyConfigBuilder.addTablePrefix("a_", "t_");
Assertions.assert... |
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
String path = ((HttpServletRequest) req).getRequestURI().replaceFirst(((HttpServletRequest) req).getContextPath(), "");
MAX_AGE_BY_PATH.entrySet().stream()
.filter(m -> pat... | @Test
public void does_nothing_on_web_service() throws Exception {
HttpServletRequest request = newRequest("/api/ping");
underTest.doFilter(request, response, chain);
verifyNoInteractions(response);
} |
public static ShorthandProjectionSegment bind(final ShorthandProjectionSegment segment, final TableSegment boundTableSegment,
final Map<String, TableSegmentBinderContext> tableBinderContexts) {
ShorthandProjectionSegment result = copy(segment);
if (segme... | @Test
void assertBindWithoutOwnerForSimpleTableSegment() {
ColumnProjectionSegment invisibleColumn = new ColumnProjectionSegment(new ColumnSegment(0, 0, new IdentifierValue("status")));
invisibleColumn.setVisible(false);
Map<String, TableSegmentBinderContext> tableBinderContexts = Collection... |
@Override
public boolean canFastDuplicate(StreamStateHandle stateHandle) throws IOException {
if (!(stateHandle instanceof FileStateHandle)) {
return false;
}
final Path srcPath = ((FileStateHandle) stateHandle).getFilePath();
final Path dst = getNewDstPath(srcPath.getNam... | @Test
void testCannotDuplicate() throws IOException {
final FsCheckpointStateToolset stateToolset =
new FsCheckpointStateToolset(
new Path("test-path"), new TestDuplicatingFileSystem());
final boolean canFastDuplicate =
stateToolset.canFastDup... |
@Nullable
public TrackerClient getTrackerClient(Request request,
RequestContext requestContext,
Ring<URI> ring,
Map<URI, TrackerClient> trackerClients)
{
TrackerClient trackerClient;
URI ... | @Test
public void testClientsPartiallyExcluded()
{
LoadBalancerStrategy.ExcludedHostHints.addRequestContextExcludedHost(_requestContext, URI_1);
LoadBalancerStrategy.ExcludedHostHints.addRequestContextExcludedHost(_requestContext, URI_2);
TrackerClient trackerClient = _clientSelector.getTrackerClient(_... |
@Override
public URI getUri() {
return DefaultServiceInstance.getUri(this);
} | @Test
public void testGetUri() {
assertThat(polarisRegistration1.getUri().toString()).isEqualTo("http://" + HOST + ":" + PORT);
} |
FileContext getLocalFileContext(Configuration conf) {
try {
return FileContext.getLocalFSFileContext(conf);
} catch (IOException e) {
throw new YarnRuntimeException("Failed to access local fs");
}
} | @Test
public void testDirectoryCleanupOnNewlyCreatedStateStore()
throws IOException, URISyntaxException {
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077");
AsyncDispatcher dispatcher = new AsyncDispatcher();
dispatcher.init(new Configuration());
ContainerExecutor exec = mock(Co... |
static Duration getDefaultPeriod(Duration size) {
if (size.isLongerThan(Duration.standardHours(1))) {
return Duration.standardHours(1);
}
if (size.isLongerThan(Duration.standardMinutes(1))) {
return Duration.standardMinutes(1);
}
if (size.isLongerThan(Duration.standardSeconds(1))) {
... | @Test
public void testDefaultPeriods() throws Exception {
assertEquals(
Duration.standardHours(1), SlidingWindows.getDefaultPeriod(Duration.standardDays(1)));
assertEquals(
Duration.standardHours(1), SlidingWindows.getDefaultPeriod(Duration.standardHours(2)));
assertEquals(
Duratio... |
public static JsonElement parseReader(Reader reader) throws JsonIOException, JsonSyntaxException {
try {
JsonReader jsonReader = new JsonReader(reader);
JsonElement element = parseReader(jsonReader);
if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) {
throw new Json... | @Test
public void testParseDeeplyNestedArrays() throws IOException {
int times = 10000;
// [[[ ... ]]]
String json = "[".repeat(times) + "]".repeat(times);
JsonReader jsonReader = new JsonReader(new StringReader(json));
jsonReader.setNestingLimit(Integer.MAX_VALUE);
int actualTimes = 0;
J... |
@Override
public boolean isBuffer() {
return dataType.isBuffer();
} | @Test
void testEventBufferIsBuffer() {
assertThat(newBuffer(1024, 1024, false).isBuffer()).isFalse();
} |
public boolean filterMatchesEntry(String filter, FeedEntry entry) throws FeedEntryFilterException {
if (StringUtils.isBlank(filter)) {
return true;
}
Script script;
try {
script = ENGINE.createScript(filter);
} catch (JexlException e) {
throw new FeedEntryFilterException("Exception while parsing exp... | @Test
void simpleExpression() throws FeedEntryFilterException {
Assertions.assertTrue(service.filterMatchesEntry("author.toString() eq 'athou'", entry));
} |
@Subscribe
public void onChatMessage(ChatMessage e)
{
if (e.getType() != ChatMessageType.GAMEMESSAGE && e.getType() != ChatMessageType.SPAM)
{
return;
}
CompostState compostUsed = determineCompostUsed(e.getMessage());
if (compostUsed == null)
{
return;
}
this.expirePendingActions();
pending... | @Test
public void onChatMessage_ignoresInvalidTypes()
{
ChatMessage chatEvent = mock(ChatMessage.class);
when(chatEvent.getType()).thenReturn(ChatMessageType.PUBLICCHAT);
compostTracker.onChatMessage(chatEvent);
verifyNoInteractions(client);
verifyNoInteractions(farmingWorld);
} |
@VisibleForTesting
WxMpService getWxMpService(Integer userType) {
// 第一步,查询 DB 的配置项,获得对应的 WxMpService 对象
SocialClientDO client = socialClientMapper.selectBySocialTypeAndUserType(
SocialTypeEnum.WECHAT_MP.getType(), userType);
if (client != null && Objects.equals(client.getSta... | @Test
public void testGetWxMpService_clientEnable() {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
// mock 数据
SocialClientDO client = randomPojo(SocialClientDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())
.setUserType(userType)... |
@Override
public String toString() {
return StringUtil.simpleClassName(this) + '(' + contentToString() + ')';
} | @Test
public void testToString() {
ByteBufHolder holder = new DefaultByteBufHolder(Unpooled.buffer());
assertEquals(1, holder.refCnt());
assertNotNull(holder.toString());
assertTrue(holder.release());
assertNotNull(holder.toString());
} |
public static List<BindAddress> validateBindAddresses(ServiceConfiguration config, Collection<String> schemes) {
// migrate the existing configuration properties
List<BindAddress> addresses = migrateBindAddresses(config);
// parse the list of additional bind addresses
Arrays
... | @Test
public void testOneListenerMultipleAddresses() {
ServiceConfiguration config = newEmptyConfiguration();
config.setBindAddresses("internal:pulsar://0.0.0.0:6650,internal:pulsar+ssl://0.0.0.0:6651");
List<BindAddress> addresses = BindAddressValidator.validateBindAddresses(config, null);
... |
public void logOnAddPassiveMember(final int memberId, final long correlationId, final String memberEndpoints)
{
final int length = addPassiveMemberLength(memberEndpoints);
final int captureLength = captureLength(length);
final int encodedLength = encodedLength(captureLength);
final M... | @Test
void logOnAddPassiveMember()
{
final int offset = ALIGNMENT + 4;
logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset);
final long correlationId = 28397456L;
final String memberEndpoints = "localhost:20113,localhost:20223,localhost:20333,localhost:0,localhost:8013";
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.