focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
boolean needsMigration() {
File mappingFile = UserIdMapper.getConfigFile(usersDirectory);
if (mappingFile.exists() && mappingFile.isFile()) {
LOGGER.finest("User mapping file already exists. No migration needed.");
return false;
}
File[] userDirectories = listUser... | @Test
public void migrateUsersXml() throws IOException {
File usersDirectory = createTestDirectory(getClass(), name);
IdStrategy idStrategy = IdStrategy.CASE_INSENSITIVE;
UserIdMigrator migrator = new UserIdMigrator(usersDirectory, idStrategy);
TestUserIdMapper mapper = new TestUserI... |
@Override
public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer) {
return aggregate(initializer, Materialized.with(null, null));
} | @Test
public void slidingWindowAggregateOverlappingWindowsTest() {
final KTable<Windowed<String>, String> customers = groupedStream.cogroup(MockAggregator.TOSTRING_ADDER)
.windowedBy(SlidingWindows.withTimeDifferenceAndGrace(ofMillis(WINDOW_SIZE_MS), ofMillis(2000L))).aggregate(
... |
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final java.nio.file.Path p = session.toPath(file);
final Set<OpenOption> options = new HashSet<>();
options.... | @Test
public void testWriteTildeFilename() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancel... |
@Override
public KubevirtPort port(MacAddress mac) {
checkArgument(mac != null, ERR_NULL_PORT_MAC);
return kubevirtPortStore.port(mac);
} | @Test
public void testGetPortById() {
createBasicPorts();
assertNotNull("Port did not match", target.port(MacAddress.valueOf(PORT_MAC)));
} |
@Override
public SingleRuleConfiguration buildToBeCreatedRuleConfiguration(final LoadSingleTableStatement sqlStatement) {
SingleRuleConfiguration result = new SingleRuleConfiguration();
if (null != rule) {
result.getTables().addAll(rule.getConfiguration().getTables());
}
... | @Test
void assertUpdate() {
Collection<String> currentTables = new LinkedList<>(Collections.singletonList("ds_0.foo"));
SingleRuleConfiguration currentConfig = new SingleRuleConfiguration(currentTables, null);
LoadSingleTableStatement sqlStatement = new LoadSingleTableStatement(Collections.s... |
public static Class getJavaType(int sqlType) {
switch (sqlType) {
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
return String.class;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
... | @Test
public void testBasic() {
assertEquals(String.class, Util.getJavaType(Types.CHAR));
assertEquals(String.class, Util.getJavaType(Types.VARCHAR));
assertEquals(String.class, Util.getJavaType(Types.LONGVARCHAR));
assertEquals(byte[].class, Util.getJavaType(Types.BINARY));
... |
@NonNull
static String getImageUrl(List<FastDocumentFile> files, Uri folderUri) {
// look for special file names
for (String iconLocation : PREFERRED_FEED_IMAGE_FILENAMES) {
for (FastDocumentFile file : files) {
if (iconLocation.equals(file.getName())) {
... | @Test
public void testGetImageUrl_OtherImageFilenameUnsupportedMimeType() {
List<FastDocumentFile> folder = Arrays.asList(mockDocumentFile("audio.mp3", "audio/mp3"),
mockDocumentFile("my-image.svg", "image/svg+xml"));
String imageUrl = LocalFeedUpdater.getImageUrl(folder, Uri.EMPTY);... |
@Override
public Object evaluate(final Map<String, Object> requestData, final PMMLRuntimeContext pmmlContext) {
throw new KiePMMLException("KiePMMLMiningModel is not meant to be used for actual evaluation");
} | @Test
void evaluate() {
assertThatExceptionOfType(KiePMMLException.class).isThrownBy(() -> {
KIE_PMML_MINING_MODEL.evaluate(Collections.EMPTY_MAP, new PMMLRuntimeContextTest());
});
} |
public static List<SubscriptionItem> readFrom(
final InputStream in, @Nullable final ImportExportEventListener eventListener)
throws InvalidSourceException {
if (in == null) {
throw new InvalidSourceException("input is null");
}
final List<SubscriptionItem> c... | @Test
public void testEmptySource() throws Exception {
final String emptySource =
"{\"app_version\":\"0.11.6\",\"app_version_int\": 47,\"subscriptions\":[]}";
final List<SubscriptionItem> items = ImportExportJsonHelper.readFrom(
new ByteArrayInputStream(emptySource.g... |
@Override
public void process(boolean validate, boolean documentsOnly) {
if (!validate) return;
String searchName = schema.getName();
Map<String, DataType> seenFields = new HashMap<>();
verifySearchAndDocFields(searchName, seenFields);
verifySummaryFields(searchName, seenFie... | @Test
void throws_exception_if_type_of_document_field_does_not_match_summary_field() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
Schema schema = createSearchWithDocument(DOCUMENT_NAME);
schema.setImportedFields(createSingleImportedField(IMPORTED_FIELD... |
@Bean
public ShenyuPlugin wafPlugin() {
return new WafPlugin();
} | @Test
public void testWafPlugin() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(WafPluginConfiguration.class))
.withBean(WafPluginConfigurationTest.class)
.withPropertyValues("debug=true")
.run(context -> {
ShenyuPlu... |
static <K, V> StateSerdes<K, V> prepareStoreSerde(final StateStoreContext context,
final String storeName,
final String changelogTopic,
final Serde<K> keySerd... | @Test
public void shouldPrepareStoreSerdeForProcessorContext() {
final Serde<String> keySerde = new Serdes.StringSerde();
final Serde<String> valueSerde = new Serdes.StringSerde();
final MockInternalNewProcessorContext<String, String> context = new MockInternalNewProcessorContext<>();
... |
public void initialize(Configuration config) throws YarnException {
setConf(config);
this.plugin.initPlugin(config);
// Try to diagnose FPGA
LOG.info("Trying to diagnose FPGA information ...");
if (!diagnose()) {
LOG.warn("Failed to pass FPGA devices diagnose");
}
} | @Test
public void testExecutablePathWhenFileIsEmpty()
throws YarnException {
conf.set(YarnConfiguration.NM_FPGA_PATH_TO_EXEC, "");
fpgaDiscoverer.initialize(conf);
assertEquals("configuration with empty string value, should use aocl",
"aocl", openclPlugin.getPathToExecutable());
} |
public static Configuration loadConfiguration(
String workingDirectory, Configuration dynamicParameters, Map<String, String> env) {
final Configuration configuration =
GlobalConfiguration.loadConfiguration(workingDirectory, dynamicParameters);
final String keytabPrincipal = ... | @Test
void testRestPortAndBindingPortSpecified() throws IOException {
final Configuration initialConfiguration = new Configuration();
final int port = 1337;
final String bindingPortRange = "1337-7331";
initialConfiguration.set(RestOptions.PORT, port);
initialConfiguration.set... |
@Override
public Iterable<RedisClusterNode> clusterGetNodes() {
return read(null, StringCodec.INSTANCE, CLUSTER_NODES);
} | @Test
public void testClusterGetNodes() {
Iterable<RedisClusterNode> nodes = connection.clusterGetNodes();
assertThat(nodes).hasSize(6);
for (RedisClusterNode redisClusterNode : nodes) {
assertThat(redisClusterNode.getLinkState()).isNotNull();
assertThat(redisClusterN... |
public char readWPChar() throws IOException {
int c = in.read();
if (c == -1) {
throw new EOFException();
}
return (char) c;
} | @Test
public void testReadChar() throws Exception {
try (WPInputStream wpInputStream = emptyWPStream()) {
wpInputStream.readWPChar();
fail("should have thrown EOF");
} catch (EOFException e) {
//swallow
}
} |
public static int optimalNumOfBits(long inputEntries, double fpp) {
int numBits = (int) (-inputEntries * Math.log(fpp) / (Math.log(2) * Math.log(2)));
return numBits;
} | @Test
void testBloomNumBits() {
assertThat(BloomFilter.optimalNumOfBits(0, 0)).isZero();
assertThat(BloomFilter.optimalNumOfBits(0, 0)).isZero();
assertThat(BloomFilter.optimalNumOfBits(0, 1)).isZero();
assertThat(BloomFilter.optimalNumOfBits(1, 1)).isZero();
assertThat(Bloom... |
public static String toDotString(Pipeline pipeline) {
final PipelineDotRenderer visitor = new PipelineDotRenderer();
visitor.begin();
pipeline.traverseTopologically(visitor);
visitor.end();
return visitor.dotBuilder.toString();
} | @Test
public void testEmptyPipeline() {
assertEquals(
"digraph {"
+ " rankdir=LR"
+ " subgraph cluster_0 {"
+ " label = \"\""
+ " }"
+ "}",
PipelineDotRenderer.toDotString(p).replaceAll(System.lineSeparator(), ""));
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(file.getType().contains(Path.Type.upload)) {
// Pending large file upload
final Wr... | @Test
public void testFind() throws Exception {
final B2VersionIdProvider fileid = new B2VersionIdProvider(session);
final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new Path(bucket, new AlphanumericRandomStringService().ran... |
@Override
public String toString() {
return "ConfigChangedEvent{" + "key='"
+ key + '\'' + ", group='"
+ group + '\'' + ", content='"
+ content + '\'' + ", changeType="
+ changeType + "} "
+ super.toString();
} | @Test
void testToString() {
ConfigChangedEvent event = new ConfigChangedEvent(KEY, GROUP, CONTENT);
assertNotNull(event.toString());
} |
@Override
public void afterRequest(long consumeTimeMs) {
baseStats(consumeTimeMs);
} | @Test
public void afterRequest() {
final InstanceStats stats = new InstanceStats();
long consumerMs = 100L;
stats.beforeRequest();
stats.afterRequest(consumerMs);
Assert.assertEquals(stats.getActiveRequests(), 0);
} |
static String getAbbreviation(Exception ex,
Integer statusCode,
String storageErrorMessage) {
String result = null;
for (RetryReasonCategory retryReasonCategory : rankedReasonCategories) {
final String abbreviation
= retryReasonCategory.captureAndGetAbbreviation(ex,
statusC... | @Test
public void testUnknownSocketException() {
Assertions.assertThat(RetryReason.getAbbreviation(new SocketException(), null, null)).isEqualTo(
SOCKET_EXCEPTION_ABBREVIATION
);
} |
@Override
public V get() throws InterruptedException, ExecutionException {
try {
return resolve(future.get());
} catch (HazelcastSerializationException e) {
throw new ExecutionException(e);
}
} | @Test(expected = ExecutionException.class)
public void test_get_Exception() throws Exception {
Throwable error = new Throwable();
Future<Object> future = new DelegatingCompletableFuture<>(serializationService, completedExceptionally(error));
future.get();
} |
public TreeMap<AggregationFunctionColumnPair, AggregationSpec> getAggregationSpecs() {
return _aggregationSpecs;
} | @Test
public void testUniqueAggregationSpecs() {
TreeMap<AggregationFunctionColumnPair, AggregationSpec> expected = new TreeMap<>();
expected.put(AggregationFunctionColumnPair.fromColumnName("count__*"), AggregationSpec.DEFAULT);
expected.put(AggregationFunctionColumnPair.fromColumnName("sum__dimX"), Aggr... |
@Override
public String toString() {
if (null != table && null != column) {
return String.format("database.table.column: '%s'.'%s'.'%s'", database, table, column);
}
if (null != table) {
return String.format("database.table: '%s'.'%s'", database, table);
}
... | @Test
void assertToStringForDatabaseIdentifier() {
assertThat(new SQLExceptionIdentifier("foo_db").toString(), is("database: 'foo_db'"));
} |
public static PDImageXObject createFromFileByExtension(File file, PDDocument doc) throws IOException
{
String name = file.getName();
int dot = name.lastIndexOf('.');
if (dot == -1)
{
throw new IllegalArgumentException("Image type not supported: " + name);
}
... | @Test
void testCreateFromFileByExtension() throws IOException, URISyntaxException
{
testCompareCreatedFileByExtensionWithCreatedByCCITTFactory("ccittg4.tif");
testCompareCreatedFileByExtensionWithCreatedByJPEGFactory("jpeg.jpg");
testCompareCreatedFileByExtensionWithCreatedByJPEGFactory... |
public static Configuration loadConfiguration(
String workingDirectory, Configuration dynamicParameters, Map<String, String> env) {
final Configuration configuration =
GlobalConfiguration.loadConfiguration(workingDirectory, dynamicParameters);
final String keytabPrincipal = ... | @Test
void testRestPortSpecified() throws IOException {
final Configuration initialConfiguration = new Configuration();
final int port = 1337;
initialConfiguration.set(RestOptions.PORT, port);
final Configuration configuration = loadConfiguration(initialConfiguration);
// i... |
static Reference<File> createBlobStorageDirectory(
Configuration configuration, @Nullable Reference<File> fallbackStorageDirectory)
throws IOException {
final String basePath = configuration.get(BlobServerOptions.STORAGE_DIRECTORY);
File baseDir = null;
if (StringUtils.i... | @Test
void testBlobUtilsFailIfNoStorageDirectoryIsSpecified() {
assertThatThrownBy(() -> BlobUtils.createBlobStorageDirectory(new Configuration(), null))
.isInstanceOf(IOException.class);
} |
@Override
public E computeIfAbsent(String key, Function<? super String, ? extends E> mappingFunction) {
try {
return cacheStore.invoke(key, new AtomicComputeProcessor<>(), mappingFunction);
} catch (EntryProcessorException e) {
throw new RuntimeException(e.getCause());
... | @Test
public void computeIfAbsent_cacheHit_mappingFunctionNotInvoked() {
doReturn(1).when(mutableEntryMock).getValue();
Function<String, Integer> mappingFunctionMock = Mockito.mock(Function.class);
entryProcessorMock = new CacheRegistryStore.AtomicComputeProcessor<>();
entryProcessor... |
@OnClose
public void onClose(final Session session) {
clearSession(session);
LOG.warn("websocket close on client[{}]", getClientIp(session));
} | @Test
public void testOnClose() {
websocketCollector.onOpen(session);
assertEquals(1L, getSessionSetSize());
doNothing().when(loggerSpy).warn(anyString(), anyString());
websocketCollector.onClose(session);
assertEquals(0L, getSessionSetSize());
assertNull(getSession()... |
@VisibleForTesting
static boolean checkHttpsStrictAndNotProvided(
HttpServletResponse resp, URI link, YarnConfiguration conf)
throws IOException {
String httpsPolicy = conf.get(
YarnConfiguration.RM_APPLICATION_HTTPS_POLICY,
YarnConfiguration.DEFAULT_RM_APPLICATION_HTTPS_POLICY);
b... | @Test
@Timeout(5000)
void testCheckHttpsStrictAndNotProvided() throws Exception {
HttpServletResponse resp = mock(HttpServletResponse.class);
StringWriter sw = new StringWriter();
when(resp.getWriter()).thenReturn(new PrintWriter(sw));
YarnConfiguration conf = new YarnConfiguration();
final URI ... |
@Override
public String getName() {
return this.jsonParser.getName();
} | @Test
public void testGetName() {
assertEquals("customParser", parserWrap.getName());
} |
@Override
public Local create(final Path file) {
return this.create(new UUIDRandomStringService().random(), file);
} | @Test
public void testTemporaryPathCustomPrefix() {
final Path file = new Path("/f1/f2/t.txt", EnumSet.of(Path.Type.file));
file.attributes().setDuplicate(true);
file.attributes().setVersionId("1");
final Local local = new DefaultTemporaryFileService().create("u", file);
asse... |
public boolean liveness() {
if (!Health.Status.GREEN.equals(dbConnectionNodeCheck.check().getStatus())) {
return false;
}
if (!Health.Status.GREEN.equals(webServerStatusNodeCheck.check().getStatus())) {
return false;
}
if (!Health.Status.GREEN.equals(ceStatusNodeCheck.check().getStatu... | @Test
public void fail_when_ce_check_fail() {
when(dbConnectionNodeCheck.check()).thenReturn(Health.GREEN);
when(webServerStatusNodeCheck.check()).thenReturn(Health.GREEN);
when(ceStatusNodeCheck.check()).thenReturn(RED);
Assertions.assertThat(underTest.liveness()).isFalse();
} |
static Map<String, ValueExtractor> instantiateExtractors(List<AttributeConfig> attributeConfigs,
ClassLoader classLoader) {
Map<String, ValueExtractor> extractors = createHashMap(attributeConfigs.size());
for (AttributeConfig config : attribut... | @Test
public void instantiate_extractors() {
// GIVEN
AttributeConfig iqExtractor
= new AttributeConfig("iq", "com.hazelcast.query.impl.getters.ExtractorHelperTest$IqExtractor");
AttributeConfig nameExtractor
= new AttributeConfig("name", "com.hazelcast.query.... |
@Override
public <T> @Nullable Schema schemaFor(TypeDescriptor<T> typeDescriptor) {
checkForDynamicType(typeDescriptor);
return ProtoSchemaTranslator.getSchema((Class<Message>) typeDescriptor.getRawType());
} | @Test
public void testOuterOneOfSchema() {
Schema schema = new ProtoMessageSchema().schemaFor(TypeDescriptor.of(OuterOneOf.class));
assertEquals(OUTER_ONEOF_SCHEMA, schema);
} |
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
while (in.readableBytes() >= 1 + MySQLBinlogEventHeader.MYSQL_BINLOG_EVENT_HEADER_LENGTH) {
in.markReaderIndex();
MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.c... | @Test
void assertBinlogEventHeaderIncomplete() {
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
byte[] completeData = StringUtil.decodeHexDump("002a80a862200100000038000000c569000000007400000000000100020004ff0801000000000000000100000007535543434553531c9580c5");
byteBuf.writeBytes(compl... |
public T add(String str) {
requireNonNull(str, JVM_OPTION_NOT_NULL_ERROR_MESSAGE);
String value = str.trim();
if (isInvalidOption(value)) {
throw new IllegalArgumentException("a JVM option can't be empty and must start with '-'");
}
checkMandatoryOptionOverwrite(value);
options.add(value);... | @Test
public void add_throws_MessageException_if_option_starts_with_prefix_of_mandatory_option_but_has_different_value() {
String[] optionOverrides = {
randomPrefix,
randomPrefix + randomAlphanumeric(1),
randomPrefix + randomAlphanumeric(2),
randomPrefix + randomAlphanumeric(3),
rand... |
public void validateMatcher() throws ValidationException {
validate(Validator.lengthValidator(255), getMatcher());
} | @Test
void shouldInvalidateMatcherMoreThan255Of() throws Exception {
user = new User("UserName", new String[]{onlyChars(200), onlyChars(55)}, "user@mail.com", true);
try {
user.validateMatcher();
fail("validator should capture the matcher");
} catch (ValidationExcepti... |
@Override
public <T> AsyncResult<T> startProcess(Callable<T> task) {
return startProcess(task, null);
} | @Test
void testNullTaskWithCallback() {
assertTimeout(ofMillis(3000), () -> {
// Instantiate a new executor and start a new 'null' task ...
final var executor = new ThreadAsyncExecutor();
final var asyncResult = executor.startProcess(null, callback);
assertNotNull(asyncResult, "The AsyncR... |
public synchronized void createTable(String tableId, Iterable<String> columnFamilies)
throws BigtableResourceManagerException {
createTable(tableId, columnFamilies, Duration.ofHours(1));
} | @Test
public void testCreateTableShouldNotCreateTableWhenTableAlreadyExists() {
when(bigtableResourceManagerClientFactory.bigtableTableAdminClient().exists(anyString()))
.thenReturn(true);
assertThrows(
BigtableResourceManagerException.class,
() -> testManager.createTable(TABLE_ID, Imm... |
public Value hexToByteDecode() throws KettleValueException {
setType( VALUE_TYPE_STRING );
if ( isNull() ) {
return this;
}
setValue( getString() );
String hexString = getString();
int len = hexString.length();
char[] chArray = new char[( len + 1 ) / 2];
boolean evenByte = true;... | @Test
public void testHexToByteDecode() throws KettleValueException {
Value vs1 = new Value( "Name1", Value.VALUE_TYPE_INTEGER );
vs1.setValue( "6120622063" );
vs1.hexToByteDecode();
assertEquals( "a b c", vs1.getString() );
vs1.setValue( "4161426243643039207A5A2E3F2F" );
vs1.hexToByteDecode... |
public synchronized <K, V> KStream<K, V> stream(final String topic) {
return stream(Collections.singleton(topic));
} | @Test
public void shouldThrowExceptionWhenNoTopicPresent() {
builder.stream(Collections.emptyList());
assertThrows(TopologyException.class, builder::build);
} |
@Override
public boolean acquirePermit(String nsId) {
if (contains(nsId)) {
return super.acquirePermit(nsId);
}
return super.acquirePermit(DEFAULT_NS);
} | @Test
public void testAllocationWithZeroProportion() {
Configuration conf = createConf(40);
conf.setDouble(DFS_ROUTER_FAIR_HANDLER_PROPORTION_KEY_PREFIX + "ns1", 0);
RouterRpcFairnessPolicyController routerRpcFairnessPolicyController =
FederationUtil.newFairnessPolicyController(conf);
// ns1 ... |
@Override
public Status check() {
if (applicationContext == null && applicationModel != null) {
SpringExtensionInjector springExtensionInjector = SpringExtensionInjector.get(applicationModel);
applicationContext = springExtensionInjector.getContext();
}
if (applicat... | @Test
void testGenericWebApplicationContext() {
GenericWebApplicationContext context = mock(GenericWebApplicationContext.class);
given(context.isRunning()).willReturn(true);
SpringStatusChecker checker = new SpringStatusChecker(context);
Status status = checker.check();
Asse... |
public static String secondToTime(int seconds) {
if (seconds < 0) {
throw new IllegalArgumentException("Seconds must be a positive number!");
}
int hour = seconds / 3600;
int other = seconds % 3600;
int minute = other / 60;
int second = other % 60;
final StringBuilder sb = new StringBuilder();
if (h... | @Test
public void secondToTimeTest() {
String time = DateUtil.secondToTime(3600);
assertEquals("01:00:00", time);
time = DateUtil.secondToTime(3800);
assertEquals("01:03:20", time);
time = DateUtil.secondToTime(0);
assertEquals("00:00:00", time);
time = DateUtil.secondToTime(30);
assertEquals("00:00:30... |
@Override
@CanIgnoreReturnValue
public Key register(Watchable watchable, Iterable<? extends WatchEvent.Kind<?>> eventTypes)
throws IOException {
JimfsPath path = checkWatchable(watchable);
Key key = super.register(path, eventTypes);
Snapshot snapshot = takeSnapshot(path);
synchronized (this... | @Test
public void testRegister_fileDoesNotExist() throws IOException {
try {
watcher.register(fs.getPath("/a/b/c"), ImmutableList.of(ENTRY_CREATE));
fail();
} catch (NoSuchFileException expected) {
}
} |
public static WindowedValueCoderComponents getWindowedValueCoderComponents(Coder coder) {
checkArgument(WINDOWED_VALUE_CODER_URN.equals(coder.getSpec().getUrn()));
return new AutoValue_ModelCoders_WindowedValueCoderComponents(
coder.getComponentCoderIds(0), coder.getComponentCoderIds(1));
} | @Test
public void windowedValueCoderComponentsWrongUrn() {
thrown.expect(IllegalArgumentException.class);
ModelCoders.getWindowedValueCoderComponents(
Coder.newBuilder()
.setSpec(FunctionSpec.newBuilder().setUrn(ModelCoders.LENGTH_PREFIX_CODER_URN))
.build());
} |
static JarFileWithEntryClass findOnlyEntryClass(Iterable<File> jarFiles) throws IOException {
List<JarFileWithEntryClass> jarsWithEntryClasses = new ArrayList<>();
for (File jarFile : jarFiles) {
findEntryClass(jarFile)
.ifPresent(
entryClass -... | @Test
void testFindOnlyEntryClassSingleJarWithNoManifest() {
assertThatThrownBy(
() -> {
File jarWithNoManifest = createJarFileWithManifest(ImmutableMap.of());
JarManifestParser.findOnlyEntryClass(
... |
@GetMapping("/search")
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.READ)
public List<String> searchRoles(@RequestParam String role) {
return roleService.findRolesLikeRoleName(role);
} | @Test
void testSearchRoles() {
List<String> test = new ArrayList<>();
when(roleService.findRolesLikeRoleName(anyString())).thenReturn(test);
List<String> list = roleController.searchRoles("test");
assertEquals(test, list);
} |
@Override
void toHtml() throws IOException {
writeHtmlHeader();
htmlCoreReport.toHtml();
writeHtmlFooter();
} | @SuppressWarnings("deprecation")
@Test
public void testCache() throws IOException {
final String cacheName = "test 1";
final CacheManager cacheManager = CacheManager.getInstance();
cacheManager.addCache(cacheName);
// test empty cache name in the cache keys link:
// cacheManager.addCache("") does nothing, b... |
abstract GenericUrl genericUrl(); | @Test
public void genericURLTest()
throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
String baseURL = "http://example.com";
HttpEventPublisher.Builder builder =
HttpEventPublisher.newBuilder()
.withUrl(baseURL)
.withToken("test-tok... |
@Override
public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args) throws Exception {
if (args.size() < 2) {
printInfo(err);
return 1;
}
int index = 0;
String input = args.get(index);
String option = "all";
if ("-o".equals(input)) {
option = args... | @Test
void repairAfterCorruptRecord() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "after", corruptRecordFile.getPath(), repairedFile.getPath());
assertTrue(output.contains("Number of blocks: 3 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records:... |
public static ResourceModel processResource(final Class<?> resourceClass)
{
return processResource(resourceClass, null);
} | @Test(description = "verifies return types of action resource methods", dataProvider = "actionReturnTypeData")
public void actionResourceMethodReturnTypes(final Class<?> resourceClass, final Class<?> expectedActionReturnType)
{
final ResourceModel model = RestLiAnnotationReader.processResource(resourceClass);
... |
public String toDataURI() {
return "data:" + contentType + ";base64," + data;
} | @Test
void convertsToDataUri() {
String encodedString = Base64.getEncoder().encodeToString("asdf".getBytes(StandardCharsets.UTF_8));
String dataURI = new Image("image/png", encodedString, "sha-256").toDataURI();
assertThat(dataURI, is("data:image/png;base64," + encodedString));
} |
Duration getLockAtLeastFor(AnnotationData annotation) {
return getValue(
annotation.getLockAtLeastFor(),
annotation.getLockAtLeastForString(),
this.defaultLockAtLeastFor,
"lockAtLeastForString");
} | @Test
public void shouldGetPositiveGracePeriodFromAnnotation() throws NoSuchMethodException {
noopResolver();
SpringLockConfigurationExtractor.AnnotationData annotation =
getAnnotation("annotatedMethodWithPositiveGracePeriod");
TemporalAmount gracePeriod = extractor.getLockAt... |
@Override
protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) {
zkClient.delete(getNodePath(metadataIdentifier));
} | @Test
void testDoRemoveMetadata() throws ExecutionException, InterruptedException {
String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService";
String version = "1.0.0";
String group = null;
String application = "etc-metadata-report-consumer... |
@Override
public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener)
throws NacosException {
group = StringUtils.isBlank(group) ? Constants.DEFAULT_GROUP : group.trim();
ConfigResponse configResponse = worker.getAgent()
.queryCo... | @Test
void testGetConfigAndSignListener() throws NacosException {
final String dataId = "1";
final String group = "2";
final String tenant = "";
final String content = "123";
final int timeout = 3000;
final Listener listener = new Listener() {
@Override
... |
@Override
public long localCount() {
return count(InputImpl.class, new BasicDBObject(MessageInput.FIELD_GLOBAL, false));
} | @Test
@MongoDBFixtures("InputServiceImplTest.json")
public void localCountReturnsNumberOfLocalInputs() {
assertThat(inputService.localCount()).isEqualTo(2);
} |
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> rule... | @Test
public void in_new_code_period_start_date_is_exclusive() {
long newCodePeriodStart = addDays(new Date(), -14).getTime();
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
SnapshotDto ... |
static String headerLine(CSVFormat csvFormat) {
return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader());
} | @Test
public void givenTrim_removesSpaces() {
CSVFormat csvFormat = csvFormat().withTrim(true);
PCollection<String> input =
pipeline.apply(
Create.of(
headerLine(csvFormat),
" a ,1,1.1",
"b, 2 ,2.2",
"c,3, 3.3 ... |
@SuppressWarnings("unchecked")
RestartRequest recordToRestartRequest(ConsumerRecord<String, byte[]> record, SchemaAndValue value) {
String connectorName = record.key().substring(RESTART_PREFIX.length());
if (!(value.value() instanceof Map)) {
log.error("Ignoring restart request because t... | @Test
public void testRecordToRestartRequestOnlyFailedInconsistent() {
ConsumerRecord<String, byte[]> record = new ConsumerRecord<>(TOPIC, 0, 0, 0L, TimestampType.CREATE_TIME, 0, 0, RESTART_CONNECTOR_KEYS.get(0),
CONFIGS_SERIALIZED.get(0), new RecordHeaders(), Optional.empty());
Stru... |
public static JibContainerBuilder toJibContainerBuilder(
ArtifactProcessor processor,
CommonCliOptions commonCliOptions,
CommonContainerConfigCliOptions commonContainerConfigCliOptions,
ConsoleLogger logger)
throws IOException, InvalidImageReferenceException {
String baseImage = common... | @Test
public void testToJibContainerBuilder_optionalParameters()
throws IOException, InvalidImageReferenceException {
when(mockCommonContainerConfigCliOptions.getFrom()).thenReturn(Optional.of("base-image"));
when(mockCommonContainerConfigCliOptions.getExposedPorts())
.thenReturn(ImmutableSet.of... |
public static <T extends Comparable<? super T>> Combine.Globally<T, T> globally() {
return Combine.globally(Min.<T>naturalOrder());
} | @Test
public void testDisplayData() {
Top.Reversed<Integer> comparer = new Top.Reversed<>();
Combine.Globally<Integer, Integer> min = Min.globally(comparer);
assertThat(DisplayData.from(min), hasDisplayItem("comparer", comparer.getClass()));
} |
@Override
public Product updateProductById(String productId, ProductUpdateRequest productUpdateRequest) {
checkProductNameUniqueness(productUpdateRequest.getName());
final ProductEntity productEntityToBeUpdate = productRepository
.findById(productId)
.orElseThrow(()... | @Test
void givenProductUpdateRequest_whenProductUpdated_thenReturnProduct() {
// Given
String productId = "1";
String newProductName = "New Product Name";
ProductUpdateRequest productUpdateRequest = ProductUpdateRequest.builder()
.name(newProductName)
... |
private void readUnknownFrame(ChannelHandlerContext ctx, ByteBuf payload,
Http2FrameListener listener) throws Http2Exception {
listener.onUnknownFrame(ctx, frameType, streamId, flags, payload);
} | @Test
public void readUnknownFrame() throws Http2Exception {
ByteBuf input = Unpooled.buffer();
ByteBuf payload = Unpooled.buffer();
try {
payload.writeByte(1);
writeFrameHeader(input, payload.readableBytes(), (byte) 0xff, new Http2Flags(), 0);
input.writ... |
public static GetAllResourceProfilesResponse mergeClusterResourceProfilesResponse(
Collection<GetAllResourceProfilesResponse> responses) {
GetAllResourceProfilesResponse profilesResponse =
Records.newRecord(GetAllResourceProfilesResponse.class);
Map<String, Resource> profilesMap = new HashMap<>();... | @Test
public void testMergeResourceProfiles() {
// normal response1
Map<String, Resource> profiles = new HashMap<>();
Resource resource1 = Resource.newInstance(1024, 1);
GetAllResourceProfilesResponse response1 = GetAllResourceProfilesResponse.newInstance();
profiles.put("maximum", resource1);
... |
static byte[] deriveMac(byte[] seed, int offset, int length) {
final MessageDigest md = DigestUtils.digest("SHA1");
md.update(seed, offset, length);
md.update(new byte[] {0, 0, 0, 2});
return Arrays.copyOfRange(md.digest(), 0, 16);
} | @Test
public void shouldDeriveMacKey() {
assertEquals(
"SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS",
ByteArrayUtils.prettyHex(TDEASecureMessaging.deriveMac(
Hex.decode("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"),0, 16)
)
);
} |
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
// Replacement is done separately for eac... | @Test
public void testReplaceAclEntries() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, USER, "bruce", ALL))
.add(aclEntry(ACCESS, GROUP, READ_EXECUTE))
.add(aclEntry(ACCESS, MASK, ALL))
.... |
@Override
public Mono<GetExpiringProfileKeyCredentialResponse> getExpiringProfileKeyCredential(
final GetExpiringProfileKeyCredentialAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
if (t... | @Test
void getExpiringProfileKeyCredentialProfileNotFound() {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final UUID targetUuid = UUID.randomUUID();
when(account.getUuid()).thenReturn(targetUuid);
when(account.getUnidentifiedAc... |
@Override
@NonNull
public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {
String sessionId = createSession(lockConfiguration);
return tryLock(sessionId, lockConfiguration);
} | @Test
void doesNotLockIfLockIsAlreadyObtained() {
mockLock(eq("naruto-leader"), false);
Optional<SimpleLock> lock = lockProvider.lock(lockConfig("naruto", SMALL_MIN_TTL, SMALL_MIN_TTL.dividedBy(2)));
assertThat(lock).isEmpty();
} |
private CompletionStage<RestResponse> putInCache(NettyRestResponse.Builder responseBuilder,
AdvancedCache<Object, Object> cache, Object key, byte[] data, Long ttl,
Long idleTime) {
Configuration config = Securi... | @Test
public void testIntegerKeysXmlToTextValues() {
Integer key = 123;
String keyContentType = "application/x-java-object;type=java.lang.Integer";
String valueContentType = "application/xml; charset=UTF-8";
String value = "<root>test</root>";
putInCache("default", key, keyContentType,... |
@Override
public Map<String, Histogram> getConnectorHistogramStatistics(Table table, List<String> columns) {
Preconditions.checkState(table != null);
List<ConnectorTableColumnKey> cacheKeys = new ArrayList<>();
for (String columnName : columns) {
cacheKeys.add(new ConnectorTable... | @Test
public void testGetConnectorHistogramStatistics(@Mocked AsyncLoadingCache<ConnectorTableColumnKey, Optional<Histogram>>
histogramCache) {
Table table = connectContext.getGlobalStateMgr().getMetadataMgr().getTable("hive0", "partitioned_db", "t1");
... |
public void validateUniverseDomain() throws IOException {
if (!(httpRequestInitializer instanceof HttpCredentialsAdapter)) {
return;
}
Credentials credentials = ((HttpCredentialsAdapter) httpRequestInitializer).getCredentials();
// No need for a null check as HttpCredentialsAdapter cannot be initi... | @Test
public void validateUniverseDomain_notUsingHttpCredentialsAdapter_defaultUniverseDomain()
throws IOException {
String rootUrl = "https://test.googleapis.com/";
String applicationName = "Test Application";
String servicePath = "test/";
AbstractGoogleClient client =
new MockGoogleCl... |
@Override
public String getMethod() {
return PATH;
} | @Test
public void testBanChatMemberWithEmptyChatId() {
BanChatMember banChatMember = BanChatMember
.builder()
.chatId("")
.userId(12345L)
.untilDate(1000)
.revokeMessages(true)
.build();
assertEquals("ban... |
@Override
public int compareTo(DateTimeStamp dateTimeStamp) {
return comparator.compare(this,dateTimeStamp);
} | @Test
void testCompareEqualsTimeStampWithoutDateTime() {
DateTimeStamp object1 = new DateTimeStamp(123);
DateTimeStamp object2 = new DateTimeStamp(123);
assertEquals(0, object2.compareTo(object1));
} |
public int tryClaim(final int msgTypeId, final int length)
{
checkTypeId(msgTypeId);
checkMsgLength(length);
final AtomicBuffer buffer = this.buffer;
final int recordLength = length + HEADER_LENGTH;
final int recordIndex = claimCapacity(buffer, recordLength);
if (IN... | @Test
void tryClaimShouldThrowIllegalArgumentExceptionIfLengthIsNegative()
{
assertThrows(IllegalArgumentException.class, () -> ringBuffer.tryClaim(MSG_TYPE_ID, -6));
} |
public static long getNumSector(String requestSize, String sectorSize) {
Double memSize = Double.parseDouble(requestSize);
Double sectorBytes = Double.parseDouble(sectorSize);
Double nSectors = memSize / sectorBytes;
Double memSizeKB = memSize / 1024;
Double memSizeGB = memSize / (1024 * 1024 * 1024... | @Test
public void getSectorTest100GB() {
String testRequestSize = "107374182400"; // 100GB
String testSectorSize = "512";
long result = HFSUtils.getNumSector(testRequestSize, testSectorSize);
assertEquals(212866577L, result); // 100GB/512B = 209715200
} |
@Override
public MaskRuleConfiguration buildToBeDroppedRuleConfiguration(final DropMaskRuleStatement sqlStatement) {
Collection<MaskTableRuleConfiguration> toBeDroppedTables = new LinkedList<>();
for (String each : sqlStatement.getTables()) {
toBeDroppedTables.add(new MaskTableRuleConfig... | @Test
void assertUpdateCurrentRuleConfiguration() {
MaskRuleConfiguration ruleConfig = createCurrentRuleConfiguration();
MaskRule rule = mock(MaskRule.class);
when(rule.getConfiguration()).thenReturn(ruleConfig);
executor.setRule(rule);
MaskRuleConfiguration toBeDroppedRuleCo... |
@Operation(
summary = "Monitor the given search keys in the key transparency log",
description = """
Enforced unauthenticated endpoint. Return proofs proving that the log tree
has been constructed correctly in later entries for each of the given search keys .
"""
)
@ApiResp... | @Test
void monitorSuccess() {
when(keyTransparencyServiceClient.monitor(any(), any(), any(), any()))
.thenReturn(CompletableFuture.completedFuture(TestRandomUtil.nextBytes(16)));
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/key-transparency/monitor")
.requ... |
@Override
public void run() {
// top-level command, do nothing
} | @Test
public void test_suspendJob_byJobId() {
// Given
Job job = newJob();
// When
run("suspend", job.getIdString());
// Then
assertThat(job).eventuallyHasStatus(JobStatus.SUSPENDED);
} |
@Override
public boolean commit() {
// TODO: add retry attempts
String name = Thread.currentThread().getName();
try {
for (ReplicationStateSync stateSync : replicationStateSyncList) {
Thread.currentThread().setName(stateSync.getClusterId());
LOG.info("starting sync for state " + stat... | @Test
public void testBasicGlobalCommit() throws Exception {
String commitTime = "100";
localCluster.createCOWTable(commitTime, 5, DB_NAME, TBL_NAME);
// simulate drs
remoteCluster.createCOWTable(commitTime, 5, DB_NAME, TBL_NAME);
HiveSyncGlobalCommitParams params = getGlobalCommitConfig(commitTim... |
@Override
public void close() {
try {
recoveryManagerService.stop();
// CHECKSTYLE:OFF
} catch (final Exception ex) {
// CHECKSTYLE:ON
throw new CloseTransactionManagerFailedException(ex);
}
recoveryManagerService.destroy();
cle... | @Test
void assertClose() throws Exception {
transactionManagerProvider.close();
verify(recoveryManagerService).stop();
verify(recoveryManagerService).destroy();
} |
private static void metricsConfig(XmlGenerator gen, Config config) {
MetricsConfig metricsConfig = config.getMetricsConfig();
gen.open("metrics", "enabled", metricsConfig.isEnabled())
.open("management-center", "enabled", metricsConfig.getManagementCenterConfig().isEnabled())
... | @Test
public void testMetricsConfig() {
Config config = new Config();
config.getMetricsConfig()
.setEnabled(false)
.setCollectionFrequencySeconds(10);
config.getMetricsConfig().getManagementCenterConfig()
.setEnabled(false)
.s... |
public static byte[] floatToBytesBE(float f, byte[] bytes, int off) {
return intToBytesBE(Float.floatToIntBits(f), bytes, off);
} | @Test
public void testFloatToBytesBE() {
assertArrayEquals(FLOAT_PI_BE ,
ByteUtils.floatToBytesBE((float) Math.PI, new byte[4], 0));
} |
public void transitionTo(ClassicGroupState groupState) {
assertValidTransition(groupState);
previousState = state;
state = groupState;
currentStateTimestamp = Optional.of(time.milliseconds());
metrics.onClassicGroupStateTransition(previousState, state);
} | @Test
public void testPreparingRebalanceToEmptyTransition() {
group.transitionTo(PREPARING_REBALANCE);
group.transitionTo(EMPTY);
assertState(group, EMPTY);
} |
@Override
public void deliverOperatorEventToCoordinator(
ExecutionAttemptID taskExecution, OperatorID operator, OperatorEvent evt)
throws FlinkException {
final StateWithExecutionGraph stateWithExecutionGraph =
state.as(StateWithExecutionGraph.class)
... | @Test
void testDeliverOperatorEventToCoordinatorFailsInIllegalState() throws Exception {
final AdaptiveScheduler scheduler =
new AdaptiveSchedulerBuilder(
createJobGraph(),
mainThreadExecutor,
EXE... |
public static KTableHolder<GenericKey> build(
final KGroupedStreamHolder groupedStream,
final StreamAggregate aggregate,
final RuntimeBuildContext buildContext,
final MaterializedFactory materializedFactory) {
return build(
groupedStream,
aggregate,
buildContext,
... | @Test
public void shouldBuildValueSerdeCorrectlyForWindowedAggregate() {
for (final Runnable given : given()) {
// Given:
clearInvocations(groupedStream, timeWindowedStream, sessionWindowedStream, aggregated, buildContext);
given.run();
// When:
windowedAggregate.build(planBuilder, ... |
public static String escape(String text) {
return encode(text);
} | @Test
public void escapeTest2() {
final char c = ' '; // 不断开空格(non-breaking space,缩写nbsp。)
assertEquals(c, 160);
final String html = "<html><body> </body></html>";
final String escape = HtmlUtil.escape(html);
assertEquals("<html><body> </body></html>", escape);
assertEquals(" "... |
static InetSocketAddress parse(
final String value, final String uriParamName, final boolean isReResolution, final NameResolver nameResolver)
{
if (Strings.isEmpty(value))
{
throw new NullPointerException("input string must not be null or empty");
}
final String ... | @Test
void shouldRejectOnMissingPort()
{
assertThrows(IllegalArgumentException.class, () -> SocketAddressParser.parse(
"192.168.1.20", ENDPOINT_PARAM_NAME, false, DEFAULT_RESOLVER));
} |
public static <T> PTransform<PCollection<T>, PCollection<Long>> globally() {
return Combine.globally(new CountFn<T>());
} | @Test
@Category(NeedsRunner.class)
public void testCountGloballyBasic() {
PCollection<String> input = p.apply(Create.of(WORDS));
PCollection<Long> output = input.apply(Count.globally());
PAssert.that(output).containsInAnyOrder(13L);
p.run();
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("brick.listing.chunksize"));
} | @Test
public void testListRootDefaultChunkSize() throws Exception {
final AttributedList<Path> list = new BrickListService(session).list(new Path("/", EnumSet.of(directory)), new DisabledListProgressListener());
assertNotSame(AttributedList.emptyList(), list);
} |
public static SerializableFunction<Row, TableRow> toTableRow() {
return ROW_TO_TABLE_ROW;
} | @Test
public void testToTableRow_flat() {
TableRow row = toTableRow().apply(FLAT_ROW);
assertThat(row.size(), equalTo(27));
assertThat(row, hasEntry("id", "123"));
assertThat(row, hasEntry("value", "123.456"));
assertThat(row, hasEntry("timestamp_variant1", "2019-08-16 13:52:07.000 UTC"));
as... |
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public void executeUpdate(final UnlockClusterStatement sqlStatement, final ContextManager contextManager) {
checkState(contextManager);
LockContext lockContext = contextManager.getComputeNodeInstanceContext().getLockContext();
Global... | @Test
void assertExecuteUpdateWithNotLockedCluster() {
ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
when(contextManager.getStateContext().getClusterState()).thenReturn(ClusterState.OK);
when(ProxyContext.getInstance().getContextManager()).thenReturn(context... |
@Override
public void setMonochrome(boolean monochrome) {
formats = monochrome ? monochrome() : ansi();
} | @Test
void should_print_table() {
Feature feature = TestFeatureParser.parse("path/test.feature", "" +
"Feature: Test feature\n" +
" Scenario: Test Scenario\n" +
" Given first step\n" +
" | key1 | key2 |\n" +
" ... |
public final Sensor clientLevelSensor(final String sensorName,
final RecordingLevel recordingLevel,
final Sensor... parents) {
synchronized (clientLevelSensors) {
final String fullSensorName = CLIENT_LEVEL_GROUP + SE... | @Test
public void shouldGetNewClientLevelSensor() {
final Metrics metrics = mock(Metrics.class);
final RecordingLevel recordingLevel = RecordingLevel.INFO;
setupGetNewSensorTest(metrics, recordingLevel);
final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, CLIENT... |
public void begin(InterpretationContext ec, String localName,
Attributes attributes) {
if ("substitutionProperty".equals(localName)) {
addWarn("[substitutionProperty] element has been deprecated. Please use the [property] element instead.");
}
String name = attributes.getValue(NAME_ATTRIBUTE);... | @Test
public void testFileNotLoaded() {
atts.setValue("file", "toto");
atts.setValue("value", "work");
propertyAction.begin(ec, null, atts);
assertEquals(1, context.getStatusManager().getCount());
assertTrue(checkError());
} |
public void shutdown() {
isShutdown = true;
responseHandlerSupplier.shutdown();
for (ClientInvocation invocation : invocations.values()) {
//connection manager and response handler threads are closed at this point.
invocation.notifyExceptionWithOwnedPermission(new Hazelc... | @Test
public void testInvokeUrgent_whenThereAreNoCompactSchemas_andClientIsNotInitializedOnCluster() {
UUID memberUuid = member.getLocalEndpoint().getUuid();
member.shutdown();
makeSureDisconnectedFromServer(client, memberUuid);
// No compact schemas, no need to check urgent invocat... |
@Override
public ListOffsetsResult listOffsets(Map<TopicPartition, OffsetSpec> topicPartitionOffsets,
ListOffsetsOptions options) {
AdminApiFuture.SimpleAdminApiFuture<TopicPartition, ListOffsetsResultInfo> future =
ListOffsetsHandler.newFuture(topicParti... | @Test
public void testListOffsetsEarliestLocalSpecMinVersion() throws Exception {
Node node = new Node(0, "localhost", 8120);
List<Node> nodes = Collections.singletonList(node);
List<PartitionInfo> pInfos = new ArrayList<>();
pInfos.add(new PartitionInfo("foo", 0, node, new Node[]{no... |
@PublicAPI(usage = ACCESS)
public Properties getExtensionProperties(String extensionIdentifier) {
String propertyPrefix = getFullExtensionPropertyPrefix(extensionIdentifier);
return getSubProperties(propertyPrefix);
} | @Test
public void if_no_extension_properties_are_found_empty_properties_are_returned() {
ArchConfiguration configuration = testConfiguration(PROPERTIES_FILE_NAME);
assertThat(configuration.getExtensionProperties("not-there")).isEmpty();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.