focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static List<HollowSchema> dependencyOrderedSchemaList(HollowDataset dataset) {
return dependencyOrderedSchemaList(dataset.getSchemas());
} | @Test
public void sortsSchemasEvenIfDependencyTypesNotPresent() throws IOException {
String schemasText = "TypeA { TypeB b; }"
+ "TypeB { TypeC c; }";
List<HollowSchema> schemas = HollowSchemaParser.parseCollectionOfSchemas(schemasText);
... |
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, Retry retry, String methodName)
throws Throwable {
RetryTransformer<?> retryTransformer = RetryTransformer.of(retry);
Object returnValue = proceedingJoinPoint.proceed();
return executeRxJava2Aspect(retryTransform... | @Test
public void testReactorTypes() throws Throwable {
Retry retry = Retry.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(rxJava2RetryAspectExt.handle(proceedingJoinPoint, retry, "testMethod"))
.isNotNull();
when(pro... |
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> loadedClass = findLoadedClass(name);
if (loadedClass != null) {
return loadedClass;
}
if (isClosed) {
throw new ClassNotFoun... | @Test
public void shouldHandleMethodsReturningArray() throws Exception {
Class<?> exampleClass = loadClass(AClassWithMethodReturningArray.class);
classHandler.valueToReturn = new String[] {"miao, mieuw"};
Method directMethod = exampleClass.getMethod("normalMethodReturningArray");
directMethod.setAcce... |
public void translate(Pipeline pipeline) {
this.flinkBatchEnv = null;
this.flinkStreamEnv = null;
final boolean hasUnboundedOutput =
PipelineTranslationModeOptimizer.hasUnboundedOutput(pipeline);
if (hasUnboundedOutput) {
LOG.info("Found unbounded PCollection. Switching to streaming execu... | @Test
public void testTranslationModeNoOverrideWithoutUnboundedSources() {
boolean[] testArgs = new boolean[] {true, false};
for (boolean streaming : testArgs) {
FlinkPipelineOptions options = getDefaultPipelineOptions();
options.setRunner(FlinkRunner.class);
options.setStreaming(streaming);... |
public void unregister(String pluginId) {
Assert.notNull(pluginId, "The pluginId must not be null.");
if (!pluginMappingInfo.containsKey(pluginId)) {
return;
}
pluginMappingInfo.remove(pluginId).forEach(this::unregisterMapping);
} | @Test
void unregister() {
UserController userController = mock(UserController.class);
// register handler methods first
handlerMapping.registerHandlerMethods("fakePlugin", userController);
assertThat(handlerMapping.getMappings("fakePlugin")).hasSize(1);
// unregister
... |
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (LDAPInputMeta) smi;
data = (LDAPInputData) sdi;
if ( super.init( smi, sdi ) ) {
data.rownr = 1L;
// Get multi valued field separator
data.multi_valuedFieldSeparator = environmentSubstitute( meta.getMultiValuedSe... | @Test
public void testRowProcessing() throws Exception {
//Setup step
LDAPInput ldapInput = new LDAPInput(
stepMockHelper.stepMeta, stepMockHelper.stepDataInterface,
0, stepMockHelper.transMeta, stepMockHelper.trans );
LDAPInputData data = new LDAPInputData();
LDAPInputMeta meta = mockMeta... |
@Override
public ResourceSet saveNew(ResourceSet rs) {
if (rs.getId() != null) {
throw new IllegalArgumentException("Can't save a new resource set with an ID already set to it.");
}
if (!checkScopeConsistency(rs)) {
throw new IllegalArgumentException("Can't save a resource set with inconsistent claims.")... | @Test(expected = IllegalArgumentException.class)
public void testSaveNew_hasId() {
ResourceSet rs = new ResourceSet();
rs.setId(1L);
resourceSetService.saveNew(rs);
} |
@Override public long get(long key1, int key2) {
return super.get0(key1, key2);
} | @Test
public void testGotoAddress() {
final long addr1 = hsa.address();
final SlotAssignmentResult slot = insert(1, 2);
hsa.gotoNew();
assertEquals(NULL_ADDRESS, hsa.get(1, 2));
hsa.gotoAddress(addr1);
assertEquals(slot.address(), hsa.get(1, 2));
} |
public void setApp(String app) {
this.app = app;
} | @Test
void testSetApp() {
assertEquals("unknown", basicContext.getApp());
basicContext.setApp("testApp");
assertEquals("testApp", basicContext.getApp());
} |
public static SSLFactory createSSLFactoryAndEnableAutoRenewalWhenUsingFileStores(TlsConfig tlsConfig) {
return createSSLFactoryAndEnableAutoRenewalWhenUsingFileStores(tlsConfig, () -> false);
} | @Test
public void createSSLFactoryAndEnableAutoRenewalWhenUsingFileStoresWithPinotInsecureMode()
throws IOException, URISyntaxException, InterruptedException {
TlsConfig tlsConfig = createTlsConfig();
SSLFactory sslFactory =
RenewableTlsUtils.createSSLFactoryAndEnableAutoRenewalWhenUsingFileStor... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void sendPhoto() {
Message message = bot.execute(new SendPhoto(chatId, photoFileId)).message();
MessageTest.checkMessage(message);
PhotoSizeTest.checkPhotos(false, message.photo());
message = bot.execute(new SendPhoto(chatId, imageFile).hasSpoiler(true)
... |
@Override
public int numPartitions() {
return numPartitions;
} | @Test
public void testNumPartitions() {
TopicMetadataImpl metadata = new TopicMetadataImpl(1234);
assertEquals(1234, metadata.numPartitions());
} |
static String determineFullyQualifiedClassName(Path baseDir, String basePackageName, Path classFile) {
String subpackageName = determineSubpackageName(baseDir, classFile);
String simpleClassName = determineSimpleClassName(classFile);
return of(basePackageName, subpackageName, simpleClassName)
... | @Test
void determineFullyQualifiedClassName() {
Path baseDir = Paths.get("path", "to", "com", "example", "app");
String basePackageName = "com.example.app";
Path classFile = Paths.get("path", "to", "com", "example", "app", "App.class");
String fqn = ClasspathSupport.determineFullyQua... |
public Page prependColumn(Block column)
{
if (column.getPositionCount() != positionCount) {
throw new IllegalArgumentException(String.format("Column does not have same position count (%s) as page (%s)", column.getPositionCount(), positionCount));
}
Block[] result = new Block[blo... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testPrependColumnWrongNumberOfRows()
{
int entries = 10;
BlockBuilder blockBuilder = BIGINT.createBlockBuilder(null, entries);
for (int i = 0; i < entries; i++) {
BIGINT.writeLong(blockBuilder, i);
... |
public void writeBytes(byte[] value) {
writeBytes(value, false);
} | @Test
public void testWriteBytes() {
byte[] first = {'a', 'b', 'c'};
byte[] second = {'d', 'e', 'f'};
byte[] last = {'x', 'y', 'z'};
OrderedCode orderedCode = new OrderedCode();
orderedCode.writeBytes(first);
byte[] firstEncoded = orderedCode.getEncodedBytes();
assertArrayEquals(orderedCod... |
@Override
public void handleRestRequest(RestRequest req, Map<String, String> wireAttrs, RequestContext requestContext,
TransportCallback<RestResponse> callback)
{
_transportDispatcher.handleRestRequest(req, wireAttrs, requestContext,
new RequestFinalizerTransportCallback<>(callback, requestContext... | @Test(dataProvider = "throwTransportCallbackException")
public void testHandleRestRequestOrdering(boolean throwTransportCallbackException)
{
when(_restTransportResponse.getResponse())
.thenReturn(_restResponse);
final TestTransportCallback<RestResponse> transportCallback = new TestTransportCallback... |
public QueueConfig setBackupCount(int backupCount) {
this.backupCount = checkBackupCount(backupCount, asyncBackupCount);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void setBackupCount_whenItsNegative() {
queueConfig.setBackupCount(-1);
} |
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
final CompositePropertySource compositePropertySource = new CompositePropertySource(
DynamicConstants.PROPERTY_NAME);
compositePropertySource
.addPropert... | @Test
public void locate() throws InterruptedException {
final SpringEnvironmentProcessor springEnvironmentProcessor = new SpringEnvironmentProcessor();
final MockEnvironment mockEnvironment = new MockEnvironment();
springEnvironmentProcessor.postProcessEnvironment(mockEnvironment, null);
... |
private boolean isConformRules(String serviceName) {
return serviceName.split(NAME_SEPARATOR, -1).length == 4;
} | @Test
void testIsConformRules() {
NamingService namingService = mock(NacosNamingService.class);
URL serviceUrlWithoutCategory = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface="
+ serviceInterface + "¬ify=false&methods=test1,test2&version=1.0.0&group=default... |
@Override
public FailoverSwitch getSwitch() {
try {
File switchFile = Paths.get(failoverDir, UtilAndComs.FAILOVER_SWITCH).toFile();
if (!switchFile.exists()) {
NAMING_LOGGER.debug("failover switch is not found, {}", switchFile.getName());
switchParams.... | @Test
void testGetSwitchForFailoverDisabledKeep() throws NoSuchFieldException, IllegalAccessException {
String dir = DiskFailoverDataSourceTest.class.getResource("/").getPath() + "/failover_test/disabled";
injectFailOverDir(dir);
assertFalse(dataSource.getSwitch().getEnabled());
asse... |
static String headerLine(CSVFormat csvFormat) {
return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader());
} | @Test
public void givenQuoteModeAll_isNoop() {
CSVFormat csvFormat = csvFormat().withQuoteMode(QuoteMode.ALL);
PCollection<String> input =
pipeline.apply(
Create.of(
headerLine(csvFormat),
"\"a\",\"1\",\"1.1\"",
"\"b\",\"2\",\"2.2\"",
... |
@Override
public boolean isNodeVersionCompatibleWith(Version clusterVersion) {
Preconditions.checkNotNull(clusterVersion);
return node.getVersion().asVersion().equals(clusterVersion);
} | @Test
public void test_nodeVersionCompatibleWith_ownClusterVersion() {
MemberVersion currentVersion = getNode(hazelcastInstance).getVersion();
assertTrue(nodeExtension.isNodeVersionCompatibleWith(currentVersion.asVersion()));
} |
@Override
public List<DatabaseTableRespVO> getDatabaseTableList(Long dataSourceConfigId, String name, String comment) {
List<TableInfo> tables = databaseTableService.getTableList(dataSourceConfigId, name, comment);
// 移除在 Codegen 中,已经存在的
Set<String> existsTables = convertSet(
... | @Test
public void testGetDatabaseTableList() {
// 准备参数
Long dataSourceConfigId = randomLongId();
String name = randomString();
String comment = randomString();
// mock 方法
TableInfo tableInfo01 = mock(TableInfo.class);
when(tableInfo01.getName()).thenReturn("t_... |
public static Trampoline<Integer> loop(int times, int prod) {
if (times == 0) {
return Trampoline.done(prod);
} else {
return Trampoline.more(() -> loop(times - 1, prod * times));
}
} | @Test
void testTrampolineWithFactorialFunction() {
long result = TrampolineApp.loop(10, 1).result();
assertEquals(3_628_800, result);
} |
@Override
public EdgeIteratorState edge(int nodeA, int nodeB) {
if (isFrozen())
throw new IllegalStateException("Cannot create edge if graph is already frozen");
if (nodeA == nodeB)
// Loop edges would only make sense if their attributes were the same for both 'directions',
... | @Test
public void setGetFlags() {
BaseGraph graph = createGHStorage();
EnumEncodedValue<RoadClass> rcEnc = encodingManager.getEnumEncodedValue(RoadClass.KEY, RoadClass.class);
EdgeIteratorState edge = graph.edge(0, 1).set(rcEnc, RoadClass.BRIDLEWAY);
assertEquals(RoadClass.BRIDLEWAY,... |
static void urlEncode(String str, StringBuilder sb) {
for (int idx = 0; idx < str.length(); ++idx) {
char c = str.charAt(idx);
if ('+' == c) {
sb.append("%2B");
} else if ('%' == c) {
sb.append("%25");
} else {
sb.ap... | @Test
void testUrlEncodePlus() {
// Arrange
final StringBuilder sb = new StringBuilder("????");
// Act
GroupKey.urlEncode("+", sb);
// Assert side effects
assertNotNull(sb);
assertEquals("????%2B", sb.toString());
} |
@Override
@SuppressWarnings("checkstyle:booleanexpressioncomplexity")
public int compareTo(MemberVersion otherVersion) {
// pack major-minor-patch to 3 least significant bytes of integer, then compare the integers
// even though major, minor & patch are not expected to be negative, masking makes... | @Test
public void testCompareTo() {
assertTrue(VERSION_3_8.compareTo(VERSION_3_8) == 0);
assertTrue(VERSION_3_8.compareTo(VERSION_3_8_1) < 0);
assertTrue(VERSION_3_8.compareTo(VERSION_3_8_2) < 0);
assertTrue(VERSION_3_8.compareTo(VERSION_3_9) < 0);
assertTrue(VERSION_3_9.com... |
public boolean commitOffsetsSync(Map<TopicPartition, OffsetAndMetadata> offsets, Timer timer) {
invokeCompletedOffsetCommitCallbacks();
if (offsets.isEmpty()) {
// We guarantee that the callbacks for all commitAsync() will be invoked when
// commitSync() completes, even if the u... | @Test
public void testCommitOffsetSyncCoordinatorDisconnected() {
client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE));
// sync commit with coordinator disconnected (should connect, get metadata, and then submit ... |
public static List<String> finalDestination(List<String> elements) {
if (isMagicPath(elements)) {
List<String> destDir = magicPathParents(elements);
List<String> children = magicPathChildren(elements);
checkArgument(!children.isEmpty(), "No path found under the prefix " +
MAGIC_PATH_PREF... | @Test
public void testFinalDestinationNoMagic() {
assertEquals(l("first", "2"),
finalDestination(l("first", "2")));
} |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldThrowOnTopicAuthorizationException() {
// Given:
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
allAndPseudoColumnNames(SCHEMA),
ImmutableList.of(
new LongLiteral(1L),
new StringLiteral("str"),
new StringLitera... |
public static void assertThatClassIsImmutable(Class<?> clazz) {
final ImmutableClassChecker checker = new ImmutableClassChecker();
if (!checker.isImmutableClass(clazz, false)) {
final Description toDescription = new StringDescription();
final Description mismatchDescription = new... | @Test
public void testNonFinalClass() throws Exception {
boolean gotException = false;
try {
assertThatClassIsImmutable(NonFinal.class);
} catch (AssertionError assertion) {
assertThat(assertion.getMessage(),
containsString("is not final"));
... |
@VisibleForTesting
void startKsql(final KsqlConfig ksqlConfigWithPort) {
cleanupOldState();
initialize(ksqlConfigWithPort);
} | @Test
public void shouldNotCreateLogStreamIfAutoCreateNotConfigured() {
// Given:
when(processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE))
.thenReturn(false);
// When:
app.startKsql(ksqlConfig);
// Then:
verify(ksqlResource, never()).handleKsqlStatements(
... |
@Override
public int hashCode() {
return Long.hashCode(toLong());
} | @Test
public void testHashCode() throws Exception {
assertEquals(Long.hashCode(MAC_ONOS_LONG), MAC_ONOS.hashCode());
} |
public static int lower(Integer orderSource, int offset) {
if (offset <= 0) {
throw new IllegalArgumentException("offset must be greater than 0");
}
if (orderSource == null) {
orderSource = Ordered.LOWEST_PRECEDENCE;
}
if (Ordered.LOWEST_PRECEDENCE - off... | @Test
public void test_lower() {
assertThat(OrderUtil.lower(1, 1)).isEqualTo(2);
assertThat(OrderUtil.lower(Ordered.LOWEST_PRECEDENCE - 1, 2)).isEqualTo(Ordered.LOWEST_PRECEDENCE);
assertThat(OrderUtil.lower(Ordered.LOWEST_PRECEDENCE, 1)).isEqualTo(Ordered.LOWEST_PRECEDENCE);
Assert... |
@Nonnull
public static <T> Sink<T> list(@Nonnull String listName) {
return fromProcessor("listSink(" + listName + ')', writeListP(listName));
} | @Test
public void when_setLocalParallelism_then_sinkHasIt() {
//Given
String sinkName = randomName();
int localParallelism = 5;
SinkStage stage = p
.readFrom(Sources.list(sinkName))
.writeTo(Sinks.list(sinkName));
//When
stage.setLocal... |
@Override
protected SchemaTransform from(Configuration configuration) {
return new JavaFilterTransform(configuration);
} | @Test
@Category(NeedsRunner.class)
public void testErrorHandling() {
Schema inputSchema = Schema.of(Schema.Field.of("s", Schema.FieldType.STRING));
PCollection<Row> input =
pipeline
.apply(
Create.of(
Row.withSchema(inputSchema).addValues("short").bui... |
public static void convertReadBasedSplittableDoFnsToPrimitiveReadsIfNecessary(Pipeline pipeline) {
if (!(ExperimentalOptions.hasExperiment(pipeline.getOptions(), "use_sdf_read")
|| ExperimentalOptions.hasExperiment(
pipeline.getOptions(), "use_unbounded_sdf_wrapper"))
|| Experime... | @Test
public void testConvertToPrimitiveReadsHappen() {
PipelineOptions deprecatedReadOptions = PipelineOptionsFactory.create();
deprecatedReadOptions.setRunner(CrashingRunner.class);
ExperimentalOptions.addExperiment(
deprecatedReadOptions.as(ExperimentalOptions.class), "use_deprecated_read");
... |
public static final void saveAttributesMap( DataNode dataNode, AttributesInterface attributesInterface )
throws KettleException {
saveAttributesMap( dataNode, attributesInterface, NODE_ATTRIBUTE_GROUPS );
} | @Test
public void testSaveAttributesMap_CustomTag_NullParameter() throws Exception {
try ( MockedStatic<AttributesMapUtil> mockedAttributesMapUtil = mockStatic( AttributesMapUtil.class ) ) {
mockedAttributesMapUtil.when( () -> AttributesMapUtil.saveAttributesMap( any( DataNode.class ),
any( Attribu... |
@Override
public String url(String remoteHost, String workingUrl) {
return String.format("%s/remoting/files/%s/%s/%s", remoteHost, workingUrl, ArtifactLogUtil.CRUISE_OUTPUT_FOLDER, ArtifactLogUtil.MD5_CHECKSUM_FILENAME);
} | @Test
public void shouldGenerateChecksumFileUrl() throws IOException {
String url = checksumFileHandler.url("http://foo/go", "cruise/1/stage/1/job");
assertThat(url, is("http://foo/go/remoting/files/cruise/1/stage/1/job/cruise-output/md5.checksum"));
} |
public Iterator<ReadRowsResponse> readRows()
{
List<ReadRowsResponse> readRowResponses = new ArrayList<>();
long readRowsCount = 0;
int retries = 0;
Iterator<ReadRowsResponse> serverResponses = fetchResponses(request);
while (serverResponses.hasNext()) {
try {
... | @Test
void testNoFailures()
{
MockResponsesBatch batch1 = new MockResponsesBatch();
batch1.addResponse(Storage.ReadRowsResponse.newBuilder().setRowCount(10).build());
batch1.addResponse(Storage.ReadRowsResponse.newBuilder().setRowCount(11).build());
// so we can run multiple tes... |
static boolean isLeaf(int nodeOrder, int depth) {
checkTrue(depth > 0, "Invalid depth: " + depth);
int leafLevel = depth - 1;
int numberOfNodes = getNumberOfNodes(depth);
int maxNodeOrder = numberOfNodes - 1;
checkTrue(nodeOrder >= 0 && nodeOrder <= maxNodeOrder, "Invalid nodeOrd... | @Test(expected = IllegalArgumentException.class)
public void testIsLeafThrowsOnNegativeNodeOrder() {
MerkleTreeUtil.isLeaf(-1, 3);
} |
public static FileSystem write(final FileSystem fs, final Path path,
final byte[] bytes) throws IOException {
Objects.requireNonNull(path);
Objects.requireNonNull(bytes);
try (FSDataOutputStream out = fs.createFile(path).overwrite(true).build()) {
out.write(bytes);
}
return fs;
} | @Test
public void testWriteBytesFileSystem() throws IOException {
URI uri = tmp.toURI();
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(uri, conf);
Path testPath = new Path(new Path(uri), "writebytes.out");
byte[] write = new byte[] {0x00, 0x01, 0x02, 0x03};
FileUti... |
@GetMapping(
path = "/api/-/search",
produces = MediaType.APPLICATION_JSON_VALUE
)
@CrossOrigin
@Operation(summary = "Search extensions via text entered by a user")
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "The search results are r... | @Test
public void testSearch() throws Exception {
var extVersions = mockSearch();
extVersions.forEach(extVersion -> Mockito.when(repositories.findLatestVersion(extVersion.getExtension(), null, false, true)).thenReturn(extVersion));
Mockito.when(repositories.findLatestVersions(extVersions.str... |
public static String replace(final String text, final String searchString, final String replacement) {
return replace(text, searchString, replacement, -1);
} | @Test
void testReplace() throws Exception {
assertThat(StringUtils.replace(null, "*", "*"), nullValue());
assertThat(StringUtils.replace("", "*", "*"), equalTo(""));
assertThat(StringUtils.replace("any", null, "*"), equalTo("any"));
assertThat(StringUtils.replace("any", "*", null), e... |
@Override
public String convert(String source) {
return source;
} | @Test
void testConvert() {
assertEquals("1", converter.convert("1"));
assertNull(converter.convert(null));
} |
public static String wrapWithMarkdownClassDiv(String html) {
return new StringBuilder()
.append("<div class=\"markdown-body\">\n")
.append(html)
.append("\n</div>")
.toString();
} | @Test
void testHeader() {
InterpreterResult r1 = md.interpret("# H1", null);
assertEquals(wrapWithMarkdownClassDiv("<h1>H1</h1>\n"), r1.message().get(0).getData());
InterpreterResult r2 = md.interpret("## H2", null);
assertEquals(wrapWithMarkdownClassDiv("<h2>H2</h2>\n"), r2.message().get(0).getData(... |
@Override
public ClientTransport getClientTransport(ClientTransportConfig config) {
ClientTransport transport = allTransports.get(config);
if (transport == null) {
transport = ExtensionLoaderFactory.getExtensionLoader(ClientTransport.class)
.getExtension(config.getContai... | @Test
public void getClientTransport() {
NotReusableClientTransportHolder holder = new NotReusableClientTransportHolder();
ClientTransportConfig config = new ClientTransportConfig();
config.setProviderInfo(new ProviderInfo().setHost("127.0.0.1").setPort(12222))
.setContainer("tes... |
@Override
public String getName() {
return "CodeMagic";
} | @Test
public void getName() {
assertThat(underTest.getName()).isEqualTo("CodeMagic");
} |
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
String subCommand = safeReadLine(reader);
boolean unknownSubCommand = false;
String param = reader.readLine();
String returnCommand = null;
try {
final String[] names;
... | @Test
public void testDirStatics() throws Exception {
String inputCommand = "s\n" + ExampleClass.class.getName() + "\ne\n";
assertTrue(gateway.getBindings().containsKey(target));
command.execute("d", new BufferedReader(new StringReader(inputCommand)), writer);
Set<String> methods = convertResponse(sWriter.toS... |
public static FlinkPod loadPodFromTemplateFile(
FlinkKubeClient kubeClient, File podTemplateFile, String mainContainerName) {
final KubernetesPod pod = kubeClient.loadPodFromTemplateFile(podTemplateFile);
final List<Container> otherContainers = new ArrayList<>();
Container mainContai... | @Test
void testLoadPodFromTemplateWithNonExistPathShouldFail() {
final String nonExistFile = "/path/of/non-exist.yaml";
final String msg = String.format("Pod template file %s does not exist.", nonExistFile);
assertThatThrownBy(
() ->
Ku... |
@GetMapping("/readiness")
public Result<String> readiness(HttpServletRequest request) {
ReadinessResult result = ModuleHealthCheckerHolder.getInstance().checkReadiness();
if (result.isSuccess()) {
return Result.success("ok");
}
return Result.failure(result.getResultMessag... | @Test
void testReadinessSuccess() throws Exception {
Mockito.when(configInfoPersistService.configInfoCount(any(String.class))).thenReturn(0);
Mockito.when(serverStatusManager.getServerStatus()).thenReturn(ServerStatus.UP);
Result<String> result = healthControllerV2.readiness(null);
... |
public static <T extends EurekaEndpoint> List<T> randomize(List<T> list) {
List<T> randomList = new ArrayList<>(list);
if (randomList.size() < 2) {
return randomList;
}
Collections.shuffle(randomList,ThreadLocalRandom.current());
return randomList;
} | @Test
public void testRandomizeReturnsACopyOfTheMethodParameter() throws Exception {
List<AwsEndpoint> firstList = SampleCluster.UsEast1a.builder().withServerPool(1).build();
List<AwsEndpoint> secondList = ResolverUtils.randomize(firstList);
assertThat(firstList, is(not(sam... |
@Override
public int hashCode() {
return Objects.hash(instance, scheme);
} | @Test
@DisplayName("test hashCode().")
public void test3() {
DefaultInstance instance1 = new DefaultInstance();
instance1.setId("test-1");
instance1.setProtocol("http");
PolarisServiceInstance polarisServiceInstance1 = new PolarisServiceInstance(instance1);
DefaultInstance instance2 = new DefaultInstance()... |
@Override
public void addSubscriber(Subscriber subscriber, Class<? extends Event> subscribeType) {
// Actually, do a classification based on the slowEvent type.
Class<? extends SlowEvent> subSlowEventType = (Class<? extends SlowEvent>) subscribeType;
// For stop waiting subscriber, see {@lin... | @Test
void testIgnoreExpiredEvent() throws InterruptedException {
MockSlowEvent1 mockSlowEvent1 = new MockSlowEvent1();
MockSlowEvent2 mockSlowEvent2 = new MockSlowEvent2();
defaultSharePublisher.addSubscriber(smartSubscriber1, MockSlowEvent1.class);
defaultSharePublisher.addSubscrib... |
public String getMode() {
return Integer.toString(toInteger(), 8);
} | @Test
public void testToMode() {
final Permission permission = new Permission(Permission.Action.read,
Permission.Action.none, Permission.Action.none);
assertEquals("400", permission.getMode());
} |
static CodecFactory getCodecFactory(JobConf job) {
CodecFactory factory = null;
if (FileOutputFormat.getCompressOutput(job)) {
int deflateLevel = job.getInt(DEFLATE_LEVEL_KEY, DEFAULT_DEFLATE_LEVEL);
int xzLevel = job.getInt(XZ_LEVEL_KEY, DEFAULT_XZ_LEVEL);
int zstdLevel = job.getInt(ZSTD_LEV... | @Test
void gZipCodecUsingHadoopClass() {
CodecFactory avroDeflateCodec = CodecFactory.fromString("deflate");
JobConf job = new JobConf();
job.set("mapred.output.compress", "true");
job.set("mapred.output.compression.codec", "org.apache.hadoop.io.compress.GZipCodec");
CodecFactory factory = AvroOu... |
@Override
public List<Container> allocateContainers(ResourceBlacklistRequest blackList,
List<ResourceRequest> oppResourceReqs,
ApplicationAttemptId applicationAttemptId,
OpportunisticContainerContext opportContext, long rmIdentifier,
String appSubmitter) throws YarnException {
// Update b... | @Test
public void testAllocationLatencyMetrics() throws Exception {
oppCntxt = spy(oppCntxt);
OpportunisticSchedulerMetrics metrics =
mock(OpportunisticSchedulerMetrics.class);
when(oppCntxt.getOppSchedulerMetrics()).thenReturn(metrics);
ResourceBlacklistRequest blacklistRequest =
Reso... |
public <T extends Instance> List<T> select(Selector selector, String consumerIp, List<T> providers) {
if (Objects.isNull(selector)) {
return providers;
}
SelectorContextBuilder selectorContextBuilder = contextBuilders.get(selector.getContextType());
if (Objects.isNull(selecto... | @Test
void testSelect() throws NacosException {
Selector selector = selectorManager.parseSelector("mock", "key=value");
Instance instance = new Instance();
instance.setIp("2.2.2.2");
List<Instance> providers = Collections.singletonList(instance);
List<Instance> insta... |
@Override
public void deleteSocialClient(Long id) {
// 校验存在
validateSocialClientExists(id);
// 删除
socialClientMapper.deleteById(id);
} | @Test
public void testDeleteSocialClient_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> socialClientService.deleteSocialClient(id), SOCIAL_CLIENT_NOT_EXISTS);
} |
public static TriggerStateMachine stateMachineForTrigger(RunnerApi.Trigger trigger) {
switch (trigger.getTriggerCase()) {
case AFTER_ALL:
return AfterAllStateMachine.of(
stateMachinesForTriggers(trigger.getAfterAll().getSubtriggersList()));
case AFTER_ANY:
return AfterFirstSt... | @Test
public void testRepeatedlyTranslation() {
RunnerApi.Trigger trigger =
RunnerApi.Trigger.newBuilder()
.setRepeat(RunnerApi.Trigger.Repeat.newBuilder().setSubtrigger(subtrigger1))
.build();
RepeatedlyStateMachine machine =
(RepeatedlyStateMachine) TriggerStateMachin... |
public static Map<String, String> getExternalResourceConfigurationKeys(
Configuration config, String suffix) {
final Set<String> resourceSet = getExternalResourceSet(config);
final Map<String, String> configKeysToResourceNameMap = new HashMap<>();
LOG.info("Enabled external resources... | @Test
public void testGetExternalResourceConfigurationKeysWithConfigKeyNotSpecifiedOrEmpty() {
final Configuration config = new Configuration();
final String resourceConfigKey = "";
config.set(ExternalResourceOptions.EXTERNAL_RESOURCE_LIST, RESOURCE_LIST);
config.setString(
... |
public static Set<String> parseDeployOutput(File buildResult) throws IOException {
try (Stream<String> linesStream = Files.lines(buildResult.toPath())) {
return parseDeployOutput(linesStream);
}
} | @Test
void testParseDeployOutputDetectsDeploymentWithAltRepository() {
assertThat(
DeployParser.parseDeployOutput(
Stream.of(
"[INFO] --- maven-deploy-plugin:2.8.2:deploy (default-deploy) @ flink-parent ---",
... |
@Override
public String pluginName() {
return PluginEnum.DIVIDE.getName();
} | @Test
public void pluginNamedTest() {
assertEquals(divideUpstreamDataHandler.pluginName(), PluginEnum.DIVIDE.getName());
} |
public static List<TimeSlot> split(TimeSlot timeSlot, SegmentInMinutes unit) {
TimeSlot normalizedSlot = normalizeToSegmentBoundaries(timeSlot, unit);
return new SlotToSegments().apply(normalizedSlot, unit);
} | @Test
void splittingIntoSegmentsWhenThereIsNoLeftover() {
//given
Instant start = Instant.parse("2023-09-09T00:00:00Z");
Instant end = Instant.parse("2023-09-09T01:00:00Z");
TimeSlot timeSlot = new TimeSlot(start, end);
//when
List<TimeSlot> segments = Segments.split... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldSupportMatchAndImplicitCastEnabled() {
// Given:
givenFunctions(
function(EXPECTED, -1, DOUBLE)
);
// When:
final KsqlFunction fun = udfIndex.getFunction(ImmutableList.of(SqlArgument.of(INTEGER)));
// Then:
assertThat(fun.name(), equalTo(EXPECTED));
... |
@Override
public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc,
boolean addFieldName, boolean addCr ) {
String retval = "";
String fieldname = v.getName();
int length = v.getLength();
int precision = v.getPrecision();
... | @Test
public void testGetFieldDefinition() throws Exception {
assertEquals( "FOO TIMESTAMP",
nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, true, false ) );
assertEquals( "TIMESTAMP",
nativeMeta.getFieldDefinition( new ValueMetaTimestamp( "FOO" ), "", "", false, fals... |
@Override
public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) {
final SchemaKStream<?> stream = getSource().buildStream(buildContext);
final List<ColumnName> keyColumnNames = getSchema().key().stream()
.map(Column::name)
.collect(Collectors.toList());
return stream.s... | @Test
public void shouldBuildSourceOnceWhenBeingBuilt() {
// When:
projectNode.buildStream(planBuildContext);
// Then:
verify(source, times(1)).buildStream(planBuildContext);
} |
@SuppressWarnings({"checkstyle:OperatorWrap"})
public static Optional<Task.Status> checkProgress(
Map<String, Task> realTaskMap,
WorkflowSummary summary,
WorkflowRuntimeOverview overview,
boolean isFinal) {
boolean allDone = true;
boolean isFailed = false; // highest order
boolean ... | @Test
public void testCheckProgressWithEmptyDag() {
Optional<Task.Status> actual =
TaskHelper.checkProgress(
Collections.emptyMap(), new WorkflowSummary(), new WorkflowRuntimeOverview(), true);
Assert.assertEquals(Task.Status.FAILED, actual.get());
} |
private Schema getSchema() {
try {
final String schemaString = getProperties().getProperty(SCHEMA);
if (schemaString == null) {
throw new ParquetEncodingException("Can not store relation in Parquet as the schema is unknown");
}
return Utils.getSchemaFromString(schemaString);
} ca... | @Test
public void testMultipleSchema() throws ExecException, Exception {
String out = "target/out";
int rows = 1000;
Properties props = new Properties();
props.setProperty("parquet.compression", "uncompressed");
props.setProperty("parquet.page.size", "1000");
PigServer pigServer = new PigServe... |
public AccessPrivilege getAccessPrivilege(InetAddress addr) {
return getAccessPrivilege(addr.getHostAddress(),
addr.getCanonicalHostName());
} | @Test
public void testWildcardRW() {
NfsExports matcher = new NfsExports(CacheSize, ExpirationPeriod, "* rw");
Assert.assertEquals(AccessPrivilege.READ_WRITE,
matcher.getAccessPrivilege(address1, hostname1));
} |
public T merge(T other) {
checkNotNull(other, "Cannot merge with null resources");
checkArgument(getClass() == other.getClass(), "Merge with different resource type");
checkArgument(name.equals(other.getName()), "Merge with different resource name");
return create(value.add(other.getVal... | @Test
void testMerge() {
final Resource v1 = new TestResource(0.1);
final Resource v2 = new TestResource(0.2);
assertTestResourceValueEquals(0.3, v1.merge(v2));
} |
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) {
OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers);
if (filteredOpenAPI == null) {
return filte... | @Test(description = "it should clone everything concurrently")
public void cloneEverythingConcurrent() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
ThreadGroup tg = new ThreadGroup("SpecFilterTest" + "|" + System.currentTimeMillis());
final Map<String, OpenAPI> fi... |
@Override
public SelType call(String methodName, SelType[] args) {
if ("min".equals(methodName) && args.length == 2) {
return SelLong.of(Math.min(((SelLong) args[0]).longVal(), ((SelLong) args[1]).longVal()));
} else if ("max".equals(methodName) && args.length == 2) {
return SelLong.of(Math.max(((... | @Test(expected = UnsupportedOperationException.class)
public void testInvalidCallArg() {
SelJavaMath.INSTANCE.call("random", new SelType[] {SelType.NULL});
} |
public Exception getException() {
if (exception != null) return exception;
try {
final Class<? extends Exception> exceptionClass = ReflectionUtils.toClass(getExceptionType());
if (getExceptionCauseType() != null) {
final Class<? extends Exception> exceptionCauseCl... | @Test
void getExceptionWithNestedException() {
final FailedState failedState = new FailedState("JobRunr message", new CustomException(new CustomException()));
assertThat(failedState.getException())
.isInstanceOf(CustomException.class)
.hasCauseInstanceOf(CustomExcept... |
public void setDestinationType(String destinationType) {
this.destinationType = destinationType;
} | @Test(timeout = 60000)
public void testInvalidDestinationTypeFailure() {
activationSpec.setDestinationType("foobar");
PropertyDescriptor[] expected = {destinationTypeProperty};
assertActivationSpecInvalid(expected);
} |
@Override
public ObjectNode encode(KubevirtApiConfig entity, CodecContext context) {
ObjectNode node = context.mapper().createObjectNode()
.put(SCHEME, entity.scheme().name())
.put(IP_ADDRESS, entity.ipAddress().toString())
.put(PORT, entity.port())
... | @Test
public void testKubevirtApiConfigEncode() {
KubevirtApiConfig config = DefaultKubevirtApiConfig.builder()
.scheme(HTTPS)
.ipAddress(IpAddress.valueOf("10.10.10.23"))
.port(6443)
.state(CONNECTED)
.token("token")
... |
@Override
public List<String> getColumnNames(Configuration conf) throws HiveJdbcDatabaseAccessException {
return getColumnMetadata(conf, ResultSetMetaData::getColumnName);
} | @Test
public void testGetColumnNames_starQuery() throws HiveJdbcDatabaseAccessException {
Configuration conf = buildConfiguration();
DatabaseAccessor accessor = DatabaseAccessorFactory.getAccessor(conf);
List<String> columnNames = accessor.getColumnNames(conf);
assertThat(columnNames, is(notNullValue... |
public static String getLocalHost() {
InetAddress address = getLocalAddress();
return address == null ? "localhost" : address.getHostName();
} | @Test
public void testGetLocalHost() {
assertThat(NetUtil.getLocalHost()).isNotNull();
} |
@GET
@Path("package")
public Response getAllPackageInfo() {
try {
return new JsonResponse<>(Response.Status.OK, "", helium.getAllPackageInfo()).build();
} catch (RuntimeException e) {
logger.error(e.getMessage(), e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR, e.getMes... | @Test
void testVisualizationPackageOrder() throws IOException {
CloseableHttpResponse get1 = httpGet("/helium/order/visualization");
assertThat(get1, isAllowed());
Map<String, Object> resp1 = gson.fromJson(EntityUtils.toString(get1.getEntity(), StandardCharsets.UTF_8),
new TypeToken<Map<String... |
static CommandLineOptions parse(Iterable<String> options) {
CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder();
List<String> expandedOptions = new ArrayList<>();
expandParamsFiles(options, expandedOptions);
Iterator<String> it = expandedOptions.iterator();
while (it.hasNext()) ... | @Test
public void paramsFile() throws IOException {
Path outer = testFolder.newFile("outer").toPath();
Path exit = testFolder.newFile("exit").toPath();
Path nested = testFolder.newFile("nested").toPath();
String[] args = {"--dry-run", "@" + exit, "L", "@" + outer, "Q"};
Files.write(exit, "--set-... |
private List<Slobrok> getSlobroks(DeployState deployState, TreeConfigProducer<AnyConfigProducer> parent, Element slobroksE) {
List<Slobrok> slobroks = new ArrayList<>();
if (slobroksE != null)
slobroks = getExplicitSlobrokSetup(deployState, parent, slobroksE);
return slobroks;
} | @Test
void testAdminServerOnly() {
Admin admin = buildAdmin(servicesAdminServerOnly());
assertEquals(1, admin.getSlobroks().size());
} |
public static List<Path> getQualifiedRemoteProvidedLibDirs(
org.apache.flink.configuration.Configuration configuration,
YarnConfiguration yarnConfiguration)
throws IOException {
return getRemoteSharedLibPaths(
configuration,
pathStr -> {
... | @Test
void testSharedLibIsNotRemotePathShouldThrowException() {
final String localLib = "file:///flink/sharedLib";
final Configuration flinkConfig = new Configuration();
flinkConfig.set(YarnConfigOptions.PROVIDED_LIB_DIRS, Collections.singletonList(localLib));
final String msg =
... |
public static int getLevenshteinDistance(final String s, final String t) {
checkNotNull(s);
checkNotNull(t);
// base cases
if (s.equals(t)) {
return 0;
}
if (s.length() == 0) {
return t.length();
}
if (t.length() == 0) {
return s.length();
}
// create two work... | @Test
public void testLevenshteinDistance() {
assertEquals(0, StringUtils.getLevenshteinDistance("", "")); // equal
assertEquals(3, StringUtils.getLevenshteinDistance("", "abc")); // first empty
assertEquals(3, StringUtils.getLevenshteinDistance("abc", "")); // second empty
assertEquals(5, StringUtils... |
public TopicRouteData queryTopicRouteData(String topic) {
TopicRouteData data = this.getAnExistTopicRouteData(topic);
if (data == null) {
this.updateTopicRouteInfoFromNameServer(topic);
data = this.getAnExistTopicRouteData(topic);
}
return data;
} | @Test
public void testQueryTopicRouteData() {
consumerTable.put(group, createMQConsumerInner());
topicRouteTable.put(topic, createTopicRouteData());
TopicRouteData actual = mqClientInstance.queryTopicRouteData(topic);
assertNotNull(actual);
assertNotNull(actual.getQueueDatas(... |
public static int compareVersions(String version1, String version2) {
ComparableVersion v1 = new ComparableVersion(version1);
ComparableVersion v2 = new ComparableVersion(version2);
return v1.compareTo(v2);
} | @Test
public void testCompareVersions() {
// Equal versions are equal.
assertEquals(0, VersionUtil.compareVersions("2.0.0", "2.0.0"));
assertEquals(0, VersionUtil.compareVersions("2.0.0a", "2.0.0a"));
assertEquals(0, VersionUtil.compareVersions(
"2.0.0-SNAPSHOT", "2.0.0-SNAPSHOT"));
asser... |
@Override
public TTableDescriptor toThrift(List<ReferencedPartitionInfo> partitions) {
Preconditions.checkNotNull(partitions);
THdfsTable tHdfsTable = new THdfsTable();
tHdfsTable.setHdfs_base_dir(tableLocation);
// columns and partition columns
Set<String> partitionColumnN... | @Test
public void testCreateExternalTableWithStorageFormat(@Mocked MetadataMgr metadataMgr) throws Exception {
List<String> targetFormats = new ArrayList<>();
targetFormats.add("AVRO");
targetFormats.add("RCBINARY");
targetFormats.add("RCTEXT");
targetFormats.add("SEQUENCE")... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseStringListWithNullLastAsString() {
String str = "[1, null]";
SchemaAndValue result = Values.parseString(str);
assertEquals(Type.STRING, result.schema().type());
assertEquals(str, result.value());
} |
public static DecisionTree fit(Formula formula, DataFrame data) {
return fit(formula, data, new Properties());
} | @Test
public void testBreastCancer() {
System.out.println("Breast Cancer");
MathEx.setSeed(19650218); // to get repeatable results.
ClassificationValidations<DecisionTree> result = CrossValidation.classification(10, BreastCancer.formula, BreastCancer.data,
(f, x) -> Decision... |
public int execute()
{
int executed = 0;
final long now = now();
sortIfNeeded();
Set<Ticket> cancelled = new HashSet<>();
for (Ticket ticket : this.tickets) {
if (now - ticket.start < ticket.delay) {
// tickets are ordered, not meeting the conditio... | @Test
public void testInvokedAfterReset()
{
long fullTimeout = 50;
testNotInvokedAfterResetHalfTime();
// Wait until the end
time.set(time.get() + fullTimeout);
int rc = tickets.execute();
assertThat(rc, is(1));
assertThat(invoked.get(), is(1));
} |
public static Env addEnvironment(String name) {
if (StringUtils.isBlank(name)) {
throw new RuntimeException("Cannot add a blank environment: " + "[" + name + "]");
}
name = getWellFormName(name);
if (STRING_ENV_MAP.containsKey(name)) {
// has been existed
logger.debug("{} already exis... | @Test(expected = RuntimeException.class)
public void testAddEnvironmentBlankString() {
Env.addEnvironment("");
} |
public static Statement sanitize(
final Statement node,
final MetaStore metaStore) {
return sanitize(node, metaStore, true);
} | @Test
public void shouldAllowDuplicateLambdaArgumentInSeparateExpression() {
// Given:
final Statement stmt = givenQuery(
"SELECT TRANSFORM_ARRAY(Col4, X => X + 5, (X,Y) => Y + 5) FROM TEST1;");
// When:
final Query result = (Query) AstSanitizer.sanitize(stmt, META_STORE);
// Then:
a... |
public String buildRealData(final ConditionData condition, final ServerWebExchange exchange) {
return ParameterDataFactory.builderData(condition.getParamType(), condition.getParamName(), exchange);
} | @Test
public void testBuildRealDataUriBranch() {
conditionData.setParamType(ParamTypeEnum.URI.getName());
assertEquals("/http", abstractMatchStrategy.buildRealData(conditionData, exchange));
} |
@Override
public T getContent() {
return content;
} | @Test
void getContent() {
String targetEngine = "targetEngine";
Object content = "content";
EfestoRedirectOutput retrieved = new EfestoRedirectOutput(modelLocalUriId, targetEngine, content) {};
assertThat(retrieved.getContent()).isEqualTo(content);
} |
@Override
public void write(InputT element, Context context) throws IOException, InterruptedException {
while (bufferedRequestEntries.size() >= maxBufferedRequests) {
flush();
}
addEntryToBuffer(elementConverter.apply(element, context), false);
nonBlockingFlush();
} | @Test
public void testFlushThresholdMetBeforeBatchLimitWillCreateASmallerBatchOfSizeAboveThreshold()
throws IOException, InterruptedException {
AsyncSinkWriterImpl sink =
new AsyncSinkWriterImplBuilder()
.context(sinkInitContext)
.m... |
public static byte[] computeHmac(final byte[] key, final String string)
throws SaslException {
Mac mac = createSha1Hmac(key);
mac.update(string.getBytes(StandardCharsets.UTF_8));
return mac.doFinal();
} | @Test
public void testComputeHmac2() throws Exception
{
// Setup test fixture.
final byte[] key = StringUtils.decodeHex("1d96ee3a529b5a5f9e47c01f229a2cb8a6e15f7d"); // 'salted password' from the test vectors.
final String value = "Server Key";
// Execute system under test.
... |
@VisibleForTesting
static JibContainerBuilder processCommonConfiguration(
RawConfiguration rawConfiguration,
InferredAuthProvider inferredAuthProvider,
ProjectProperties projectProperties)
throws InvalidFilesModificationTimeException, InvalidAppRootException,
IncompatibleBaseImageJav... | @Test
public void testEntrypoint()
throws InvalidImageReferenceException, IOException, MainClassInferenceException,
InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException,
InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException,
Numbe... |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowFunctionStatusStatement) {
return Optional.of(new ShowFunctionStatusExecutor((ShowFu... | @Test
void assertCreateWithSelectStatementFromInformationSchemaOfOtherTable() {
initProxyContext(Collections.emptyMap());
SimpleTableSegment tableSegment = new SimpleTableSegment(new TableNameSegment(10, 13, new IdentifierValue("CHARACTER_SETS")));
tableSegment.setOwner(new OwnerSegment(7, 8... |
@Override
public void loadGlue(Glue glue, List<URI> gluePaths) {
gluePaths.stream()
.filter(gluePath -> CLASSPATH_SCHEME.equals(gluePath.getScheme()))
.map(ClasspathSupport::packageName)
.map(classFinder::scanForClassesInPackage)
.flatMap(Colle... | @Test
void doesnt_save_anything_in_glue() {
GuiceBackend backend = new GuiceBackend(factory, classLoader);
backend.loadGlue(null, singletonList(URI.create("classpath:io/cucumber/guice/integration")));
verify(factory).addClass(YourInjectorSource.class);
} |
long snapshotsRetrieved() {
return snapshotsRetrieved.get();
} | @Test
public void metrics_are_not_refreshed_if_ttl_not_expired() {
assertEquals(0, nodeMetricsClient.snapshotsRetrieved());
updateSnapshot(defaultMetricsConsumerId, TTL);
assertEquals(1, nodeMetricsClient.snapshotsRetrieved());
updateSnapshot(defaultMetricsConsumerId, TTL);
a... |
@Override
@SuppressWarnings("unchecked")
public TypeSerializer<T> restoreSerializer() {
final int numFields = snapshotData.getFieldSerializerSnapshots().size();
final ArrayList<Field> restoredFields = new ArrayList<>(numFields);
final ArrayList<TypeSerializer<?>> restoredFieldSerializer... | @Test
void testRestoreSerializerWithRemovedFields() {
final PojoSerializerSnapshot<TestPojo> testSnapshot =
buildTestSnapshot(
Arrays.asList(
mockRemovedField(ID_FIELD),
NAME_FIELD,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.