focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static Byte getCodeByAlias(String protocol) {
return TYPE_CODE_MAP.get(protocol);
} | @Test
public void getCodeByAlias() throws Exception {
Assert.assertTrue(ProtocolFactory.getCodeByAlias("xx") == 121);
} |
@Override
public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
boolean endStream, ChannelPromise promise) {
return writeHeaders0(ctx, streamId, headers, false, 0, (short) 0, false, padding, endStream, promise);
} | @Test
public void writeHeadersUsingVoidPromise() throws Exception {
final Throwable cause = new RuntimeException("fake exception");
when(writer.writeHeaders(eq(ctx), eq(STREAM_ID), any(Http2Headers.class),
anyInt(), anyBoolean(), any(ChannelPromise.class)))
... |
@Field
public void setDetectAngles(boolean detectAngles) {
defaultConfig.setDetectAngles(detectAngles);
} | @Test
public void testAnglesOnPageRotation() throws Exception {
PDFParserConfig pdfParserConfig = new PDFParserConfig();
pdfParserConfig.setDetectAngles(true);
ParseContext parseContext = new ParseContext();
parseContext.set(PDFParserConfig.class, pdfParserConfig);
String xml... |
public static <InputT, OutputT> MapElements<InputT, OutputT> via(
final InferableFunction<InputT, OutputT> fn) {
return new MapElements<>(fn, fn.getInputTypeDescriptor(), fn.getOutputTypeDescriptor());
} | @Test
public void testNestedPolymorphicSimpleFunction() throws Exception {
pipeline.enableAbandonedNodeEnforcement(false);
pipeline
.apply(Create.of(1, 2, 3))
// This is the function that needs to propagate the input T to output T
.apply("Polymorphic Identity", MapElements.via(new Ne... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
try {
if (statement.getStatement() instanceof CreateAsSelect) {
registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement);
... | @Test
public void shouldSupportPrimitiveValueSchemasInCreateStmts() throws Exception {
// Given:
givenStatement("CREATE STREAM source (f1 VARCHAR) "
+ "WITH ("
+ " kafka_topic='expectedName', "
+ " key_format='KAFKA', "
+ " value_format='AVRO', "
+ " partitions=1, "... |
@Override
public AddToClusterNodeLabelsResponse addToClusterNodeLabels(
AddToClusterNodeLabelsRequest request) throws YarnException, IOException {
// parameter verification.
if (request == null) {
routerMetrics.incrAddToClusterNodeLabelsFailedRetrieved();
RouterServerUtil.logAndThrowExceptio... | @Test
public void testAddToClusterNodeLabelsNormalRequest() throws Exception {
// case1, We add NodeLabel to subCluster SC-1
NodeLabel nodeLabelA = NodeLabel.newInstance("a");
NodeLabel nodeLabelB = NodeLabel.newInstance("b");
List<NodeLabel> labels = new ArrayList<>();
labels.add(nodeLabelA);
... |
@Override
public int rmdir(String path) {
return AlluxioFuseUtils.call(LOG, () -> rmInternal(path),
FuseConstants.FUSE_RMDIR, "path=%s", path);
} | @Test
@DoraTestTodoItem(action = DoraTestTodoItem.Action.FIX, owner = "LuQQiu")
@Ignore
public void rmdir() throws Exception {
AlluxioURI expectedPath = BASE_EXPECTED_URI.join("/foo/bar");
doNothing().when(mFileSystem).delete(expectedPath);
mFuseFs.rmdir("/foo/bar");
verify(mFileSystem).delete(exp... |
protected static boolean isMatchingMetricTags(Set<Tag> meterTags, Set<Tag> expectedTags) {
if (!meterTags.containsAll(expectedTags)) {
return false;
}
return expectedTags.stream().allMatch(tag -> isMatchingTag(meterTags, tag));
} | @Test
void nonMatchingMetricTagsReturnsFalse() {
meterTags.add(Tag.of("key", "value"));
Set<Tag> expectedTags = new HashSet<>();
expectedTags.add(Tag.of("key", "differentValue"));
assertFalse(MetricsUtils.isMatchingMetricTags(meterTags, expectedTags));
} |
public static ListenableFuture<EntityId> findEntityAsync(
TbContext ctx,
EntityId originator,
RelationsQuery relationsQuery
) {
var relationService = ctx.getRelationService();
var query = buildQuery(originator, relationsQuery);
var relationListFuture = rel... | @Test
public void givenRelationQuery_whenFindEntityAsync_thenReturnNull() {
// GIVEN
List<EntityRelation> entityRelations = new ArrayList<>();
when(relationServiceMock.findByQuery(ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(Futures.immediateFuture(entityRelations));
... |
@SuppressWarnings("unchecked")
protected ValueWrapper getSingleFactValueResult(FactMapping factMapping,
FactMappingValue expectedResult,
DMNDecisionResult decisionResult,
... | @Test
public void getSingleFactValueResult_failDecisionWithMessages() {
DMNMessage errorMessage = new DMNMessageImpl(ERROR, "DMN Internal Error", DMNMessageType.FEEL_EVALUATION_ERROR, null);
DMNMessage warnMessage = new DMNMessageImpl(WARN, "DMN Internal Warn", DMNMessageType.FEEL_EVALUATION_ERROR, ... |
@Override
public void process(HttpResponse response, HttpContext context) throws
HttpException, IOException {
List<Header> warnings = Arrays.stream(response.getHeaders("Warning")).filter(header -> !this.isDeprecationMessage(header.getValue())).collect(Collectors.toList());
response.remov... | @Test
public void testInterceptorNoHeader() throws IOException, HttpException {
OpenSearchFilterDeprecationWarningsInterceptor interceptor = new OpenSearchFilterDeprecationWarningsInterceptor();
HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 0, 0), 0, ... |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, final Callback<RestResponse> callback)
{
if (HttpMethod.POST != HttpMethod.valueOf(request.getMethod()))
{
_log.error("POST is expected, but " + request.getMethod() + " received");
callback.onError(RestExcept... | @Test(dataProvider = "multiplexerConfigurations")
public void testMultiplexedSingletonFilterFailures(MultiplexerRunMode multiplexerRunMode) throws Exception
{
// This test validates when a failure occurred in MultiplexedSingletonFilter for an individual request, only the individual
// request should fail. T... |
public TemplateException(String message, Throwable cause) {
super(message, cause);
} | @Test
public void testTemplateException() throws Exception {
try {
throw new TemplateException("not found template");
} catch (TemplateException e) {
assertEquals("not found template", e.getMessage());
}
} |
@Override
public <VO, VR> KStream<K, VR> outerJoin(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return outerJoin(otherStream, toValueJoin... | @SuppressWarnings("deprecation")
@Test
public void shouldNotAllowNullValueJoinerWithKeyOnOuterJoinWithStreamJoined() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.outerJoin(
testStream,
... |
public static ImmutableList<String> glob(final String glob) {
Path path = getGlobPath(glob);
int globIndex = getGlobIndex(path);
if (globIndex < 0) {
return of(glob);
}
return doGlob(path, searchPath(path, globIndex));
} | @Test
public void should_glob_files() {
ImmutableList<String> glob = Globs.glob("*.json");
assertThat(glob.isEmpty(), is(true));
} |
@SuppressWarnings("unchecked")
public <V> V run(String callableName, RetryOperation<V> operation)
{
int attempt = 1;
while (true) {
try {
return operation.run();
}
catch (Exception e) {
if (!exceptionClass.isInstance(e)) {
... | @Test(expectedExceptions = QueryException.class)
public void testNonRetryableFailure()
{
retryDriver.run("test", new MockOperation(3, NON_RETRYABLE_EXCEPTION));
} |
void appendValuesClause(StringBuilder sb) {
sb.append("VALUES ");
appendValues(sb, jdbcTable.dbFieldNames().size());
} | @Test
void appendValuesClause() {
MySQLUpsertQueryBuilder builder = new MySQLUpsertQueryBuilder(jdbcTable, dialect);
StringBuilder sb = new StringBuilder();
builder.appendValuesClause(sb);
String valuesClause = sb.toString();
assertThat(valuesClause).isEqualTo("VALUES (?,?)"... |
public static <K, C, V, T> V computeIfAbsent(Map<K, V> target, K key, BiFunction<C, T, V> mappingFunction, C param1,
T param2) {
Objects.requireNonNull(target, "target");
Objects.requireNonNull(key, "key");
Objects.requireNonNull(mappingFunction, ... | @Test
public void computeIfAbsentValIsNullTest() {
Map<String, Object> map = new HashMap<>();
map.put("abc", "123");
BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
Object ret = MapUtil.computeIfAbsent(map, "xyz", mappingFunction, "param1", "param2");
As... |
public static <T extends PipelineOptions> T as(Class<T> klass) {
return new Builder().as(klass);
} | @Test
public void testMultipleSettersAnnotatedWithJsonIgnore() throws Exception {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Found setters marked with @JsonIgnore:");
expectedException.expectMessage(
"property [other] should not be marked with @JsonI... |
@Override
public AppSettings load() {
Properties p = loadPropertiesFile(homeDir);
Set<String> keysOverridableFromEnv = stream(ProcessProperties.Property.values()).map(ProcessProperties.Property::getKey)
.collect(Collectors.toSet());
keysOverridableFromEnv.addAll(p.stringPropertyNames());
// 1st... | @Test
public void env_vars_take_precedence_over_properties_file() throws Exception {
when(system.getenv()).thenReturn(ImmutableMap.of("SONAR_CUSTOMPROP", "11"));
when(system.getenv("SONAR_CUSTOMPROP")).thenReturn("11");
File homeDir = temp.newFolder();
File propsFile = new File(homeDir, "conf/sonar.pr... |
private static File targetFile(String dataId, String group, String tenant) {
// fix https://github.com/alibaba/nacos/issues/10067
dataId = PathEncoderManager.getInstance().encode(dataId);
group = PathEncoderManager.getInstance().encode(group);
tenant = PathEncoderManager.getInstance().en... | @Test
void testTargetFile() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Method method = ConfigRawDiskService.class.getDeclaredMethod("targetFile", String.class, String.class, String.class);
method.setAccessible(true);
File result = (File) method.invoke(n... |
public boolean evaluate( RowMetaInterface rowMeta, Object[] r ) {
// Start of evaluate
boolean retval = false;
// If we have 0 items in the list, evaluate the current condition
// Otherwise, evaluate all sub-conditions
//
try {
if ( isAtomic() ) {
if ( function == FUNC_TRUE ) {
... | @Test
public void testZeroLargerOrEqualsThanNull() {
String left = "left";
String right = "right";
Long leftValue = 0L;
Long rightValue = null;
RowMetaInterface rowMeta = new RowMeta();
rowMeta.addValueMeta( new ValueMetaInteger( left ) );
rowMeta.addValueMeta( new ValueMetaInteger( righ... |
public static <T> Values<T> of(Iterable<T> elems) {
return new Values<>(elems, Optional.absent(), Optional.absent(), false);
} | @Test
public void testSourceSplitVoid() throws Exception {
CreateSource<Void> source =
CreateSource.fromIterable(Lists.newArrayList(null, null, null, null, null), VoidCoder.of());
PipelineOptions options = PipelineOptionsFactory.create();
List<? extends BoundedSource<Void>> splitSources = source.s... |
public AbstractPushCallBack(long timeout) {
this.timeout = timeout;
} | @Test
void testAbstractPushCallBack() {
AbstractPushCallBack callBack = new AbstractPushCallBack(2000) {
@Override
public void onSuccess() {
testValue = true;
}
@Override
public void onFail(Throwable e) {
... |
@Override
protected void validateDataImpl(TenantId tenantId, ComponentDescriptor plugin) {
validateString("Component name", plugin.getName());
if (plugin.getType() == null) {
throw new DataValidationException("Component type should be specified!");
}
if (plugin.getScope()... | @Test
void testValidateNameInvocation() {
ComponentDescriptor plugin = new ComponentDescriptor();
plugin.setType(ComponentType.ENRICHMENT);
plugin.setScope(ComponentScope.SYSTEM);
plugin.setName("originator attributes");
plugin.setClazz("org.thingsboard.rule.engine.metadata.T... |
@Override
public int getLineHashesVersion(Component component) {
if (significantCodeRepository.getRangesPerLine(component).isPresent()) {
return LineHashVersion.WITH_SIGNIFICANT_CODE.getDbValue();
} else {
return LineHashVersion.WITHOUT_SIGNIFICANT_CODE.getDbValue();
}
} | @Test
public void should_return_without_significant_code_if_report_does_not_contain_it() {
when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.empty());
assertThat(underTest.getLineHashesVersion(file)).isEqualTo(LineHashVersion.WITHOUT_SIGNIFICANT_CODE.getDbValue());
verify(signifi... |
@Override
public List<InetSocketAddress> lookup(String key) throws Exception {
final String cluster = getServiceGroup(key);
if (cluster == null) {
String missingDataId = PREFIX_SERVICE_ROOT + CONFIG_SPLIT_CHAR + PREFIX_SERVICE_MAPPING + key;
throw new ConfigNotFoundException(... | @Test
public void testLookup() throws Exception {
RegistryService registryService = mock(ConsulRegistryServiceImpl.class);
registryService.lookup("test-key");
verify(registryService).lookup("test-key");
} |
@Override
public InternalNode getCurrentNode()
{
return currentNode;
} | @Test
public void testGetCurrentNode()
{
DiscoveryNodeManager manager = new DiscoveryNodeManager(selector, workerNodeInfo, new NoOpFailureDetector(), Optional.empty(), expectedVersion, testHttpClient, new TestingDriftClient<>(), internalCommunicationConfig);
try {
assertEquals(manage... |
@VisibleForTesting
void validateTableInfo(TableInfo tableInfo) {
if (tableInfo == null) {
throw exception(CODEGEN_IMPORT_TABLE_NULL);
}
if (StrUtil.isEmpty(tableInfo.getComment())) {
throw exception(CODEGEN_TABLE_INFO_TABLE_COMMENT_IS_NULL);
}
if (Coll... | @Test
public void testValidateTableInfo() {
// 情况一
assertServiceException(() -> codegenService.validateTableInfo(null),
CODEGEN_IMPORT_TABLE_NULL);
// 情况二
TableInfo tableInfo = mock(TableInfo.class);
assertServiceException(() -> codegenService.validateTableInf... |
public static UIf create(
UExpression condition, UStatement thenStatement, UStatement elseStatement) {
return new AutoValue_UIf(condition, thenStatement, elseStatement);
} | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(
UIf.create(
UFreeIdent.create("cond"),
UBlock.create(
UExpressionStatement.create(
UAssign.create(UFreeIdent.create("x"), UFreeIdent.create("y")))),
... |
@WorkerThread
@Override
public Unit call()
throws IOException,
StreamNotFoundException,
ShellNotRunningException,
IllegalArgumentException {
OutputStream outputStream;
File destFile = null;
switch (fileAbstraction.scheme) {
case CONTENT:
Objects.require... | @Test
public void testWriteFileNonRoot()
throws IOException, StreamNotFoundException, ShellNotRunningException {
File file = new File(Environment.getExternalStorageDirectory(), "test.txt");
Uri uri = Uri.fromFile(file);
Context ctx = ApplicationProvider.getApplicationContext();
ContentResolver c... |
public static Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setFeature(X... | @Test
public void getDocument() throws Exception {
Document retrieved = DOMParserUtil.getDocument(XML);
assertThat(retrieved).isNotNull();
} |
@VisibleForTesting
static Comparator<ActualProperties> streamingExecutionPreference(PreferredProperties preferred)
{
// Calculating the matches can be a bit expensive, so cache the results between comparisons
LoadingCache<List<LocalProperty<VariableReferenceExpression>>, List<Optional<LocalPrope... | @Test
public void testPickLayoutGrouped()
{
Comparator<ActualProperties> preference = streamingExecutionPreference
(PreferredProperties.local(ImmutableList.of(grouped("a"))));
List<ActualProperties> input = ImmutableList.<ActualProperties>builder()
.add(builder()... |
@GET
@Path("/{connector}/tasks-config")
@Operation(deprecated = true, summary = "Get the configuration of all tasks for the specified connector")
public Map<ConnectorTaskId, Map<String, String>> getTasksConfig(
final @PathParam("connector") String connector) throws Throwable {
log.warn("... | @Test
public void testGetTasksConfigConnectorNotFound() {
final ArgumentCaptor<Callback<Map<ConnectorTaskId, Map<String, String>>>> cb = ArgumentCaptor.forClass(Callback.class);
expectAndCallbackException(cb, new NotFoundException("not found"))
.when(herder).tasksConfig(eq(CONNECTOR_NAME... |
public static String javaCharArray(String str){
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) {
result.append(c);
}
return result.toString();
} | @Test
public void whenUseCharArrayMethod_thenIterate() {
String input = "Hello, Baeldung!";
String expectedOutput = "Hello, Baeldung!";
String result = StringIterator.javaCharArray(input);
assertEquals(expectedOutput, result);
} |
@Override
public R transform(final K readOnlyKey, final GenericRow value) {
return delegate.transform(
readOnlyKey,
value,
context.orElseThrow(() -> new IllegalStateException("Not initialized"))
);
} | @Test
public void shouldReturnValueFromInnerTransformer() {
// When:
final String result = ksTransformer.transform(KEY, VALUE);
// Then:
assertThat(result, is(RESULT));
} |
@Override
public FileLock lock(long position, long size, boolean shared) throws IOException {
checkLockArguments(position, size, shared);
// lock is interruptible
boolean completed = false;
try {
begin();
completed = true;
return new FakeFileLock(this, position, size, shared);
}... | @Test
public void testAsynchronousClose() throws Exception {
RegularFile file = regularFile(10);
final FileChannel channel = channel(file, READ, WRITE);
file.writeLock().lock(); // ensure all operations on the channel will block
ExecutorService executor = Executors.newCachedThreadPool();
CountD... |
@SuppressWarnings("unchecked")
public final <T> T getValue(final E key) {
return (T) cache.get(key).getValue();
} | @Test
void assertGetDefaultValue() {
TypedPropertiesFixture actual = new TypedPropertiesFixture(new Properties());
assertFalse((Boolean) actual.getValue(TypedPropertyKeyFixture.BOOLEAN_VALUE));
assertFalse((Boolean) actual.getValue(TypedPropertyKeyFixture.BOOLEAN_OBJECT_VALUE));
asse... |
public static DataflowRunner fromOptions(PipelineOptions options) {
DataflowPipelineOptions dataflowOptions =
PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options);
ArrayList<String> missing = new ArrayList<>();
if (dataflowOptions.getAppName() == null) {
missing.add("appN... | @Test
public void testProjectId() throws IOException {
DataflowPipelineOptions options = buildPipelineOptions();
options.setProject("foo-12345");
DataflowRunner.fromOptions(options);
} |
public static boolean containsSystemSchema(final DatabaseType databaseType, final Collection<String> schemaNames, final ShardingSphereDatabase database) {
DialectDatabaseMetaData dialectDatabaseMetaData = new DatabaseTypeRegistry(databaseType).getDialectDatabaseMetaData();
if (database.isComplete() && !... | @Test
void assertContainsSystemSchemaForOpenGaussSQL() {
DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "openGauss");
ShardingSphereDatabase informationSchemaDatabase = mockShardingSphereDatabase("information_schema", false);
assertTrue(SystemSchemaUtils.containsSy... |
@Override
public List<ServiceDTO> getServiceInstances(String serviceId) {
String configName = SERVICE_ID_TO_CONFIG_NAME.get(serviceId);
if (configName == null) {
return Collections.emptyList();
}
return assembleServiceDTO(serviceId, bizConfig.getValue(configName));
} | @Test
public void testGetServiceInstancesWithInvalidServiceId() {
String someInvalidServiceId = "someInvalidServiceId";
assertTrue(kubernetesDiscoveryService.getServiceInstances(someInvalidServiceId).isEmpty());
} |
void moveHeadIndexByOne() {
this.headIndex = (headIndex + 1) % windowSize;
} | @Test
public void testMoveHeadIndexByOne() {
FixedSizeSlidingWindowMetrics metrics = new FixedSizeSlidingWindowMetrics(3);
assertThat(metrics.headIndex).isZero();
metrics.moveHeadIndexByOne();
assertThat(metrics.headIndex).isEqualTo(1);
metrics.moveHeadIndexByOne();
... |
public static String formatTopology(String topology) {
String prefix = "";
StringBuilder builder = new StringBuilder();
boolean params = false;
char previous = ' ';
for (char c : topology.toCharArray()) {
switch (c) {
case '[':
case '{'... | @Test
public void testFormatTopology() {
String topology = "topology on Topology@2ec5aa9[owner=ClusterConnectionImpl@1518657274[nodeUUID=b7a794ee-b5af-11ec-ae2f-3ce1a1c35439, connector=TransportConfiguration(name=netty, factory=org-apache-activemq-artemis-core-remoting-impl-netty-NettyConnectorFactory) ?por... |
public static Checksum newInstance(final String className)
{
Objects.requireNonNull(className, "className is required!");
if (Crc32.class.getName().equals(className))
{
return crc32();
}
else if (Crc32c.class.getName().equals(className))
{
ret... | @Test
void newInstanceThrowsClassCastExceptionIfCreatedInstanceDoesNotImplementChecksumInterface()
{
assertThrows(ClassCastException.class, () -> Checksums.newInstance(Object.class.getName()));
} |
public static Long convertTimestampToMillis(String timeStr) {
long millis = 0L;
if (timeStr != null) {
try {
millis = Instant.parse(timeStr).toEpochMilli();
} catch (Exception e) {
// rethrowing with more contextual information
throw new IllegalArgumentException("Invalid time... | @Test
public void testConvertDateTimeToMillis() {
assertEquals((long) TimeUtils.convertTimestampToMillis("2022-08-09T12:31:38.222Z"), 1660048298222L);
Assert.assertThrows(IllegalArgumentException.class, () -> TimeUtils
.convertTimestampToMillis("2022-08-09X12:31:38.222Z"));
assertEquals((long) Tim... |
@Bean
public TimerRegistry timerRegistry(
TimerConfigurationProperties timerConfigurationProperties,
EventConsumerRegistry<TimerEvent> timerEventConsumerRegistry,
RegistryEventConsumer<Timer> timerRegistryEventConsumer,
@Qualifier("compositeTimerCustomizer") Composite... | @Test
public void shouldConfigureInstancesUsingCustomSharedConfig() {
InstanceProperties sharedProperties = new InstanceProperties()
.setMetricNames("resilience4j.timer.shared")
.setOnFailureTagResolver(FixedOnFailureTagResolver.class);
InstanceProperties instanceProp... |
public static SelectExpression parseSelectExpression(final String expressionText) {
final SqlBaseParser.SelectItemContext parseCtx = GrammarParseUtil.getParseTree(
expressionText,
SqlBaseParser::selectItem
);
if (!(parseCtx instanceof SqlBaseParser.SelectSingleContext)) {
throw new Ill... | @Test
public void shouldParseSelectExpression() {
// When:
final SelectExpression parsed =
ExpressionParser.parseSelectExpression("1 + 2 AS `three`");
// Then:
assertThat(
parsed,
equalTo(
SelectExpression.of(
ColumnName.of("three"),
... |
@Override
public List<String> detect(ClassLoader classLoader) {
List<File> classpathContents =
classGraph
.disableNestedJarScanning()
.addClassLoader(classLoader)
.scan(1)
.getClasspathFiles();
return classpathContents.stream().map(File::getAbsolutePath... | @Test
public void shouldDetectClassPathResourceFromJavaClassPathEnvVariable() throws IOException {
String path = tmpFolder.newFolder("folder").getCanonicalPath();
System.setProperty("java.class.path", path);
ClasspathScanningResourcesDetector detector =
new ClasspathScanningResourcesDetector(new C... |
@Override
public MaterializedTable nonWindowed() {
return new KsqlMaterializedTable(inner.nonWindowed());
} | @Test
public void shouldPipeTransforms_fullTableScan() {
// Given:
final MaterializedTable table = materialization.nonWindowed();
givenNoopProject();
when(filter.apply(any(), any(), any())).thenReturn(Optional.of(transformed));
// When:
final Iterator<Row> result =
table.get(partition... |
public static String longToIpv4(long longIP) {
return Ipv4Util.longToIpv4(longIP);
} | @Test
public void longToIpTest() {
final String ipv4 = NetUtil.longToIpv4(2130706433L);
assertEquals("127.0.0.1", ipv4);
} |
public static CDCResponse succeed(final String requestId) {
return succeed(requestId, ResponseCase.RESPONSE_NOT_SET, null);
} | @Test
void assertSucceedWhenResponseCaseServerGreetingResult() {
Message msg = ServerGreetingResult.newBuilder().build();
CDCResponse actualResponse = CDCResponseUtils.succeed("request_id_1", CDCResponse.ResponseCase.SERVER_GREETING_RESULT, msg);
assertThat(actualResponse.getStatus(), is(CDC... |
IdBatchAndWaitTime newIdBaseLocal(int batchSize) {
return newIdBaseLocal(Clock.currentTimeMillis(), getNodeId(), batchSize);
} | @Test
public void when_epochStart_then_used() {
int epochStart = 456;
int timeSinceEpochStart = 1;
initialize(new FlakeIdGeneratorConfig().setEpochStart(epochStart));
long id = gen.newIdBaseLocal(epochStart + timeSinceEpochStart, 1234, 10).idBatch.base();
assertEquals((timeSi... |
@Override
public List<AdminUserDO> getUserListByDeptIds(Collection<Long> deptIds) {
if (CollUtil.isEmpty(deptIds)) {
return Collections.emptyList();
}
return userMapper.selectListByDeptIds(deptIds);
} | @Test
public void testGetUserListByDeptIds() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO(o -> o.setDeptId(1L));
userMapper.insert(dbUser);
// 测试 deptId 不匹配
userMapper.insert(cloneIgnoreId(dbUser, o -> o.setDeptId(2L)));
// 准备参数
Collection<Long> deptIds... |
void placeOrder(Order order) {
sendShippingRequest(order);
} | @Test
void testPlaceOrderWithoutDatabase() throws Exception {
long paymentTime = timeLimits.paymentTime();
long queueTaskTime = timeLimits.queueTaskTime();
long messageTime = timeLimits.messageTime();
long employeeTime = timeLimits.employeeTime();
long queueTime = timeLimits.queueTime(... |
public static PTransformMatcher flattenWithDuplicateInputs() {
return new PTransformMatcher() {
@Override
public boolean matches(AppliedPTransform<?, ?, ?> application) {
if (application.getTransform() instanceof Flatten.PCollections) {
Set<PValue> observed = new HashSet<>();
... | @Test
public void flattenWithDuplicateInputsWithDuplicates() {
PCollection<Integer> duplicate =
PCollection.createPrimitiveOutputInternal(
p, WindowingStrategy.globalDefault(), IsBounded.BOUNDED, VarIntCoder.of());
AppliedPTransform application =
AppliedPTransform.of(
"... |
@Override
public String toString() {
return String.format(
"IcebergStagedScan(table=%s, type=%s, taskSetID=%s, caseSensitive=%s)",
table(), expectedSchema().asStruct(), taskSetId, caseSensitive());
} | @Test
public void testTaskSetPlanning() throws NoSuchTableException, IOException {
sql("CREATE TABLE %s (id INT, data STRING) USING iceberg", tableName);
List<SimpleRecord> records =
ImmutableList.of(new SimpleRecord(1, "a"), new SimpleRecord(2, "b"));
Dataset<Row> df = spark.createDataFrame(reco... |
public boolean shouldRecord() {
return this.recordingLevel.shouldRecord(config.recordLevel().id);
} | @Test
public void testShouldRecordForInfoLevelSensor() {
Sensor infoSensor = new Sensor(null, "infoSensor", null, INFO_CONFIG, Time.SYSTEM,
0, Sensor.RecordingLevel.INFO);
assertTrue(infoSensor.shouldRecord());
infoSensor = new Sensor(null, "infoSensor", null, DEBUG_CONFIG, Ti... |
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
return inject(statement, new TopicProperties.Builder());
} | @Test
public void shouldDoNothingForNonCAS() {
// Given:
final ConfiguredStatement<?> statement = givenStatement("LIST PROPERTIES;");
// When:
final ConfiguredStatement<?> result = injector.inject(statement);
// Then:
assertThat(result, is(sameInstance(statement)));
} |
@Override
public Optional<DateTime> calculateNextTime(DateTime previousExecutionTime, DateTime lastNextTime, JobSchedulerClock clock) {
final Cron cron = CronUtils.getParser().parse(cronExpression());
final ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime zdt = getZo... | @Test
void testCalculateNextTime() {
final long midnight01Jan2020Millis = 1577836800000L;
final DateTime midnight01Jan2020 = new DateTime(midnight01Jan2020Millis, DateTimeZone.UTC);
final JobSchedulerTestClock clock = new JobSchedulerTestClock(DateTime.now(DateTimeZone.UTC));
// Ever... |
public String toString() {
if (queryGuid == null) {
return String.format("%s: %s", message, query);
}
return String.format("%s (%s): %s", message, queryGuid.getQueryGuid(), query);
} | @Test
public void toStringShouldReturnCorrectQueryLoggerMessageString() {
// without query guid
QueryLoggerMessage message = new QueryLoggerMessage(TEST_MESSAGE, TEST_QUERY);
assertEquals("test message: describe stream1;", message.toString());
// with query guid
message = new QueryLoggerMessage(T... |
public MetricGroup group(String groupName, String... tagKeyValues) {
MetricGroupId groupId = groupId(groupName, tagKeyValues);
MetricGroup group = groupsByName.get(groupId);
if (group == null) {
group = new MetricGroup(groupId);
MetricGroup previous = groupsByName.putIfAb... | @Test
public void testGettingGroupWithTags() {
MetricGroup group1 = metrics.group("name", "k1", "v1", "k2", "v2");
assertEquals("v1", group1.tags().get("k1"));
assertEquals("v2", group1.tags().get("k2"));
assertEquals(2, group1.tags().size());
} |
@Override
@CheckReturnValue
public boolean offer(Entry<? extends Data, ? extends Data> entry) {
int partitionId = partitionService.getPartitionId(entry.getKey());
int length = entry.getKey().totalSize() + entry.getValue().totalSize() - 2 * HeapData.TYPE_OFFSET;
// if the entry is larger... | @Test
public void when_cannotAutoFlush_then_offerReturnsFalse() {
// When
// artificially increase number of async ops so that the writer cannot proceed
writer.numConcurrentAsyncOps.set(JetServiceBackend.MAX_PARALLEL_ASYNC_OPS);
Entry<Data, Data> entry = entry(serialize("k"), seriali... |
public String getModule() {
return module;
} | @Test
public void testGetModule() {
shenyuRequestLog.setModule("test");
Assertions.assertEquals(shenyuRequestLog.getModule(), "test");
} |
@BuildStep
HealthBuildItem addHealthCheck(Capabilities capabilities, JobRunrBuildTimeConfiguration jobRunrBuildTimeConfiguration) {
if (capabilities.isPresent(Capability.SMALLRYE_HEALTH)) {
return new HealthBuildItem(JobRunrHealthCheck.class.getName(), jobRunrBuildTimeConfiguration.healthEnabled... | @Test
void addHealthCheckAddsHealthBuildItemIfSmallRyeHealthCapabilityIsPresent() {
lenient().when(capabilities.isPresent(Capability.SMALLRYE_HEALTH)).thenReturn(true);
final HealthBuildItem healthBuildItem = jobRunrExtensionProcessor.addHealthCheck(capabilities, jobRunrBuildTimeConfiguration);
... |
@Override
public Acl getPermission(final Path file) throws BackgroundException {
try {
if(file.getType().contains(Path.Type.upload)) {
// Incomplete multipart upload has no ACL set
return Acl.EMPTY;
}
final Path bucket = containerService.ge... | @Test
public void testReadKey() throws Exception {
final Path container = new Path("test-acl-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Acl acl = new S3AccessControlListFeature(session).getPermission(new Path(container, "test", EnumSet.of(Path.Type.file)));
... |
@Override
public void write(int b) throws IOException
{
checkClosed();
if (chunkSize - currentBufferPointer <= 0)
{
expandBuffer();
}
currentBuffer.put((byte) b);
currentBufferPointer++;
pointer++;
if (pointer > size)
{
... | @Test
void testPaging() throws IOException
{
try (RandomAccess randomAccessReadWrite = new RandomAccessReadWriteBuffer(5))
{
assertEquals(0, randomAccessReadWrite.length());
randomAccessReadWrite.write(new byte[] { 1, 2, 3, 4, 5, 6, 7 });
assertEquals(7, rando... |
@Nullable
private static JobID getJobId(CommandLine commandLine) throws FlinkParseException {
String jobId = commandLine.getOptionValue(JOB_ID_OPTION.getOpt());
if (jobId == null) {
return null;
}
try {
return JobID.fromHexString(jobId);
} catch (Illeg... | @Test
void testShortOptions() throws FlinkParseException {
final String jobClassName = JOB_CLASS_NAME;
final JobID jobId = new JobID();
final String savepointRestorePath = "s3://foo/bar";
final String jars = String.join(",", JOB_JARS);
final String[] args = {
"-c"... |
@SuppressWarnings("deprecation")
public boolean setSocketOpt(int option, Object optval)
{
final ValueReference<Boolean> result = new ValueReference<>(false);
switch (option) {
case ZMQ.ZMQ_SNDHWM:
sendHwm = (Integer) optval;
if (sendHwm < 0) {
thro... | @Test(expected = IllegalArgumentException.class)
public void testSelectorFailed()
{
Options opt = new Options();
Assert.assertFalse(opt.setSocketOpt(ZMQ.ZMQ_SELECTOR_PROVIDERCHOOSER, ""));
} |
public Map<String, Long> numberOfOverdueTriggers() {
final DateTime now = clock.nowUTC();
final AggregateIterable<OverdueTrigger> result = collection.aggregate(List.of(
Aggregates.match(
// We deliberately don't include the filter to include expired trigger locks ... | @Test
@MongoDBFixtures("job-triggers-for-overdue-count.json")
public void numberOfOverdueTriggers() {
final JobSchedulerTestClock clock = new JobSchedulerTestClock(DateTime.parse("2019-01-01T04:00:00.000Z"));
final DBJobTriggerService service = serviceWithClock(clock);
final Map<String,... |
@Override
public <K, T_OTHER, OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> connectAndProcess(
KeyedPartitionStream<K, T_OTHER> other,
TwoInputBroadcastStreamProcessFunction<T_OTHER, T, OUT> processFunction) {
// no state redistribution mode check is required here, since al... | @Test
void testConnectNonKeyedStream() throws Exception {
ExecutionEnvironmentImpl env = StreamTestUtils.getEnv();
BroadcastStreamImpl<Integer> stream =
new BroadcastStreamImpl<>(env, new TestingTransformation<>("t1", Types.INT, 1));
NonKeyedPartitionStreamImpl<Long> nonKeyed... |
@Override
public ConnectorPageSource createPageSource(
ConnectorTransactionHandle transaction,
ConnectorSession session,
ConnectorSplit split,
ConnectorTableLayoutHandle layout,
List<ColumnHandle> columns,
SplitContext splitContext,
... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Not all columns are of 'AGGREGATED' type")
public void testFailsWhenMixOfAggregatedAndRegularColumns()
{
HivePageSourceProvider pageSourceProvider = createPageSourceProvider();
pageSourceProvider.create... |
public static boolean startsWith(final CharSequence str, final CharSequence prefix) {
return startsWith(str, prefix, false);
} | @Test
void testStartsWith() {
assertTrue(StringUtils.startsWith(null, null));
assertFalse(StringUtils.startsWith(null, "abc"));
assertFalse(StringUtils.startsWith("abcdef", null));
assertTrue(StringUtils.startsWith("abcdef", "abc"));
assertFalse(StringUtils.startsWith("ABCDEF... |
@Override
public String getMethod() {
return davMethod;
} | @Test
public void testGetMethod() throws URISyntaxException {
for (String method : VALID_METHODS) {
HttpRequestBase request = new HttpWebdav(method, new URI(
"http://example.com"));
Assertions.assertEquals(method, request.getMethod());
}
} |
static int validatePubsubMessageSize(PubsubMessage message, int maxPublishBatchSize)
throws SizeLimitExceededException {
int payloadSize = message.getPayload().length;
if (payloadSize > PUBSUB_MESSAGE_DATA_MAX_BYTES) {
throw new SizeLimitExceededException(
"Pubsub message data field of len... | @Test
public void testValidatePubsubMessageSizePayloadPlusAttributesTooLarge() {
byte[] data = new byte[(10 << 20)];
String attributeKey = "key";
String attributeValue = "value";
Map<String, String> attributes = ImmutableMap.of(attributeKey, attributeValue);
PubsubMessage message = new PubsubMessa... |
@Override
public Result detect(ChannelBuffer in) {
int prefaceLen = clientPrefaceString.readableBytes();
int bytesRead = min(in.readableBytes(), prefaceLen);
// If the input so far doesn't match the preface, break the connection.
if (bytesRead == 0 || !ChannelBuffers.prefixEquals(in... | @Test
void testDetect() {
ProtocolDetector detector = new Http2ProtocolDetector();
ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
ByteBuf connectionPrefaceBuf = Http2CodecUtil.connectionPrefaceBuf();
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
... |
public static String encodeHexStr(byte[] data) {
return encodeHexStr(data, true);
} | @Test
public void issueI50MI6Test(){
final String s = HexUtil.encodeHexStr("烟".getBytes(StandardCharsets.UTF_16BE));
assertEquals("70df", s);
} |
public void replay(
ConsumerGroupMemberMetadataKey key,
ConsumerGroupMemberMetadataValue value
) {
String groupId = key.groupId();
String memberId = key.memberId();
ConsumerGroup consumerGroup = getOrMaybeCreatePersistedConsumerGroup(groupId, value != null);
Set<Stri... | @Test
public void testOnConsumerGroupStateTransitionOnLoading() {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
// Even if there are more group epoch records loaded than tombstone records, the last replayed record
// (tombstone... |
@Override
synchronized public void close() {
if (stream != null) {
IOUtils.cleanupWithLogger(LOG, stream);
stream = null;
}
} | @Test(timeout=120000)
public void testRandomLong() throws Exception {
OsSecureRandom random = getOsSecureRandom();
long rand1 = random.nextLong();
long rand2 = random.nextLong();
while (rand1 == rand2) {
rand2 = random.nextLong();
}
random.close();
} |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SessionCredentials other = (SessionCredentials) obj;
if (accessKey == null) {
... | @Test
public void equalsTest() {
SessionCredentials sessionCredentials = new SessionCredentials("RocketMQ","12345678");
sessionCredentials.setSecurityToken("abcd");
SessionCredentials other = new SessionCredentials("RocketMQ","12345678","abcd");
Assert.assertTrue(sessionCredentials.e... |
public void setup(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to setup internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final Map<String, Map<String, String>> streamsSideTopicCo... | @Test
public void shouldThrowTimeoutExceptionWhenFuturesNeverCompleteDuringSetup() {
final AdminClient admin = mock(AdminClient.class);
final MockTime time = new MockTime(
(Integer) config.get(StreamsConfig.consumerPrefix(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG)) / 3
);
... |
public static <T> List<List<T>> splitBySize(List<T> list, int expectedSize)
throws NullPointerException, IllegalArgumentException {
Preconditions.checkNotNull(list, "list must not be null");
Preconditions.checkArgument(expectedSize > 0, "expectedSize must larger than 0");
if (1 == e... | @Test
public void testSplitBySizeWithEmptyList() {
List<Integer> lists = Lists.newArrayList();
int expectSize = 10;
List<List<Integer>> splitLists = ListUtil.splitBySize(lists, expectSize);
Assert.assertEquals(splitLists.size(), lists.size());
} |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
try {
if (statement.getStatement() instanceof CreateAsSelect) {
registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement);
... | @Test
public void shouldNotPlanQueryOnOriginalExecutionContext() {
// Given:
givenStatement("CREATE STREAM sink WITH(value_format='AVRO') AS SELECT * FROM SOURCE;");
// When:
injector.inject(statement);
// Then:
verify(executionContext, Mockito.never()).plan(any(), any(ConfiguredStatement.cl... |
@Override
protected void flush(MessageTuple item) {
prepare(item);
channel.flush();
} | @Test
public void testFlush() {
Object message = new Object();
NettyBatchWriteQueue.MessageTuple messageTuple = new NettyBatchWriteQueue.MessageTuple(message,
mockChannelPromise);
nettyBatchWriteQueue.flush(messageTuple);
Mockito.verify(mockChannel).write(eq(message), eq... |
@Override
public NacosUser authenticate(String username, String rawPassword) throws AccessException {
if (StringUtils.isBlank(username) || StringUtils.isBlank(rawPassword)) {
throw new AccessException("user not found!");
}
NacosUserDetails nacosUserDetails = (NacosUserDetails) us... | @Test
void testAuthenticate7() throws AccessException {
NacosUser nacosUser = new NacosUser();
when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser);
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
mockHttpServletRequest.addHeader(... |
public int getInt(int rowId, int colId) {
return ((IntColumnVector) columns[colId]).getInt(rowId);
} | @Test
void testDictionary() {
// all null
HeapIntVector col = new HeapIntVector(VECTOR_SIZE);
Integer[] dict = new Integer[2];
dict[0] = 1998;
dict[1] = 9998;
col.setDictionary(new ColumnVectorTest.TestDictionary(dict));
HeapIntVector heapIntVector = col.reser... |
static void checkManifestPlatform(
BuildContext buildContext, ContainerConfigurationTemplate containerConfig)
throws PlatformNotFoundInBaseImageException {
Optional<Path> path = buildContext.getBaseImageConfiguration().getTarPath();
String baseImageName =
path.map(Path::toString)
... | @Test
public void testCheckManifestPlatform_mismatch() {
Mockito.when(containerConfig.getPlatforms())
.thenReturn(ImmutableSet.of(new Platform("configured arch", "configured OS")));
ContainerConfigurationTemplate containerConfigJson = new ContainerConfigurationTemplate();
containerConfigJson.setA... |
public FEELFnResult<Boolean> invoke(@ParameterName( "point" ) Comparable point, @ParameterName( "range" ) Range range) {
if ( point == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null"));
}
if ( range == null ) {
ret... | @Test
void invokeParamsCantBeCompared() {
FunctionTestUtil.assertResultError( duringFunction.invoke(
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ),
new RangeImpl( Range.RangeBoundary.CLOSED, 1, 2, Range.RangeBoundary.CLOSED ) ), InvalidPar... |
public static double regularizedIncompleteGamma(double s, double x) {
if (s < 0.0) {
throw new IllegalArgumentException("Invalid s: " + s);
}
if (x < 0.0) {
throw new IllegalArgumentException("Invalid x: " + x);
}
double igf;
if (x < s + 1.0) {
... | @Test
public void testIncompleteGamma() {
System.out.println("incompleteGamma");
assertEquals(0.7807, Gamma.regularizedIncompleteGamma(2.1, 3), 1E-4);
assertEquals(0.3504, Gamma.regularizedIncompleteGamma(3, 2.1), 1E-4);
} |
public static Version of(int major, int minor) {
if (major == UNKNOWN_VERSION && minor == UNKNOWN_VERSION) {
return UNKNOWN;
} else {
return new Version(major, minor);
}
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void construct_withOverflowingMinor() {
Version.of(1, Byte.MAX_VALUE + 1);
} |
@Override
public boolean localMember() {
return localMember;
} | @Test
public void testConstructor_withLocalMember_isTrue() {
MemberImpl member = new MemberImpl(address, MemberVersion.of("3.8.0"), true);
assertBasicMemberImplFields(member);
assertTrue(member.localMember());
} |
@Override
public void startBundle() {
// This can contain user code. Wrap it in case it throws an exception.
try {
invoker.invokeStartBundle(new DoFnStartBundleArgumentProvider());
} catch (Throwable t) {
// Exception in user code.
throw wrapUserCodeException(t);
}
} | @Test
public void testStartBundleExceptionsWrappedAsUserCodeException() {
ThrowingDoFn fn = new ThrowingDoFn();
DoFnRunner<String, String> runner =
new SimpleDoFnRunner<>(
null,
fn,
NullSideInputReader.empty(),
null,
null,
Collect... |
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
return criterionValue1.isGreaterThan(criterionValue2);
} | @Test
public void betterThan() {
AnalysisCriterion criterion = getCriterion();
assertTrue(criterion.betterThan(numOf(5000), numOf(4500)));
assertFalse(criterion.betterThan(numOf(4500), numOf(5000)));
} |
@Override
public void registerRemote(RemoteInstance remoteInstance) throws ServiceRegisterException {
if (needUsingInternalAddr()) {
remoteInstance = new RemoteInstance(
new Address(config.getInternalComHost(), config.getInternalComPort(), true));
}
this.selfAddre... | @Test
public void registerRemote() {
registerRemote(remoteAddress);
} |
public int deleteExpiredFileByOffset(long offset, int unitSize) {
Object[] mfs = this.copyMappedFiles(0);
List<MappedFile> files = new ArrayList<>();
int deleteCount = 0;
if (null != mfs) {
int mfsLength = mfs.length - 1;
for (int i = 0; i < mfsLength; i++) {
... | @Test
public void testDeleteExpiredFileByOffset() {
MappedFileQueue mappedFileQueue =
new MappedFileQueue(storePath + File.separator + "e/", 5120, null);
for (int i = 0; i < 2048; i++) {
MappedFile mappedFile = mappedFileQueue.getLastMappedFile(0);
assertThat(map... |
@Nonnull
@Override
public List<DataConnectionResource> listResources() {
try {
try (Connection connection = getConnection()) {
DatabaseMetaData databaseMetaData = connection.getMetaData();
ResourceReader reader = new ResourceReader();
switch (... | @Test
public void list_resources_should_return_table_in_schema() throws Exception {
jdbcDataConnection = new JdbcDataConnection(SHARED_DATA_CONNECTION_CONFIG);
executeJdbc(JDBC_URL_SHARED, "CREATE SCHEMA MY_SCHEMA");
executeJdbc(JDBC_URL_SHARED, "CREATE TABLE MY_SCHEMA.MY_TABLE (ID INT, NAM... |
@Override
public RemotingCommand processRequest(final ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final long beginTimeMills = this.brokerController.getMessageStore().now();
request.addExtFieldIfNotExist(BORN_TIME, String.valueOf(System.currentTimeMil... | @Test
public void testProcessRequest_MsgWasRemoving() throws RemotingCommandException {
GetMessageResult getMessageResult = createGetMessageResult(1);
getMessageResult.setStatus(GetMessageStatus.MESSAGE_WAS_REMOVING);
when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConf... |
public static <T> Collection<T> checkedSubTypeCast(
Collection<? super T> collection, Class<T> subTypeClass) {
for (Object o : collection) {
// probe each object, will throw ClassCastException on mismatch.
subTypeClass.cast(o);
}
return subTypeCast(collection)... | @Test
void testCheckedSubTypeCast() {
List<A> list = new ArrayList<>();
B b = new B();
C c = new C();
list.add(b);
list.add(c);
list.add(null);
Collection<B> castSuccess = CollectionUtil.checkedSubTypeCast(list, B.class);
Iterator<B> iterator = castSuc... |
public static void writeEmptyHeader(ByteBuffer buffer,
byte magic,
long producerId,
short producerEpoch,
int baseSequence,
... | @Test
public void testWriteEmptyHeader() {
long producerId = 23423L;
short producerEpoch = 145;
int baseSequence = 983;
long baseOffset = 15L;
long lastOffset = 37;
int partitionLeaderEpoch = 15;
long timestamp = System.currentTimeMillis();
for (Times... |
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isEmpty(args)) {
return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \... | @Test
void testInvokeByPassingEnumValue() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName());
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willRetur... |
static void checkNearCacheNativeMemoryConfig(InMemoryFormat inMemoryFormat, NativeMemoryConfig nativeMemoryConfig,
boolean isEnterprise) {
if (!isEnterprise) {
return;
}
if (inMemoryFormat != NATIVE) {
return;
}
... | @Test
public void checkNearCacheNativeMemoryConfig_shouldNotNeedNativeMemoryConfig_BINARY_onOS() {
checkNearCacheNativeMemoryConfig(BINARY, null, false);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.