focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
protected void refresh() {
Iterable<ServerConfig> dbConfigs = serverConfigRepository.findAll();
Map<String, Object> newConfigs = Maps.newHashMap();
//default cluster's configs
for (ServerConfig config : dbConfigs) {
if (Objects.equals(ConfigConsts.CLUSTER_NAME_DEFAULT, config.getClust... | @Test
public void testGetClusterConfig() {
propertySource.refresh();
assertEquals(propertySource.getProperty(clusterConfigKey), clusterConfigValue);
} |
@Override
public void login(final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
try {
final IRODSAccount account = client.getIRODSAccount();
final Credentials credentials = host.getCredentials();
account.setUserName(credentials.getUsernam... | @Test(expected = LoginFailureException.class)
public void testLoginFailure() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
this.getClass(... |
@Override
public InetSocketAddress resolve(ServerWebExchange exchange) {
List<String> xForwardedValues = extractXForwardedValues(exchange);
if (!xForwardedValues.isEmpty()) {
int index = Math.max(0, xForwardedValues.size() - maxTrustedIndex);
return new InetSocketAddress(xForwardedValues.get(index), 0);
}
... | @Test
public void trustOneFallsBackOnMultipleHeaders() {
ServerWebExchange exchange = buildExchange(
remoteAddressOnlyBuilder().header("X-Forwarded-For", "0.0.0.1").header("X-Forwarded-For", "0.0.0.2"));
InetSocketAddress address = trustOne.resolve(exchange);
assertThat(address.getHostName()).isEqualTo("0.... |
static List<MappingField> resolveFields(Schema schema) {
Map<String, MappingField> fields = new LinkedHashMap<>();
for (Schema.Field schemaField : schema.getFields()) {
String name = schemaField.name();
// SQL types are nullable by default and NOT NULL is currently unsupported.
... | @Test
public void test_resolveFields() {
// given
Schema schema = SchemaBuilder.record("name")
.fields()
.name("boolean").type().booleanType().noDefault()
.name("int").type().intType().noDefault()
.name("long").type().longType().noDefau... |
@Override
public EurekaHttpResponse<Void> statusUpdate(String asgName, ASGStatus newStatus) {
Response response = null;
try {
String urlPath = "asg/" + asgName + "/status";
response = jerseyClient.target(serviceUrl)
.path(urlPath)
.quer... | @Test
public void testAsgStatusUpdateReplication() throws Exception {
serverMockClient.when(
request()
.withMethod("PUT")
.withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
.withPath("/eureka/v2/asg/" + insta... |
public static <T extends Throwable> void checkMustEmpty(final Collection<?> values, final Supplier<T> exceptionSupplierIfUnexpected) throws T {
if (!values.isEmpty()) {
throw exceptionSupplierIfUnexpected.get();
}
} | @Test
void assertCheckMustEmptyWithMapToThrowsException() {
assertThrows(SQLException.class, () -> ShardingSpherePreconditions.checkMustEmpty(Collections.singletonMap("key", "value"), SQLException::new));
} |
@Override
protected void write(final MySQLPacketPayload payload) {
payload.writeIntLenenc(columnCount);
} | @Test
void assertWrite() {
when(payload.readInt1()).thenReturn(3);
MySQLFieldCountPacket actual = new MySQLFieldCountPacket(payload);
assertThat(actual.getColumnCount(), is(3));
actual.write(payload);
verify(payload).writeIntLenenc(3L);
} |
public long getValue(final K key)
{
final int mask = values.length - 1;
int index = Hashing.hash(key, mask);
long value;
while (missingValue != (value = values[index]))
{
if (key.equals(keys[index]))
{
break;
}
... | @Test
public void getShouldReturnMissingValueWhenEmpty() {
assertEquals(MISSING_VALUE, map.getValue("1"));
} |
public boolean devMode() {
return this.environment.getBoolean(BladeConst.ENV_KEY_DEV_MODE, true);
} | @Test
public void testDevMode() {
Blade blade = Blade.create();
blade.devMode(false);
assertEquals(Boolean.FALSE, blade.devMode());
} |
@VisibleForTesting
static SortedMap<OffsetRange, Integer> computeOverlappingRanges(Iterable<OffsetRange> ranges) {
ImmutableSortedMap.Builder<OffsetRange, Integer> rval =
ImmutableSortedMap.orderedBy(OffsetRangeComparator.INSTANCE);
List<OffsetRange> sortedRanges = Lists.newArrayList(ranges);
if (... | @Test
public void testOverlappingFromsAndTos() {
Iterable<OffsetRange> ranges = Arrays.asList(range(0, 4), range(0, 4), range(0, 4));
Map<OffsetRange, Integer> nonOverlappingRangesToNumElementsPerPosition =
computeOverlappingRanges(ranges);
assertEquals(
ImmutableMap.builder().put(range(0... |
@Override
public ParamCheckResponse checkParamInfoList(List<ParamInfo> paramInfos) {
ParamCheckResponse paramCheckResponse = new ParamCheckResponse();
if (paramInfos == null) {
paramCheckResponse.setSuccess(true);
return paramCheckResponse;
}
for (ParamInfo pa... | @Test
void testCheckParamInfoForPort() {
ParamInfo paramInfo = new ParamInfo();
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
paramInfos.add(paramInfo);
// Negative port
paramInfo.setPort("-1");
ParamCheckResponse actual = paramChecker.checkParamInfoList(paramI... |
@Udf
public String encodeParam(
@UdfParameter(description = "the value to encode") final String input) {
if (input == null) {
return null;
}
final Escaper escaper = UrlEscapers.urlFormParameterEscaper();
return escaper.escape(input);
} | @Test
public void shouldReturnEmptyStringForEmptyInput() {
assertThat(encodeUdf.encodeParam(""), equalTo(""));
} |
@Override
public boolean accept(RequestedField field) {
return FIELD_ENTITY_MAPPER.containsKey(field.name()) && acceptsDecorator(field.decorator());
} | @Test
void testPermitted() {
final FieldDecorator decorator = new TitleDecorator((request, permissions) -> EntitiesTitleResponse.EMPTY_RESPONSE);
Assertions.assertThat(decorator.accept(RequestedField.parse("streams"))).isTrue();
Assertions.assertThat(decorator.accept(RequestedField.parse("st... |
@VisibleForTesting
void handleResponse(DiscoveryResponseData response)
{
ResourceType resourceType = response.getResourceType();
switch (resourceType)
{
case NODE:
handleD2NodeResponse(response);
break;
case D2_URI_MAP:
handleD2URIMapResponse(response);
break;... | @Test
public void testHandleD2URIMapResponseWithRemoval()
{
XdsClientImplFixture fixture = new XdsClientImplFixture();
fixture._clusterSubscriber.setData(D2_URI_MAP_UPDATE_WITH_DATA1);
fixture._xdsClientImpl.handleResponse(DISCOVERY_RESPONSE_URI_MAP_DATA_WITH_REMOVAL);
fixture.verifyAckSent(1);
... |
@Override
public void close() {
if (!sharedYarnClient) {
yarnClient.stop();
}
} | @Test
void testYarnClientShutDown() {
YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor();
yarnClusterDescriptor.close();
assertThat(yarnClient.isInState(Service.STATE.STARTED)).isTrue();
final YarnClient closableYarnClient = YarnClient.createYarnClient();
... |
public Set<String> getFinalParameters() {
Set<String> setFinalParams = Collections.newSetFromMap(
new ConcurrentHashMap<String, Boolean>());
setFinalParams.addAll(finalParameters);
return setFinalParams;
} | @Test
public void testGetFinalParameters() throws Exception {
out=new BufferedWriter(new FileWriter(CONFIG));
startConfig();
declareProperty("my.var", "x", "x", true);
endConfig();
Path fileResource = new Path(CONFIG);
Configuration conf = new Configuration();
Set<String> finalParameters =... |
public V get(K key) {
lock.readLock().lock();
try {
return rawMap.get(MutableObj.of(key));
} finally {
lock.readLock().unlock();
}
} | @Test
public void getConcurrencyTest(){
final SimpleCache<String, String> cache = new SimpleCache<>();
final ConcurrencyTester tester = new ConcurrencyTester(9000);
tester.test(()-> cache.get("aaa", ()-> {
ThreadUtil.sleep(200);
return "aaaValue";
}));
assertTrue(tester.getInterval() > 0);
assertEqu... |
public static FunctionSegment bind(final FunctionSegment segment, final SegmentType parentSegmentType, final SQLStatementBinderContext binderContext,
final Map<String, TableSegmentBinderContext> tableBinderContexts, final Map<String, TableSegmentBinderContext> outerTableBinderCont... | @Test
void assertBindFunctionExpressionSegment() {
FunctionSegment functionSegment = new FunctionSegment(0, 0, "CONCAT", "('%','abc','%')");
SQLStatementBinderContext binderContext = new SQLStatementBinderContext(new ShardingSphereMetaData(), DefaultDatabase.LOGIC_NAME, new MockedDatabaseType(), Col... |
public int getAppTimeoutFailedRetrieved() {
return numGetAppTimeoutFailedRetrieved.value();
} | @Test
public void testGetAppTimeoutRetrievedFailed() {
long totalBadBefore = metrics.getAppTimeoutFailedRetrieved();
badSubCluster.getAppTimeoutFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getAppTimeoutFailedRetrieved());
} |
public Range<PartitionKey> handleNewSinglePartitionDesc(Map<ColumnId, Column> schema, SingleRangePartitionDesc desc,
long partitionId, boolean isTemp) throws DdlException {
Range<PartitionKey> range;
try {
range = checkAndCreateRang... | @Test
public void testFixedRange2() throws DdlException, AnalysisException {
//add columns
int columns = 2;
Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", "");
Column k2 = new Column("k2", new ScalarType(PrimitiveType.BIGINT), true, null, "", "");
... |
@VisibleForTesting
public File getStorageLocation(JobID jobId, BlobKey key) throws IOException {
checkNotNull(jobId);
return BlobUtils.getStorageLocation(storageDir.deref(), jobId, key);
} | @Test
void permanentBlobCacheTimesOutRecoveredBlobs(@TempDir Path storageDirectory) throws Exception {
final JobID jobId = new JobID();
final PermanentBlobKey permanentBlobKey =
TestingBlobUtils.writePermanentBlob(
storageDirectory, jobId, new byte[] {1, 2, 3,... |
public static String substVars(String val, PropertyContainer pc1) throws ScanException {
return substVars(val, pc1, null);
} | @Test
public void jackrabbit_standalone() throws ScanException {
String r = OptionHelper.substVars("${jackrabbit.log:-${repo:-jackrabbit}/log/jackrabbit.log}", context);
assertEquals("jackrabbit/log/jackrabbit.log", r);
} |
@Override
public final boolean readBoolean() throws EOFException {
final int ch = read();
if (ch < 0) {
throw new EOFException();
}
return (ch != 0);
} | @Test
public void testReadBooleanPosition() throws Exception {
boolean read1 = in.readBoolean(0);
boolean read2 = in.readBoolean(1);
assertFalse(read1);
assertTrue(read2);
} |
public static Builder withSchema(Schema schema) {
return new Builder(schema);
} | @Test(expected = IllegalArgumentException.class)
public void testLogicalTypeWithInvalidInputValueByFieldIndex() {
Schema schema = Schema.builder().addLogicalTypeField("char", FixedBytes.of(10)).build();
byte[] byteArrayWithLengthFive = {1, 2, 3, 4, 5};
Row.withSchema(schema).addValues(byteArrayWithLengthF... |
@Override
public boolean supportsSelectForUpdate() {
return false;
} | @Test
void assertSupportsSelectForUpdate() {
assertFalse(metaData.supportsSelectForUpdate());
} |
public KsqlTopic getPrimarySourceTopic() {
return primarySourceTopic;
} | @Test
public void shouldExtractPrimaryTopicFromJoinSelect() {
// Given:
final Statement statement = givenStatement(String.format(
"SELECT * FROM %s A JOIN %s B ON A.F1 = B.F1;", STREAM_TOPIC_1, STREAM_TOPIC_2
));
// When:
extractor.process(statement, null);
// Then:
assertThat(ex... |
@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_when_search_disabled() {
settings.setProperty(CLUSTER_ENABLED.getKey(), true);
settings.setProperty(CLUSTER_NODE_TYPE.getKey(), "application");
settings.setProperty(CLUSTER_SEARCH_HOSTS.getKey(), format("%s:100000,%s:8081", lo... |
public Map<String, Long> getEtlFilePaths(String outputPath, BrokerDesc brokerDesc) throws Exception {
Map<String, Long> filePathToSize = Maps.newHashMap();
List<TBrokerFileStatus> fileStatuses = Lists.newArrayList();
String etlFilePaths = outputPath + "/*";
try {
if (brokerD... | @Test
public void testGetEtlFilePaths(@Mocked TFileBrokerService.Client client, @Mocked GlobalStateMgr globalStateMgr,
@Injectable BrokerMgr brokerMgr) throws Exception {
// list response
TBrokerListResponse response = new TBrokerListResponse();
TBrokerOpe... |
public static AlterReplicaTask alterLakeTablet(long backendId, long dbId, long tableId, long partitionId, long rollupIndexId,
long rollupTabletId, long baseTabletId, long version, long jobId, long txnId) {
return new AlterReplicaTask(backendId, dbId, tableId, p... | @Test
public void testAlterLakeTablet() {
AlterReplicaTask task = AlterReplicaTask.alterLakeTablet(1, 2, 3, 4, 5, 6,
7, 8, 9, 10);
Assert.assertEquals(1, task.getBackendId());
Assert.assertEquals(2, task.getDbId());
Assert.assertEquals(3, task.getTableId());
... |
@Override
public boolean revokeToken(String clientId, String accessToken) {
// 先查询,保证 clientId 时匹配的
OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.getAccessToken(accessToken);
if (accessTokenDO == null || ObjectUtil.notEqual(clientId, accessTokenDO.getClientId())) {
retur... | @Test
public void testRevokeToken_clientIdError() {
// 准备参数
String clientId = randomString();
String accessToken = randomString();
// mock 方法
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class);
when(oauth2TokenService.getAccessToken(eq(accessTok... |
public static <T> Deduplicate.Values<T> values() {
return new Deduplicate.Values<>(DEFAULT_TIME_DOMAIN, DEFAULT_DURATION);
} | @Test
@Category({NeedsRunner.class, UsesTestStream.class})
public void testEventTime() {
Instant base = new Instant(0);
TestStream<String> values =
TestStream.create(StringUtf8Coder.of())
.advanceWatermarkTo(base)
.addElements(
TimestampedValue.of("k1", base),... |
public static String bytes2HexString(final byte[] bytes) {
if (bytes == null) return null;
int len = bytes.length;
if (len <= 0) return null;
char[] ret = new char[len << 1];
for (int i = 0, j = 0; i < len; i++) {
ret[j++] = HEX_DIGITS[bytes[i] >>> 4 & 0x0f];
... | @Test
public void bytes2HexString() throws Exception {
Assert.assertEquals(
hexString,
ConvertKit.bytes2HexString(mBytes)
);
} |
public static Object getInjectValue(String string, boolean decrypt) {
Matcher m = pattern.matcher(string);
StringBuffer sb = new StringBuffer();
// Parse the content inside pattern "${}" when this pattern is found
while (m.find()) {
// Get parsing result
Object va... | @Test
@Ignore
public void testGetInjectValueIssue744() {
Object oldConfigValue = null;
try {
oldConfigValue = ConfigInjection.getInjectValue(value, true);
} catch (Exception ce) {
// expected exception since no valuemap defined yet.
assertTrue(ce inst... |
public static void disablePushConsumption(DefaultMqPushConsumerWrapper wrapper, Set<String> topics) {
Set<String> subscribedTopic = wrapper.getSubscribedTopics();
if (subscribedTopic.stream().anyMatch(topics::contains)) {
suspendPushConsumer(wrapper);
return;
}
re... | @Test
public void testDisablePushConsumptionNoTopic() {
pushConsumerWrapper.setProhibition(true);
RocketMqPushConsumerController.disablePushConsumption(pushConsumerWrapper, prohibitionTopics);
Assert.assertFalse(pushConsumerWrapper.isProhibition());
} |
@Nullable public Span currentSpan() {
TraceContext context = currentTraceContext.get();
if (context == null) return null;
// Returns a lazy span to reduce overhead when tracer.currentSpan() is invoked just to see if
// one exists, or when the result is never used.
return new LazySpan(this, context);... | @Test void currentSpan_decoratesExternalContext() {
try (Scope scope = currentTraceContext.newScope(context)) {
assertThat(tracer.currentSpan().context())
.isNotSameAs(context)
.extracting(TraceContext::localRootId)
.isEqualTo(context.spanId());
}
} |
public void logResponse(Config config, HttpRequest request, Response response) {
long startTime = request.getStartTime();
long elapsedTime = request.getEndTime() - startTime;
response.setResponseTime(elapsedTime);
StringBuilder sb = new StringBuilder();
String uri = request.getUr... | @Test
void testResponseLoggingJson() {
setup("json", "{a: 1}", "application/json");
httpRequestBuilder.path("/json");
Response response = handle();
match(response.getBodyAsString(), "{a: 1}");
match(response.getContentType(), "application/json");
httpLogger.logRespon... |
@Override
public String toString() {
StringBuilder builder = new StringBuilder("AfterEach.inOrder(");
Joiner.on(", ").appendTo(builder, subTriggers);
builder.append(")");
return builder.toString();
} | @Test
public void testToString() {
Trigger trigger =
AfterEach.inOrder(
StubTrigger.named("t1"), StubTrigger.named("t2"), StubTrigger.named("t3"));
assertEquals("AfterEach.inOrder(t1, t2, t3)", trigger.toString());
} |
public String getValue() {
return value;
} | @Test
public void shouldHandleIntegerValueAsAString() throws Exception {
final ConfigurationValue configurationValue = new ConfigurationValue(1);
assertThat(configurationValue.getValue(), is("1"));
} |
@VisibleForTesting
void generateScript(File localScript) throws IOException {
if (verbose) {
LOG.info("Generating script at: " + localScript.getAbsolutePath());
}
String halrJarPath = HadoopArchiveLogsRunner.class.getProtectionDomain()
.getCodeSource().getLocation().getPath();
String har... | @Test(timeout = 10000)
public void testGenerateScript() throws Exception {
_testGenerateScript(false);
_testGenerateScript(true);
} |
@Override
public boolean isUsedInLabelTemplate(PipelineConfig pipelineConfig) {
CaseInsensitiveString materialName = getName();
return materialName != null && pipelineConfig.getLabelTemplate().toLowerCase().contains(String.format("${%s}", materialName.toLower()));
} | @Test
void shouldReturnFalseIfMaterialNameIsNotDefined() {
AbstractMaterialConfig material = new TestMaterialConfig("test");
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("blah"), "${COUNT}-${test}-test", "", false, null, new BaseCollection<>());
assertThat(mat... |
@GetMapping("edit")
public String getProductEditPage() {
return "catalogue/products/edit";
} | @Test
void getProductEditPage_ReturnsProductEditPage() {
// given
// when
var result = this.controller.getProductEditPage();
// then
assertEquals("catalogue/products/edit", result);
verifyNoInteractions(this.productsRestClient);
} |
@Override
public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId)
throws PiInterpreterException {
if (FORWARDING_CTRL_TBLS.contains(piTableId)) {
return treatmentInterpreter.mapForwardingTreatment(treatment, piTableId);
} else if (PRE_NEXT_CTRL_TBLS.cont... | @Test
public void testRoutingV4TreatmentEmpty() throws Exception {
TrafficTreatment treatment = DefaultTrafficTreatment.emptyTreatment();
PiAction mappedAction = interpreter.mapTreatment(
treatment, FabricConstants.FABRIC_INGRESS_FORWARDING_ROUTING_V4);
PiAction expectedActio... |
public static SqlDecimal widen(final SqlType t0, final SqlType t1) {
final SqlDecimal lDecimal = DecimalUtil.toSqlDecimal(t0);
final SqlDecimal rDecimal = DecimalUtil.toSqlDecimal(t1);
final int wholePrecision = Math.max(
lDecimal.getPrecision() - lDecimal.getScale(),
rDecimal.getPrecision(... | @Test
public void shouldWidenDecimalAndDecimal() {
assertThat(
"first contained",
DecimalUtil.widen(
SqlTypes.decimal(1, 0),
SqlTypes.decimal(14, 3)
),
is(SqlTypes.decimal(14, 3))
);
assertThat(
"second contained",
DecimalUtil.widen(... |
@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_expiredFedmasterConfig() {
var client = new FederationMasterClientImpl(FEDERATION_MASTER, federationApiClient, clock);
var issuer = URI.create("https://idp-tk.example.com");
var fedmasterKeypair = ECKeyGenerator.example();
var fedmasterEntityConfigurationJws = expiredFedm... |
public long getEarliestMsgStoretime(final String addr, final MessageQueue mq, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
GetEarliestMsgStoretimeRequestHeader requestHeader = new GetEarliestMsgStoretimeRequestHeader();
requestHeader.setTopic(mq.g... | @Test
public void testGetEarliestMsgStoretime() throws Exception {
doAnswer((Answer<RemotingCommand>) mock -> {
RemotingCommand request = mock.getArgument(1);
final RemotingCommand response = RemotingCommand.createResponseCommand(GetEarliestMsgStoretimeResponseHeader.class);
... |
public static SqlType fromValue(final BigDecimal value) {
// SqlDecimal does not support negative scale:
final BigDecimal decimal = value.scale() < 0
? value.setScale(0, BigDecimal.ROUND_UNNECESSARY)
: value;
/* We can't use BigDecimal.precision() directly for all cases, since it defines
... | @Test
public void shouldConvertFromBigDecimalWithNegativeScale() {
assertThat(
DecimalUtil.fromValue(new BigDecimal("1e3")),
is(SqlTypes.decimal(4, 0))
);
} |
public Set<String> getFieldNames() {
return Collections.unmodifiableSet(fields.keySet());
} | @Test
public void testGetFieldNames() throws Exception {
assertTrue("Missing fields in set!", symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message")).isEmpty());
message.addField("testfield", "testvalue");
assertTrue("Missing fields in set!", ... |
@Override
public InMemoryReaderIterator iterator() throws IOException {
return new InMemoryReaderIterator();
} | @Test
public void testDynamicSplit() throws Exception {
List<Integer> elements = Arrays.asList(33, 44, 55, 66, 77, 88);
// Should initially read elements at indices: 44@1, 55@2, 66@3, 77@4
Coder<Integer> coder = BigEndianIntegerCoder.of();
InMemoryReader<Integer> inMemoryReader =
new InMemory... |
public void setAllDisabled( boolean value ) {
for ( PermissionsCheckboxes permissionsCheckboxes : ALL_PERMISSIONS ) {
permissionsCheckboxes.permissionCheckbox.setDisabled( value );
}
} | @Test
public void testSetAllEnabledEnablesAll() {
boolean disabled = false;
permissionsCheckboxHandler.setAllDisabled( disabled );
verify( readCheckbox, times( 1 ) ).setDisabled( disabled );
verify( writeCheckbox, times( 1 ) ).setDisabled( disabled );
verify( deleteCheckbox, times( 1 ) ).setDisabl... |
public boolean compareIndexSetting(String tableName, Map<String, Object> settings) {
if ((CollectionUtils.isEmpty(settings) || CollectionUtils.isEmpty((Map) settings.get("index")))
&& Objects.isNull(indexSettingStructures.get(tableName))) {
return true;
}
return indexSet... | @Test
public void compareIndexSetting() {
IndexStructures structures = new IndexStructures();
HashMap<String, Object> settings = new HashMap<>();
HashMap<String, Object> indexSettings = new HashMap<>();
settings.put("index", indexSettings);
indexSettings.put("number_of_replic... |
static void populateOutputFields(final PMML4Result toUpdate,
final ProcessingDTO processingDTO) {
logger.debug("populateOutputFields {} {}", toUpdate, processingDTO);
for (KiePMMLOutputField outputField : processingDTO.getOutputFields()) {
Object variable... | @Test
void populatePredictedOutputField2() {
KiePMMLNameValue kiePMMLNameValue = new KiePMMLNameValue("targetField", 54346.32454);
KiePMMLOutputField outputField = KiePMMLOutputField.builder(OUTPUT_NAME, Collections.emptyList())
.withResultFeature(RESULT_FEATURE.PREDICTED_VALUE)
... |
@Override
public CompletableFuture<Void> applyExperimentTreatment(final Account account, final Device device) {
return idleDeviceNotificationScheduler.scheduleNotification(account, device, PREFERRED_NOTIFICATION_TIME);
} | @Test
void applyExperimentTreatment() {
final Account account = mock(Account.class);
final Device device = mock(Device.class);
experiment.applyExperimentTreatment(account, device);
verify(idleDeviceNotificationScheduler)
.scheduleNotification(account, device, NotifyIdleDevicesWithMessagesExp... |
public String generateNacosServiceName(String rawServiceName) {
if (rawServiceName.contains(Constants.DEFAULT_GROUP)) {
return rawServiceName;
}
return Constants.DEFAULT_GROUP + AddressServerConstants.GROUP_SERVICE_NAME_SEP + rawServiceName;
} | @Test
void testGenerateNacosServiceName() {
AddressServerGeneratorManager manager = new AddressServerGeneratorManager();
final String containDefault = manager.generateNacosServiceName("DEFAULT_GROUP@@test");
assertEquals("DEFAULT_GROUP@@test", containDefault);
final String ... |
@SuppressWarnings("unchecked")
public static List<String> createRobotVariablesFromCamelExchange(Exchange exchange, boolean allowContextMapAll)
throws TypeConversionException, NoTypeConversionAvailableException {
Map<String, Object> variablesMap = ExchangeHelper.createVariableMap(exchange, allowC... | @SuppressWarnings("unchecked")
@Test
public void testCreateRobotVariablesFromCamelExchange() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMinimumMessageCount(1);
Map<String, Object> headers = new HashMap<>();
headers.put("stringKey", "str1")... |
public static List<Event> computeEventDiff(final Params params) {
final List<Event> events = new ArrayList<>();
emitPerNodeDiffEvents(createBaselineParams(params), events);
emitWholeClusterDiffEvent(createBaselineParams(params), events);
emitDerivedBucketSpaceStatesDiffEvents(params, ev... | @Test
void may_have_merges_pending_down_edge_event_emitted_if_derived_bucket_space_state_differs_from_baseline() {
EventFixture f = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.derivedClusterStateBefore("default", "distributor:3 storage:3 .1.... |
public KafkaConfiguration getConfiguration() {
return configuration;
} | @Test
public void testPropertiesSet() {
String uri = "kafka:mytopic?brokers=broker1:12345,broker2:12566&partitioner=com.class.Party";
KafkaEndpoint endpoint = context.getEndpoint(uri, KafkaEndpoint.class);
assertEquals("broker1:12345,broker2:12566", endpoint.getConfiguration().getBrokers())... |
public static String convertFreshnessToCron(IntervalFreshness intervalFreshness) {
switch (intervalFreshness.getTimeUnit()) {
case SECOND:
return validateAndConvertCron(
intervalFreshness,
SECOND_CRON_UPPER_BOUND,
... | @Test
void testConvertHourFreshnessToCronExpression() {
// verify illegal freshness
assertThatThrownBy(() -> convertFreshnessToCron(IntervalFreshness.ofHour("24")))
.isInstanceOf(ValidationException.class)
.hasMessageContaining(
"In full refres... |
public PublisherAgreement getPublisherAgreement(UserData user) {
var eclipseToken = checkEclipseToken(user);
var personId = user.getEclipsePersonId();
if (StringUtils.isEmpty(personId)) {
return null;
}
checkApiUrl();
var urlTemplate = eclipseApiUrl + "openvsx... | @Test
public void testGetPublisherAgreementNotFound() throws Exception {
var user = mockUser();
user.setEclipsePersonId("test");
var urlTemplate = "https://test.openvsx.eclipse.org/openvsx/publisher_agreement/{personId}";
Mockito.when(restTemplate.exchange(eq(urlTemplate), eq(HttpMe... |
public List<ColumnMatchResult<?>> getMismatchedColumns(List<Column> columns, ChecksumResult controlChecksum, ChecksumResult testChecksum)
{
return columns.stream()
.flatMap(column -> columnValidators.get(column.getCategory()).get().validate(column, controlChecksum, testChecksum).stream())
... | @Test
public void testFloatingPointArray()
{
List<Column> columns = ImmutableList.of(DOUBLE_ARRAY_COLUMN, REAL_ARRAY_COLUMN);
Map<String, Object> stableCounts = new HashMap<>(10);
stableCounts.put("double_array$nan_count", 2L);
stableCounts.put("double_array$pos_inf_count", 3L);... |
public static AlluxioSinkConfig load(String yamlFile) throws IOException {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
return mapper.readValue(new File(yamlFile), AlluxioSinkConfig.class);
} | @Test
public final void loadFromMapTest() throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("alluxioMasterHost", "localhost");
map.put("alluxioMasterPort", "19998");
map.put("alluxioDir", "pulsar");
map.put("filePrefix", "TopicA");
map.put("fileE... |
static String strip(final String line) {
return new Parser(line).parse();
} | @Test
public void shouldReturnLineWithCommentInSingleQuotesAsIs() {
// Given:
final String line = "no comment here '-- even this is not a comment'...";
// Then:
assertThat(CommentStripper.strip(line), is(sameInstance(line)));
} |
public static Object[] realize(Object[] objs, Class<?>[] types) {
if (objs.length != types.length) {
throw new IllegalArgumentException("args.length != types.length");
}
Object[] dests = new Object[objs.length];
for (int i = 0; i < objs.length; i++) {
dests[i] = ... | @Test
void testRealizeCollectionWithNullElement() {
LinkedList<String> listStr = new LinkedList<>();
listStr.add("arrayValue");
listStr.add(null);
HashSet<String> setStr = new HashSet<>();
setStr.add("setValue");
setStr.add(null);
Object listResult = PojoUtil... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldSupportExplicitEmitFinalForCsas() {
// Given:
final SingleStatementContext stmt =
givenQuery("CREATE STREAM X AS SELECT * FROM TEST1 EMIT FINAL;");
// When:
final Query result = ((QueryContainer) builder.buildStatement(stmt)).getQuery();
// Then:
assertThat("S... |
static Properties resolveProducerProperties(Map<String, String> options, Object keySchema, Object valueSchema) {
Properties properties = from(options);
withSerdeProducerProperties(true, options, keySchema, properties);
withSerdeProducerProperties(false, options, valueSchema, properties);
... | @Test
public void test_producerProperties_absentFormat() {
assertThat(resolveProducerProperties(emptyMap()))
.containsExactlyEntriesOf(Map.of(KEY_SERIALIZER, ByteArraySerializer.class.getCanonicalName()));
} |
public void validateIdentity(WorkflowInstance toRestart) {
// instance id will not always match for foreach
if (initiator.getType() == Initiator.Type.FOREACH) {
Checks.checkTrue(
getRestartWorkflowId().equals(toRestart.getWorkflowId()),
"Cannot restart a FOREACH iteration [%s] as it do... | @Test
public void testValidateIdentityForManualRun() {
RestartConfig config = RestartConfig.builder().addRestartNode("foo", 1, "bar").build();
RunRequest runRequest =
RunRequest.builder()
.currentPolicy(RunPolicy.RESTART_FROM_INCOMPLETE)
.restartConfig(config)
.requ... |
public void command(String primaryCommand, SecureConfig config, String... allArguments) {
terminal.writeLine("");
final Optional<CommandLine> commandParseResult;
try {
commandParseResult = Command.parse(primaryCommand, allArguments);
} catch (InvalidCommandException e) {
... | @Test
public void testHelpRemove() {
cli.command("remove", null, "--help");
assertThat(terminal.out).containsIgnoringCase("Remove secrets from the keystore");
} |
@Override
public void initialize(ServiceConfiguration config) throws IOException, IllegalArgumentException {
String prefix = (String) config.getProperty(CONF_TOKEN_SETTING_PREFIX);
if (null == prefix) {
prefix = "";
}
this.confTokenSecretKeySettingName = prefix + CONF_TOK... | @Test(expectedExceptions = IOException.class)
public void testInitializeWhenSecretKeyIsValidPathOrBase64() throws IOException {
Properties properties = new Properties();
properties.setProperty(AuthenticationProviderToken.CONF_TOKEN_SECRET_KEY,
"secret_key_file_not_exist");
S... |
public static String[] getTrimmedStrings(String str){
if (null == str || str.trim().isEmpty()) {
return emptyStringArray;
}
return str.trim().split("\\s*[,\n]\\s*");
} | @Test (timeout = 30000)
public void testGetTrimmedStrings() throws Exception {
String compactDirList = "/spindle1/hdfs,/spindle2/hdfs,/spindle3/hdfs";
String spacedDirList = "/spindle1/hdfs, /spindle2/hdfs, /spindle3/hdfs";
String pathologicalDirList1 = " /spindle1/hdfs , /spindle2/hdfs ,/spindle3/hdfs ... |
static CommandLineOptions parse(Iterable<String> options) {
CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder();
List<String> expandedOptions = new ArrayList<>();
expandParamsFiles(options, expandedOptions);
Iterator<String> it = expandedOptions.iterator();
while (it.hasNext()) ... | @Test
public void skipJavadocFormatting() {
assertThat(
CommandLineOptionsParser.parse(Arrays.asList("--skip-javadoc-formatting"))
.formatJavadoc())
.isFalse();
} |
public static BigDecimal toNanos(Timestamp timestamp) {
final BigDecimal secondsAsNanos =
BigDecimal.valueOf(timestamp.getSeconds()).subtract(MIN_SECONDS).scaleByPowerOfTen(9);
final BigDecimal nanos = BigDecimal.valueOf(timestamp.getNanos());
return secondsAsNanos.add(nanos);
} | @Test
public void testToNanosConvertTimestampMaxToNanos() {
assertEquals(
new BigDecimal("315537897599999999999"), TimestampUtils.toNanos(Timestamp.MAX_VALUE));
} |
public void reset() {
lock.lock();
try {
clearTransactions();
lastBlockSeenHash = null;
lastBlockSeenHeight = -1; // Magic value for 'never'.
lastBlockSeenTime = null;
saveLater();
maybeQueueOnWalletChanged();
} finally {
... | @Test
public void reset() {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN, myAddress);
assertNotEquals(Coin.ZERO, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
assertNotEquals(0, wallet.getTransactions(false).size());
assertNotEquals(0, wallet.getUnspents().s... |
public static <T> T readValue(String jsonStr, Class<T> clazz) {
try {
return getInstance().readValue(jsonStr, clazz);
} catch (JsonParseException e) {
logger.error(e.getMessage(), e);
} catch (JsonMappingException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getM... | @Test
public void shouldReadValueAsObject() {
//given
String jsonString = "{\"aaa\":\"111\",\"bbb\":\"222\"}";
//when
Map result = JacksonUtil.readValue(jsonString, Map.class);
//then
assertEquals(result.get("aaa"), "111");
assertEquals(result.get("bbb"),"22... |
public static short translateBucketAcl(GSAccessControlList acl, String userId) {
short mode = (short) 0;
for (GrantAndPermission gp : acl.getGrantAndPermissions()) {
Permission perm = gp.getPermission();
GranteeInterface grantee = gp.getGrantee();
if (perm.equals(Permission.PERMISSION_READ)) {... | @Test
public void translateAuthenticatedUserReadPermission() {
GroupGrantee authenticatedUsersGrantee = GroupGrantee.AUTHENTICATED_USERS;
mAcl.grantPermission(authenticatedUsersGrantee, Permission.PERMISSION_READ);
assertEquals((short) 0500, GCSUtils.translateBucketAcl(mAcl, ID));
assertEquals((short)... |
public Map<TopicPartition, Long> retryEndOffsets(Set<TopicPartition> partitions, Duration timeoutDuration, long retryBackoffMs) {
try {
return RetryUtil.retryUntilTimeout(
() -> endOffsets(partitions),
() -> "list offsets for topic partitions",
... | @Test
public void retryEndOffsetsShouldWrapNonRetriableExceptionsWithConnectException() {
String topicName = "myTopic";
TopicPartition tp1 = new TopicPartition(topicName, 0);
Set<TopicPartition> tps = Collections.singleton(tp1);
Long offset = 1000L;
Cluster cluster = createCl... |
public static GrpcDataWriter create(FileSystemContext context, WorkerNetAddress address,
long id, long length, RequestType type, OutStreamOptions options)
throws IOException {
long chunkSize = context.getClusterConf()
.getBytes(PropertyKey.USER_STREAMING_WRITER_CHUNK_SIZE_BYTES);
CloseableRe... | @Test(timeout = 1000 * 60)
public void writeFileManyChunks() throws Exception {
long checksumActual;
Future<Long> checksumExpected;
long length = CHUNK_SIZE * 30000 + CHUNK_SIZE / 3;
try (DataWriter writer = create(Long.MAX_VALUE)) {
checksumExpected = writeFile(writer, length, 10, length / 3);
... |
public long get(T item) {
MutableLong count = map.get(item);
return count == null ? 0 : count.value;
} | @Test
public void testGet_returnsZeroWhenEmpty() {
long count = counter.get(new Object());
assertEquals(0, count);
} |
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> backwardFindSessions(final Bytes key,
final long earliestSessionEndTime,
final long latestSessionStartTime) {... | @Test
public void shouldDelegateToUnderlyingStoreWhenBackwardFindingSessions() {
store.backwardFindSessions(bytesKey, 0, 1);
verify(inner).backwardFindSessions(bytesKey, 0, 1);
} |
@Override
public ProcResult fetchResult() throws AnalysisException {
Preconditions.checkNotNull(globalStateMgr);
BaseProcResult result = new BaseProcResult();
result.setNames(TITLE_NAMES);
List<String> dbNames = globalStateMgr.getLocalMetastore().listDbNames();
if (dbNames =... | @Test
public void testFetchResultNormal() throws AnalysisException {
new Expectations(globalStateMgr) {
{
globalStateMgr.getLocalMetastore().listDbNames();
minTimes = 0;
result = Lists.newArrayList("db1", "db2");
globalStateMgr.get... |
public static List<AclEntry> filterAclEntriesByAclSpec(
List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
EnumMap<AclEntryScope, AclEntry>... | @Test
public void testFilterAclEntriesByAclSpecUnchanged() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, USER, "bruce", ALL))
.add(aclEntry(ACCESS, GROUP, READ_EXECUTE))
.add(aclEntry(ACCESS, GR... |
public static boolean isSystem(String topic, String group) {
return TopicValidator.isSystemTopic(topic) || isSystemGroup(group);
} | @Test
public void testIsSystem_NonSystemTopicAndGroup_ReturnsFalse() {
String topic = "FooTopic";
String group = "FooGroup";
boolean result = BrokerMetricsManager.isSystem(topic, group);
assertThat(result).isFalse();
} |
@Override
@Deprecated
public <VR> KStream<K, VR> flatTransformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, Iterable<VR>> valueTransformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(valueTransf... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullValueTransformerSupplierOnFlatTransformValues() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransformValues((org.apache.kafka.streams.kstream.ValueTran... |
@Override
public Object getCalendarValue(final int columnIndex, final Class<?> type, final Calendar calendar) throws SQLException {
return mergedResult.getCalendarValue(columnIndex, type, calendar);
} | @Test
void assertGetCalendarValue() throws SQLException {
Calendar calendar = Calendar.getInstance();
when(mergedResult.getCalendarValue(1, Date.class, calendar)).thenReturn(new Date(0L));
assertThat(new EncryptMergedResult(database, encryptRule, selectStatementContext, mergedResult).getCale... |
@Override
public void login(String loginId) {
} | @Test
public void login() {
mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
Assert.fail();
return false;
}
});
mSe... |
int getMessageCountAndThenIncrement(String msg) {
// don't insert null elements
if (msg == null) {
return 0;
}
Integer i;
// LinkedHashMap is not LinkedHashMap. See also LBCLASSIC-255
synchronized (this) {
i = super.get(msg);
if (i == ... | @Test
public void testEldestEntriesRemoval() {
final LRUMessageCache cache = new LRUMessageCache(2);
assertEquals(0, cache.getMessageCountAndThenIncrement("0"));
assertEquals(1, cache.getMessageCountAndThenIncrement("0"));
assertEquals(0, cache.getMessageCountAndThenIncrement("1"));
... |
@Override
public ScalarOperator visitCloneOperator(CloneOperator operator, Void context) {
return shuttleIfUpdate(operator);
} | @Test
void testCloneOperator() {
BinaryPredicateOperator binary1 = new BinaryPredicateOperator(BinaryType.EQ,
new ColumnRefOperator(1, INT, "id", true), ConstantOperator.createInt(1));
CloneOperator clone = new CloneOperator(binary1);
{
ScalarOperator newOperator ... |
public GsonAzureProjectList getProjects(String serverUrl, String token) {
String url = String.format("%s/_apis/projects?%s", getTrimmedUrl(serverUrl), API_VERSION_3);
return doGet(token, url, r -> buildGson().fromJson(r.body().charStream(), GsonAzureProjectList.class));
} | @Test
public void get_projects_with_invalid_pat() {
enqueueResponse(401);
assertThatThrownBy(() -> underTest.getProjects(server.url("").toString(), "invalid-token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid personal access token");
assertThat(logTester.logs(Level.ER... |
public void write(
ByteBuffer record,
TieredStorageSubpartitionId subpartitionId,
Buffer.DataType dataType,
boolean isBroadcast)
throws IOException {
if (isBroadcast && !isBroadcastOnly) {
int currentPosition = record.position();
... | @TestTemplate
void testTierCanNotStartNewSegment() {
int numSubpartitions = 10;
int bufferSize = 1024;
Random random = new Random();
TestingTierProducerAgent tierProducerAgent =
new TestingTierProducerAgent.Builder()
.setTryStartSegmentSupplie... |
@Override
public void updateTag(MemberTagUpdateReqVO updateReqVO) {
// 校验存在
validateTagExists(updateReqVO.getId());
// 校验名称唯一
validateTagNameUnique(updateReqVO.getId(), updateReqVO.getName());
// 更新
MemberTagDO updateObj = MemberTagConvert.INSTANCE.convert(updateReqVO... | @Test
public void testUpdateTag_notExists() {
// 准备参数
MemberTagUpdateReqVO reqVO = randomPojo(MemberTagUpdateReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> tagService.updateTag(reqVO), TAG_NOT_EXISTS);
} |
@Override
protected CompletableFuture<EmptyResponseBody> handleRequest(
@Nonnull final HandlerRequest<EmptyRequestBody> request,
@Nonnull final RestfulGateway gateway)
throws RestHandlerException {
final String jarId = request.getPathParameter(JarIdPathParameter.class);
... | @Test
void testDeleteUnknownJar() throws Exception {
final HandlerRequest<EmptyRequestBody> request = createRequest("doesnotexist.jar");
assertThatThrownBy(() -> jarDeleteHandler.handleRequest(request, restfulGateway).get())
.satisfies(
e -> {
... |
public void startsWith(@Nullable String string) {
checkNotNull(string);
if (actual == null) {
failWithActual("expected a string that starts with", string);
} else if (!actual.startsWith(string)) {
failWithActual("expected to start with", string);
}
} | @Test
public void stringStartsWith() {
assertThat("abc").startsWith("ab");
} |
MethodSpec buildFunction(AbiDefinition functionDefinition) throws ClassNotFoundException {
return buildFunction(functionDefinition, true);
} | @Test
public void testBuildFunctionConstantMultipleValueReturn() throws Exception {
AbiDefinition functionDefinition =
new AbiDefinition(
true,
Arrays.asList(
new NamedType("param1", "uint8"),
... |
public static boolean isNullOrEmpty(final CharSequence cs) {
return (cs == null) || (cs.length() == 0);
} | @Test
public void testIsNullOrEmpty() throws IOException {
assertTrue(StringUtils.isNullOrEmpty(null));
assertTrue(StringUtils.isNullOrEmpty(""));
assertFalse(StringUtils.isNullOrEmpty(" "));
assertFalse(StringUtils.isNullOrEmpty("abc"));
assertFalse(StringUtils.isNullOrEmpty(" a"));
} |
@Override
public void doLimit(String sql) throws SQLException {
if (!enabledLimit) {
return;
}
String trimmedSql = sql.trim();
if (StringUtils.isEmpty(trimmedSql)) {
return;
}
int firstTokenIndex = trimmedSql.indexOf(" ");
if (-1 == fir... | @Test
void testDoLimitForDisabledLimit() throws SQLException {
MockEnvironment environment = new MockEnvironment();
environment.setProperty("nacos.persistence.sql.derby.limit.enabled", "false");
EnvUtil.setEnvironment(environment);
sqlLimiter = new SqlTypeLimiter();
sqlLimite... |
public <T extends MongoEntity> MongoCollection<T> collection(String collectionName, Class<T> valueType) {
return getCollection(collectionName, valueType);
} | @Test
void testTimestampToJodaDateTimeConversion() {
final MongoCollection<TimestampTest> collection = collections.collection("timestamp-test", TimestampTest.class);
final DateTime now = DateTime.now(DateTimeZone.UTC);
final ObjectId objectId = new ObjectId();
final Map<String, Obj... |
public static INodeFile valueOf(INode inode, String path
) throws FileNotFoundException {
return valueOf(inode, path, false);
} | @Test
public void testValueOf () throws IOException {
final String path = "/testValueOf";
final short replication = 3;
{//cast from null
final INode from = null;
//cast to INodeFile, should fail
try {
INodeFile.valueOf(from, path);
fail();
} catch(FileNotFoundExce... |
static <K, V> ReadFromKafkaDoFn<K, V> create(
ReadSourceDescriptors<K, V> transform,
TupleTag<KV<KafkaSourceDescriptor, KafkaRecord<K, V>>> recordTag) {
if (transform.isBounded()) {
return new Bounded<>(transform, recordTag);
} else {
return new Unbounded<>(transform, recordTag);
}
... | @Test
public void testConstructorWithPollTimeout() {
ReadSourceDescriptors<String, String> descriptors = makeReadSourceDescriptor(consumer);
// default poll timeout = 1 scond
ReadFromKafkaDoFn<String, String> dofnInstance = ReadFromKafkaDoFn.create(descriptors, RECORDS);
Assert.assertEquals(2L, dofnIn... |
public static String hump2Line(String str) {
Matcher matcher = CAMEL_PATTERN.matcher(str);
StringBuffer sb = new StringBuffer();
if (matcher.find()) {
matcher.appendReplacement(sb, "-" + matcher.group(0).toLowerCase());
while (matcher.find()) {
matcher.app... | @Test
public void testHump2Line(){
assertThat(StringUtils.hump2Line("abc-d").equals("abcD")).isTrue();
assertThat(StringUtils.hump2Line("aBc").equals("a-bc")).isTrue();
assertThat(StringUtils.hump2Line("abc").equals("abc")).isTrue();
} |
@Override
public boolean setIfExists(V value) {
return get(setIfExistsAsync(value));
} | @Test
public void testSetIfExists() {
RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class));
TestType t = new TestType();
t.setName("name1");
al.set(t);
NestedType nt2 = new NestedType();
nt2.setValue(124);
nt2.setValu... |
@Override
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @Test
public void isEqualTo_WithoutToleranceParameter_Fail_DifferentOrder() {
expectFailureWhenTestingThat(array(2.2d, 3.3d)).isEqualTo(array(3.3d, 2.2d));
} |
@Override
protected CompletableFuture<JobStatusInfo> handleRequest(
@Nonnull HandlerRequest<EmptyRequestBody> request, @Nonnull RestfulGateway gateway)
throws RestHandlerException {
JobID jobId = request.getPathParameter(JobIDPathParameter.class);
return gateway.requestJobSta... | @Test
void testRequestJobStatus() throws Exception {
final JobStatusHandler jobStatusHandler =
new JobStatusHandler(
CompletableFuture::new,
TestingUtils.TIMEOUT,
Collections.emptyMap(),
JobStatus... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.