focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static List<?> toList(Object value) {
return convert(List.class, value);
} | @Test
public void toListTest() {
final List<String> list = Arrays.asList("1", "2");
final String str = Convert.toStr(list);
final List<String> list2 = Convert.toList(String.class, str);
assertEquals("1", list2.get(0));
assertEquals("2", list2.get(1));
final List<Integer> list3 = Convert.toList(Integer.cla... |
public boolean onSameSegment(LogOffsetMetadata that) {
if (messageOffsetOnly() || that.messageOffsetOnly())
return false;
return this.segmentBaseOffset == that.segmentBaseOffset;
} | @Test
void testOnSameSegment() {
LogOffsetMetadata metadata1 = new LogOffsetMetadata(1L, 0L, 1);
LogOffsetMetadata metadata2 = new LogOffsetMetadata(5L, 4L, 2);
LogOffsetMetadata metadata3 = new LogOffsetMetadata(10L, 4L, 200);
assertFalse(metadata1.onSameSegment(metadata2));
... |
public static String getUserName() {
return Optional.ofNullable(USER_THREAD_LOCAL.get()).map(User::getUsername).orElse("");
} | @Test
public void testGetUserName() {
UserContext.setUserInfo(USERNAME, USER_ROLE);
String userName = UserContext.getUserName();
Assert.isTrue(USERNAME.equals(userName));
} |
public static String initEndpoint(final NacosClientProperties properties) {
if (properties == null) {
return "";
}
// Whether to enable domain name resolution rules
String isUseEndpointRuleParsing = properties.getProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE,
... | @Test
void testInitEndpointFromPropertiesWithCloudParsing() {
System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true");
final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive();
String endpoint = "1.1.1.1";
String endpointPort = "1234";... |
@ApiOperation(value = "Get a historic process instance", tags = { "History Process" }, nickname = "getHistoricProcessInstance")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates that the historic process instances could be found."),
@ApiResponse(code = 404, message = "Ind... | @Test
@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testGetProcessInstance() throws Exception {
ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder()
.processDefinitionKey("oneTaskProcess")
... |
@VisibleForTesting
protected String buildShortMessage(Map<String, Object> fields) {
final StringBuilder shortMessage = new StringBuilder();
shortMessage.append("JSON API poll result: ");
if (!flatten) {
shortMessage.append(jsonPath.getPath());
}
shortMessage.appen... | @Test
public void testBuildShortMessageThatGetsCutFullJson() throws Exception {
Map<String, Object> fields = Maps.newLinkedHashMap();
fields.put("baz", 9001);
fields.put("foo", "bargggdzrtdfgfdgldfsjgkfdlgjdflkjglfdjgljslfperitperoujglkdnfkndsbafdofhasdpfoöadjsFOO");
JsonPathCodec s... |
@Override
public boolean enableSendingOldValues(final boolean forceMaterialization) {
if (queryableName != null) {
sendOldValues = true;
return true;
}
if (parent.enableSendingOldValues(forceMaterialization)) {
sendOldValues = true;
}
retu... | @Test
public void shouldSetSendOldValuesOnParentIfNotMaterialized() {
when(parent.enableSendingOldValues(true)).thenReturn(true);
new KTableTransformValues<>(parent, new NoOpValueTransformerWithKeySupplier<>(), null).enableSendingOldValues(true);
} |
public static boolean webSocketHostPathMatches(String hostPath, String targetPath) {
boolean exactPathMatch = true;
if (ObjectHelper.isEmpty(hostPath) || ObjectHelper.isEmpty(targetPath)) {
// This scenario should not really be possible as the input args come from the vertx-websocket consum... | @Test
void webSocketHostEmptyPathNotMatches() {
String hostPath = "";
String targetPath = "";
assertFalse(VertxWebsocketHelper.webSocketHostPathMatches(hostPath, targetPath));
} |
public static CoordinatorRecord newConsumerGroupSubscriptionMetadataTombstoneRecord(
String groupId
) {
return new CoordinatorRecord(
new ApiMessageAndVersion(
new ConsumerGroupPartitionMetadataKey()
.setGroupId(groupId),
(short) 4
... | @Test
public void testNewConsumerGroupSubscriptionMetadataTombstoneRecord() {
CoordinatorRecord expectedRecord = new CoordinatorRecord(
new ApiMessageAndVersion(
new ConsumerGroupPartitionMetadataKey()
.setGroupId("group-id"),
(short) 4
... |
@Override
public int compare( Object data1, Object data2 ) throws KettleValueException {
boolean n1 = isNull( data1 );
boolean n2 = isNull( data2 );
if ( n1 && !n2 ) {
if ( isSortedDescending() ) {
// BACKLOG-14028
return 1;
} else {
return -1;
}
}
if ( !... | @Test
public void testCompareIntegerToDouble() throws KettleValueException {
ValueMetaBase intMeta = new ValueMetaBase( "int", ValueMetaInterface.TYPE_INTEGER );
Long int1 = 2L;
ValueMetaBase numberMeta = new ValueMetaBase( "number", ValueMetaInterface.TYPE_NUMBER );
Double double2 = 1.5D;
assertE... |
@SuppressWarnings({
"nullness" // TODO(https://github.com/apache/beam/issues/20497)
})
public static TableReference parseTableSpec(String tableSpec) {
Matcher match = BigQueryIO.TABLE_SPEC.matcher(tableSpec);
if (!match.matches()) {
throw new IllegalArgumentException(
String.format(
... | @Test
public void testTableParsingError_slash() {
thrown.expect(IllegalArgumentException.class);
BigQueryHelpers.parseTableSpec("a\\b12345:c.d");
} |
@ShellMethod(key = "cleans show", value = "Show the cleans")
public String showCleans(
@ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "-1") final Integer limit,
@ShellOption(value = {"--sortBy"}, help = "Sorting Field", defaultValue = "") final String sortByField,
@ShellOpt... | @Test
public void testShowCleans() throws Exception {
// Check properties file exists.
assertNotNull(propsFilePath, "Not found properties file");
// First, run clean
SparkMain.clean(jsc(), HoodieCLI.basePath, propsFilePath.getPath(), new ArrayList<>());
assertEquals(1, metaClient.getActiveTimelin... |
public synchronized Topology addSource(final String name,
final String... topics) {
internalTopologyBuilder.addSource(null, name, null, null, null, topics);
return this;
} | @Test
public void shouldNotAllowNullNameWhenAddingSourceWithTopic() {
assertThrows(NullPointerException.class, () -> topology.addSource((String) null, "topic"));
} |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseQuotedTimeStringAsTimeInMap() throws Exception {
String keyStr = "k1";
String timeStr = "14:34:54.346Z";
String mapStr = "{\"" + keyStr + "\":\"" + timeStr + "\"}";
SchemaAndValue result = Values.parseString(mapStr);
assertEquals(Type.MAP, result.... |
public SmppMessage createSmppMessage(CamelContext camelContext, AlertNotification alertNotification) {
SmppMessage smppMessage = new SmppMessage(camelContext, alertNotification, configuration);
smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.AlertNotification.toString());
smpp... | @Test
public void createSmppMessageFromDeliveryReceiptWithPayloadInOptionalParameterShouldReturnASmppMessage() {
DeliverSm deliverSm = new DeliverSm();
deliverSm.setSmscDeliveryReceipt();
deliverSm.setOptionalParameters(new OctetString(
OptionalParameter.Tag.MESSAGE_PAYLOAD,
... |
public static <T extends Throwable> void checkContains(final Collection<?> values, final Object element, final Supplier<T> exceptionSupplierIfUnexpected) throws T {
if (!values.contains(element)) {
throw exceptionSupplierIfUnexpected.get();
}
} | @Test
void assertCheckContainsToNotThrowException() {
assertDoesNotThrow(() -> ShardingSpherePreconditions.checkContains(Collections.singleton("foo"), "foo", SQLException::new));
} |
public static Class<?> forName(String name) throws ClassNotFoundException {
return forName(name, getClassLoader());
} | @Test
void testForName3() throws Exception {
ClassLoader classLoader = Mockito.mock(ClassLoader.class);
ClassUtils.forName("a.b.c.D", classLoader);
verify(classLoader).loadClass("a.b.c.D");
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return delegate.find(file, listener);
}
if(cache.isValid(file.getParent())) {
final AttributedList<Path> list = cache.get(file.g... | @Test
public void testFindErrorWhilePagingDirectoryListing() throws Exception {
final PathCache cache = new PathCache(1);
final Path directory = new Path("/", EnumSet.of(Path.Type.directory));
final Path file = new Path(directory, "f", EnumSet.of(Path.Type.file));
final CachingAttrib... |
public void deleteFavorite(long favoriteId) {
Favorite favorite = favoriteRepository.findById(favoriteId).orElse(null);
checkUserOperatePermission(favorite);
favoriteRepository.delete(favorite);
} | @Test(expected = BadRequestException.class)
@Sql(scripts = "/sql/favorites/favorites.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testDeleteFavoriteFail() {
long anotherPersonFavoriteId = 23L... |
@Override
public JCTypeApply inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.TypeApply(getType().inline(inliner), inliner.<JCExpression>inlineList(getTypeArguments()));
} | @Test
public void inline() {
ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL);
assertInlines(
"List<String>",
UTypeApply.create(
UClassIdent.create("java.util.List"), UClassIdent.create("java.lang.String")));
} |
@Override
public RemoveFromClusterNodeLabelsResponse removeFromClusterNodeLabels(
RemoveFromClusterNodeLabelsRequest request)
throws YarnException, IOException {
// parameter verification.
if (request == null) {
routerMetrics.incrRemoveFromClusterNodeLabelsFailedRetrieved();
RouterServ... | @Test
public void testRemoveFromClusterNodeLabelsEmptyRequest() throws Exception {
// null request1.
LambdaTestUtils.intercept(YarnException.class, "Missing RemoveFromClusterNodeLabels request.",
() -> interceptor.removeFromClusterNodeLabels(null));
// null request2.
RemoveFromClusterNodeLabe... |
@Deprecated
public final boolean recycle(T o, Handle<T> handle) {
if (handle == NOOP_HANDLE) {
return false;
}
handle.recycle(o);
return true;
} | @Test
public void testRecycle() {
Recycler<HandledObject> recycler = newRecycler(1024);
HandledObject object = recycler.get();
object.recycle();
HandledObject object2 = recycler.get();
assertSame(object, object2);
object2.recycle();
} |
@Override
public synchronized void write(int b) throws IOException {
mUfsOutStream.write(b);
mBytesWritten++;
} | @Test
public void writeIncreasingByteArrayOffsetLen() throws IOException, AlluxioException {
AlluxioURI ufsPath = getUfsPath();
try (FileOutStream outStream = mFileSystem.createFile(ufsPath)) {
outStream.write(BufferUtils.getIncreasingByteArray(CHUNK_SIZE), 0, CHUNK_SIZE);
}
verifyIncreasingByte... |
public boolean match(int left, int right) {
return left == right;
} | @Test
public void longShouldEqual() {
long a = 21474836478L;
long b = 21474836478L;
boolean match = new NumberMatch().match(a, b);
assertTrue(match);
a = -21474836478L;
b = -21474836479L;
match = new NumberMatch().match(a, b);
assertFalse(match);
... |
FileContext getLocalFileContext(Configuration conf) {
try {
return FileContext.getLocalFSFileContext(conf);
} catch (IOException e) {
throw new YarnRuntimeException("Failed to access local fs");
}
} | @Test
public void testLocalizationInit() throws Exception {
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077");
AsyncDispatcher dispatcher = new AsyncDispatcher();
dispatcher.init(new Configuration());
ContainerExecutor exec = mock(ContainerExecutor.class);
DeletionService delServi... |
static JobManagerProcessSpec processSpecFromConfig(Configuration config) {
return createMemoryProcessSpec(PROCESS_MEMORY_UTILS.memoryProcessSpecFromConfig(config));
} | @Test
void testLogFailureOfJvmHeapSizeMinSizeVerification() {
MemorySize jvmHeapMemory = MemorySize.parse("50m");
Configuration conf = new Configuration();
conf.set(JobManagerOptions.JVM_HEAP_MEMORY, jvmHeapMemory);
JobManagerProcessUtils.processSpecFromConfig(conf);
asser... |
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not f... | @Test
public void testStaticMemberRejoinWithKnownLeaderIdToTriggerRebalanceAndFollowerWithChangeofProtocol()
throws Exception {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
GroupMetadataManagerTestContext.RebalanceResult reba... |
@Override
public JwtToken getToken(@Nullable @QueryParameter("expiryTimeInMins") Integer expiryTimeInMins, @Nullable @QueryParameter("maxExpiryTimeInMins") Integer maxExpiryTimeInMins) {
long expiryTime= Long.getLong("EXPIRY_TIME_IN_MINS",DEFAULT_EXPIRY_IN_SEC);
int maxExpiryTime = Integer.getInteg... | @Test
public void getJwks() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
JenkinsRule.WebClient webClient = j.createWebClient();
User user = User.get("alice");
user.setFullName("Alice Cooper");
user.addProperty(new Mailer.UserProperty("alice@je... |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) {
if (readerWay.hasTag("hazmat:adr_tunnel_cat", TUNNEL_CATEGORY_NAMES)) {
HazmatTunnel code = HazmatTunnel.valueOf(readerWay.getTag("hazmat:adr_tunnel_cat"));
hazT... | @Test
public void testIgnoreNonTunnelSubtags() {
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
ReaderWay readerWay = new ReaderWay(1);
readerWay.setTag("hazmat:B", "no");
int edgeId = 0;
parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags);
asse... |
public static void main(String[] args) throws Exception {
TikaCLI cli = new TikaCLI();
if (cli.testForHelp(args)) {
cli.usage();
return;
} else if (cli.testForBatch(args)) {
String[] batchArgs = BatchCommandLineBuilder.build(args);
BatchProcessDri... | @Test
public void testExtractTgz() throws Exception {
//TIKA-2564
String[] params = {"--extract-dir=" + extractDir.toAbsolutePath(), "-z", resourcePrefix + "/test-documents.tgz"};
TikaCLI.main(params);
String[] tempFileNames = extractDir
.toFile()
.... |
@Override
public boolean apply(InputFile inputFile) {
return originalPredicate.apply(inputFile) && InputFile.Status.SAME != inputFile.status();
} | @Test
public void apply_when_file_is_changed_and_predicate_is_true() {
when(inputFile.status()).thenReturn(InputFile.Status.CHANGED);
when(predicate.apply(inputFile)).thenReturn(true);
Assertions.assertThat(underTest.apply(inputFile)).isTrue();
verify(predicate, times(1)).apply(any());
verify(in... |
@Override
public byte[] serialize() {
final byte[] data = new byte[LENGTH - HEADER_LENGTH];
final ByteBuffer bb = ByteBuffer.wrap(data);
bb.putShort(this.systemPriority);
bb.put(this.systemMac.toBytes());
bb.putShort(this.key);
bb.putShort(this.portPriority);
... | @Test
public void serialize() {
assertArrayEquals(data, BASE_TLV.serialize());
} |
public static FullyQualifiedKotlinType convert(FullyQualifiedJavaType javaType) {
FullyQualifiedKotlinType kotlinType = convertBaseType(javaType);
for (FullyQualifiedJavaType argument : javaType.getTypeArguments()) {
kotlinType.addTypeArgument(convert(argument));
}
return k... | @Test
void testByteWrapperArray() {
FullyQualifiedJavaType jt = new FullyQualifiedJavaType("java.lang.Byte[]");
FullyQualifiedKotlinType kt = JavaToKotlinTypeConverter.convert(jt);
assertThat(kt.getShortNameWithTypeArguments()).isEqualTo("Array<Byte>");
assertThat(kt.getImportList()... |
public static <T> CompletableFuture<T> supplyAsync(
SupplierWithException<T, ?> supplier, Executor executor) {
return CompletableFuture.supplyAsync(
() -> {
try {
return supplier.get();
} catch (Throwable e) {
... | @Test
void testSupplyAsyncFailure() {
final String exceptionMessage = "Test exception";
final FlinkException testException = new FlinkException(exceptionMessage);
final CompletableFuture<Object> future =
FutureUtils.supplyAsync(
() -> {
... |
@Override
public Block toBlock(Type desiredType)
{
checkArgument(BIGINT.equals(desiredType), "type doesn't match: %s", desiredType);
int numberOfRecords = numberOfRecords();
return new LongArrayBlock(
numberOfRecords,
Optional.ofNullable(nulls),
... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testReadBlockWrongDesiredType()
{
PrestoThriftBlock columnsData = longColumn(null, null);
columnsData.toBlock(INTEGER);
} |
static EfestoInputPMML getEfestoInputPMML(String modelName, PMMLRuntimeContext context) {
LocalComponentIdPmml modelLocalUriId = new EfestoAppRoot()
.get(KiePmmlComponentRoot.class)
.get(PmmlIdFactory.class)
.get(context.getFileNameNoSuffix(), getSanitizedClassNam... | @Test
void getEfestoInputPMML() {
String modelName = "modelName";
EfestoInputPMML retrieved = PMMLRuntimeInternalImpl.getEfestoInputPMML(modelName, pmmlRuntimeContext);
assertThat(retrieved).isNotNull();
LocalComponentIdPmml expected = new LocalComponentIdPmml(pmmlRuntimeContext.getF... |
@Nonnull
@Override
public Collection<DataConnectionResource> listResources() {
HazelcastInstance instance = getClient();
try {
return instance.getDistributedObjects()
.stream()
.filter(IMap.class::isInstance)
.map(o -> new D... | @Test
public void list_resources_should_return_map() {
IMap<Integer, String> map = instance.getMap("my_map");
map.put(42, "42");
DataConnectionConfig dataConnectionConfig = sharedDataConnectionConfig(clusterName);
hazelcastDataConnection = new HazelcastDataConnection(dataConnection... |
@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 returns_empty_if_404() {
when(wsClient.call(any())).thenThrow(new HttpException("url", 404, "content"));
assertThat(loader.load()).isEmpty();
assertThat(logs.logs()).anyMatch(s -> s.startsWith("Load analysis cache (404) | time="));
} |
public void close() {
sessionExpirationService.shutdown();
// Update all not clean session with the proper expiry date
updateNotCleanSessionsWithProperExpire();
queueRepository.close();
} | @Test
public void testSerializabilityOfPublishedMessage() {
LOG.info("testSerializabilityOfPublishedMessage");
MVStore mvStore = new MVStore.Builder()
.fileName(BrokerConstants.DEFAULT_PERSISTENT_PATH)
.autoCommitDisabled()
.open();
final MVMap.Builder<Str... |
public TimelineEntity getEntity(
String entityType,
String entityId,
EnumSet<Field> fields,
UserGroupInformation callerUGI) throws YarnException, IOException {
long startTime = Time.monotonicNow();
metrics.incrGetEntityOps();
try {
return doGetEntity(entityType, entityId, field... | @Test
void testGetOldEntityWithOutDomainId() throws Exception {
TimelineEntity entity = dataManaer.getEntity(
"OLD_ENTITY_TYPE_1", "OLD_ENTITY_ID_1", null,
UserGroupInformation.getCurrentUser());
assertNotNull(entity);
assertEquals("OLD_ENTITY_ID_1", entity.getEntityId());
assertEquals... |
@Override
public void readFrame(ChannelHandlerContext ctx, ByteBuf input, Http2FrameListener listener)
throws Http2Exception {
if (readError) {
input.skipBytes(input.readableBytes());
return;
}
try {
do {
if (readingHeaders && !... | @Test
public void failedWhenPriorityFrameDependsOnItself() throws Http2Exception {
final ByteBuf input = Unpooled.buffer();
try {
writePriorityFrame(input, 1, 1, 10);
assertThrows(Http2Exception.class, new Executable() {
@Override
public void e... |
@Override
public void check(final EncryptRule encryptRule, final ShardingSphereSchema schema, final SelectStatementContext sqlStatementContext) {
checkSelect(encryptRule, sqlStatementContext);
for (SelectStatementContext each : sqlStatementContext.getSubqueryContexts().values()) {
checkS... | @Test
void assertCheckWhenShorthandExpandContainsSubqueryTable() {
SelectStatementContext sqlStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS);
when(sqlStatementContext.containsTableSubquery()).thenReturn(true);
when(sqlStatementContext.getSqlStatement().getProjection... |
public static String escapeXML( String content ) {
if ( Utils.isEmpty( content ) ) {
return content;
}
return StringEscapeUtils.escapeXml( content );
} | @Test
public void testEscapeXml() {
final String xml = "<xml xmlns:test=\"http://test\">";
final String escaped = "<xml xmlns:test="http://test">";
assertNull( Const.escapeXml( null ) );
assertEquals( escaped, Const.escapeXml( xml ) );
} |
@Description("Beta cdf given the a, b parameters and value")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double betaCdf(
@SqlType(StandardTypes.DOUBLE) double a,
@SqlType(StandardTypes.DOUBLE) double b,
@SqlType(StandardTypes.DOUBLE) double value)
{
... | @Test
public void testBetaCdf()
{
assertFunction("beta_cdf(3, 3.6, 0.0)", DOUBLE, 0.0);
assertFunction("beta_cdf(3, 3.6, 1.0)", DOUBLE, 1.0);
assertFunction("beta_cdf(3, 3.6, 0.3)", DOUBLE, 0.21764809997679938);
assertFunction("beta_cdf(3, 3.6, 0.9)", DOUBLE, 0.9972502881611551);... |
public final void containsEntry(@Nullable Object key, @Nullable Object value) {
// TODO(kak): Can we share any of this logic w/ MapSubject.containsEntry()?
checkNotNull(actual);
if (!actual.containsEntry(key, value)) {
Map.Entry<@Nullable Object, @Nullable Object> entry = immutableEntry(key, value);
... | @Test
public void containsEntry_failsWithSameToString() throws Exception {
expectFailureWhenTestingThat(
ImmutableMultimap.builder().put(1, "1").put(1, 1L).put(1L, 1).put(2, 3).build())
.containsEntry(1, 1);
assertFailureKeys(
"expected to contain entry",
"an instance of",
... |
@Override
public AppResponse process(Flow flow, CancelFlowRequest request) {
if (appAuthenticator != null && "no_nfc".equals(request.getCode())) {
appAuthenticator.setNfcSupport(false);
}
appSession.setAbortCode(request.getCode());
return new OkResponse();
} | @Test
public void processReturnsOkResponseWithoutNfcCode() {
//given
cancelFlowRequest.setCode("otherCode");
//when
AppResponse appResponse = aborted.process(mockedFlow, cancelFlowRequest);
//then
assertTrue(appResponse instanceof OkResponse);
Assertions.asse... |
@Override
public RunSharedCacheCleanerTaskResponse runCleanerTask(
RunSharedCacheCleanerTaskRequest request) throws YarnException {
checkAcls("runCleanerTask");
RunSharedCacheCleanerTaskResponse response =
recordFactory.newRecordInstance(RunSharedCacheCleanerTaskResponse.class);
this.cleaner... | @Test
void testRunCleanerTaskCLI() throws Exception {
String[] args = {"-runCleanerTask"};
RunSharedCacheCleanerTaskResponse rp =
new RunSharedCacheCleanerTaskResponsePBImpl();
rp.setAccepted(true);
when(mockAdmin.runCleanerTask(isA(RunSharedCacheCleanerTaskRequest.class)))
.thenReturn... |
public static Write write() {
return Write.create();
} | @Test
public void testWriteValidationFailsMissingProjectId() {
BigtableIO.WriteWithResults write =
BigtableIO.write()
.withTableId("table")
.withInstanceId("instance")
.withBigtableOptions(BigtableOptions.builder().build())
.withWriteResults();
thrown.e... |
@Override
public ModelLocalUriId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
JsonNode node = p.getCodec().readTree(p);
String path = node.get("fullPath").asText();
return new ModelLocalUriId(LocalUri.parse(path));
} | @Test
void deserializeEncodedPath() throws IOException {
String json = "{\"model\":\"To%2Bdecode%2Bfirst%2Bpart\"," +
"\"basePath\":\"/To+decode+second+part/To+decode+third+part\"," +
"\"fullPath\":\"/To+decode+first+part/To+decode+second+part/To+decode+third+part\"}";
... |
public void logTerminationAck(
final int memberId,
final long logLeadershipTermId,
final long logPosition,
final int senderMemberId)
{
final int length = ClusterEventEncoder.terminationAckLength();
final int captureLength = captureLength(length);
final int enc... | @Test
void logTerminationAck()
{
final long logLeadershipTermId = 96;
final long logPosition = 128L;
final int memberId = 222;
final int senderMemberId = 982374;
final int offset = 64;
logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset);
logger.log... |
@Override
public List<String> listSchemaNames(ConnectorSession session)
{
return ImmutableList.of(JMX_SCHEMA_NAME, HISTORY_SCHEMA_NAME);
} | @Test
public void testListSchemas()
{
assertEquals(metadata.listSchemaNames(SESSION), ImmutableList.of(JMX_SCHEMA_NAME, HISTORY_SCHEMA_NAME));
} |
@Override
public int hashCode() {
return timestamp.hashCode();
} | @Test
public final void testHashCode() {
Timestamped<String> a = new Timestamped<>("a", TS_1_1);
Timestamped<String> b = new Timestamped<>("b", TS_1_1);
assertTrue("value does not impact hashCode",
a.hashCode() == b.hashCode());
} |
@Override
public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) {
LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats);
TimestampColumnStatsDataInspector aggregateData = timestampInspectorFromStats(aggregateColStats);
... | @Test
public void testMergeNullValues() {
ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(Timestamp.class)
.low(null)
.high(null)
.numNulls(1)
.numDVs(0)
.build());
merger.merge(aggrObj, aggrObj);
ColumnStatisticsData expectedColumnSta... |
@Override
public Status check() {
if (applicationContext == null) {
SpringExtensionInjector springExtensionInjector = SpringExtensionInjector.get(applicationModel);
applicationContext = springExtensionInjector.getContext();
}
if (applicationContext == null) {
... | @Test
void testWithDatasourceHasNextResult() throws SQLException {
Map<String, DataSource> map = new HashMap<String, DataSource>();
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class, Answers.RETURNS_DEEP_STUBS);
given(dataSource.getConnecti... |
@Override
public Set<SystemScope> getDefaults() {
return Sets.filter(getAll(), isDefault);
} | @Test
public void getDefaults() {
Set<SystemScope> defaults = Sets.newHashSet(defaultDynScope1, defaultDynScope2, defaultScope1, defaultScope2);
assertThat(service.getDefaults(), equalTo(defaults));
} |
@Override
protected ObjectListingChunk getObjectListingChunk(String key, boolean recursive)
throws IOException {
String delimiter = recursive ? "" : PATH_SEPARATOR;
key = PathUtils.normalizePath(key, PATH_SEPARATOR);
// In case key is root (empty string) do not normalize prefix
key = key.equals(... | @Test
public void testGetObjectListingChunk() {
// test successful get object listing chunk
Mockito.when(mClient.listObjects(ArgumentMatchers.any(ListObjectsRequest.class)))
.thenReturn(new ObjectListing());
ListObjectsRequest request = new ListObjectsRequest();
Serializable result = mCOSUnder... |
@Override
public List<RoleDO> getRoleList() {
return roleMapper.selectList();
} | @Test
public void testGetRoleList() {
// mock 数据
RoleDO dbRole01 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()));
roleMapper.insert(dbRole01);
RoleDO dbRole02 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()));
... |
public RunResponse restartDirectly(WorkflowInstance instance, RunRequest runRequest) {
Checks.checkTrue(
!runRequest.isFreshRun(),
"Cannot restart a workflow instance %s using fresh run policy [%s]",
instance.getIdentity(),
runRequest.getCurrentPolicy());
if (runRequest.getRestar... | @Test
public void testRestartSubworkflow() {
WorkflowInstance wfInstance = new WorkflowInstance();
SubworkflowInitiator initiator = new SubworkflowInitiator();
UpstreamInitiator.Info info = new UpstreamInitiator.Info();
info.setWorkflowId("foo");
info.setInstanceId(123L);
info.setRunId(2L);
... |
public long getMsgOutCounter() {
return msgOutCounter.longValue();
} | @Test
public void testGetMsgOutCounter() {
stats.msgOutCounter = 1L;
consumer.updateStats(stats);
assertEquals(consumer.getMsgOutCounter(), 1L);
} |
@Override
public List<SnowflakeIdentifier> listIcebergTables(SnowflakeIdentifier scope) {
StringBuilder baseQuery = new StringBuilder("SHOW ICEBERG TABLES");
String[] queryParams = null;
switch (scope.type()) {
case ROOT:
// account-level listing
baseQuery.append(" IN ACCOUNT");
... | @SuppressWarnings("unchecked")
@Test
public void testListIcebergTablesSQLExceptionAtRootLevel()
throws SQLException, InterruptedException {
Exception injectedException =
new SQLException(String.format("SQL exception with Error Code %d", 0), "2000", 0, null);
when(mockClientPool.run(any(ClientP... |
@Override
public PollResult poll(long currentTimeMs) {
if (memberId == null) {
return PollResult.EMPTY;
}
// Send any pending acknowledgements before fetching more records.
PollResult pollResult = processAcknowledgements(currentTimeMs);
if (pollResult != null) {
... | @Test
public void testParseInvalidRecordBatch() {
buildRequestManager();
MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L,
Compression.NONE, TimestampType.CREATE_TIME,
new SimpleRecord(1L, "a".getBytes(), "1".getBytes()),
... |
static int toInteger(final JsonNode object) {
if (object instanceof NumericNode) {
return object.intValue();
}
if (object instanceof TextNode) {
try {
return Integer.parseInt(object.textValue());
} catch (final NumberFormatException e) {
throw failedStringCoercionException(... | @Test(expected = IllegalArgumentException.class)
public void shouldFailWhenConvertingNonIntegerToIntegr() {
JsonSerdeUtils.toInteger(JsonNodeFactory.instance.booleanNode(true));
} |
public static boolean shouldLoadInIsolation(String name) {
return !(EXCLUDE.matcher(name).matches() && !INCLUDE.matcher(name).matches());
} | @Test
public void testMirrorClasses() {
assertTrue(PluginUtils.shouldLoadInIsolation(
"org.apache.kafka.connect.mirror.MirrorSourceTask")
);
assertTrue(PluginUtils.shouldLoadInIsolation(
"org.apache.kafka.connect.mirror.MirrorSourceConnector")
);
} |
public MediaType detect(InputStream input, Metadata metadata) throws IOException {
if (input == null) {
return MediaType.OCTET_STREAM;
}
input.mark(offsetRangeEnd + length);
try {
int offset = 0;
// Skip bytes at the beginning, using skip() or read()... | @Test
public void testDetectNull() throws Exception {
MediaType html = new MediaType("text", "html");
Detector detector = new MagicDetector(html, "<html".getBytes(US_ASCII));
assertEquals(MediaType.OCTET_STREAM, detector.detect(null, new Metadata()));
} |
public static String[] extractRecordKeysByFields(String recordKey, List<String> fields) {
String[] fieldKV = recordKey.split(DEFAULT_RECORD_KEY_PARTS_SEPARATOR);
return Arrays.stream(fieldKV).map(kv -> kv.split(DEFAULT_COMPOSITE_KEY_FILED_VALUE, 2))
.filter(kvArray -> kvArray.length == 1 || fields.isEmp... | @Test
public void testExtractRecordKeysWithFields() {
List<String> fields = new ArrayList<>(1);
fields.add("id2");
String[] s1 = KeyGenUtils.extractRecordKeysByFields("id1:1,id2:2,id3:3", fields);
Assertions.assertArrayEquals(new String[] {"2"}, s1);
String[] s2 = KeyGenUtils.extractRecordKeysBy... |
@CheckForNull
public static File resolveSymlinkToFile(@NonNull File link) throws InterruptedException, IOException {
String target = resolveSymlink(link);
if (target == null) return null;
File f = new File(target);
if (f.isAbsolute()) return f; // absolute symlink
return... | @Test
@Issue("SECURITY-904")
public void resolveSymlinkToFile() throws Exception {
assumeFalse(Functions.isWindows());
// root
// /a
// /aa
// aa.txt
// /_b => symlink to /root/b
// /b
// /_a => sy... |
@Override
public List<MailTemplateDO> getMailTemplateList() {return mailTemplateMapper.selectList();} | @Test
public void testGetMailTemplateList() {
// mock 数据
MailTemplateDO dbMailTemplate01 = randomPojo(MailTemplateDO.class);
mailTemplateMapper.insert(dbMailTemplate01);
MailTemplateDO dbMailTemplate02 = randomPojo(MailTemplateDO.class);
mailTemplateMapper.insert(dbMailTempla... |
public int generate(Class<? extends CustomResource> crdClass, Writer out) throws IOException {
ObjectNode node = nf.objectNode();
Crd crd = crdClass.getAnnotation(Crd.class);
if (crd == null) {
err(crdClass + " is not annotated with @Crd");
} else {
node.put("apiV... | @Test
void generateHelmMetadataLabels() throws IOException {
Map<String, String> labels = new LinkedHashMap<>();
labels.put("app", "{{ template \"strimzi.name\" . }}");
labels.put("chart", "{{ template \"strimzi.chart\" . }}");
labels.put("component", "%plural%.%group%-crd");
... |
@InvokeOnHeader(Web3jConstants.ETH_GET_STORAGE_AT)
void ethGetStorageAt(Message message) throws IOException {
String address = message.getHeader(Web3jConstants.ADDRESS, configuration::getAddress, String.class);
DefaultBlockParameter atBlock
= toDefaultBlockParameter(message.getHeader... | @Test
public void ethGetStorageAtTest() throws Exception {
EthGetStorageAt response = Mockito.mock(EthGetStorageAt.class);
Mockito.when(mockWeb3j.ethGetStorageAt(any(), any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getDat... |
@Override
public List<String> assignSegment(String segmentName, Map<String, Map<String, String>> currentAssignment,
InstancePartitions instancePartitions, InstancePartitionsType instancePartitionsType) {
int numPartitions = instancePartitions.getNumPartitions();
checkReplication(instancePartitions, _rep... | @Test
public void testAssignSegmentWithPartition() {
int numInstancesPerReplicaGroup = NUM_INSTANCES / NUM_REPLICAS;
Map<String, Map<String, String>> currentAssignment = new TreeMap<>();
int numInstancesPerPartition = numInstancesPerReplicaGroup / NUM_PARTITIONS;
for (int segmentId = 0; segmentId < NU... |
@CanIgnoreReturnValue
public final Ordered containsExactly() {
return containsExactlyEntriesIn(ImmutableMap.of());
} | @Test
public void containsExactlyExtraKeyAndMissingKeyAndWrongValue() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "march", 3);
expectFailureWhenTestingThat(actual).containsExactly("march", 33, "feb", 2);
assertFailureKeys(
"keys with wrong values",
"for key",
... |
public String type(Class<?> clz) {
if (!sourcePkgLevelAccessible(clz)) {
clz = Object.class;
}
if (clz.isArray()) {
return getArrayType(clz);
}
String type = ReflectionUtils.getLiteralName(clz);
if (type.startsWith("java.lang")) {
if (!type.substring("java.lang.".length()).cont... | @Test
public void type() {
TypeRef<List<List<String>>> typeRef = new TypeRef<List<List<String>>>() {};
{
CodegenContext ctx = new CodegenContext();
ctx.addImport(List.class);
Assert.assertEquals("List", ctx.type(List.class));
}
CodegenContext ctx = new CodegenContext();
String ty... |
public boolean registerClient(final String addr, final HeartbeatData heartbeat, final long timeoutMillis)
throws RemotingException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.HEART_BEAT, new HeartbeatRequestHeader());
request.setBody(heartb... | @Test
public void testRegisterClient() throws RemotingException, InterruptedException {
mockInvokeSync();
HeartbeatData heartbeatData = new HeartbeatData();
assertTrue(mqClientAPI.registerClient(defaultBrokerAddr, heartbeatData, defaultTimeout));
} |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof BandwidthProfileAction) {
final BandwidthProfileAction that = (BandwidthProfileAction) obj;
return this.getClass() == that.getClass() &&
... | @Test
public void testEquals() {
BandwidthProfileAction passAction1 = BandwidthProfileAction.builder()
.action(Action.PASS)
.build();
BandwidthProfileAction passAction2 = BandwidthProfileAction.builder()
.action(Action.PASS)
.build();
... |
public static FusedPipeline fuse(Pipeline p) {
return new GreedyPipelineFuser(p).fusedPipeline;
} | @Test
public void singleEnvironmentAcrossGroupByKeyMultipleStages() {
Components components =
partialComponents
.toBuilder()
.putTransforms(
"read",
PTransform.newBuilder()
.setUniqueName("Read")
.putInputs("in... |
@Description("Returns the minimum convex geometry that encloses all input geometries")
@ScalarFunction("ST_ConvexHull")
@SqlType(GEOMETRY_TYPE_NAME)
public static Slice stConvexHull(@SqlType(GEOMETRY_TYPE_NAME) Slice input)
{
OGCGeometry geometry = EsriGeometrySerde.deserialize(input);
i... | @Test
public void testSTConvexHull()
{
// test empty geometry
assertConvexHull("POINT EMPTY", "POINT EMPTY");
assertConvexHull("MULTIPOINT EMPTY", "MULTIPOINT EMPTY");
assertConvexHull("LINESTRING EMPTY", "LINESTRING EMPTY");
assertConvexHull("MULTILINESTRING EMPTY", "MUL... |
@ScalarFunction(nullableParameters = true)
public static byte[] toIntegerSumTupleSketch(@Nullable Object key, @Nullable Integer value) {
return toIntegerSumTupleSketch(key, value, CommonConstants.Helix.DEFAULT_TUPLE_SKETCH_LGK);
} | @Test
public void intTupleSumCreation() {
for (Object i : _inputs) {
Assert.assertEquals(intTupleEstimate(SketchFunctions.toIntegerSumTupleSketch(i, 1)), 1.0d);
Assert.assertEquals(intTupleEstimate(SketchFunctions.toIntegerSumTupleSketch(i, 1, 16)), 1.0d);
}
Assert.assertEquals(intTupleEstimat... |
int interact(Cell c, CellPool pool, Cell[][] cellMatrix) {
if (this.candy.getType().equals(Type.REWARD_FRUIT) || c.candy.getType()
.equals(Type.REWARD_FRUIT)) {
return 0;
} else {
if (this.candy.name.equals(c.candy.name)) {
var pointsWon = this.candy.getPoints() + c.candy.getPoints()... | @Test
void interactTest() {
var c1 = new Candy("green jelly", "jelly", Type.CRUSHABLE_CANDY, 5);
var c2 = new Candy("green apple", "apple", Type.REWARD_FRUIT, 10);
var matrix = new Cell[4][4];
matrix[0][0] = new Cell(c1, 0, 0);
matrix[0][1] = new Cell(c1, 1, 0);
matrix[0][2] = new Cell(c2, 2, ... |
public static String generateFullNewWalletFile(String password, File destinationDirectory)
throws NoSuchAlgorithmException,
NoSuchProviderException,
InvalidAlgorithmParameterException,
CipherException,
IOException {
ret... | @Test
public void testGenerateFullNewWalletFile() throws Exception {
String fileName = WalletUtils.generateFullNewWalletFile(PASSWORD, tempDir);
testGeneratedNewWalletFile(fileName);
} |
@Override
public int hashCode() {
return Objects.hash(partition, topicId);
} | @Test
public void testCachedSharePartitionEqualsAndHashCode() {
Uuid topicId = Uuid.randomUuid();
String topicName = "topic";
int partition = 0;
CachedSharePartition cachedSharePartitionWithIdAndName = new
CachedSharePartition(topicName, topicId, partition, false);
... |
public abstract void scan(File dir, FileVisitor visitor) throws IOException; | @Test public void globShouldIgnoreDefaultExcludesByRequest() throws Exception {
FilePath tmp = new FilePath(tmpRule.getRoot());
try {
tmp.child(".gitignore").touch(0);
FilePath git = tmp.child(".git");
git.mkdirs();
git.child("HEAD").touch(0);
... |
public void updateNodeLabels(NodeId node) {
synchronized (lock) {
newlyRegisteredNodes.add(node);
}
} | @Test
public void testWithNodeLabelUpdateEnabled() throws Exception {
conf.setLong(YarnConfiguration.RM_NODE_LABELS_PROVIDER_FETCH_INTERVAL_MS,
1000);
MockRM rm = new MockRM(conf);
rm.init(conf);
rm.getRMContext().getRMDelegatedNodeLabelsUpdater().nodeLabelsUpdateInterval
= 3 * 1000;
... |
public static String getClassMethodKey(final String className, final String methodName) {
return String.join("_", className, methodName);
} | @Test
public void testGetClassMethodKey() {
assertEquals("className_methodName", ApplicationConfigCache.getClassMethodKey("className", "methodName"));
} |
public static HybridPartitionDataConsumeConstraint
getOrDecideHybridPartitionDataConsumeConstraint(
Configuration configuration, boolean enableSpeculativeExecution) {
final HybridPartitionDataConsumeConstraint hybridPartitionDataConsumeConstraint =
configuration
... | @Test
void testOnlyConsumeFinishedPartitionWillSetForSpeculativeEnable() {
HybridPartitionDataConsumeConstraint hybridPartitionDataConsumeConstraint =
getOrDecideHybridPartitionDataConsumeConstraint(new Configuration(), true);
assertThat(hybridPartitionDataConsumeConstraint.isOnlyCon... |
public void completeAllJoinFutures(
Errors error
) {
members.forEach((memberId, member) -> completeJoinFuture(
member,
new JoinGroupResponseData()
.setMemberId(memberId)
.setErrorCode(error.code())
));
} | @Test
public void testCompleteAllJoinFutures() throws ExecutionException, InterruptedException {
JoinGroupRequestProtocolCollection protocols = new JoinGroupRequestProtocolCollection();
protocols.add(new JoinGroupRequestProtocol()
.setName("roundrobin")
.setMetadata(new byte[... |
@Udf(description = "Returns a masked version of the input string. All characters except for the"
+ " last n will be replaced according to the default masking rules.")
@SuppressWarnings("MethodMayBeStatic") // Invoked via reflection
public String mask(
@UdfParameter("input STRING to be masked") final Str... | @Test
public void shouldMaskOnlySpecifiedCharTypes() {
final String result = udf.mask("AbCd#$123xy Z", 5, null, "q", null, "=");
assertThat(result, is("AqCq==123xy Z"));
} |
@Config("resource-groups.config-db-url")
public DbResourceGroupConfig setConfigDbUrl(String configUrl)
{
this.configUrl = configUrl;
return this;
} | @Test
public void testExplicitPropertyMappings()
{
Map<String, String> properties = new ImmutableMap.Builder<String, String>()
.put("resource-groups.config-db-url", "jdbc:mysql//localhost:3306/config?user=presto_admin")
.build();
DbResourceGroupConfig expected = n... |
@Override
public List<ValidationMessage> validate(ValidationContext context) {
return context.query().tokens().stream()
.filter(this::isInvalidOperator)
.map(token -> {
final String errorMessage = String.format(Locale.ROOT, "Query contains invalid operator... | @Test
void testInvalidOperatorLowercaseOr() {
final ValidationContext context = TestValidationContext.create("foo:bar or")
.build();
final List<ValidationMessage> messages = sut.validate(context);
assertThat(messages.size()).isEqualTo(1);
final ValidationMessage messa... |
public Optional<Column> findValueColumn(final ColumnName columnName) {
return findColumnMatching(withNamespace(VALUE).and(withName(columnName)));
} | @Test
public void shouldNotGetKeyColumnFromValue() {
assertThat(SOME_SCHEMA.findValueColumn(K0), is(Optional.empty()));
} |
@Override
public void deleteJournals(long deleteToJournalId) {
List<Long> dbNames = bdbEnvironment.getDatabaseNamesWithPrefix(prefix);
if (dbNames == null) {
LOG.info("delete database names is null.");
return;
}
StringBuilder msg = new StringBuilder("existing... | @Test
public void testDeleteJournals(@Mocked BDBEnvironment environment) throws Exception {
BDBJEJournal journal = new BDBJEJournal(environment);
// failed to get database names; do nothing
new Expectations(environment) {
{
environment.getDatabaseNamesWithPrefix... |
public void setup(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to setup internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final Map<String, Map<String, String>> streamsSideTopicCo... | @Test
public void shouldCreateTopics() throws Exception {
final InternalTopicConfig internalTopicConfig1 = setupRepartitionTopicConfig(topic1, 1);
final InternalTopicConfig internalTopicConfig2 = setupRepartitionTopicConfig(topic2, 1);
internalTopicManager.setup(mkMap(
mkEntry(t... |
public void register(String id, SocketChannel socketChannel) throws IOException {
ensureNotRegistered(id);
registerChannel(id, socketChannel, SelectionKey.OP_READ);
this.sensors.connectionCreated.record();
// Default to empty client information as the ApiVersionsRequest is not
//... | @Test
public void testInboundConnectionsCountInConnectionCreationMetric() throws Exception {
int conns = 5;
try (ServerSocketChannel ss = ServerSocketChannel.open()) {
ss.bind(new InetSocketAddress(0));
InetSocketAddress serverAddress = (InetSocketAddress) ss.getLocalAddress... |
@Override
public void execute(GraphModel graphModel) {
Graph graph = graphModel.getGraphVisible();
execute(graph);
} | @Test
public void testDirectedStarOutGraphDegree() {
GraphModel graphModel = GraphModel.Factory.newInstance();
DirectedGraph directedGraph = graphModel.getDirectedGraph();
Node firstNode = graphModel.factory().newNode("0");
directedGraph.addNode(firstNode);
for (int i = 1; i... |
public <T> T getStore(final StoreQueryParameters<T> storeQueryParameters) {
final String storeName = storeQueryParameters.storeName();
final QueryableStoreType<T> queryableStoreType = storeQueryParameters.queryableStoreType();
final List<T> globalStore = globalStoreProvider.stores(storeName, que... | @Test
public void shouldThrowExceptionWhenLookingForKVStoreWithDifferentType() {
assertThrows(InvalidStateStoreException.class, () -> storeProvider.getStore(StoreQueryParameters.fromNameAndType(keyValueStore,
QueryableStoreTypes.windowStore())).fetch("1", System.currentTimeMillis()));
} |
public CompletableFuture<Acknowledge> stopWithSavepoint(
AsynchronousJobOperationKey operationKey,
String targetDirectory,
SavepointFormatType formatType,
TriggerSavepointMode savepointMode,
Time timeout) {
return registerOperationIdempotently(
... | @Test
public void stopWithSavepointRepeatedly() throws ExecutionException, InterruptedException {
CompletableFuture<Acknowledge> firstAcknowledge =
handler.stopWithSavepoint(
operationKey,
targetDirectory,
SavepointForma... |
public static SqlPrimitiveType of(final String typeName) {
switch (typeName.toUpperCase()) {
case INT:
return SqlPrimitiveType.of(SqlBaseType.INTEGER);
case VARCHAR:
return SqlPrimitiveType.of(SqlBaseType.STRING);
default:
try {
final SqlBaseType sqlType = SqlBase... | @Test
public void shouldReturnSqlType() {
assertThat(SqlPrimitiveType.of(SqlBaseType.INTEGER).baseType(), is(SqlBaseType.INTEGER));
} |
public static String getShortName(String destinationName) {
if (destinationName == null) {
throw new IllegalArgumentException("destinationName is null");
}
if (destinationName.startsWith("queue:")) {
return destinationName.substring(6);
} else if (destinationName.... | @Test
public void testGetShortName() {
assertEquals("foo.DestinationNameParserTest",
DestinationNameParser.getShortName("topic:foo.DestinationNameParserTest"));
assertFalse(DestinationNameParser.isTopic("queue:bar.DestinationNameParserTest"), "bar");
assertFalse(DestinationNa... |
public static IRubyObject deep(final Ruby runtime, final Object input) {
if (input == null) {
return runtime.getNil();
}
final Class<?> cls = input.getClass();
final Rubyfier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return con... | @Test
public void testDeepListWithString() throws Exception {
List<String> data = new ArrayList<>();
data.add("foo");
@SuppressWarnings("rawtypes")
RubyArray rubyArray = (RubyArray)Rubyfier.deep(RubyUtil.RUBY, data);
// toJavaArray does not newFromRubyArray inner elements t... |
@Override
public void subscribeService(Service service, Subscriber subscriber, String clientId) {
Service singleton = ServiceManager.getInstance().getSingletonIfExist(service).orElse(service);
Client client = clientManager.getClient(clientId);
checkClientIsLegal(client, clientId);
cl... | @Test
void testSubscribeWhenClientPersistent() {
assertThrows(NacosRuntimeException.class, () -> {
Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false);
when(clientManager.getClient(anyString())).thenReturn(persistentClient);
// Excepted exception
... |
@Override
public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
if(proxy.isSupported(source, target)) {
return proxy.copy(source, target, status, callback, listener);
... | @Test
public void testCopyWithRenameToExistingFile() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.