focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static long getPid()
{
return PID;
} | @Test
void shouldReturnPid()
{
assertNotEquals(PID_NOT_FOUND, getPid());
} |
@Override
protected void rename(
List<LocalResourceId> srcResourceIds,
List<LocalResourceId> destResourceIds,
MoveOptions... moveOptions)
throws IOException {
if (moveOptions.length > 0) {
throw new UnsupportedOperationException("Support for move options is not yet implemented.");
... | @Test
public void testMoveWithExistingSrcFile() throws Exception {
Path srcPath1 = temporaryFolder.newFile().toPath();
Path srcPath2 = temporaryFolder.newFile().toPath();
Path destPath1 = temporaryFolder.getRoot().toPath().resolve("nonexistentdir").resolve("dest1");
Path destPath2 = srcPath2.resolveS... |
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
ctx.channel().attr(PROTOCOL_NAME).set(PROTOCOL_HTTP_2);
configureHttp2(ctx.pipeline());
return;
}
... | @Test
void skipProtocolCloseHandler() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel();
ChannelConfig channelConfig = new ChannelConfig();
channelConfig.add(new ChannelConfigValue<>(CommonChannelConfigKeys.http2CatchConnectionErrors, false));
channelConfig.add(new C... |
public static boolean isEmpty(Collection coll) {
return (coll == null || coll.isEmpty());
} | @Test
void testIsEmpty() {
assertFalse(CollectionUtils.isEmpty(Collections.singletonList("target")));
assertTrue(CollectionUtils.isEmpty(Collections.emptyList()));
assertTrue(CollectionUtils.isEmpty(null));
} |
public AMRMClient.ContainerRequest getContainerRequest(
Resource containerResource, Priority priority, String nodeLabel) {
if (StringUtils.isNullOrWhitespaceOnly(nodeLabel) || defaultConstructor == null) {
return new AMRMClient.ContainerRequest(containerResource, null, null, priority);
... | @Test
void testGetContainerRequestWithYarnSupport()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
assumeThat(HadoopUtils.isMinHadoopVersion(2, 6)).isTrue();
Resource resource = Resource.newInstance(100, 1);
Priority priority = Priority.newInst... |
public void cacheSubscriberForRedo(String serviceName, String groupName, String cluster) {
String key = ServiceInfo.getKey(NamingUtils.getGroupedName(serviceName, groupName), cluster);
SubscriberRedoData redoData = SubscriberRedoData.build(serviceName, groupName, cluster);
synchronized (subscrib... | @Test
void testCacheSubscriberForRedo() {
ConcurrentMap<String, SubscriberRedoData> subscribes = getSubscriberRedoDataMap();
assertTrue(subscribes.isEmpty());
redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER);
assertFalse(subscribes.isEmpty());
SubscriberRedoData ac... |
public String getContent(String path) {
String htmlPath = HTML_PATHS.contains(path) ? path : INDEX_HTML_PATH;
checkState(servletContext != null, "init has not been called");
// Optimization to not have to call platform.currentStatus on each call
if (Objects.equals(status, UP)) {
return indexHtmlBy... | @Test
public void contains_web_context() {
doInit();
assertThat(underTest.getContent("/foo"))
.contains(TEST_CONTEXT);
} |
public List<ScanFilterData> createScanFilterDataForBeaconParser(BeaconParser beaconParser, List<Identifier> identifiers) {
ArrayList<ScanFilterData> scanFilters = new ArrayList<ScanFilterData>();
long typeCode = beaconParser.getMatchingBeaconTypeCode();
int startOffset = beaconParser.getMatching... | @Test
public void testEddystoneScanFilterData() throws Exception {
org.robolectric.shadows.ShadowLog.stream = System.err;
BeaconParser parser = new BeaconParser();
parser.setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT);
BeaconManager.setManifestCheckingDisabled(true); // no manife... |
protected String escape(final String path) {
final StringBuilder escaped = new StringBuilder();
for(char c : path.toCharArray()) {
if(StringUtils.isAlphanumeric(String.valueOf(c))
|| c == Path.DELIMITER) {
escaped.append(c);
}
else ... | @Test
public void testEscape() {
Archive a = Archive.TAR;
assertEquals("file\\ name", a.escape("file name"));
assertEquals("file\\(name", a.escape("file(name"));
assertEquals("\\$filename", a.escape("$filename"));
} |
void registerSessionIfNeeded(HttpSession session) {
if (session != null) {
synchronized (session) {
if (!SESSION_MAP_BY_ID.containsKey(session.getId())) {
sessionCreated(new HttpSessionEvent(session));
}
}
}
} | @Test
public void registerSessionIfNeeded() {
final HttpSession session = createSession();
sessionListener.registerSessionIfNeeded(session);
sessionListener.registerSessionIfNeeded(session);
sessionListener.registerSessionIfNeeded(null);
sessionListener.unregisterInvalidatedSessions();
sessionListener.un... |
public static <K> KTableHolder<K> build(
final KTableHolder<K> left,
final KTableHolder<K> right,
final TableTableJoin<K> join
) {
final LogicalSchema leftSchema;
final LogicalSchema rightSchema;
if (join.getJoinType().equals(RIGHT)) {
leftSchema = right.getSchema();
rightSc... | @Test
public void shouldDoLeftJoin() {
// Given:
givenLeftJoin(L_KEY);
// When:
final KTableHolder<Struct> result = join.build(planBuilder, planInfo);
// Then:
verify(leftKTable).leftJoin(
same(rightKTable),
eq(new KsqlValueJoiner(LEFT_SCHEMA.value().size(), RIGHT_SCHEMA.valu... |
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) {
return Optional.ofNullable(HANDLERS.get(step.getClass()))
.map(h -> h.handle(this, schema, step))
.orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass()));
} | @Test
public void shouldResolveSchemaForStreamSelectWithoutColumnNames() {
// Given:
final StreamSelect<?> step = new StreamSelect<>(
PROPERTIES,
streamSource,
ImmutableList.of(ColumnName.of("NEW_KEY")),
Optional.empty(),
ImmutableList.of(
add("JUICE", "ORAN... |
static KiePMMLTargetValue getKiePMMLTargetValue(final TargetValue targetValue) {
final String value = targetValue.getValue() != null ? targetValue.getValue().toString() : null;
final String displayValue = targetValue.getDisplayValue() != null ? targetValue.getDisplayValue() : null;
final org.kie... | @Test
void getKiePMMLTargetValue() {
final TargetValue toConvert = getRandomTargetValue();
KiePMMLTargetValue retrieved = KiePMMLTargetValueInstanceFactory.getKiePMMLTargetValue(toConvert);
commonVerifyKiePMMLTargetValue(retrieved, toConvert);
} |
@Override
public OffsetFetchResponseData data() {
return data;
} | @Test
public void testNullableMetadataV0ToV7() {
PartitionData pd = new PartitionData(
offset,
leaderEpochOne,
null,
Errors.UNKNOWN_TOPIC_OR_PARTITION);
// test PartitionData.equals with null metadata
assertEquals(pd, pd);
partitionData... |
public static Builder withSchema(Schema schema) {
return new Builder(schema);
} | @Test
public void testThrowsForIncorrectNumberOfFields() {
Schema type =
Stream.of(
Schema.Field.of("f_int", FieldType.INT32),
Schema.Field.of("f_str", FieldType.STRING),
Schema.Field.of("f_double", FieldType.DOUBLE))
.collect(toSchema());
t... |
static String formatDuration(long durationInMinutes) {
if (durationInMinutes == 0) {
return ZERO;
}
double days = (double) durationInMinutes / DURATION_HOURS_IN_DAY / DURATION_OF_ONE_HOUR_IN_MINUTES;
if (days > DURATION_ALMOST_ONE) {
return format(DURATION_DAYS_FORMAT, Math.round(days));
... | @Test
public void format_duration_is_rounding_result() {
// When starting to add more than 4 hours, the result will be rounded to the next day (as 4 hour is a half day)
assertThat(formatDuration(5 * ONE_DAY + 4 * ONE_HOUR)).isEqualTo("6d");
assertThat(formatDuration(5 * ONE_DAY + 5 * ONE_HOUR)).isEqualTo(... |
public String doLayout(ILoggingEvent event) {
StringBuilder buf = new StringBuilder();
startNewTableIfLimitReached(buf);
boolean odd = true;
if (((counter++) & 1) == 0) {
odd = false;
}
String level = event.getLevel().toString().toLowerCase(Locale.US);
buf.append(LINE_SEPARATOR);
... | @SuppressWarnings("unchecked")
@Test
public void layoutWithException() throws Exception {
layout.setPattern("%level %thread %msg %ex");
LoggingEvent le = createLoggingEvent();
le.setThrowableProxy(new ThrowableProxy(new Exception("test Exception")));
String result = layout.doLayout(le);
String ... |
@Override
public Database getDb(String dbName) {
if (databases.containsKey(dbName)) {
return databases.get(dbName);
}
Database db;
try {
db = icebergCatalog.getDB(dbName);
} catch (NoSuchNamespaceException e) {
LOG.error("Database {} not fo... | @Test
public void testGetDB(@Mocked IcebergHiveCatalog icebergHiveCatalog) {
String db = "db";
new Expectations() {
{
icebergHiveCatalog.getDB(db);
result = new Database(0, db);
minTimes = 0;
}
};
IcebergMetada... |
public HollowHashIndexResult findMatches(Object... query) {
if (hashStateVolatile == null) {
throw new IllegalStateException(this + " wasn't initialized");
}
int hashCode = 0;
for(int i=0;i<query.length;i++) {
if(query[i] == null)
throw new Illega... | @Test(expected = IllegalArgumentException.class)
public void testFindingMatchForNullQueryValue() throws Exception {
mapper.add(new TypeB("one:"));
roundTripSnapshot();
HollowHashIndex index = new HollowHashIndex(readStateEngine, "TypeB", "", "b1.value");
index.findMatches(new Object[... |
public static String rangeKey(long value) {
return encodeBase62(value, true);
} | @Test
public void testLargeRangeKey() {
Assert.assertEquals("44C92", IdHelper.rangeKey(1000000L));
Assert.assertEquals("BAzL8n0Y58m7", IdHelper.rangeKey(Long.MAX_VALUE));
Assert.assertTrue(IdHelper.rangeKey(1000000L).compareTo(IdHelper.rangeKey(Long.MAX_VALUE)) < 0);
} |
public StatisticRange intersect(StatisticRange other)
{
double newLow = max(low, other.low);
boolean newOpenLow = newLow == low ? openLow : other.openLow;
// epsilon is an arbitrary choice
newOpenLow = nearlyEqual(low, other.low, 1E-10) ? openLow || other.openLow : newOpenLow;
... | @Test
public void testIntersect()
{
StatisticRange zeroToTen = range(0, 10, 10);
StatisticRange fiveToFifteen = range(5, 15, 60);
assertEquals(zeroToTen.intersect(fiveToFifteen), range(5, 10, 10));
} |
public static Map<String, Object> getResolvedPropertiesByPath(String pathSpec, DataSchema dataSchema)
{
if (dataSchema == null)
{
throw new IllegalArgumentException("Invalid data schema input");
}
if (pathSpec == null || (!pathSpec.isEmpty() && !PathSpec.validatePathSpecString(pathSpec)))
{... | @Test
public void testGetResolvedPropertiesByPath() throws Exception
{
RecordDataSchema testSchema = (RecordDataSchema) TestUtil.dataSchemaFromPdlString(simpleTestSchema);
try
{
SchemaAnnotationProcessor.getResolvedPropertiesByPath("/f0/f3", testSchema);
}
catch (IllegalArgumentException e... |
public CompletableFuture<Void> storeEcOneTimePreKeys(final UUID identifier, final byte deviceId,
final List<ECPreKey> preKeys) {
return ecPreKeys.store(identifier, deviceId, preKeys);
} | @Test
void storeEcOneTimePreKeys() {
assertEquals(0, keysManager.getEcCount(ACCOUNT_UUID, DEVICE_ID).join(),
"Initial pre-key count for an account should be zero");
keysManager.storeEcOneTimePreKeys(ACCOUNT_UUID, DEVICE_ID, List.of(generateTestPreKey(1))).join();
assertEquals(1, keysManager.getEc... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testShhPost() throws Exception {
web3j.shhPost(
new ShhPost(
"0x04f96a5e25610293e42a73908e93ccc8c4d4dc0edcfa9fa872f50cb214e08ebf61a03e245533f97284d442460f2998cd41858798ddfd4d661997d3940272b717b1",
"0x3... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGasPrice() throws Exception {
web3j.ethGasPrice().send();
verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"eth_gasPrice\",\"params\":[],\"id\":1}");
} |
public boolean containsValue(final int value)
{
boolean found = false;
if (initialValue != value)
{
final int[] entries = this.entries;
@DoNotSub final int length = entries.length;
for (@DoNotSub int i = 1; i < length; i += 2)
{
... | @Test
void shouldNotContainValueForAMissingEntry()
{
assertFalse(map.containsValue(1));
} |
boolean isWriteEnclosed( ValueMetaInterface v ) {
return meta.isEnclosureForced() && data.binaryEnclosure.length > 0 && v != null && v.isString();
} | @Test
public void testWriteEnclosed() {
TextFileOutputData data = new TextFileOutputData();
data.binaryEnclosure = new byte[1];
data.writer = new ByteArrayOutputStream();
TextFileOutputMeta meta = getTextFileOutputMeta();
meta.setEnclosureForced(true);
stepMockHelper.stepMeta.setStepMetaInterf... |
<K, V> ShareInFlightBatch<K, V> fetchRecords(final Deserializers<K, V> deserializers,
final int maxRecords,
final boolean checkCrcs) {
// Creating an empty ShareInFlightBatch
ShareInFlightBatch<K, V> inFlig... | @Test
public void testSimple() {
long firstMessageId = 5;
long startingOffset = 10L;
int numRecords = 11; // Records for 10-20
ShareFetchResponseData.PartitionData partitionData = new ShareFetchResponseData.PartitionData()
.setRecords(newRecords(startingOffset,... |
@Override
public void close() {
close(Duration.ofMillis(0));
} | @Test
public void shouldThrowOnInitTransactionIfProducerIsClosed() {
buildMockProducer(true);
producer.close();
assertThrows(IllegalStateException.class, producer::initTransactions);
} |
@Override
public ObjectNode encode(MappingInstruction instruction, CodecContext context) {
checkNotNull(instruction, "Mapping instruction cannot be null");
return new EncodeMappingInstructionCodecHelper(instruction, context).encode();
} | @Test
public void unicastPriorityInstructionTest() {
final UnicastMappingInstruction.PriorityMappingInstruction instruction =
(UnicastMappingInstruction.PriorityMappingInstruction)
MappingInstructions.unicastPriority(UNICAST_PRIORITY);
final ObjectNode instructionJson... |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema == null && value == null) {
return null;
}
JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value);
... | @Test
public void dateToJson() {
GregorianCalendar calendar = new GregorianCalendar(1970, Calendar.JANUARY, 1, 0, 0, 0);
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.add(Calendar.DATE, 10000);
java.util.Date date = calendar.getTime();
JsonNode converted = pars... |
@Override
public void setMaxParallelism(int maxParallelism) {
maxParallelism = normalizeAndCheckMaxParallelism(maxParallelism);
Optional<String> validationResult = rescaleMaxValidator.apply(maxParallelism);
if (validationResult.isPresent()) {
throw new IllegalArgumentException(
... | @Test
void setMaxInvalid() {
DefaultVertexParallelismInfo info =
new DefaultVertexParallelismInfo(1, 1, (max) -> Optional.of("not valid"));
assertThatThrownBy(() -> info.setMaxParallelism(4))
.withFailMessage("not valid")
.isInstanceOf(IllegalArgument... |
void writeConfigToDisk() {
VespaTlsConfig config = VespaZookeeperTlsContextUtils.tlsContext()
.map(ctx -> new VespaTlsConfig(ctx, TransportSecurityUtils.getInsecureMixedMode()))
.orElse(Vesp... | @Test
public void config_is_written_correctly_with_tls_for_quorum_communication_tls_with_mixed_mode() {
ZookeeperServerConfig.Builder builder = createConfigBuilderForSingleHost(cfgFile, idFile);
TlsContext tlsContext = createTlsContext();
new Configurator(builder.build()).writeConfigToDisk(n... |
@Override
public List<Namespace> listNamespaces(Namespace namespace) {
SnowflakeIdentifier scope = NamespaceHelpers.toSnowflakeIdentifier(namespace);
List<SnowflakeIdentifier> results;
switch (scope.type()) {
case ROOT:
results = snowflakeClient.listDatabases();
break;
case DAT... | @Test
public void testListNamespaceWithinDB() {
String dbName = "DB_1";
assertThat(catalog.listNamespaces(Namespace.of(dbName)))
.containsExactly(Namespace.of(dbName, "SCHEMA_1"));
} |
@VisibleForTesting
@Nullable
public UUID getLeaderSessionID(String componentId) {
synchronized (lock) {
return leaderContenderRegistry.containsKey(componentId)
? confirmedLeaderInformation
.forComponentIdOrEmpty(componentId)
... | @Test
void testOnGrantAndRevokeLeadership() throws Exception {
final AtomicReference<LeaderInformationRegister> storedLeaderInformation =
new AtomicReference<>(LeaderInformationRegister.empty());
new Context(storedLeaderInformation) {
{
runTestWithSynchron... |
public static NamespaceName get(String tenant, String namespace) {
validateNamespaceName(tenant, namespace);
return get(tenant + '/' + namespace);
} | @Test(expectedExceptions = IllegalArgumentException.class)
public void namespace_null() {
NamespaceName.get(null);
} |
public HttpResponse error(Throwable t) {
data(500, ContentType.TEXT_PLAIN, stream -> t.printStackTrace(new PrintStream(stream)));
return this;
} | @Test
void testError() throws IOException {
httpResponse.error(new Exception());
verify(httpExchange).sendResponseHeaders(500, 0);
verify(outputStream, atLeastOnce()).write(any(), anyInt(), anyInt());
} |
@SuppressWarnings("unchecked")
@Override
public RegisterNodeManagerResponse registerNodeManager(
RegisterNodeManagerRequest request) throws YarnException,
IOException {
NodeId nodeId = request.getNodeId();
String host = nodeId.getHost();
int cmPort = nodeId.getPort();
int httpPort = requ... | @Test
public void testNodeRegistrationWithInvalidAttributes() throws Exception {
writeToHostsFile("host2");
Configuration conf = new Configuration();
conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH,
hostFile.getAbsolutePath());
conf.setClass(YarnConfiguration.FS_NODE_ATTRIBUTE_STORE_IMPL... |
@Nullable
@Override
public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable {
AdapterInvocationWrapper adapterInvocationWrapper = new AdapterInvocationWrapper(invocation);
Object result = proxyInvocationHandler.invoke(adapterInvocationWrapper);
return result;
} | @Test
void should_success_when_call_prepare_with_ProxyInvocationHandler() throws Throwable {
MyMockMethodInvocation myMockMethodInvocation = new MyMockMethodInvocation(NormalTccAction.class.getMethod("prepare", BusinessActionContext.class), () -> normalTccAction.prepare(null));
//when then
... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(containerService.isContainer(file)) {
final PathAttributes attributes = new PathAttributes();
... | @Test
public void testDeleted() throws Exception {
final Path bucket = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final Path test = new S3TouchFeature(session, new S3AccessControlListFeature(session)).touch(new Path(bucket, new Alphanumeric... |
public static Subject.Factory<Re2jStringSubject, String> re2jString() {
return Re2jStringSubject.FACTORY;
} | @Test
public void doesNotContainMatch_pattern_succeeds() {
assertAbout(re2jString()).that("hello cruel world").doesNotContainMatch(PATTERN);
} |
public static FileLocationOptions defaults() {
return new FileLocationOptions();
} | @Test
public void defaults() throws IOException {
FileLocationOptions options = FileLocationOptions.defaults();
assertEquals(0, options.getOffset());
} |
@SuppressWarnings("unchecked")
public static void validateResponse(HttpURLConnection conn,
int expectedStatus) throws IOException {
if (conn.getResponseCode() != expectedStatus) {
Exception toThrow;
InputStream es = null;
try {
es = conn.getErrorStream();
Map json = JsonSer... | @Test
public void testValidateResponseJsonErrorNonException() throws Exception {
Map<String, Object> json = new HashMap<String, Object>();
json.put(HttpExceptionUtils.ERROR_EXCEPTION_JSON, "invalid");
// test case where the exception classname is not a valid exception class
json.put(HttpExceptionUtils... |
@JsonProperty
public boolean isAppendRowNumberEnabled()
{
return appendRowNumberEnabled;
} | @Test
public void testIsAppendRowNumberEnabled()
{
List<Column> dataColumns = new ArrayList<>();
List<BaseHiveColumnHandle> partitionColumns = new ArrayList<>();
Map<String, String> tableParameters = Collections.emptyMap();
TupleDomain<Subfield> domainPredicate = TupleDomain.none... |
@Override
public Iterable<DefaultLogicalResult> getConsumedResults() {
return jobVertex.getInputs().stream()
.map(JobEdge::getSource)
.map(IntermediateDataSet::getId)
.map(resultRetriever)
.collect(Collectors.toList());
} | @Test
public void testGetConsumedResults() {
assertResultsEquals(results, downstreamLogicalVertex.getConsumedResults());
} |
public static ErrorProneOptions processArgs(Iterable<String> args) {
Preconditions.checkNotNull(args);
ImmutableList.Builder<String> remainingArgs = ImmutableList.builder();
/* By default, we throw an error when an unknown option is passed in, if for example you
* try to disable a check that doesn't m... | @Test
public void noSuchXepFlag() {
assertThrows(
InvalidCommandLineOptionException.class,
() -> ErrorProneOptions.processArgs(new String[] {"-XepNoSuchFlag"}));
} |
protected static boolean isNewVersion(String latest, String current) {
String gephiVersionTst = current.replaceAll("[0-9]{12}", "").replaceAll("[a-zA-Z -]", "");
latest = latest.replaceAll("[a-zA-Z -]", "");
int res = ModuleDescriptor.Version.parse(gephiVersionTst)
.compareTo(ModuleD... | @Test
public void testNewVersion() {
Assert.assertFalse(Installer.isNewVersion("0.9.2", "0.9.2"));
Assert.assertTrue(Installer.isNewVersion("0.9.3", "0.9.2"));
Assert.assertTrue(Installer.isNewVersion("0.10.0", "0.9.2"));
Assert.assertTrue(Installer.isNewVersion("0.10.1", "0.10.0"));... |
@Override
public NearCacheConfig setName(String name) {
this.name = isNotNull(name, "name");
return this;
} | @Test(expected = IllegalArgumentException.class)
public void test_null_name_throws_exception() {
config.setName(null);
} |
@EventListener
void updateTask(TaskChangeEvent event) {
removeTaskFromScheduler(event.getTask().getId());
if (!event.isRemoved() && event.getTask().getActive()) {
addTaskToScheduler(event.getTask().getId(), new SimpleTaskRunnable(event.getTask(), clientFactory.getClientForApplication(event.ge... | @Test
public void updatedTaskIsRemovedFromScheduleWhenInactive() {
Task taskA = new Task();
taskA.setId(1l);
taskA.setName("old");
taskA.setCron("0 0 * * * *");
Map<Long, ScheduledFuture<?>> jobsMap = new HashMap<>();
jobsMap.put(taskA.getId(), mock(ScheduledFuture.c... |
static VersionInfo parseVersionInfo(String str) throws ParseException {
Map<String, String> map = Util.parseMap(str);
VersionInfo.Builder vib = new VersionInfo.Builder();
for (Map.Entry<String, String> entry: map.entrySet()) {
switch (entry.getKey()) {
case "major" -... | @Test
public void versionInfoFromMap(VertxTestContext context) throws ParseException {
String version = """
major=1
minor=16
gitVersion=v1.16.2
gitCommit=c97fe5036ef3df2967d086711e6c0c405941e14b
gitTreeState=clean
... |
public static ExpressionEvaluator compileExpression(
String code,
List<String> argumentNames,
List<Class<?>> argumentClasses,
Class<?> returnClass) {
try {
ExpressionKey key =
new ExpressionKey(code, argumentNames, argumentClasses, ... | @Test
public void testExpressionCacheReuse() {
String code = "a + b";
ExpressionEvaluator evaluator1 =
CompileUtils.compileExpression(
code,
Arrays.asList("a", "b"),
Arrays.asList(Integer.class, Integer.class),
... |
UserDetails toUserDetails(UserCredentials userCredentials) {
return User.withUsername(userCredentials.getUsername())
.password(userCredentials.getPassword())
.roles(userCredentials.getRoles().toArray(String[]::new))
.build();
} | @Test
void toUserDetails() {
// given
UserCredentials userCredentials =
UserCredentials.builder()
.enabled(true)
.password("password")
.username("user")
.roles(Set.of("USER", "ADMIN"))
.build();
// when
UserDetails userDetails = user... |
@Override
public int hashCode() {
return Objects.hash(start, end);
} | @Test
public void hashcode_is_based__on_start_and_end() {
assertThat(new TextBlock(15, 15)).hasSameHashCodeAs(new TextBlock(15, 15));
assertThat(new TextBlock(15, 300)).hasSameHashCodeAs(new TextBlock(15, 300));
assertThat(new TextBlock(15, 300).hashCode()).isNotEqualTo(new TextBlock(15, 15).hashCode());
... |
public void onBuffer(Buffer buffer, int sequenceNumber, int backlog, int subpartitionId)
throws IOException {
boolean recycleBuffer = true;
try {
if (expectedSequenceNumber != sequenceNumber) {
onError(new BufferReorderingException(expectedSequenceNumber, sequenc... | @Test
void testConcurrentOnBufferAndRelease() throws Exception {
testConcurrentReleaseAndSomething(
8192,
(inputChannel, buffer, j) -> {
inputChannel.onBuffer(buffer, j, -1, 0);
return true;
});
} |
public XAQueueConnection xaQueueConnection(XAQueueConnection connection) {
return TracingXAConnection.create(connection, this);
} | @Test void xaQueueConnection_doesntDoubleWrap() {
XAQueueConnection wrapped = jmsTracing.xaQueueConnection(mock(XAQueueConnection.class));
assertThat(jmsTracing.xaQueueConnection(wrapped))
.isSameAs(wrapped);
} |
@Override
public Map<String, ByteBuffer> performAssignment(String leaderId, String protocol,
List<JoinGroupResponseMember> allMemberMetadata,
WorkerCoordinator coordinator) {
log.debug("Performing task ... | @Test
public void testProtocolV2() {
// Sanity test to make sure that the right protocol is chosen during the assignment
connectors.clear();
String leader = "followMe";
List<JoinGroupResponseData.JoinGroupResponseMember> memberMetadata = new ArrayList<>();
ExtendedAssignment ... |
@Override
@Transactional
public boolean checkForPreApproval(Long userId, Integer userType, String clientId, Collection<String> requestedScopes) {
// 第一步,基于 Client 的自动授权计算,如果 scopes 都在自动授权中,则返回 true 通过
OAuth2ClientDO clientDO = oauth2ClientService.validOAuthClientFromCache(clientId);
Asse... | @Test
public void checkForPreApproval_reject() {
// 准备参数
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String clientId = randomString();
List<String> requestedScopes = Lists.newArrayList("read");
// mock 方法
when(... |
@Override
public ListenableFuture<List<Device>> findDevicesByTenantIdCustomerIdAndIdsAsync(UUID tenantId, UUID customerId, List<UUID> deviceIds) {
return service.submit(() -> DaoUtil.convertDataList(
deviceRepository.findDevicesByTenantIdAndCustomerIdAndIdIn(tenantId, customerId, deviceIds))... | @Test
public void testFindDevicesByTenantIdAndCustomerIdAndIdsAsync() throws ExecutionException, InterruptedException, TimeoutException {
ListenableFuture<List<Device>> devicesFuture = deviceDao.findDevicesByTenantIdCustomerIdAndIdsAsync(tenantId1, customerId1, deviceIds);
List<Device> devices = dev... |
public static Model readPom(File file) throws AnalysisException {
Model model = null;
final PomParser parser = new PomParser();
try {
model = parser.parse(file);
} catch (PomParseException ex) {
if (ex.getCause() instanceof SAXParseException) {
try... | @Test
public void testReadPom_File() throws Exception {
File file = BaseTest.getResourceAsFile(this, "dwr-pom.xml");
String expResult = "Direct Web Remoting";
Model result = PomUtils.readPom(file);
assertEquals(expResult, result.getName());
expResult = "get ahead";
a... |
@Override
public int run(String[] args) throws Exception {
try {
webServiceClient = WebServiceClient.getWebServiceClient().createClient();
return runCommand(args);
} finally {
if (yarnClient != null) {
yarnClient.close();
}
if (webServiceClient != null) {
webServi... | @Test(timeout = 10000l)
public void testInvalidOpts() throws Exception {
YarnClient mockYarnClient = createMockYarnClient(
YarnApplicationState.FINISHED,
UserGroupInformation.getCurrentUser().getShortUserName());
LogsCLI cli = new LogsCLIForTest(mockYarnClient);
cli.setConf(conf);
int... |
@Override
public OAuth2AccessTokenDO checkAccessToken(String accessToken) {
OAuth2AccessTokenDO accessTokenDO = getAccessToken(accessToken);
if (accessTokenDO == null) {
throw exception0(GlobalErrorCodeConstants.UNAUTHORIZED.getCode(), "访问令牌不存在");
}
if (DateUtils.isExpire... | @Test
public void testCheckAccessToken_null() {
// 调研,并断言
assertServiceException(() -> oauth2TokenService.checkAccessToken(randomString()),
new ErrorCode(401, "访问令牌不存在"));
} |
@Override
public Optional<SensorCacheData> load() {
String url = URL + "?project=" + project.key();
if (branchConfiguration.referenceBranchName() != null) {
url = url + "&branch=" + branchConfiguration.referenceBranchName();
}
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
Get... | @Test
public void loads_content_for_branch() throws IOException {
when(branchConfiguration.referenceBranchName()).thenReturn("name");
setResponse(MSG);
SensorCacheData msg = loader.load().get();
assertThat(msg.getEntries()).containsOnly(entry(MSG.getKey(), MSG.getData()));
assertRequestPath("api... |
public static RectL getBounds(final RectL pIn,
final long pCenterX, final long pCenterY, final double pDegrees,
final RectL pReuse) {
final RectL out = pReuse != null ? pReuse : new RectL();
if (pDegrees == 0) { // optimization
... | @Test
public void testGetBounds180() {
final double degrees = 180;
final RectL in = new RectL();
final RectL out = new RectL();
for (int i = 0; i < mIterations; i++) {
in.top = getRandomCoordinate();
in.left = getRandomCoordinate();
in.bottom = get... |
@Override
public ConfigData load(ConfigDataLoaderContext context, PolarisConfigDataResource resource)
throws ConfigDataResourceNotFoundException {
try {
return load(context.getBootstrapContext(), resource);
}
catch (Exception e) {
log.warn("Error getting properties from polaris: " + resource, e);
if ... | @Test
public void loadConfigDataInternalConfigFilesTest() {
try (MockedStatic<ConfigFileServiceFactory> mockedStatic = mockStatic(ConfigFileServiceFactory.class)) {
ConfigDataLoaderContext context = mock(ConfigDataLoaderContext.class);
PolarisConfigDataResource polarisConfigDataResource = mock(PolarisConfigDat... |
ControllerResult<ElectLeadersResponseData> electLeaders(ElectLeadersRequestData request) {
ElectionType electionType = electionType(request.electionType());
List<ApiMessageAndVersion> records = BoundedList.newArrayBacked(MAX_RECORDS_PER_USER_OP);
ElectLeadersResponseData response = new ElectLead... | @Test
public void testPreferredElectionDoesNotTriggerUncleanElection() {
ReplicationControlTestContext ctx = new ReplicationControlTestContext.Builder().build();
ReplicationControlManager replication = ctx.replicationControl;
ctx.registerBrokers(1, 2, 3, 4);
ctx.unfenceBrokers(1, 2, ... |
public void startsWith(@Nullable String string) {
checkNotNull(string);
if (actual == null) {
failWithActual("expected a string that starts with", string);
} else if (!actual.startsWith(string)) {
failWithActual("expected to start with", string);
}
} | @Test
public void stringStartsWithFail() {
expectFailureWhenTestingThat("abc").startsWith("bc");
assertFailureValue("expected to start with", "bc");
} |
public static void main( String[] args )
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
int exitCode = new CommandLine(new ExtractText()).execute(args);
System.exit(exitCode);
} | @Test
void testPDFBoxRepeatableSubcommandAddFileNameOutfile(@TempDir Path tempDir) throws Exception
{
Path path = null;
try
{
path = tempDir.resolve("outfile.txt");
Files.deleteIfExists(path);
}
catch (InvalidPathException ipe)
{
... |
public static TimelineEvent getApplicationEvent(TimelineEntity te,
String eventId) {
if (isApplicationEntity(te)) {
for (TimelineEvent event : te.getEvents()) {
if (event.getId().equals(eventId)) {
return event;
}
}
}
return null;
} | @Test
void testGetApplicationEvent() {
TimelineEntity te = null;
TimelineEvent tEvent = ApplicationEntity.getApplicationEvent(te,
"no event");
assertEquals(null, tEvent);
te = new TimelineEntity();
te.setType(TimelineEntityType.YARN_APPLICATION.toString());
TimelineEvent event = new T... |
protected void commonDeclarePatternWithConstraint(final CEDescrBuilder<?, ?> descrBuilder, final String patternType, final String constraintString) {
descrBuilder.pattern(patternType).constraint(constraintString);
} | @Test
void commonDeclarePatternWithConstraint() {
String patternType = "TEMPERATURE";
String constraintsString = "value < 35";
final CEDescrBuilder<CEDescrBuilder<CEDescrBuilder<RuleDescrBuilder, AndDescr>, NotDescr>, ExistsDescr> existsBuilder = lhsBuilder.not().exists();
KiePMMLDes... |
@Config("discovery-server.enabled")
public EmbeddedDiscoveryConfig setEnabled(boolean enabled)
{
this.enabled = enabled;
return this;
} | @Test
public void testDefaults()
{
assertRecordedDefaults(recordDefaults(EmbeddedDiscoveryConfig.class)
.setEnabled(false));
} |
Future<String> findZookeeperLeader(Reconciliation reconciliation, Set<String> pods, TlsPemIdentity coTlsPemIdentity) {
if (pods.size() == 0) {
return Future.succeededFuture(UNKNOWN_LEADER);
} else if (pods.size() == 1) {
return Future.succeededFuture(pods.stream().findFirst().get... | @Test
public void test0PodsClusterReturnsUnknownLeader(VertxTestContext context) {
ZookeeperLeaderFinder finder = new ZookeeperLeaderFinder(vertx, this::backoff);
Checkpoint a = context.checkpoint();
finder.findZookeeperLeader(Reconciliation.DUMMY_RECONCILIATION, emptySet(), DUMMY_IDENTITY)
... |
public ZKClientConfig toConfig(Path configFile) throws IOException, QuorumPeerConfig.ConfigException {
String configString = toConfigString();
Files.createDirectories(configFile.getParent());
Path tempFile = Files.createTempFile(configFile.toAbsolutePath().getParent(), "." + configFile.getFileNa... | @Test
void config_when_not_using_tls_context() {
ZkClientConfigBuilder builder = new ZkClientConfigBuilder(null);
ZKClientConfig config = builder.toConfig();
assertEquals("false", config.getProperty(CLIENT_SECURE_PROPERTY));
assertEquals("org.apache.zookeeper.ClientCnxnSocketNetty", ... |
@Override
public Iterator<MessageProcessor> iterator() {
return sortedProcessors.get().iterator();
} | @Test
public void testIterator() throws Exception {
final Iterator<MessageProcessor> iterator = orderedMessageProcessors.iterator();
assertEquals("A is first", A.class, iterator.next().getClass());
assertEquals("B is last", B.class, iterator.next().getClass());
assertFalse("Iterator ... |
@Override
public TimelineEntity getApplicationEntity(ApplicationId appId, String fields,
Map<String, String> filters)
throws IOException {
String path = PATH_JOINER.join("clusters", clusterId, "apps", appId);
if (fields == null || fields.isEmpty()) {
fields = "INFO";
}
MultivaluedMa... | @Test
void testGetApplication() throws Exception {
ApplicationId applicationId =
ApplicationId.fromString("application_1234_0001");
TimelineEntity entity = client.getApplicationEntity(applicationId,
null, null);
assertEquals("mockApp1", entity.getId());
} |
@Override
public void initChannel(final Channel channel) {
channel.pipeline().addBefore(FrontendChannelInboundHandler.class.getSimpleName(), MySQLSequenceIdInboundHandler.class.getSimpleName(), new MySQLSequenceIdInboundHandler(channel));
} | @Test
void assertInitChannel() {
engine.initChannel(channel);
verify(channel.attr(MySQLConstants.SEQUENCE_ID_ATTRIBUTE_KEY)).set(any(AtomicInteger.class));
verify(channel.pipeline())
.addBefore(eq(FrontendChannelInboundHandler.class.getSimpleName()), eq(MySQLSequenceIdInbound... |
@Override
public Local getFile() {
return LocalFactory.get(PreferencesFactory.get().getProperty("bookmark.import.fetch.location"));
} | @Test
public void testGetFile() throws Exception {
FetchBookmarkCollection c = new FetchBookmarkCollection();
assertEquals(0, c.size());
c.parse(new ProtocolFactory(new HashSet<>(Arrays.asList(new TestProtocol(Scheme.ftp), new TestProtocol(Scheme.ftps), new TestProtocol(Scheme.sftp)))), new ... |
@NotNull
@Override
public List<InetAddress> lookup(@NotNull String host) throws UnknownHostException {
InetAddress address = InetAddress.getByName(host);
if (configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY).orElse(SONAR_VALIDATE_WEBHOOKS_DEFAULT_VALUE)
&& (address.isLoopbackAddress() || addr... | @Test
public void lookup_fail_on_127_0_0_1() {
when(configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY))
.thenReturn(Optional.of(true));
Assertions.assertThatThrownBy(() -> underTest.lookup("127.0.0.1"))
.hasMessageContaining(INVALID_URL)
.isInstanceOf(IllegalArgumentException.class)... |
@Override
public List<Point> geoPos(byte[] key, byte[]... members) {
List<Object> params = new ArrayList<Object>(members.length + 1);
params.add(key);
params.addAll(Arrays.asList(members));
MultiDecoder<Map<Object, Object>> decoder = new ListMultiDecoder2(new ObjectListRepla... | @Test
public void testGeoPos() {
connection.geoAdd("key1".getBytes(), new Point(13.361389, 38.115556), "value1".getBytes());
connection.geoAdd("key1".getBytes(), new Point(15.087269, 37.502669), "value2".getBytes());
List<Point> s = connection.geoPos("key1".getBytes(), "value1".getBytes(), ... |
void handleTestStepFinished(TestStepFinished event) {
if (event.getTestStep() instanceof PickleStepTestStep && event.getResult().getStatus().is(Status.PASSED)) {
PickleStepTestStep testStep = (PickleStepTestStep) event.getTestStep();
addUsageEntry(event.getResult(), testStep);
}
... | @Test
void resultWithPassedAndFailedStep() {
OutputStream out = new ByteArrayOutputStream();
UsageFormatter usageFormatter = new UsageFormatter(out);
TestStep testStep = mockTestStep();
Result passed = new Result(Status.PASSED, Duration.ofSeconds(12345L), null);
usageFormatt... |
public static SortOrder buildSortOrder(Table table) {
return buildSortOrder(table.schema(), table.spec(), table.sortOrder());
} | @Test
public void testSortOrderClusteringSatisfiedPartitionLast() {
PartitionSpec spec = PartitionSpec.builderFor(SCHEMA).identity("category").day("ts").build();
SortOrder order =
SortOrder.builderFor(SCHEMA)
.withOrderId(1)
.asc("category")
.asc("ts") // satisfies ... |
@Override
public void deleteFiles(Iterable<String> paths) throws BulkDeletionFailureException {
if (s3FileIOProperties.deleteTags() != null && !s3FileIOProperties.deleteTags().isEmpty()) {
Tasks.foreach(paths)
.noRetry()
.executeWith(executorService())
.suppressFailureWhenFinis... | @Test
public void testDeleteFilesS3ReturnsError() {
String location = "s3://bucket/path/to/file-to-delete.txt";
DeleteObjectsResponse deleteObjectsResponse =
DeleteObjectsResponse.builder()
.errors(ImmutableList.of(S3Error.builder().key("path/to/file.txt").build()))
.build();
... |
@Override
public abstract int compare(@NonNull String id1, @NonNull String id2); | @Test
public void testCompareCaseInsensitive() {
IdStrategy idStrategy = IdStrategy.CASE_INSENSITIVE;
assertTrue(idStrategy.compare("user1", "user2") < 0);
assertTrue(idStrategy.compare("user2", "user1") > 0);
assertEquals(0, idStrategy.compare("user1", "user1"));
assertTrue(... |
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 testIsLeafThrowsOnInvalidDepth() {
MerkleTreeUtil.isLeaf(0, 0);
} |
public void delete(final String id) throws BackgroundException {
if(log.isInfoEnabled()) {
log.info(String.format("Delete multipart upload for fileid %s", id));
}
try {
session.getClient().cancelLargeFileUpload(id);
}
catch(B2ApiException e) {
... | @Test
public void testDelete() throws Exception {
final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
final B2StartLargeFileResponse startResponse = se... |
@Override
public void start() {
DefaultInputModule root = moduleHierarchy.root();
componentStore.put(root);
indexChildren(root);
} | @Test
public void testIndex() {
ProjectDefinition rootDef = mock(ProjectDefinition.class);
ProjectDefinition def = mock(ProjectDefinition.class);
when(rootDef.getParent()).thenReturn(null);
when(def.getParent()).thenReturn(rootDef);
DefaultInputModule root = mock(DefaultInputModule.class);
De... |
@Override
public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
try {
if(status.isExists()) {
if(log.isWarnEnabled()) {
log.warn(String.f... | @Test
public void testCopyFile() throws Exception {
final BoxFileidProvider fileid = new BoxFileidProvider(session);
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new BoxTouchFeature(sessi... |
public static void checkNullOrNonNullNonEmptyEntries(
@Nullable Collection<String> values, String propertyName) {
if (values == null) {
// pass
return;
}
for (String value : values) {
Preconditions.checkNotNull(
value, "Property '" + propertyName + "' cannot contain null en... | @Test
public void testCheckNullOrNonNullNonEmptyEntries_mapNullValueFail() {
try {
Validator.checkNullOrNonNullNonEmptyEntries(Collections.singletonMap("key1", null), "test");
Assert.fail();
} catch (NullPointerException npe) {
Assert.assertEquals("Property 'test' cannot contain null values"... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @Test
public void testUnpartitionedBucketLong() throws Exception {
createUnpartitionedTable(spark, tableName);
SparkScanBuilder builder = scanBuilder();
BucketFunction.BucketLong function = new BucketFunction.BucketLong(DataTypes.LongType);
UserDefinedScalarFunc udf = toUDF(function, expressions(int... |
@Override
public String getMime(final String filename) {
if(StringUtils.startsWith(filename, "._")) {
return DEFAULT_CONTENT_TYPE;
}
// Reads from core.mime.types in classpath
return types.getMimetype(StringUtils.lowerCase(filename));
} | @Test
public void testGetMime() {
MappingMimeTypeService s = new MappingMimeTypeService();
assertEquals("text/plain", s.getMime("f.txt"));
assertEquals("text/plain", s.getMime("f.TXT"));
assertEquals("video/x-f4v", s.getMime("f.f4v"));
assertEquals("application/javascript", s... |
public Map<String, String> getTypes(final Set<String> streamIds,
final Set<String> fields) {
final Map<String, Set<String>> allFieldTypes = this.get(streamIds);
final Map<String, String> result = new HashMap<>(fields.size());
fields.forEach(field -> {
... | @Test
void getTypesReturnsEmptyMapIfStreamsAreEmpty() {
final Pair<IndexFieldTypesService, StreamService> services = mockServices();
final FieldTypesLookup lookup = new FieldTypesLookup(services.getLeft(), services.getRight());
assertThat(lookup.getTypes(Set.of(), Set.of("somefield"))).isEmp... |
public static IpPrefix valueOf(int address, int prefixLength) {
return new IpPrefix(IpAddress.valueOf(address), prefixLength);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfStringNegativePrefixLengthIPv6() {
IpPrefix ipPrefix;
ipPrefix =
IpPrefix.valueOf("1111:2222:3333:4444:5555:6666:7777:8888/-1");
} |
@Override
public Set<City> findAllByCanton(Canton canton) {
return cityRepository.findAllByCanton(canton).stream()
.map(city -> City.builder()
.of(city)
.setCanton(canton)
.build())
.collect(Collectors.to... | @Test
void findAllByCanton() {
City city = createCity();
Canton canton = city.getCanton();
Mockito.when(cityRepository.findAllByCanton(canton))
.thenReturn(Collections.singleton(city));
Set<City> expected = Set.of(city);
Set<City> actual = cityService.findAllB... |
public void retrieveDocuments() throws DocumentRetrieverException {
boolean first = true;
String route = params.cluster.isEmpty() ? params.route : resolveClusterRoute(params.cluster);
MessageBusParams messageBusParams = createMessageBusParams(params.configId, params.timeout, route);
doc... | @Test
void testHandlingErrorFromMessageBus() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.build();
Reply r = new GetDocumentReply(null);
r.addError(new Error(0, "Error message"));
... |
public boolean isIp4() {
return (version() == Ip4Address.VERSION);
} | @Test
public void testIsIp4() {
IpAddress ipAddress;
// IPv4
ipAddress = IpAddress.valueOf("0.0.0.0");
assertTrue(ipAddress.isIp4());
// IPv6
ipAddress = IpAddress.valueOf("::");
assertFalse(ipAddress.isIp4());
} |
Queue<String> prepareRollingOrder(List<String> podNamesToConsider, List<Pod> pods) {
Deque<String> rollingOrder = new ArrayDeque<>();
for (String podName : podNamesToConsider) {
Pod matchingPod = pods.stream().filter(pod -> podName.equals(pod.getMetadata().getName())).findFirst().orElse... | @Test
public void testRollingWithSomePodsOnly() {
List<Pod> pods = List.of(
renamePod(READY_POD, "my-connect-connect-0"),
renamePod(READY_POD, "my-connect-connect-1"),
renamePod(READY_POD, "my-connect-connect-2")
);
KafkaConnectRoller roller ... |
public static Db use() {
return use(DSFactory.get());
} | @Test
public void pageTest2() throws SQLException {
String sql = "select * from user order by name";
// 测试数据库中一共4条数据,第0页有3条,第1页有1条
List<Entity> page0 = Db.use().page(
sql, Page.of(0, 3));
assertEquals(3, page0.size());
List<Entity> page1 = Db.use().page(
sql, Page.of(1, 3));
assertEquals(1, page1.... |
@Override
public void setChannelStateWriter(ChannelStateWriter channelStateWriter) {
checkState(this.channelStateWriter == null, "Already initialized");
this.channelStateWriter = checkNotNull(channelStateWriter);
} | @TestTemplate
void testTimeoutAlignedToUnalignedBarrier() throws Exception {
PipelinedSubpartition subpartition = createSubpartition();
subpartition.setChannelStateWriter(ChannelStateWriter.NO_OP);
assertSubpartitionChannelStateFuturesAndQueuedBuffers(subpartition, null, true, 0, false);
... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DeviceFragmentId)) {
return false;
}
DeviceFragmentId that = (DeviceFragmentId) obj;
return Objects.equals(this.deviceId, that.deviceId) &&
... | @Test
public final void testEquals() {
new EqualsTester()
.addEqualityGroup(new DeviceFragmentId(DID1, PID),
new DeviceFragmentId(DID1, PID))
.addEqualityGroup(new DeviceFragmentId(DID2, PID),
new DeviceFragmentId(DID2, PID... |
public static GenericSchemaImpl of(SchemaInfo schemaInfo) {
return of(schemaInfo, true);
} | @Test
public void testGenericJsonSchema() {
Schema<Foo> encodeSchema = Schema.JSON(Foo.class);
GenericSchema decodeSchema = GenericSchemaImpl.of(encodeSchema.getSchemaInfo());
testEncodeAndDecodeGenericRecord(encodeSchema, decodeSchema);
} |
@Override
public void printItem(Map<String, String> item) {
int cols = item.size();
if (rowPrinter.showHeader() && header) {
for (int row = 0; row < 2; row++) {
for (int col = 0; col < cols; col++) {
if (col > 0) {
shell.write(row == 0 ? "|" : "+");
... | @Test
public void testTableWrapping() throws IOException {
CacheEntryRowPrinter rowPrinter = new CacheEntryRowPrinter(WIDTH, COLUMNS);
AeshTestShell shell = new AeshTestShell();
TablePrettyPrinter t = new TablePrettyPrinter(shell, rowPrinter);
try (InputStream is = TablePrettyPrinter.class.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.