focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Operation(summary= "Cancel current session from digid")
@PostMapping(value = "cancel", consumes = "application/json", produces = "application/json")
public Map<String, String> cancel(@Valid @RequestBody AppRequest request) {
RdaSession session = null;
try{
session = findSession(req... | @Test
public void testCancelRestService() {
AppRequest appRequest = new AppRequest();
appRequest.setSessionId("sessionId");
RdaSession session = new RdaSession();
session.setId("sessionId");
mockSession(session);
Map<String, String> responseData = controller.cancel(a... |
@Override
public Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) {
ParamMappingRuleHandle paramMappingRuleHandle = ParamMappingPluginDataHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(rule));
... | @Test
public void testDoExecute() {
SelectorData selectorData = mock(SelectorData.class);
when(this.chain.execute(any())).thenReturn(Mono.empty());
paramMappingPluginDataHandler.handlerRule(ruleData);
StepVerifier.create(paramMappingPlugin.doExecute(this.exchange, this.chain, selecto... |
static void handleJvmOptions(String[] args, String lsJavaOpts) {
final JvmOptionsParser parser = new JvmOptionsParser(args[0]);
final String jvmOpts = args.length == 2 ? args[1] : null;
try {
Optional<Path> jvmOptions = parser.lookupJvmOptionsFile(jvmOpts);
parser.handleJ... | @Test
public void testNettyMaxOrderRuleDoNotAppliesIfAlreadyDefinedExplicitlyByUser() throws IOException {
File optionsFile = writeIntoTempOptionsFile(writer -> writer.println("-Dio.netty.allocator.maxOrder=10"));
JvmOptionsParser.handleJvmOptions(new String[] {"/path/to/ls_home", optionsFile.toStr... |
public ParseResult parse(File file) throws IOException, SchemaParseException {
return parse(file, null);
} | @Test
void testParseByCustomParser() {
Schema schema = new SchemaParser().parse(DummySchemaParser.SCHEMA_TEXT_ONE).mainSchema();
assertEquals(DummySchemaParser.FIXED_SCHEMA, schema);
} |
static InjectorSource instantiateUserSpecifiedInjectorSource(Class<?> injectorSourceClass) {
try {
return (InjectorSource) injectorSourceClass.getConstructor().newInstance();
} catch (Exception e) {
String message = format("Instantiation of '%s' failed. Check the caused by except... | @Test
void failsToInstantiateClassNotImplementingInjectorSource() {
Executable testMethod = () -> instantiateUserSpecifiedInjectorSource(String.class);
InjectorSourceInstantiationFailed actualThrown = assertThrows(InjectorSourceInstantiationFailed.class,
testMethod);
assertAll(
... |
public T getValue() {
T resolvedValue = resolveValue();
if (log.isDebugEnabled()) {
log.debug("Resolved value for property {}={}", key, resolvedValue);
}
return resolveValue();
} | @Test
void testResolveValueWithoutOverride() {
byte defaultByteValue = 9;
short defaultShortValue = 9;
long defaultLongValue = 9;
int defaultIntValue = 9;
float defaultFloatValue = 9.0f;
double defaultDoubleValue = 9.0;
boolean defaultBooleanValue = false;
String defaultStringValue = "... |
@Override
public int compareTo(DateTimeStamp dateTimeStamp) {
return comparator.compare(this,dateTimeStamp);
} | @Test
void testCompareSmallerTimeStampWithoutDateTime() {
DateTimeStamp smaller = new DateTimeStamp(123);
DateTimeStamp greater = new DateTimeStamp(124);
assertEquals(-1, smaller.compareTo(greater));
} |
@Override
public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) {
AbstractWALEvent result;
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
String dataText = new String(bytes, StandardCharsets.UTF_8);
if (decodeWithTX)... | @Test
void assertDecodeWriteRowEventWithByteA() {
MppTableData tableData = new MppTableData();
tableData.setTableName("public.test");
tableData.setOpType("INSERT");
tableData.setColumnsName(new String[]{"data"});
tableData.setColumnsType(new String[]{"bytea"});
tableD... |
public int completeName(String buffer, int cursor, List<InterpreterCompletion> candidates,
Map<String, String> aliases) {
CursorArgument cursorArgument = parseCursorArgument(buffer, cursor);
// find schema and table name if they are
String schema;
String table;
String colu... | @Test
void testCompleteName_WithAliasAndPoint() {
String buffer = "a.";
int cursor = 2;
List<InterpreterCompletion> candidates = new ArrayList<>();
Map<String, String> aliases = new HashMap<>();
aliases.put("a", "prod_dds.financial_account");
sqlCompleter.completeName(buffer, cursor, candidate... |
@Around(DELETE_CONFIG)
public Object aroundDeleteConfig(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response,
String dataId, String group, String tenant) throws Throwable {
if (!PropertyUtil.isManageCapacity()) {
return pjp.proceed();
}
LO... | @Test
void testAroundDeleteConfigForTenant() throws Throwable {
when(PropertyUtil.isManageCapacity()).thenReturn(true);
when(configInfoPersistService.findConfigInfo(any(), any(), any())).thenReturn(null);
when(capacityService.insertAndUpdateClusterUsage(any(), anyBoolean())).thenReturn(true)... |
protected void setInternalEntryCurrentDirectory() {
variables.setVariable( Const.INTERNAL_VARIABLE_ENTRY_CURRENT_DIRECTORY, variables.getVariable(
repository != null ? Const.INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY
: filename != null ? Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRE... | @Test
public void testSetInternalEntryCurrentDirectoryWithFilename( ) {
TransMeta transMetaTest = new TransMeta( );
transMetaTest.setFilename( "hasFilename" );
transMetaTest.setVariable( Const.INTERNAL_VARIABLE_ENTRY_CURRENT_DIRECTORY, "Original value defined at run execution" );
transMetaTest.setVar... |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void terminateQueryShouldGetAnonymized() {
Assert.assertEquals("TERMINATE query;",
anon.anonymize("TERMINATE my_query;"));
Assert.assertEquals("TERMINATE ALL;",
anon.anonymize("TERMINATE ALL;"));
} |
public static <T> List<List<T>> partition(List<T> originalList, int pageSize) {
Preconditions.checkArgument(originalList != null && originalList.size() > 0,
"Invalid original list");
Preconditions.checkArgument(pageSize > 0, "Page size should " +
"be greater than 0 for performing partit... | @Test
public void testListsPartition() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
List<List<String>> res = Lists.
partition(list, 2);
Assertions.assertThat(res)
.describedAs("Number of part... |
@Override
public void checkExit(int status) {
if (userSystemExitMonitored()) {
switch (userSystemExitMode) {
case DISABLED:
break;
case LOG:
// Add exception trace log to help users to debug where exit came from.
... | @Test
void testExistingSecurityManagerRespected() {
// Don't set the following security manager directly to system, which makes test hang.
SecurityManager originalSecurityManager =
new SecurityManager() {
@Override
public void checkPermission(P... |
ConcurrentPublication addPublication(final String channel, final int streamId)
{
clientLock.lock();
try
{
ensureActive();
ensureNotReentrant();
final long registrationId = driverProxy.addPublication(channel, streamId);
stashedChannelByRegistra... | @Test
void closingPublicationShouldPurgeCache()
{
whenReceiveBroadcastOnMessage(
ControlProtocolEvents.ON_PUBLICATION_READY, publicationReadyBuffer, (buffer) -> publicationReady.length());
final Publication firstPublication = conductor.addPublication(CHANNEL, STREAM_ID_1);
... |
@Override
public int compare(ChronoZonedDateTime<?> date1, ChronoZonedDateTime<?> date2) {
return ChronoZonedDateTime.timeLineOrder().compare(date1, date2);
} | @Test
void should_disregard_chronology_difference() {
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime inTokyo = now.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
ChronoZonedDateTime<JapaneseDate> inTokyoJapanese = JapaneseChronology.INSTANCE.zonedDateTime(now);
assertThat(inTokyoJapanese.compa... |
public static SerializableFunction<Row, byte[]> getRowToProtoBytesFromSchema(
String schemaString, String messageName) {
Descriptors.Descriptor descriptor = getDescriptorFromProtoSchema(schemaString, messageName);
ProtoDynamicMessageSchema<DynamicMessage> protoDynamicMessageSchema =
ProtoDynamic... | @Test
public void testRowToProtoSchemaFunction() {
Row row =
Row.withSchema(SCHEMA)
.withFieldValue("id", 1234)
.withFieldValue("name", "Doe")
.withFieldValue("active", false)
.withFieldValue("address.city", "seattle")
.withFieldValue("address.st... |
@Override
public void execute(ComputationStep.Context context) {
DuplicationVisitor visitor = new DuplicationVisitor();
new DepthTraversalTypeAwareCrawler(visitor).visit(treeRootHolder.getReportTreeRoot());
context.getStatistics().add("duplications", visitor.count);
} | @Test
public void loads_multiple_duplications_with_multiple_duplicates() {
reportReader.putDuplications(
FILE_2_REF,
createDuplication(
singleLineTextRange(LINE),
createInnerDuplicate(LINE + 1), createInnerDuplicate(LINE + 2), createInProjectDuplicate(FILE_1_REF, LINE), createInProject... |
public ParsedQuery parse(final String query) throws ParseException {
final TokenCollectingQueryParser parser = new TokenCollectingQueryParser(ParsedTerm.DEFAULT_FIELD, ANALYZER);
parser.setSplitOnWhitespace(true);
parser.setAllowLeadingWildcard(allowLeadingWildcard);
final Query parsed ... | @Test
void getFieldExistPosition() throws ParseException {
final ParsedQuery fields = parser.parse("_exists_:lorem");
assertThat(fields.allFieldNames()).contains("lorem");
assertThat(fields.terms())
.hasSize(1)
.extracting(ParsedTerm::keyToken)
... |
@Override
public boolean shouldWait() {
RingbufferContainer ringbuffer = getRingBufferContainerOrNull();
if (ringbuffer == null) {
return true;
}
if (ringbuffer.isTooLargeSequence(sequence) || ringbuffer.isStaleSequence(sequence)) {
//no need to wait, let the ... | @Test
public void whenBeforeHead() {
ringbuffer.add("item1");
ringbuffer.add("item2");
ringbuffer.add("item3");
long oldhead = ringbuffer.headSequence();
ringbufferContainer.setHeadSequence(ringbufferContainer.tailSequence());
ReadOneOperation op = getReadOneOperati... |
public static SerdeFeatures buildValueFeatures(
final LogicalSchema schema,
final Format valueFormat,
final SerdeFeatures explicitFeatures,
final KsqlConfig ksqlConfig
) {
final boolean singleColumn = schema.value().size() == 1;
final ImmutableSet.Builder<SerdeFeature> builder = Immut... | @Test
public void shouldThrowIfWrapSingleValuePresentForMultiField() {
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> SerdeFeaturesFactory.buildValueFeatures(
MULTI_FIELD_SCHEMA,
JSON,
SerdeFeatures.of(SerdeFeature.WRAP_SINGLES),
... |
public Optional<MaskTable> findMaskTable(final String tableName) {
return Optional.ofNullable(tables.get(tableName));
} | @Test
void assertFindMaskTableWhenTableNameExists() {
assertTrue(maskRule.findMaskTable("t_mask").isPresent());
} |
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
allEntries = true) // allEntries 清空所有缓存,因为此时不知道 id 对应的 permission 是多少。直接清理,简单有效
public void deleteMenu(Long id) {
// 校验是否还有子菜单
if (menuMapper.selectCountByParent... | @Test
public void testDeleteMenu_menuNotExist() {
assertServiceException(() -> menuService.deleteMenu(randomLongId()),
MENU_NOT_EXISTS);
} |
public List<Supplier<PageProjectionWithOutputs>> compileProjections(
SqlFunctionProperties sqlFunctionProperties,
Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions,
List<? extends RowExpression> projections,
boolean isOptimizeCommonSubExpression,
Optiona... | @Test
public void testCommonSubExpressionDuplicatesInProjection()
{
PageFunctionCompiler functionCompiler = new PageFunctionCompiler(createTestMetadataManager(), 0);
List<Supplier<PageProjectionWithOutputs>> pageProjections = functionCompiler.compileProjections(SESSION.getSqlFunctionProperties()... |
@Override
public String rpcType() {
return RpcTypeEnum.SPRING_CLOUD.getName();
} | @Test
public void testRpcType() {
Assertions.assertEquals(springCloudShenyuContextDecorator.rpcType(), "springCloud");
} |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldSupportExplicitEmitChangesForInsertInto() {
// Given:
final SingleStatementContext stmt =
givenQuery("INSERT INTO TEST1 SELECT * FROM TEST2 EMIT CHANGES;");
// When:
final Query result = ((QueryContainer) builder.buildStatement(stmt)).getQuery();
// Then:
asse... |
@Override
public String toString() {
char[] encoded = new char[2 * value.size() + 2];
encoded[0] = '[';
int cnt = 1;
ByteIterator iterator = value.iterator();
while (iterator.hasNext()) {
byte b = iterator.nextByte();
encoded[cnt] = HEX[(b & 0xF0) >>> 4];
++cnt;
encoded[cnt... | @Test
public void testToString() {
assertEquals("[]", ByteKey.EMPTY.toString());
assertEquals("[00]", ByteKey.of(0).toString());
assertEquals("[0000]", ByteKey.of(0x00, 0x00).toString());
assertEquals(
"[0123456789abcdef]",
ByteKey.of(0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef).toS... |
public SendResult putMessageToRemoteBroker(MessageExtBrokerInner messageExt, String brokerNameToSend) {
if (this.brokerController.getBrokerConfig().getBrokerName().equals(brokerNameToSend)) { // not remote broker
return null;
}
final boolean isTransHalfMessage = TransactionalMessageU... | @Test
public void testPutMessageToRemoteBroker_noSpecificBrokerName_hasRemoteBroker() throws Exception {
MessageExtBrokerInner message = new MessageExtBrokerInner();
message.setTopic(TEST_TOPIC);
String anotherBrokerName = "broker_b";
TopicPublishInfo publishInfo = mockTopicPublishIn... |
@Override
public Object get(int ordinal, DataType dataType) {
if (ordinal < metaFields.length) {
validateMetaFieldDataType(dataType);
return metaFields[ordinal];
}
return sourceRow.get(rebaseOrdinal(ordinal), dataType);
} | @Test
public void testGet() {
Object[] values = getRandomValue(true);
InternalRow row = new GenericInternalRow(values);
HoodieInternalRow hoodieInternalRow = new HoodieInternalRow(UTF8String.fromString("commitTime"),
UTF8String.fromString("commitSeqNo"),
UTF8String.fromString("recordKey")... |
@Override
public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) {
AbstractConfig config = new AbstractConfig(CONFIG_DEF, connectorConfig);
String filename = config.getString(FILE_CONFIG);
if (filename == null || filename.isEmpty()) {
... | @Test
public void testSuccessfulAlterOffsets() {
Map<Map<String, ?>, Map<String, ?>> offsets = Collections.singletonMap(
Collections.singletonMap(FILENAME_FIELD, FILENAME),
Collections.singletonMap(POSITION_FIELD, 0L)
);
// Expect no exception to be thrown wh... |
public int attempts() {
return this.attempts.intValue();
} | @Test
void attempts() {
final var e = new BusinessException("unhandled");
final var retry = new Retry<String>(
() -> {
throw e;
},
2,
0
);
try {
retry.perform();
} catch (BusinessException ex) {
//ignore
}
assertThat(retry.attempts(), ... |
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) {
return new DateTime(dateStr, dateFormat);
} | @Test
public void parseUTCTest4() {
final String dateStr = "2023-02-07T00:02:16.12345+08:00";
final DateTime dateTime = DateUtil.parse(dateStr);
assertNotNull(dateTime);
assertEquals("2023-02-07 00:02:16", dateTime.toString());
final String dateStr2 = "2023-02-07T00:02:16.12345-08:00";
final DateTime date... |
public static Locale createLocale( String localeCode ) {
if ( Utils.isEmpty( localeCode ) ) {
return null;
}
StringTokenizer parser = new StringTokenizer( localeCode, "_" );
if ( parser.countTokens() == 2 ) {
return new Locale( parser.nextToken(), parser.nextToken() );
}
if ( parser.... | @Test
public void createLocale_SingleCode() throws Exception {
assertEquals( Locale.ENGLISH, EnvUtil.createLocale( "en" ) );
} |
public static Map<String, List<String>> tagInstantsOfBaseAndLogFiles(
String basePath, List<StoragePath> allPaths) {
// Instant time -> Set of base and log file paths
Map<String, List<String>> instantToFilesMap = new HashMap<>();
allPaths.forEach(path -> {
String instantTime = FSUtils.getCommitT... | @Test
public void testTagInstantsOfBaseAndLogFiles() {
Map<String, List<String>> expectedResult = new HashMap<>();
List<StoragePath> inputPathList = new ArrayList<>();
for (Map.Entry<String, List<Pair<String, String>>> entry : BASE_FILE_INFO.entrySet()) {
String instantTime = entry.getKey();
... |
@Override
public ByteBuf setInt(int index, int value) {
checkIndex(index, 4);
_setInt(index, value);
return this;
} | @Test
public void testSetIntAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().setInt(0, 1);
}
});
} |
public synchronized RepositoryConnectResult connect( final String username, final String password )
throws KettleException {
if ( serviceManager != null ) {
disconnect();
}
serviceManager = new WebServiceManager( repositoryMeta.getRepositoryLocation().getUrl(), username );
RepositoryServiceReg... | @Test
public void testConnect() {
PurRepository mockPurRepository = mock( PurRepository.class );
PurRepositoryMeta mockPurRepositoryMeta = mock( PurRepositoryMeta.class );
PurRepositoryLocation location = mock( PurRepositoryLocation.class );
RootRef mockRootRef = mock( RootRef.class );
PurReposito... |
static ApplicationId getFromApplicationId(HttpRequest request) {
String from = request.getProperty("from");
if (from == null || "".equals(from))
throw new BadRequestException("Parameter 'from' has illegal value '" + from + "'");
return getAndValidateFromParameter(URI.create(from));
... | @Test
public void require_that_application_urls_can_be_given_as_from_parameter() throws Exception {
ApplicationId applicationId = ApplicationId.from(tenant.value(), "foo", "quux");
HttpRequest request = post(Map.of(
"from",
"http://myhost:40555/application/v2/tenant/"... |
@Override
public ConfigOperateResult insertOrUpdateBeta(final ConfigInfo configInfo, final String betaIps, final String srcIp,
final String srcUser) {
if (findConfigInfo4BetaState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant()) == null) {
return addConfigInfo4B... | @Test
void testInsertOrUpdateBetaOfAdd() {
String dataId = "betaDataId113";
String group = "group113";
String tenant = "tenant113";
//mock exist beta
ConfigInfoStateWrapper mockedConfigInfoStateWrapper = new ConfigInfoStateWrapper();
mockedConfigInfoStateWrapper.setDa... |
static void populateSchemaWithConstraints(Schema toPopulate, SimpleTypeImpl t) {
if (t.getAllowedValues() != null && !t.getAllowedValues().isEmpty()) {
parseSimpleType(DMNOASConstants.X_DMN_ALLOWED_VALUES, toPopulate, t.getAllowedValuesFEEL(), t.getAllowedValues());
}
if (t.getTypeCo... | @Test
void populateSchemaWithRangesForAllowedValues() {
List<Object> toRange = Arrays.asList("(>1)", "(<=10)");
String allowedValuesString = String.join(",",
toRange.stream().map(toMap -> String.format("%s", toMap)).toList());
SimpleTypeImpl t... |
@Override
public void dispose() {
mDisposable.dispose();
} | @Test
public void testDispose() {
DefaultSkinTonePrefTracker tracker =
new DefaultSkinTonePrefTracker(AnyApplication.prefs(getApplicationContext()));
Assert.assertFalse(tracker.isDisposed());
Assert.assertNull(tracker.getDefaultSkinTone());
SharedPrefsHelper.setPrefsValue(R.string.settings_ke... |
@Draft
public ZMsg msgBinaryPicture(String picture, Object... args)
{
if (!BINARY_FORMAT.matcher(picture).matches()) {
throw new ZMQException(picture + " is not in expected binary format " + BINARY_FORMAT.pattern(),
ZError.EPROTO);
}
ZMsg msg = new ZMsg();... | @Test(expected = ZMQException.class)
public void testInvalidPictureMsgNotInTheEnd()
{
String picture = "m1";
ZMsg msg = new ZMsg().push("Hello");
pic.msgBinaryPicture(picture, msg, 255);
} |
@Override
public RList<V> get(K key) {
String keyHash = keyHash(key);
String setName = getValuesName(keyHash);
return new RedissonList<V>(codec, commandExecutor, setName, null) {
@Override
public RFuture<Boolean> addAsync(V value) {
retur... | @Test
public void testDistributedIterator() {
RListMultimap<String, String> map = redisson.getListMultimap("set", StringCodec.INSTANCE);
// populate set with elements
List<String> stringsOne = IntStream.range(0, 64).mapToObj(i -> "" + i).collect(Collectors.toList());
map.putAll("som... |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type =... | @Test
public void applyGeneratesArray() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
objectNode.put("type", "array");
JClass mockArrayType = mock(JClass.class);
ArrayRule ... |
static Polygon buildPolygon(TDWay way) {
Coordinate[] coordinates = JTSUtils.toCoordinates(way);
return GEOMETRY_FACTORY.createPolygon(GEOMETRY_FACTORY.createLinearRing(coordinates), null);
} | @Test
public void testBuildInValidPolygonWith2InnerRings() {
String testfile = "invalid-polygon-2-inner-rings.wkt";
List<TDWay> ways = MockingUtils.wktPolygonToWays(testfile);
Polygon polygon = JTSUtils.buildPolygon(ways.get(0), ways.subList(1, ways.size()));
Geometry expected = Moc... |
@Override
public double get(int i, int j) {
return values[i][j];
} | @Test
public void serialization431Test() throws URISyntaxException, IOException {
Path matrixPath = Paths.get(DenseMatrixTest.class.getResource("dense-matrix-431.tribuo").toURI());
try (InputStream fis = Files.newInputStream(matrixPath)) {
TensorProto proto = TensorProto.parseFrom(fis);
... |
public static void testHandleResourceUsageReport(long backendId, TResourceUsage usage) {
resourceUsageReport(backendId, usage);
} | @Test
public void testHandleResourceUsageReport() {
ResourceUsageMonitor resourceUsageMonitor = GlobalStateMgr.getCurrentState().getResourceUsageMonitor();
Backend backend = new Backend(0, "127.0.0.1", 80);
ComputeNode computeNode = new ComputeNode(2, "127.0.0.1", 88);
new MockUp<S... |
@Override
protected Class<?> loadClass(final String name, final boolean resolve)
throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
try {
final Class<?> loadedClass = findLoadedClass(name);
if (loadedClass != null) {
... | @Test
void testOwnerFirstClassNotFoundFallsBackToComponent() throws Exception {
TestUrlClassLoader owner = new TestUrlClassLoader();
final ComponentClassLoader componentClassLoader =
new ComponentClassLoader(
new URL[0],
owner,
... |
public static long getPresetReminder(Long currentReminder) {
long now = Calendar.getInstance().getTimeInMillis();
return currentReminder != null && currentReminder > now ? currentReminder : getNextMinute();
} | @Test
public void getPresetReminder() {
var nextHour = Calendar.getInstance().getTimeInMillis() + 60 * 60 * 1000;
assertEquals(nextHour, DateUtils.getPresetReminder(nextHour));
var previousMinute = Calendar.getInstance().getTimeInMillis() - 60 * 1000;
var nextMinute = Calendar.getInstance().getTimeIn... |
public static void info(final Object message, final String query) {
log(Level.INFO, message, query);
} | @Test
public void shouldContainAQueryID() {
String message = "my message";
String query = "DESCRIBE cat EXTENDED;";
QueryLogger.info(message, query);
testAppender
.getLog()
.forEach(
(e) -> {
final QueryLoggerMessage msg = (QueryLoggerMessage) e.getMessage();... |
static SortedMap<Field, Descriptor> buildBeanedDescriptorsMap(
Class<?> clz, boolean searchParent) {
List<Field> fieldList = new ArrayList<>();
Class<?> clazz = clz;
Map<Tuple2<Class, String>, Method> methodMap = new HashMap<>();
do {
Field[] fields = clazz.getDeclaredFields();
for (Fi... | @Test
public void testBuildBeanedDescriptorsMap() throws Exception {
Assert.assertEquals(BeanA.class.getDeclaredField("f1"), BeanA.class.getDeclaredField("f1"));
Assert.assertNotSame(BeanA.class.getDeclaredField("f1"), BeanA.class.getDeclaredField("f1"));
SortedMap<Field, Descriptor> map = Descriptor.buil... |
public static SourceDescription create(
final DataSource dataSource,
final boolean extended,
final List<RunningQuery> readQueries,
final List<RunningQuery> writeQueries,
final Optional<TopicDescription> topicDescription,
final List<QueryOffsetSummary> queryOffsetSummaries,
fina... | @Test
public void testShouldIncludeRemoteStatsIfProvided() {
final List<QueryHostStat> remoteStats = IntStream.range(0, 5)
.boxed()
.map(x -> new QueryHostStat(
new KsqlHostInfoEntity("otherhost:1090"),
ConsumerCollector.CONSUMER_MESSAGES_PER_SEC,
x,
... |
public static ScheduledTaskHandler of(UUID uuid, String schedulerName, String taskName) {
return new ScheduledTaskHandlerImpl(uuid, -1, schedulerName, taskName);
} | @Test(expected = IllegalArgumentException.class)
public void of_withWrongBase() {
ScheduledTaskHandler.of("wrongbase:-\u00000\u0000Scheduler\u0000Task");
} |
@Override
public <T extends ComponentRoot> T get(Class<T> providerId) {
try {
return providerId.getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException(e);
}
} | @Test
void getNoDefaultConstructorImplementation() {
IllegalArgumentException thrown = assertThrows(
IllegalArgumentException.class,
() -> appRoot.get(ComponentRootNoDefaultConstructor.class),
"Expected constructor to throw, but it didn't"
);
S... |
@Operation(summary = "get services", tags = { SwaggerConfig.SHARED }, operationId = "app_services",
parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter(ref = "OS-V"), @Parameter(ref = "REL-T")})
@GetMapping(value = "services", produces = "application/jso... | @Test
void validateIfCorrectProcessesAreCalledGetUrls() {
configController.getWebserversUrls();
verify(configService, times(1)).getWebserverUrls();
} |
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) {
return new DateTime(dateStr, dateFormat);
} | @SuppressWarnings("ConstantConditions")
@Test
public void parseSingleNumberTest() {
DateTime dateTime = DateUtil.parse("2020-5-08");
assertEquals("2020-05-08 00:00:00", dateTime.toString());
dateTime = DateUtil.parse("2020-5-8");
assertEquals("2020-05-08 00:00:00", dateTime.toString());
dateTime = DateUtil.... |
public void shiftOffsetsBy(final Consumer<byte[], byte[]> client,
final Set<TopicPartition> inputTopicPartitions,
final long shiftBy) {
final Map<TopicPartition, Long> endOffsets = client.endOffsets(inputTopicPartitions);
final Map<TopicParti... | @Test
public void testShiftOffsetByWhenBeforeBeginningOffset() {
final Map<TopicPartition, Long> endOffsets = new HashMap<>();
endOffsets.put(topicPartition, 4L);
consumer.updateEndOffsets(endOffsets);
final Map<TopicPartition, Long> beginningOffsets = new HashMap<>();
begin... |
public static String getPasswordFromProperties(Properties properties, Function<String, String> keyTransform)
throws HiveException, IOException {
String passwd = properties.getProperty(keyTransform.apply(CONFIG_PWD));
String keystore = properties.getProperty(keyTransform.apply(CONFIG_PWD_KEYSTORE));
St... | @Test
public void testExtractPassword() throws Exception {
String prefix = "test.";
String password = "my-super-secret";
Properties props = new Properties();
props.put(prefix + JdbcStorageConfigManager.CONFIG_PWD, password);
props.put(prefix + JdbcStorageConfigManager.CONFIG_PWD_URI, "test:///rand... |
public int initialWindowLength()
{
return CongestionControl.receiverWindowLength(ccOutcome);
} | @Test
void shouldSetWindowLengthFromContext()
{
final UdpChannel channelWithoutWindow = UdpChannel.parse("aeron:udp?endpoint=127.0.0.1:9999");
final MediaDriver.Context context = new MediaDriver.Context().initialWindowLength(16536);
final int termLength = 1_000_000;
final Static... |
@Override
public void loginSuccess(HttpRequest request, @Nullable String login, Source source) {
checkRequest(request);
requireNonNull(source, "source can't be null");
LOGGER.atDebug().setMessage("login success [method|{}][provider|{}|{}][IP|{}|{}][login|{}]")
.addArgument(source::getMethod)
.... | @Test
public void login_success_does_not_interact_with_request_if_log_level_is_above_DEBUG() {
HttpRequest request = mock(HttpRequest.class);
logTester.setLevel(Level.INFO);
underTest.loginSuccess(request, "login", Source.sso());
assertThat(logTester.logs()).isEmpty();
} |
public String toJsonString(Object object) {
return String.valueOf(toJson(object));
} | @Test
public void testJsonString() {
String output = _obfuscator.toJsonString("{\"key\":\"VALUE\",\"my.secret\":\"SECRET\"}");
Assert.assertTrue(output.contains(VALUE));
Assert.assertFalse(output.contains(SECRET));
} |
@Override
public void upload(UploadTask uploadTask) throws IOException {
Throwable error = getErrorSafe();
if (error != null) {
LOG.debug("don't persist {} changesets, already failed", uploadTask.changeSets.size());
uploadTask.fail(error);
return;
}
... | @Test
void testInterruptedWhenBackPressured() throws Exception {
int limit = MAX_BYTES_IN_FLIGHT;
TestScenario test =
(uploader, probe) -> {
List<StateChangeSet> changes = getChanges(limit + 1);
upload(uploader, changes);
as... |
public Object evaluate(
final GenericRow row,
final Object defaultValue,
final ProcessingLogger logger,
final Supplier<String> errorMsg
) {
try {
return expressionEvaluator.evaluate(new Object[]{
spec.resolveArguments(row),
defaultValue,
logger,
... | @Test
public void shouldReturnDefaultIfEvalThrows() throws Exception {
// Given:
spec.addParameter(
ColumnName.of("foo1"),
Integer.class,
0
);
compiledExpression = new CompiledExpression(
expressionEvaluator,
spec.build(),
EXPRESSION_TYPE,
expre... |
public String[] getPathComponents() {
return getFullPath().split(QUEUE_REGEX_DELIMITER);
} | @Test
public void testGetPathComponents() {
Assert.assertArrayEquals(TEST_QUEUE_PATH.getPathComponents(),
new String[] {"root", "level_1", "level_2", "level_3"});
Assert.assertArrayEquals(ROOT_PATH.getPathComponents(), new String[] {"root"});
Assert.assertArrayEquals(EMPTY_PATH.getPathComponents()... |
public HikariDataSource getDataSource() {
return ds;
} | @Test
@Ignore
public void testGetDataSource() {
DataSource ds = SingletonServiceFactory.getBean(DataSource.class);
assertNotNull(ds);
HikariDataSource hds = (HikariDataSource)ds;
System.out.println(hds.getMaximumPoolSize());
try(Connection connection = ds.getConnection(... |
@Override
public Mono<Long> delete(final long id) {
return Mono.zip(
dataSourceRepository.existsByNamespace(id),
collectorRepository.existsByNamespace(id),
termRepository.existsByNamespace(id),
dataEntityRepository.existsNonDeletedByNamespaceId... | @Test
@DisplayName("Tries to delete a namespace which is tied with existing data source and fails with an error")
public void testDeleteTiedNamespaceWithDataSource() {
final long namespaceId = 1L;
when(collectorRepository.existsByNamespace(eq(namespaceId))).thenReturn(Mono.just(false));
... |
@PostMapping("/change_two_factor")
@Operation(summary = "Set the two factor setting of an account")
public AccountResult changeTwoFactor(@RequestBody DTwoFactorChangeRequest deprecatedRequest) {
validateSettingTwoFactor(deprecatedRequest);
AppSession appSession = validate(deprecatedRequest);
... | @Test
public void invalidSettingTwoFactor() {
DTwoFactorChangeRequest request = new DTwoFactorChangeRequest();
request.setAppSessionId("id");
DAccountException exc = assertThrows(DAccountException.class, () -> {
twoFactorController.changeTwoFactor(request);
});
... |
public TimeUnit getConnTimeToLiveTimeUnit() {
return connTimeToLiveTimeUnit;
} | @Test
void testGetConnTimeToLiveTimeUnit() {
HttpClientConfig config = HttpClientConfig.builder().setConnectionTimeToLive(4000, TimeUnit.SECONDS).build();
assertEquals(TimeUnit.SECONDS, config.getConnTimeToLiveTimeUnit());
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
try {
try {
final PreferencesReader preferences = new HostPreferences(session.get... | @Test
public void testFindRoot() throws Exception {
final FTPAttributesFinderFeature f = new FTPAttributesFinderFeature(session);
assertEquals(PathAttributes.EMPTY, f.find(new Path("/", EnumSet.of(Path.Type.directory))));
} |
public String fingerprint(final PublicKey key) throws BackgroundException {
return this.fingerprint(new ByteArrayInputStream(
new Buffer.PlainBuffer().putPublicKey(key).getCompactData()));
} | @Test
public void testFingerprint() throws Exception {
final FileKeyProvider f = new OpenSSHKeyFile.Factory().create();
f.init("", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC/71hmi4R+CZqGvZ+aVdaKIt5yb2H87yNAAcdtPAQBJBqKw/vR0iYeU/tnwKWRfnTK/NcN2H6yG/wx0o9WiavUhUaSUPesJo3/PpZ7fZMUk/Va8I7WI0i25XlWJTE8SMFf... |
public static boolean deleteQuietly(@Nullable File file) {
if (file == null) {
return false;
}
try {
if (file.isDirectory()) {
deleteDirectory(file);
if (file.exists()) {
LOG.warn("Unable to delete directory '{}'", file);
}
} else {
Files.delete(... | @Test
public void deleteQuietly_deletes_directory_and_content() throws IOException {
Path target = temporaryFolder.newFolder().toPath();
Path childFile1 = Files.createFile(target.resolve("file1.txt"));
Path childDir1 = Files.createDirectory(target.resolve("subDir1"));
Path childFile2 = Files.createFil... |
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
} | @Test
public void testIncrementalFromLatestSnapshotWithNonEmptyTable() throws Exception {
appendTwoSnapshots();
ScanContext scanContext =
ScanContext.builder()
.startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_LATEST_SNAPSHOT)
.build();
ContinuousSplitPlannerImp... |
@Override
public String convert(IAccessEvent accessEvent) {
if (!isStarted()) {
return "INACTIVE_REQUEST_PARAM_CONV";
}
// This call should be safe, because the request map is cached beforehand
final String[] paramArray = accessEvent.getRequestParameterMap().get(key);
... | @Test
void testConvertSeveralParameters() throws Exception {
Mockito.when(httpServletRequest.getParameterValues("name")).thenReturn(new String[]{"Alice", "Bob"});
Mockito.when(httpServletRequest.getParameterNames())
.thenReturn(Collections.enumeration(Collections.singleton("name")));... |
@Override
public void upgrade() {
if (clusterConfigService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already done.");
return;
}
// Do not overwrite an existing default index config
boolean defaultDone = clusterConfigService.get(DefaultInde... | @Test
@MongoDBFixtures("V20161215163900_MoveIndexSetDefaultConfigTest.json")
public void upgradeWhenMigrationCompleted() throws Exception {
// Count how many documents with a "default" field are in the database.
final long count = collection.countDocuments(Filters.exists("default"));
as... |
public Plan validateReservationSubmissionRequest(
ReservationSystem reservationSystem, ReservationSubmissionRequest request,
ReservationId reservationId) throws YarnException {
String message;
if (reservationId == null) {
message = "Reservation id cannot be null. Please try again specifying "
... | @Test
public void testSubmitReservationEmptyRR() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 0, 1, 5, 3);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUt... |
public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) {
HttpHeaders inHeaders = in.headers();
final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size());
if (in instanceof HttpRequest) {
HttpRequest request = (HttpRequest) in;
... | @Test
public void cookieNoSpace() {
final HttpHeaders inHeaders = new DefaultHttpHeaders();
inHeaders.add(COOKIE, "one=foo;two=bar");
final Http2Headers out = new DefaultHttp2Headers();
HttpConversionUtil.toHttp2Headers(inHeaders, out);
assertEquals("one=foo;two=bar", out.get... |
public void setSendFullErrorException(boolean sendFullErrorException) {
this.sendFullErrorException = sendFullErrorException;
} | @Test
void handleFlowableIllegalStateExceptionWithoutSendFullErrorException() throws Exception {
testController.exceptionSupplier = () -> new FlowableIllegalStateException("task not active");
handlerAdvice.setSendFullErrorException(false);
String body = mockMvc.perform(get("/"))
... |
public String getTag() {
return tag;
} | @Test
void testGetTag() {
String tag = metadataOperation.getTag();
assertNull(tag);
} |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
void testNestedTupleGenerics() {
RichMapFunction<?, ?> function =
new RichMapFunction<Nested<String, Integer>, Nested<String, Integer>>() {
private static final long serialVersionUID = 1L;
@Overri... |
public static Map<String, Object> flatten(Map<String, Object> originalMap, String parentKey, String separator) {
final Map<String, Object> result = new HashMap<>();
for (Map.Entry<String, Object> entry : originalMap.entrySet()) {
final String key = parentKey.isEmpty() ? entry.getKey() : pare... | @Test
public void flattenHandlesEmptyMap() throws Exception {
assertThat(MapUtils.flatten(Collections.emptyMap(), "", "_")).isEmpty();
} |
public List<KuduPredicate> convert(ScalarOperator operator) {
if (operator == null) {
return null;
}
return operator.accept(this, null);
} | @Test
public void testIn() {
ConstantOperator value = ConstantOperator.createInt(5);
ConstantOperator value1 = ConstantOperator.createInt(6);
ConstantOperator value2 = ConstantOperator.createInt(7);
ScalarOperator op = new InPredicateOperator(false, F0, value, value1, value2);
... |
@GET
@Path("{name}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getConfig(@PathParam("name") String configName) {
log.trace(String.format(MESSAGE_CONFIG, QUERY));
final TelemetryConfig config =
nullIsNotFound(configService... | @Test
public void testDeleteConfigWithModifyOperation() {
expect(mockConfigAdminService.getConfig(anyString()))
.andReturn(telemetryConfig).once();
mockConfigAdminService.removeTelemetryConfig(anyString());
replay(mockConfigAdminService);
final WebTarget wt = target(... |
@Nullable
public <T> Map<String, T> getInstancesWithoutAncestors(String name, Class<T> type) {
return getContext(name).getBeansOfType(type);
} | @Test
void getInstancesWithoutAncestors_verifyEmptyForMissing() {
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
parent.refresh();
FeignClientFactory feignClientFactory = new FeignClientFactory();
feignClientFactory.setApplicationContext(parent);
feignClientFactory.set... |
@Override
public void visit(Entry entry) {
if(Boolean.FALSE.equals(entry.getAttribute("allowed")))
return;
if (containsSubmenu(entry))
addSubmenu(entry);
else
addActionItem(entry);
} | @Test
public void createsSubmenuWithAction() {
Entry parentMenuEntry = new Entry();
final JMenu parentMenu = new JMenu();
new EntryAccessor().setComponent(parentMenuEntry, parentMenu);
parentMenuEntry.addChild(menuEntry);
menuEntry.addChild(actionEntry);
new EntryAccessor().setAction(menuEntry, action);
... |
public boolean isExpired() {
Instant now = clock.instant();
Duration between = Duration.between(lastUpdatedTime, now);
// Compare elapsed time to EXPIRATION_MINUTES
long minutes = between.toMinutes();
return minutes >= EXPIRATION_MINUTES;
} | @Test
public void testIsExpired() {
Instant now = Instant.now();
Instant expiredTime = now.minus(JobUploadStatus.EXPIRATION_MINUTES, ChronoUnit.MINUTES);
when(clock.instant()).thenReturn(expiredTime, now);
jobUploadStatus.changeLastUpdatedTime();
boolean result = jobUpload... |
public static ColumnDataType convertToColumnDataType(RelDataType relDataType) {
SqlTypeName sqlTypeName = relDataType.getSqlTypeName();
if (sqlTypeName == SqlTypeName.NULL) {
return ColumnDataType.UNKNOWN;
}
boolean isArray = (sqlTypeName == SqlTypeName.ARRAY);
if (isArray) {
assert relD... | @Test
public void testConvertToColumnDataTypeForArray() {
Assert.assertEquals(RelToPlanNodeConverter.convertToColumnDataType(
new ArraySqlType(new ObjectSqlType(SqlTypeName.BOOLEAN, SqlIdentifier.STAR, true, null, null), true)),
DataSchema.ColumnDataType.BOOLEAN_ARRAY);
Assert.assertEquals... |
public static DwrfTableEncryptionProperties forPerColumn(ColumnEncryptionInformation columnEncryptionInformation, String encryptionAlgorithm, String encryptionProvider)
{
return new DwrfTableEncryptionProperties(Optional.empty(), Optional.of(columnEncryptionInformation), encryptionAlgorithm, encryptionProvi... | @Test
public void testEncryptColumns()
{
ColumnEncryptionInformation columnEncryptionInformation = fromMap(ImmutableMap.of("c1", "abcd", "c2", "defg"));
DwrfTableEncryptionProperties properties = forPerColumn(columnEncryptionInformation, "test_algo", "test_prov");
assertEquals(propertie... |
public static <NumT extends Number>
Combine.AccumulatingCombineFn<NumT, CountSum<NumT>, Double> of() {
return new MeanFn<>();
} | @Test
public void testMeanFn() throws Exception {
testCombineFn(Mean.of(), Lists.newArrayList(1, 2, 3, 4), 2.5);
} |
public FEELFnResult<Boolean> invoke(@ParameterName("string") String string, @ParameterName("match") String match) {
if ( string == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null"));
}
if ( match == null ) {
return... | @Test
void invokeContains() {
FunctionTestUtil.assertResult(containsFunction.invoke("test", "es"), true);
FunctionTestUtil.assertResult(containsFunction.invoke("test", "t"), true);
FunctionTestUtil.assertResult(containsFunction.invoke("testy", "y"), true);
} |
public synchronized void doMigrate(MigrationRule rule) {
if (migrationInvoker instanceof ServiceDiscoveryMigrationInvoker) {
refreshInvoker(MigrationStep.FORCE_APPLICATION, 1.0f, rule);
return;
}
// initial step : APPLICATION_FIRST
MigrationStep step = MigrationS... | @Test
void test() {
MigrationClusterInvoker<?> invoker = Mockito.mock(MigrationClusterInvoker.class);
URL url = Mockito.mock(URL.class);
Mockito.when(url.getDisplayServiceKey()).thenReturn("test");
Mockito.when(url.getParameter(Mockito.any(), (String) Mockito.any())).thenAnswer(i -> ... |
public static void renameTo(File src, File dst)
throws IOException {
if (!nativeLoaded) {
if (!src.renameTo(dst)) {
throw new IOException("renameTo(src=" + src + ", dst=" +
dst + ") failed.");
}
} else {
renameTo0(src.getAbsolutePath(), dst.getAbsolutePath());
}
} | @Test (timeout = 30000)
public void testCreateFile() throws Exception {
assumeWindows();
LOG.info("Open a file on Windows with SHARE_DELETE shared mode");
try {
File testfile = new File(TEST_DIR, "testCreateFile");
assertTrue("Create test subject",
testfile.exists() || testfile.crea... |
@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 anonymousUserToken() throws Exception{
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
JenkinsRule.WebClient webClient = j.createWebClient();
String token = getToken(webClient);
Assert.assertNotNull(token);
JsonWebStructure jsonWebStructure = Jso... |
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessageByDestinationAndGuid(
final UUID destinationAccountUuid, final Device destinationDevice, final UUID messageUuid) {
return Stream.of(convertPartitionKey(destinationAccountUuid, destinationDevice),
convertPartitionKeyDeprecated(dest... | @Test
void testDeleteMessageByDestinationAndGuid() throws Exception {
final UUID destinationUuid = UUID.randomUUID();
final UUID secondDestinationUuid = UUID.randomUUID();
final Device primary = DevicesHelper.createDevice((byte) 1);
final Device device2 = DevicesHelper.createDevice((byte) 2);
mes... |
@Override
public boolean removeAll(Collection<?> collection) {
// Using this implementation from the Android ArrayList since the Java 1.8 ArrayList
// doesn't call through to remove. Calling through to remove lets us leverage the notification
// done there
boolean result = false;
Iterator<?> it = ... | @Test
public void testRemoveAll() {
List<EpoxyModel<?>> modelsToRemove = new ArrayList<>();
modelsToRemove.add(modelList.get(0));
modelsToRemove.add(modelList.get(1));
modelList.removeAll(modelsToRemove);
verify(observer, times(2)).onItemRangeRemoved(0, 1);
} |
@Override
public boolean createMep(MdId mdName, MaIdShort maName, Mep newMep) throws CfmConfigException {
MepKeyId key = new MepKeyId(mdName, maName, newMep.mepId());
log.debug("Creating MEP " + newMep.mepId() + " on MD {}, MA {} on Device {}",
mdName, maName, newMep.deviceId().toStr... | @Test
public void testCreateMep() throws CfmConfigException {
expect(mdService.getMaintenanceAssociation(MDNAME1, MANAME1))
.andReturn(Optional.ofNullable(ma1))
.anyTimes();
replay(mdService);
expect(deviceService.getDevice(DEVICE_ID1)).andReturn(device1).any... |
public boolean sendEventToJS(String eventName, Bundle data, ReactContext reactContext) {
if (reactContext != null) {
sendEventToJS(eventName, Arguments.fromBundle(data), reactContext);
return true;
}
return false;
} | @Test
public void sendEventToJS_hasReactContext_emitsEventToJs() throws Exception {
WritableMap data = mock(WritableMap.class);
final JsIOHelper uut = createUUT();
boolean result = uut.sendEventToJS("my-event", data, mReactContext);
assertTrue(result);
verify(mRCTDeviceEven... |
@Override
public void onUpdate(Extension oldExtension, Extension newExtension) {
if (isDisposed() || !matchers.onUpdateMatcher().match(newExtension)) {
return;
}
// TODO filter the event
queue.addImmediately(new Request(newExtension.getMetadata().getName()));
} | @Test
void shouldUpdateExtensionWhenUpdatePredicateAlwaysTrue() {
when(matchers.onUpdateMatcher()).thenReturn(getEmptyMatcher());
watcher.onUpdate(createFake("old-fake-name"), createFake("new-fake-name"));
verify(matchers, times(1)).onUpdateMatcher();
verify(queue, times(1)).addImme... |
public static Criterion matchInPhyPort(PortNumber port) {
return new PortCriterion(port, Type.IN_PHY_PORT);
} | @Test
public void testMatchInPhyPortMethod() {
PortNumber p1 = portNumber(1);
Criterion matchInPhyPort = Criteria.matchInPhyPort(p1);
PortCriterion portCriterion =
checkAndConvert(matchInPhyPort,
Criterion.Type.IN_PHY_PORT,
... |
@Override
public void configure(Map<String, ?> configs) {
final SimpleConfig simpleConfig = new SimpleConfig(CONFIG_DEF, configs);
final String field = simpleConfig.getString(FIELD_CONFIG);
final String type = simpleConfig.getString(TARGET_TYPE_CONFIG);
String formatPattern = simpleC... | @Test
public void testConfigNoTargetType() {
assertThrows(ConfigException.class, () -> xformValue.configure(Collections.emptyMap()));
} |
private static Object parseInstance( String value, Function<String, String> resolver, List<ClassLoader> addonClassLoaders ) {
return (LazyValue) t -> {
try {
if( value.indexOf( ',' ) >= 0 ) {
// Syntax: className,param1,param2,...
List<String> parts = splitFunctionParams( value, ',' );
String cl... | @Test
void parseInstance() {
String className = TestInstance.class.getName();
assertEquals( new TestInstance(), ((LazyValue)UIDefaultsLoader.parseValue( "dummyIcon", className, null )).createValue( null ) );
assertInstanceEquals( new TestInstance(), null );
assertInstanceEquals( new TestInstance( "some string"... |
@Override
public Collection<Process> getProcessList() {
return ProcessRegistry.getInstance().listAll();
} | @Test
void assertGetProcessList() {
ProcessRegistry processRegistry = mock(ProcessRegistry.class);
when(ProcessRegistry.getInstance()).thenReturn(processRegistry);
processPersistService.getProcessList();
verify(processRegistry).listAll();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.