focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static LogCollector<ShenyuRequestLog> getInstance() {
return INSTANCE;
} | @Test
public void testAbstractLogCollector() throws Exception {
ElasticSearchLogCollector.getInstance().start();
Field field1 = AbstractLogCollector.class.getDeclaredField("started");
field1.setAccessible(true);
Assertions.assertEquals(field1.get(ElasticSearchLogCollector.getInstance... |
@Activate
public void activate() {
eventDispatcher.addSink(ApplicationEvent.class, listenerRegistry);
store.setDelegate(delegate);
log.info("Started");
} | @Test
public void activate() {
install();
mgr.activate(APP_ID);
assertEquals("incorrect app state", ACTIVE, mgr.getState(APP_ID));
assertFalse("preDeactivate hook wrongly called", deactivated);
} |
public void checkLimit() {
if (!rateLimiter.tryAcquire()) {
rejectSensor.record();
throw new KsqlRateLimitException("Host is at rate limit for pull queries. Currently set to "
+ rateLimiter.getRate() + " qps.");
}
} | @Test
public void shouldSucceedUnderLimit() {
final Metrics metrics = new Metrics();
final Map<String, String> tags = Collections.emptyMap();
// It doesn't look like the underlying guava rate limiter has a way to control time, so we're
// just going to have to hope that these tests reliably run in und... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatTerminateQuery() {
// Given:
final TerminateQuery terminateQuery = TerminateQuery.query(Optional.empty(), new QueryId("FOO"));
// When:
final String formatted = SqlFormatter.formatSql(terminateQuery);
// Then:
assertThat(formatted, is("TERMINATE FOO"));
} |
@Override
public InetSocketAddress getRemoteAddress() {
return channel.getRemoteAddress();
} | @Test
void getRemoteAddressTest() {
Assertions.assertNull(header.getRemoteAddress());
} |
public static Map<String, String> resolve(ServerWebExchange exchange) {
Map<String, String> result = new HashMap<>();
HttpHeaders headers = exchange.getRequest().getHeaders();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
if (StringUtils.isBlank(key)) {
... | @Test
public void testPolarisServletTransitiveMetadata() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("X-Polaris-Metadata-Transitive-a", "test");
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(request);
assertThat(resolve.size()).isEqualTo(1);
ass... |
public static int getCombatLevel(int attackLevel, int strengthLevel,
int defenceLevel, int hitpointsLevel, int magicLevel,
int rangeLevel, int prayerLevel)
{
return (int) getCombatLevelPrecise(attackLevel, strengthLevel, defenceLevel, hitpointsLevel, magicLevel, rangeLevel, prayerLevel);
} | @Test
public void testGetCombatLevel()
{
assertEquals(126, Experience.getCombatLevel(99, 99, 99, 99, 70, 42, 98));
assertEquals(40, Experience.getCombatLevel(27, 22, 1, 36, 64, 45, 1));
} |
@Override
public void checkBeforeUpdate(final AlterReadwriteSplittingRuleStatement sqlStatement) {
ReadwriteSplittingRuleStatementChecker.checkAlteration(database, sqlStatement.getRules(), rule.getConfiguration());
} | @Test
void assertCheckSQLStatementWithDuplicateWriteResourceNames() {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getResourceMetaData()).thenReturn(resourceMetaData);
ReadwriteSplittingRule rule = mock(ReadwriteSplittingRule.class);... |
public void hasLength(int expectedLength) {
checkArgument(expectedLength >= 0, "expectedLength(%s) must be >= 0", expectedLength);
check("length()").that(checkNotNull(actual).length()).isEqualTo(expectedLength);
} | @Test
public void hasLength() {
assertThat("kurt").hasLength(4);
} |
public void onClose()
{
if (asyncTaskExecutor instanceof ExecutorService)
{
try
{
final ExecutorService executor = (ExecutorService)asyncTaskExecutor;
executor.shutdownNow();
if (!executor.awaitTermination(EXECUTOR_SHUTDOWN_TIME... | @Test
void onCloseShouldNotifyIfExecutorDoesNotCloseOnTime(@TempDir final Path dir) throws InterruptedException
{
final ExecutorService asyncTaskExecutor = mock(ExecutorService.class);
final DriverConductor conductor = new DriverConductor(ctx.clone()
.cncByteBuffer(IoUtil.mapNewFile(... |
@Override
public String toString() {
return toString(true);
} | @Test
public void testToStringNoQuota() {
long length = 11111;
long fileCount = 22222;
long directoryCount = 33333;
ContentSummary contentSummary = new ContentSummary.Builder().length(length).
fileCount(fileCount).directoryCount(directoryCount).build();
String expected = " none ... |
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 testFloatingPointCloseToZero()
{
List<Column> columns = ImmutableList.of(DOUBLE_COLUMN, REAL_COLUMN);
// Matched
ChecksumResult controlChecksum = new ChecksumResult(
5,
ImmutableMap.<String, Object>builder()
.putA... |
public PushOffsetVector mergeCopy(final OffsetVector other) {
final PushOffsetVector copy = copy();
copy.merge(other);
return copy;
} | @Test
public void shouldMerge_empty() {
// Given:
PushOffsetVector pushOffsetVector1 = new PushOffsetVector(ImmutableList.of(1L, 2L, 3L));
PushOffsetVector pushOffsetVector2 = new PushOffsetVector();
// Then:
assertThat(pushOffsetVector1.mergeCopy(pushOffsetVector2),
is(new PushOffsetVect... |
public B ondisconnect(String ondisconnect) {
this.ondisconnect = ondisconnect;
return getThis();
} | @Test
void ondisconnect() {
InterfaceBuilder builder = new InterfaceBuilder();
builder.ondisconnect("ondisconnect");
Assertions.assertEquals("ondisconnect", builder.build().getOndisconnect());
} |
public static List<SqlGatewayEndpoint> createSqlGatewayEndpoint(
SqlGatewayService service, Configuration configuration) {
List<String> identifiers = configuration.get(SQL_GATEWAY_ENDPOINT_TYPE);
if (identifiers == null || identifiers.isEmpty()) {
throw new ValidationException(
... | @Test
public void testCreateEndpoints() {
String id = UUID.randomUUID().toString();
Map<String, String> config = getDefaultConfig(id);
config.put("sql-gateway.endpoint.type", "mocked;fake");
List<SqlGatewayEndpoint> actual =
createSqlGatewayEndpoint(
... |
public static <T> Write<T> write(String jdbcUrl, String table) {
return new AutoValue_ClickHouseIO_Write.Builder<T>()
.jdbcUrl(jdbcUrl)
.table(table)
.properties(new Properties())
.maxInsertBlockSize(DEFAULT_MAX_INSERT_BLOCK_SIZE)
.initialBackoff(DEFAULT_INITIAL_BACKOFF)
... | @Test
public void testTupleType() throws Exception {
Schema tupleSchema =
Schema.of(
Schema.Field.of("f0", FieldType.STRING), Schema.Field.of("f1", FieldType.BOOLEAN));
Schema schema = Schema.of(Schema.Field.of("t0", FieldType.row(tupleSchema)));
Row row1Tuple = Row.withSchema(tupleSch... |
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) {
return Optional.ofNullable(HANDLERS.get(step.getClass()))
.map(h -> h.handle(this, schema, step))
.orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass()));
} | @Test
public void shouldResolveSchemaForWindowedTableSource() {
// Given:
final WindowedTableSource step = new WindowedTableSource(
PROPERTIES,
"foo",
formats,
mock(WindowInfo.class),
Optional.empty(),
SCHEMA,
OptionalInt.of(SystemColumns.CURRENT_PSEUDOC... |
boolean handleCorruption(final Set<TaskId> corruptedTasks) {
final Set<TaskId> activeTasks = new HashSet<>(tasks.activeTaskIds());
// We need to stop all processing, since we need to commit non-corrupted tasks as well.
maybeLockTasks(activeTasks);
final Set<Task> corruptedActiveTasks =... | @Test
public void shouldReAddRevivedTasksToStateUpdater() {
final StreamTask corruptedActiveTask = statefulTask(taskId03, taskId03ChangelogPartitions)
.inState(State.RESTORING)
.withInputPartitions(taskId03Partitions).build();
final StandbyTask corruptedStandbyTask = standbyT... |
public static MemberSelector or(MemberSelector... selectors) {
return new OrMemberSelector(selectors);
} | @Test
public void testOrMemberSelector() {
when(member.localMember()).thenReturn(true);
MemberSelector selector = MemberSelectors.or(LOCAL_MEMBER_SELECTOR, LITE_MEMBER_SELECTOR);
assertTrue(selector.select(member));
verify(member).localMember();
verify(member, never()).isLite... |
public static Schema toBeamSchema(Class<?> clazz) {
ReflectData data = new ReflectData(clazz.getClassLoader());
return toBeamSchema(data.getSchema(clazz));
} | @Test
public void testFromAvroSchema() {
assertEquals(getBeamSchema(), AvroUtils.toBeamSchema(getAvroSchema()));
} |
@Override
public String getAbsolute() {
return path;
} | @Test
public void testPathContainer() {
final Path path = new Path(new Path("test.cyberduck.ch",
EnumSet.of(Path.Type.volume, Path.Type.directory)), "/test", EnumSet.of(Path.Type.directory));
assertEquals("/test.cyberduck.ch/test", path.getAbsolute());
} |
private CompletableFuture<Boolean> verifyTxnOwnership(TxnID txnID) {
assert ctx.executor().inEventLoop();
return service.pulsar().getTransactionMetadataStoreService()
.verifyTxnOwnership(txnID, getPrincipal())
.thenComposeAsync(isOwner -> {
if (isOwner... | @Test(timeOut = 30000)
public void sendAddPartitionToTxnResponseFailed() throws Exception {
final TransactionMetadataStoreService txnStore = mock(TransactionMetadataStoreService.class);
when(txnStore.getTxnMeta(any())).thenReturn(CompletableFuture.completedFuture(mock(TxnMeta.class)));
when(... |
public static String validateIndexName(@Nullable String indexName) {
checkDbIdentifier(indexName, "Index name", INDEX_NAME_MAX_SIZE);
return indexName;
} | @Test
public void validateIndexName_returns_valid_name() {
assertThat(validateIndexName("foo")).isEqualTo("foo");
} |
@Override
public void destroy() {
if (this.sqsClient != null) {
try {
this.sqsClient.shutdown();
} catch (Exception e) {
log.error("Failed to shutdown SQS client during destroy()", e);
}
}
} | @Test
void givenSqsClientIsNotNull_whenDestroy_thenShutdown() {
node.destroy();
then(sqsClientMock).should().shutdown();
} |
public static UDoWhileLoop create(UStatement body, UExpression condition) {
return new AutoValue_UDoWhileLoop((USimpleStatement) body, condition);
} | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(
UDoWhileLoop.create(
UBlock.create(
UExpressionStatement.create(
UAssign.create(
ULocalVarIdent.create("old"),
... |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefi... | @Test
public void testOr() {
Expression expr =
resolve(
Expressions.$("field1")
.isEqual(Expressions.lit(1))
.or(Expressions.$("field2").isEqual(Expressions.lit(2L))));
Optional<org.apache.iceberg.expressions.Expression> actual = FlinkFilters.convert(expr);
... |
public static boolean isSelectable(Transaction tx, Network network) {
// Only pick chain-included transactions, or transactions that are ours and pending.
TransactionConfidence confidence = tx.getConfidence();
TransactionConfidence.ConfidenceType type = confidence.getConfidenceType();
re... | @Test
public void selectable() throws Exception {
Transaction t;
t = new Transaction();
t.getConfidence().setConfidenceType(TransactionConfidence.ConfidenceType.PENDING);
assertFalse(DefaultCoinSelector.isSelectable(t, TESTNET));
t.getConfidence().setSource(TransactionConfide... |
public static Set<Port> parse(List<String> ports) throws NumberFormatException {
Set<Port> result = new HashSet<>();
for (String port : ports) {
Matcher matcher = portPattern.matcher(port);
if (!matcher.matches()) {
throw new NumberFormatException(
"Invalid port configuration: ... | @Test
public void testParse() {
List<String> goodInputs =
Arrays.asList("1000", "2000-2003", "3000-3000", "4000/tcp", "5000/udp", "6000-6002/udp");
ImmutableSet<Port> expected =
new ImmutableSet.Builder<Port>()
.add(
Port.tcp(1000),
Port.tcp(2000),
... |
@Nullable
public static ByteBuf accumulate(
ByteBuf target, ByteBuf source, int targetAccumulationSize, int accumulatedSize) {
if (accumulatedSize == 0 && source.readableBytes() >= targetAccumulationSize) {
return source;
}
int copyLength = Math.min(source.readableBy... | @Test
void testAccumulateWithoutCopy() {
int sourceLength = 128;
int sourceReaderIndex = 32;
int expectedAccumulationSize = 16;
ByteBuf src = createSourceBuffer(sourceLength, sourceReaderIndex, expectedAccumulationSize);
ByteBuf target = Unpooled.buffer(expectedAccumulationS... |
public void setMemoryLimit(final long memoryLimit) {
if (memoryLimit <= 0) {
throw new IllegalArgumentException();
}
this.memoryLimit = memoryLimit;
} | @Test
public void testSetMemoryLimiterWhenIllegal() {
long lessThanZero = -1;
MemoryLimiter memoryLimiter = new MemoryLimiter(instrumentation);
assertThrows(IllegalArgumentException.class, () -> memoryLimiter.setMemoryLimit(lessThanZero));
} |
@Override
public boolean isIndividual() {
return false;
} | @Test
public void testIsIndividual() {
CorporateEdsLoginAuthenticator authenticator = new CorporateEdsLoginAuthenticator();
assertThat(authenticator.isIndividual()).isFalse();
} |
public static boolean isIn(ChronoLocalDateTime<?> date, ChronoLocalDateTime<?> beginDate, ChronoLocalDateTime<?> endDate) {
return TemporalAccessorUtil.isIn(date, beginDate, endDate);
} | @SuppressWarnings("ConstantConditions")
@Test
public void isIn() {
// 时间范围 8点-9点
final LocalDateTime begin = LocalDateTime.parse("2019-02-02T08:00:00");
final LocalDateTime end = LocalDateTime.parse("2019-02-02T09:00:00");
// 不在时间范围内 用例
assertFalse(LocalDateTimeUtil.isIn(LocalDateTime.parse("2019-02-02T06:... |
public String redirectWithCorrectAttributesForAd(HttpServletRequest httpRequest, AuthenticationRequest authenticationRequest) throws SamlParseException {
try {
String redirectUrl;
SamlSession samlSession = authenticationRequest.getSamlSession();
if (samlSession.getValidation... | @Test
public void redirectWithCorrectAttributesToAdForBvDTest() throws SamlParseException, SamlSessionException, DienstencatalogusException, SharedServiceClientException, UnsupportedEncodingException, ComponentInitializationException, SamlValidationException, MessageDecodingException, MetadataException, DecryptionE... |
public Map<String, MountInfo> getMountTable() {
try (LockResource r = new LockResource(mReadLock)) {
return new HashMap<>(mState.getMountTable());
}
} | @Test
public void getMountTable() throws Exception {
Map<String, MountInfo> mountTable = new HashMap<>(2);
mountTable.put("/mnt/foo",
new MountInfo(new AlluxioURI("/mnt/foo"), new AlluxioURI("hdfs://localhost:5678/foo"), 2L,
MountContext.defaults().getOptions().build()));
mountTable.pu... |
@Override
public List<byte[]> clusterGetKeysInSlot(int slot, Integer count) {
RFuture<List<byte[]>> f = executorService.readAsync((String)null, ByteArrayCodec.INSTANCE, CLUSTER_GETKEYSINSLOT, slot, count);
return syncFuture(f);
} | @Test
public void testClusterGetKeysInSlot() {
List<byte[]> keys = connection.clusterGetKeysInSlot(12, 10);
assertThat(keys).isEmpty();
} |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final String msg = new String(rawMessage.getPayload(), charset);
try (Timer.Context ignored = this.decodeTime.time()) {
final ResolvableInetSocketAddress address = rawMessage.getRemoteAddress();
f... | @Test
public void testDecodeUnstructuredWithFullMessage() throws Exception {
when(configuration.getBoolean(SyslogCodec.CK_STORE_FULL_MESSAGE)).thenReturn(true);
final Message message = codec.decode(buildRawMessage(UNSTRUCTURED));
assertNotNull(message);
assertEquals("c4dc57ba1ebb s... |
public static <InputT, OutputT> TimestampExtractTransform<InputT, OutputT> of(
PCollectionTransform<InputT, OutputT> transform) {
return new TimestampExtractTransform<>(null, transform);
} | @SuppressWarnings("unchecked")
@Test(timeout = 10000)
public void testTransform() {
Pipeline p = Pipeline.create();
PCollection<Integer> input = p.apply(Create.of(1, 2, 3));
PCollection<KV<Integer, Long>> result =
input.apply(
TimestampExtractTransform.of(
in -> Count... |
public static List<CredentialRetriever> getToCredentialRetrievers(
CommonCliOptions commonCliOptions, DefaultCredentialRetrievers defaultCredentialRetrievers)
throws FileNotFoundException {
// these are all mutually exclusive as enforced by the CLI
commonCliOptions
.getUsernamePassword()
... | @Test
@Parameters(method = "paramsToUsernamePassword")
public void testGetToUsernamePassword(String expectedSource, String[] args)
throws FileNotFoundException {
CommonCliOptions commonCliOptions =
CommandLine.populateCommand(new CommonCliOptions(), ArrayUtils.addAll(DEFAULT_ARGS, args));
Cred... |
@Implementation
protected HttpResponse execute(
HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext)
throws HttpException, IOException {
if (FakeHttp.getFakeHttpLayer().isInterceptingHttpRequests()) {
return FakeHttp.getFakeHttpLayer()
.emulateRequest(httpHost, httpRequ... | @Test
public void clearPendingHttpResponses() throws Exception {
FakeHttp.addPendingHttpResponse(200, "earlier");
FakeHttp.clearPendingHttpResponses();
FakeHttp.addPendingHttpResponse(500, "later");
HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
asse... |
@Cacheable(value = "metadata-response", key = "#samlMetadataRequest.cacheableKey()")
public SamlMetadataResponse resolveSamlMetadata(SamlMetadataRequest samlMetadataRequest) {
LOGGER.info("Cache not found for saml-metadata {}", samlMetadataRequest.hashCode());
Connection connection = connectionServ... | @Test
void organizationRoleInactiveTest() {
Connection connection = newConnection(SAML_COMBICONNECT, true, true, false);
when(connectionServiceMock.getConnectionByEntityId(anyString())).thenReturn(connection);
SamlMetadataResponse response = metadataRetrieverServiceMock.resolveSamlMetadata(n... |
static Map<String, Expression> getNumericPredictorsExpressions(final List<NumericPredictor> numericPredictors) {
return numericPredictors.stream()
.collect(Collectors.toMap(numericPredictor ->numericPredictor.getField(),
KiePMMLRegressionTableFactory::ge... | @Test
void getNumericPredictorsExpressions() {
final List<NumericPredictor> numericPredictors = IntStream.range(0, 3).mapToObj(index -> {
String predictorName = "predictorName-" + index;
double coefficient = 1.23 * index;
return PMMLModelTestUtils.getNumericPredictor(pred... |
@Override
public Future<?> submit(Runnable runnable) {
submitted.mark();
return delegate.submit(new InstrumentedRunnable(runnable));
} | @Test
public void reportsTasksInformationForRunnable() throws Exception {
assertThat(submitted.getCount()).isEqualTo(0);
assertThat(running.getCount()).isEqualTo(0);
assertThat(completed.getCount()).isEqualTo(0);
assertThat(duration.getCount()).isEqualTo(0);
assertThat(idle.... |
public static RecordBatchRowIterator rowsFromRecordBatch(
Schema schema, VectorSchemaRoot vectorSchemaRoot) {
return new RecordBatchRowIterator(schema, vectorSchemaRoot);
} | @Test
public void rowIterator() {
org.apache.arrow.vector.types.pojo.Schema schema =
new org.apache.arrow.vector.types.pojo.Schema(
asList(
field("int32", new ArrowType.Int(32, true)),
field("float64", new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)),... |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testTimerIdNonFinal() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Timer declarations must be final");
thrown.expectMessage("Non-final field");
thrown.expectMessage("myfield");
thrown.expectMessage(not(containsString("State"))); // lower... |
public boolean canUserEditTemplate(PipelineTemplateConfig template, CaseInsensitiveString username, List<Role> roles) {
return template.getAuthorization().isUserAnAdmin(username, roles);
} | @Test
public void shouldReturnFalseIfUserWithinARoleCannotEditTemplate() {
CaseInsensitiveString templateAdmin = new CaseInsensitiveString("template-admin");
Role securityConfigRole = getSecurityConfigRole(templateAdmin);
List<Role> roles = setupRoles(securityConfigRole);
String tem... |
@Override
public void setUpTableMissEntry(DeviceId deviceId, int table) {
TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
treatment.drop();
FlowRule flowRule = DefaultFlowRule.builder()
... | @Test
public void testSetUpTableMissEntry() {
int testTable = 10;
fros = Sets.newConcurrentHashSet();
TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
target.setUpTabl... |
@Override
public Optional<KsqlConstants.PersistentQueryType> getPersistentQueryType() {
if (!queryPlan.isPresent()) {
return Optional.empty();
}
// CREATE_AS and CREATE_SOURCE commands contain a DDL command and a Query plan.
if (ddlCommand.isPresent()) {
if (ddlCommand.get() instanceof Cr... | @Test
public void shouldReturnNoPersistentQueryTypeOnPlansWithoutQueryPlans() {
// Given:
final KsqlPlanV1 plan = new KsqlPlanV1(
"stmt",
Optional.of(ddlCommand1),
Optional.empty());
// When/Then:
assertThat(plan.getPersistentQueryType(), is(Optional.empty()));
} |
void validateManualPartitionAssignment(
PartitionAssignment assignment,
OptionalInt replicationFactor
) {
if (assignment.replicas().isEmpty()) {
throw new InvalidReplicaAssignmentException("The manual partition " +
"assignment includes an empty replica list.");
... | @Test
public void testValidateBadManualPartitionAssignments() {
ReplicationControlTestContext ctx = new ReplicationControlTestContext.Builder().build();
ctx.registerBrokers(1, 2);
assertEquals("The manual partition assignment includes an empty replica list.",
assertThrows(Invalid... |
@Override
public void close() throws IOException {
if (open.compareAndSet(true, false)) {
onClose.run();
Throwable thrown = null;
do {
for (Closeable resource : resources) {
try {
resource.close();
} catch (Throwable e) {
if (thrown == null) {... | @Test
public void testClose_multipleTimesDoNothing() throws IOException {
state.close();
assertEquals(1, onClose.runCount);
state.close();
state.close();
assertEquals(1, onClose.runCount);
} |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testReservedSpdyRstStreamFrameBits() throws Exception {
short type = 3;
byte flags = 0;
int length = 8;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int statusCode = RANDOM.nextInt() | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + l... |
public void populate(LiveOperations liveOperations) {
this.liveOperations.forEach((key, value) -> value.keySet().forEach(callId -> liveOperations.add(key, callId)));
} | @Test
public void testPopulate() throws UnknownHostException {
r.register(createOperation("1.2.3.4", 1234, 2223L));
r.register(createOperation("1.2.3.4", 1234, 2222L));
r.register(createOperation("1.2.3.3", 1234, 2222L));
CallsPerMember liveOperations = new CallsPerMember(new Addres... |
public boolean shouldLog(final Logger logger, final String path, final int responseCode) {
if (rateLimitersByPath.containsKey(path)) {
final RateLimiter rateLimiter = rateLimitersByPath.get(path);
if (!rateLimiter.tryAcquire()) {
if (pathLimitHit.tryAcquire()) {
logger.info("Hit rate l... | @Test
public void shouldSkipRateLimited_path() {
// Given:
when(rateLimiter.tryAcquire()).thenReturn(true, true, false, false);
when(rateLimiter.getRate()).thenReturn(2d);
// When:
assertThat(loggingRateLimiter.shouldLog(logger, PATH, 200), is(true));
assertThat(loggingRateLimiter.shouldLog(l... |
public ListenableFuture<RunResponse> runWithDeadline(RunRequest request, Deadline deadline) {
return pluginService.withDeadline(deadline).run(request);
} | @Test
public void run_multiplePluginValidRequest_returnMultipleDetectionReports() throws Exception {
int numPluginsToTest = 5;
List<NetworkEndpoint> endpoints = new ArrayList<>(numPluginsToTest);
endpoints.add(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80));
endpoints.add(NetworkEndpointUtils.forIp... |
@Override
public List<String> splitAndEvaluate() {
try (ReflectContext context = new ReflectContext(JAVA_CLASSPATH)) {
if (Strings.isNullOrEmpty(inlineExpression)) {
return Collections.emptyList();
}
return flatten(evaluate(context, GroovyUtils.split(handl... | @Test
void assertEvaluateForLiteral() {
List<String> expected = createInlineExpressionParser("t_order_${'xx'}").splitAndEvaluate();
assertThat(expected.size(), is(1));
assertThat(expected, hasItems("t_order_xx"));
} |
public ApplicationDescription getApplicationDescription(String appName) {
try {
XMLConfiguration cfg = new XMLConfiguration();
cfg.setAttributeSplittingDisabled(true);
cfg.setDelimiterParsingDisabled(true);
cfg.load(appFile(appName, APP_XML));
return l... | @Test
public void loadApp() throws IOException {
saveZippedApp();
ApplicationDescription app = aar.getApplicationDescription(APP_NAME);
validate(app);
} |
@Override
public String format(final Schema schema) {
final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema);
return options.contains(Option.AS_COLUMN_LIST)
? stripTopLevelStruct(converted)
: converted;
} | @Test
public void shouldFormatOptionalBoolean() {
assertThat(DEFAULT.format(Schema.OPTIONAL_BOOLEAN_SCHEMA), is("BOOLEAN"));
assertThat(STRICT.format(Schema.OPTIONAL_BOOLEAN_SCHEMA), is("BOOLEAN"));
} |
@Override
@NonNull
public Mono<ServerResponse> handle(@NonNull ServerRequest request) {
var queryParams = new SortableRequest(request.exchange());
return client.listBy(scheme.type(),
queryParams.toListOptions(),
queryParams.toPageRequest()
)
... | @Test
void shouldHandleCorrectly() {
var scheme = Scheme.buildFromType(FakeExtension.class);
var listHandler = new ExtensionListHandler(scheme, client);
var exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/fake")
.queryParam("sort", "metadata.name,desc"));
... |
public boolean match(String pattern, String path) {
return match(pattern, path, true);
} | @Test
public void testCaseSensitive() {
AntPathMatcher matcher = new AntPathMatcher();
assertTrue(matcher.match("foo/**/*.txt", "foo/blah.txt", true));
assertTrue(matcher.match("foo/**/*.txt", "foo/blah.txt", false));
assertTrue(matcher.match("foo/**/*.txt", "foo/BLAH.txt"));
... |
public int byteLength()
{
// per https://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html#toByteArray--
return (bitSet.length() + 7) / 8;
} | @Test
public static void testByteLength()
{
for (int length : new int[] {8, 800}) {
Bitmap bitmap = new Bitmap(length);
for (int i = 0; i < length; i++) {
bitmap.setBit(i, true);
assertEquals(bitmap.byteLength(), bitmap.toBytes().length);
... |
public static Object convert(YamlNode yamlNode) {
if (yamlNode == null) {
return JSONObject.NULL;
}
if (yamlNode instanceof YamlMapping yamlMapping) {
JSONObject resultObject = new JSONObject();
for (YamlNameNodePair pair : yamlMapping.childrenPairs()) {
... | @Test
public void convertUnknownNode() {
YamlMappingImpl parentNode = createYamlMapping();
YamlMappingImpl hazelcast = (YamlMappingImpl) parentNode.childAsMapping("hazelcast");
YamlNode unknownNode = new YamlNode() {
@Override
public YamlNode parent() {
... |
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
final ServletContext context = config.getServletContext();
if (null == registry) {
final Object registryAttr = context.getAttribute(METRICS_REGISTRY);
if (registryAttr inst... | @Test
public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception {
final MetricRegistry metricRegistry = mock(MetricRegistry.class);
final ServletContext servletContext = mock(ServletContext.class);
final ServletConfig servletConfig = mock(ServletConfig.class);... |
public Connection deleteConnectionById(Connection connection) {
connectionRepository.delete(connection);
return connection;
} | @Test
void deleteConnectionById() {
doNothing().when(connectionRepositoryMock).delete(any(Connection.class));
Connection result = connectionServiceMock.deleteConnectionById(new Connection());
verify(connectionRepositoryMock, times(1)).delete(any(Connection.class));
assertNotNull(re... |
public static void main(String[] args) {
LOGGER.info("Constructing parts and car");
var wheelProperties = Map.of(
Property.TYPE.toString(), "wheel",
Property.MODEL.toString(), "15C",
Property.PRICE.toString(), 100L);
var doorProperties = Map.of(
Property.TYPE.toString(), "d... | @Test
void shouldExecuteAppWithoutException() {
assertDoesNotThrow(() -> App.main(null));
} |
@ConstantFunction(name = "multiply", argTypes = {LARGEINT, LARGEINT}, returnType = LARGEINT)
public static ConstantOperator multiplyLargeInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createLargeInt(first.getLargeInt().multiply(second.getLargeInt()));
} | @Test
public void multiplyLargeInt() {
assertEquals("10000",
ScalarOperatorFunctions.multiplyLargeInt(O_LI_100, O_LI_100).getLargeInt().toString());
} |
public void shutdownConfigRetriever() {
retriever.shutdown();
} | @Test
void components_can_be_created_from_config() {
writeBootstrapConfigs();
dirConfigSource.writeConfig("test", "stringVal \"myString\"");
Container container = newContainer(dirConfigSource);
ComponentTakingConfig component = createComponentTakingConfig(getNewComponentGraph(conta... |
private void run() {
pushMetrics();
if (pipelineResult != null) {
PipelineResult.State pipelineState = pipelineResult.getState();
if (pipelineState.isTerminal()) {
tearDown();
}
}
} | @Category({ValidatesRunner.class, UsesAttemptedMetrics.class, UsesCounterMetrics.class})
@Test
public void pushesUserMetrics() throws Exception {
TestMetricsSink.clear();
pipeline
.apply(
// Use maxReadTime to force unbounded mode.
GenerateSequence.from(0).to(NUM_ELEMENTS).wi... |
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public @Nullable <InputT> TransformEvaluator<InputT> forApplication(
AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) {
return createEvaluator((AppliedPTransform) application);
} | @Test
public void evaluatorClosesReaderAndResumesFromCheckpoint() throws Exception {
ContiguousSet<Long> elems = ContiguousSet.create(Range.closed(0L, 20L), DiscreteDomain.longs());
TestUnboundedSource<Long> source =
new TestUnboundedSource<>(BigEndianLongCoder.of(), elems.toArray(new Long[0]));
... |
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 feed_block_engage_edge_with_node_exhaustion_info_emits_cluster_and_node_events() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(null)
.clusterStateAfter("distributor:3 st... |
@Override
public void seek(long newPos) {
Preconditions.checkState(!closed, "already closed");
Preconditions.checkArgument(newPos >= 0, "position is negative: %s", newPos);
pos = newPos;
try {
channel.seek(newPos);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} | @Test
public void testSeek() throws Exception {
BlobId blobId = BlobId.fromGsUtilUri("gs://bucket/path/to/seek.dat");
byte[] data = randomData(1024 * 1024);
writeGCSData(blobId, data);
try (SeekableInputStream in =
new GCSInputStream(storage, blobId, null, gcpProperties, MetricsContext.nullM... |
@Override
public boolean isValid(final int timeout) throws SQLException {
return databaseConnectionManager.isValid(timeout);
} | @Test
void assertIsValidWhenEmptyConnection() throws SQLException {
try (ShardingSphereConnection connection = new ShardingSphereConnection(DefaultDatabase.LOGIC_NAME, mockContextManager())) {
assertTrue(connection.isValid(0));
}
} |
public static long getTransactionId(String xid) {
if (xid == null) {
return -1;
}
int idx = xid.lastIndexOf(":");
return Long.parseLong(xid.substring(idx + 1));
} | @Test
public void testGetTransactionId() {
assertThat(XID.getTransactionId(null)).isEqualTo(-1);
assertThat(XID.getTransactionId("127.0.0.1:8080:8577662204289747564")).isEqualTo(8577662204289747564L);
} |
@Override
public boolean isAdaptedLogger(Class<?> loggerClass) {
Class<?> expectedLoggerClass = getExpectedLoggerClass();
return null != expectedLoggerClass && expectedLoggerClass.isAssignableFrom(loggerClass);
} | @Test
void testIsAdaptedLogger() {
assertTrue(log4J2NacosLoggingAdapter.isAdaptedLogger(org.apache.logging.slf4j.Log4jLogger.class));
assertFalse(log4J2NacosLoggingAdapter.isAdaptedLogger(Logger.class));
} |
@Override
public RouteContext route(final RouteContext routeContext, final BroadcastRule broadcastRule) {
Collection<String> logicTableNames = broadcastRule.getBroadcastRuleTableNames(broadcastRuleTableNames);
if (logicTableNames.isEmpty()) {
routeContext.getRouteUnits().addAll(getRouteC... | @Test
void assertRouteWithoutBroadcastRuleTable() {
Collection<String> broadcastRuleTableNames = Collections.singleton("t_address");
BroadcastTableBroadcastRoutingEngine engine = new BroadcastTableBroadcastRoutingEngine(broadcastRuleTableNames);
BroadcastRule broadcastRule = mock(BroadcastRu... |
public static <E, T> Set<T> toSet(Collection<E> collection, Function<E, T> function) {
return toSet(collection, function, false);
} | @Test
public void testTranslate2Set() {
Set<String> set = CollStreamUtil.toSet(null, Student::getName);
assertEquals(set, Collections.EMPTY_SET);
List<Student> students = new ArrayList<>();
set = CollStreamUtil.toSet(students, Student::getName);
assertEquals(set, Collections.EMPTY_SET);
students.add(new St... |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @Test
void testFunctionDependingOnInputWithTupleInputWithTypeMismatch() {
IdentityMapper2<Boolean> function = new IdentityMapper2<Boolean>();
TypeInformation<Tuple2<Boolean, String>> inputType =
new TupleTypeInfo<Tuple2<Boolean, String>>(
BasicTypeInfo.BOOLEA... |
public static int chineseToNumber(String chinese) {
final int length = chinese.length();
int result = 0;
// 节总和
int section = 0;
int number = 0;
ChineseUnit unit = null;
char c;
for (int i = 0; i < length; i++) {
c = chinese.charAt(i);
final int num = chineseToNumber(c);
if (num >= 0) {
if... | @Test
public void badNumberTest2() {
assertThrows(IllegalArgumentException.class, () -> {
// 非法字符
NumberChineseFormatter.chineseToNumber("一百你三");
});
} |
@Activate
public void activate(ComponentContext context) {
providerService = providerRegistry.register(this);
appId = coreService.registerApplication(APP_NAME);
controller.addXmppDeviceListener(deviceListener);
logger.info("Started");
} | @Test
public void activate() throws Exception {
assertTrue("Provider should be registered", deviceRegistry.getProviders().contains(provider.id()));
assertEquals("Incorrect device service", deviceService, provider.deviceService);
assertEquals("Incorrect provider service", providerService, pro... |
public List<String> toPrefix(String in) {
List<String> tokens = buildTokens(alignINClause(in));
List<String> output = new ArrayList<>();
List<String> stack = new ArrayList<>();
for (String token : tokens) {
if (isOperand(token)) {
if (token.equals(")")) {
... | @Test
public void parserShouldThrowOnInvalidInput() {
parser.toPrefix(")");
} |
public int compare(Logger l1, Logger l2) {
if (l1.getName().equals(l2.getName())) {
return 0;
}
if (l1.getName().equals(Logger.ROOT_LOGGER_NAME)) {
return -1;
}
if (l2.getName().equals(Logger.ROOT_LOGGER_NAME)) {
return 1;
}
return l1.getName().compareTo(l2.getName());
} | @Test
public void testSmoke() {
assertEquals(0, comparator.compare(a, a));
assertEquals(-1, comparator.compare(a, b));
assertEquals(1, comparator.compare(b, a));
assertEquals(-1, comparator.compare(root, a));
// following two tests failed before bug #127 was fixed
assertEquals(1, comparator.co... |
public SessionFactory getSessionFactory() {
return sessionFactory;
} | @Test
void hasASessionFactory() throws Exception {
assertThat(healthCheck().getSessionFactory())
.isEqualTo(factory);
} |
void add(StorageType[] storageTypes, BlockStoragePolicy policy) {
StorageTypeAllocation storageCombo =
new StorageTypeAllocation(storageTypes, policy);
Long count = storageComboCounts.get(storageCombo);
if (count == null) {
storageComboCounts.put(storageCombo, 1l);
storageCombo.setActua... | @Test
public void testMultipleWarmsInDifferentOrder() {
BlockStoragePolicySuite bsps = BlockStoragePolicySuite.createDefaultSuite();
StoragePolicySummary sts = new StoragePolicySummary(bsps.getAllPolicies());
BlockStoragePolicy warm = bsps.getPolicy("WARM");
//DISK:1,ARCHIVE:1
sts.add(new StorageT... |
public static long hash64(CharSequence data) {
return hash64(StrUtil.bytes(data, DEFAULT_CHARSET));
} | @Test
public void hash64Test() {
long hv = MurmurHash.hash64(StrUtil.utf8Bytes("你"));
assertEquals(-1349759534971957051L, hv);
hv = MurmurHash.hash64(StrUtil.utf8Bytes("你好"));
assertEquals(-7563732748897304996L, hv);
hv = MurmurHash.hash64(StrUtil.utf8Bytes("见到你很高兴"));
assertEquals(-766658210119995316L, ... |
public static String baToHexString(byte[] ba) {
StringBuilder sb = new StringBuilder(ba.length * 2);
for (byte b : ba) {
int j = b & 0xff;
if (j < 16) {
sb.append('0'); // $NON-NLS-1$ add zero padding
}
sb.append(Integer.toHexString(j));
... | @Test
public void testBaToHexStringSeparator() {
assertEquals("", JOrphanUtils.baToHexString(new byte[]{}, '-'));
assertEquals("00", JOrphanUtils.baToHexString(new byte[]{0}, '-'));
assertEquals("0f-10-7f-80-81-ff", JOrphanUtils.baToHexString(new byte[]{15, 16, 127, -128, -127, -1}, '-'));
... |
public Map<String, String> parse(String body) {
final ImmutableMap.Builder<String, String> newLookupBuilder = ImmutableMap.builder();
final String[] lines = body.split(lineSeparator);
for (String line : lines) {
if (line.startsWith(this.ignorechar)) {
continue;
... | @Test
public void parseSimpleFile() throws Exception {
final String input = "# Sample file for testing\n" +
"foo:23\n" +
"bar:42\n" +
"baz:17";
final DSVParser dsvParser = new DSVParser("#", "\n", ":", "", false, false, 0, Optional.of(1));
fin... |
public static <T> Set<T> ofNullable(@Nullable T obj) {
return obj == null ? Collections.emptySet() : Collections.singleton(obj);
} | @Test
void testOfNullableWithNull() {
assertThat(CollectionUtil.ofNullable(null)).isEmpty();
} |
MessageType fromParquetSchema(List<SchemaElement> schema, List<ColumnOrder> columnOrders) {
Iterator<SchemaElement> iterator = schema.iterator();
SchemaElement root = iterator.next();
Types.MessageTypeBuilder builder = Types.buildMessage();
if (root.isSetField_id()) {
builder.id(root.field_id);
... | @Test
public void testMapConvertedTypeReadWrite() throws Exception {
List<SchemaElement> oldConvertedTypeSchemaElements = new ArrayList<>();
oldConvertedTypeSchemaElements.add(new SchemaElement("example").setNum_children(1));
oldConvertedTypeSchemaElements.add(new SchemaElement("testMap")
.setRepe... |
@VisibleForTesting
URL getAuthenticationUrl(@Nullable Credential credential, Map<String, String> repositoryScopes)
throws MalformedURLException {
return isOAuth2Auth(credential)
? new URL(realm) // Required parameters will be sent via POST .
: new URL(realm + "?" + getServiceScopeRequestPara... | @Test
public void getAuthenticationUrl_basicAuth() throws MalformedURLException {
Assert.assertEquals(
new URL("https://somerealm?service=someservice&scope=repository:someimage:scope"),
registryAuthenticator.getAuthenticationUrl(
null, Collections.singletonMap("someimage", "scope")));
... |
private String getEnv(String envName, InterpreterLaunchContext context) {
String env = context.getProperties().getProperty(envName);
if (StringUtils.isBlank(env)) {
env = System.getenv(envName);
}
if (StringUtils.isBlank(env)) {
LOGGER.warn("environment variable: {} is empty", envName);
... | @Test
void testYarnClusterMode_1() throws IOException {
SparkInterpreterLauncher launcher = new SparkInterpreterLauncher(zConf, null);
Properties properties = new Properties();
properties.setProperty("SPARK_HOME", sparkHome);
properties.setProperty("property_1", "value_1");
properties.setProperty(... |
public RuntimeOptionsBuilder parse(Map<String, String> properties) {
return parse(properties::get);
} | @Test
void should_parse_object_factory() {
properties.put(Constants.OBJECT_FACTORY_PROPERTY_NAME, CustomObjectFactory.class.getName());
RuntimeOptions options = cucumberPropertiesParser.parse(properties).build();
assertThat(options.getObjectFactoryClass(), equalTo(CustomObjectFactory.class))... |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testIllegalSpdyDataFrameStreamId() throws Exception {
int streamId = 0; // illegal stream identifier
byte flags = 0;
int length = 0;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeDataFrameHeader(buf, streamId, flags, length);
deco... |
public Response get(URL url, Request request) throws IOException {
return call(HttpMethods.GET, url, request);
} | @Test
public void testGet_secureClientOnNonListeningServerAndNoPortSpecified() throws IOException {
FailoverHttpClient httpClient = newHttpClient(false, false);
Mockito.when(mockHttpRequest.execute())
.thenThrow(new ConnectException("my exception")); // server not listening on 443
try (Response ... |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final String msg = new String(rawMessage.getPayload(), charset);
try (Timer.Context ignored = this.decodeTime.time()) {
final ResolvableInetSocketAddress address = rawMessage.getRemoteAddress();
f... | @Test
public void testDecodeStructuredWithFullMessage() throws Exception {
when(configuration.getBoolean(SyslogCodec.CK_STORE_FULL_MESSAGE)).thenReturn(true);
final Message message = codec.decode(buildRawMessage(STRUCTURED));
assertNotNull(message);
assertEquals("BOMAn application ... |
public static String byte2FitMemoryString(final long byteNum) {
if (byteNum < 0) {
return "shouldn't be less than zero!";
} else if (byteNum < MemoryConst.KB) {
return String.format("%d B", byteNum);
} else if (byteNum < MemoryConst.MB) {
return String.format(... | @Test
public void byte2FitMemoryStringGB() {
Assert.assertEquals(
"1 GB",
ConvertKit.byte2FitMemoryString(1024 * 1024 * 1024)
);
} |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testUnknownSpdySynStreamFrameFlags() throws Exception {
short type = 1;
byte flags = (byte) 0xFC; // undefined flags
int length = 10;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF;
byte ... |
public static MongoSinkConfig load(String yamlFile) throws IOException {
final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
final MongoSinkConfig cfg = mapper.readValue(new File(yamlFile), MongoSinkConfig.class);
return cfg;
} | @Test
public void testLoadMapConfig() throws IOException {
final Map<String, Object> commonConfigMap = TestHelper.createCommonConfigMap();
commonConfigMap.put("batchSize", TestHelper.BATCH_SIZE);
commonConfigMap.put("batchTimeMs", TestHelper.BATCH_TIME);
SinkContext sinkContext = Mo... |
@Override
public String getTypeAsString() {
String type;
// Handle dynamic array of zero length. This will fail if the dynamic array
// is an array of structs.
if (value.isEmpty()) {
if (StructType.class.isAssignableFrom(getComponentType())) {
type = Utils... | @Test
public void testDynamicArrayWithDynamicStruct() {
final List<DynamicStruct> list = Collections.singletonList(new DynamicStruct());
final DynamicArray<DynamicStruct> array = new DynamicArray<>(DynamicStruct.class, list);
assertEquals("()[]", array.getTypeAsString());
} |
@Override
public String name() {
return icebergTable.toString();
} | @Test
public void testTableEquality() throws NoSuchTableException {
CatalogManager catalogManager = spark.sessionState().catalogManager();
TableCatalog catalog = (TableCatalog) catalogManager.catalog(catalogName);
Identifier identifier = Identifier.of(tableIdent.namespace().levels(), tableIdent.name());
... |
@Override
public int getColumnLength(final Object value) {
return ((byte[]) value).length;
} | @Test
void assertGetColumnLength() {
assertThat(new PostgreSQLByteaBinaryProtocolValue().getColumnLength(new byte[10]), is(10));
} |
public static Map<String, FormUrlEncoded.FormPart> read(String body) {
var parts = new HashMap<String, FormUrlEncoded.FormPart>();
for (var s : body.split("&")) {
if (s.isBlank()) {
continue;
}
var pair = s.split("=");
var name = URLDecoder... | @Test
void test() {
var string = "val1=2112&val1=3232&val2=test";
var map = FormUrlEncodedServerRequestMapper.read(string);
assertThat(map)
.hasSize(2)
.hasEntrySatisfying("val1", v -> assertThat(v.values()).containsExactly("2112", "3232"))
.hasEntrySati... |
public static <T> T[] remove(final T[] oldElements, final T elementToRemove)
{
final int length = oldElements.length;
int index = UNKNOWN_INDEX;
for (int i = 0; i < length; i++)
{
if (oldElements[i] == elementToRemove)
{
index = i;
... | @Test
void shouldRemovePresentElementAtEnd()
{
final Integer[] result = ArrayUtil.remove(values, TWO);
assertArrayEquals(new Integer[]{ ONE }, result);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.