focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static HttpResponseStatus parseLine(CharSequence line) {
return (line instanceof AsciiString) ? parseLine((AsciiString) line) : parseLine(line.toString());
} | @Test
public void parseLineStringMalformedCode() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
parseLine("200a");
}
});
} |
public static <T> ListenableFuture<T> submit(final RequestBuilder<T> requestBuilder) {
return transformFromTargetAndResult(submitInternal(requestBuilder));
} | @Test
public void testErrorLoad() {
// Load some unsupported model.
final ListenableFuture<Bitmap> future =
GlideFutures.submit(Glide.with(app).asBitmap().load(app));
// Make sure that it throws.
assertThrows(
ExecutionException.class,
new ThrowingRunnable() {
@Overri... |
public static int read(
final UnsafeBuffer termBuffer,
final int termOffset,
final FragmentHandler handler,
final int fragmentsLimit,
final Header header,
final ErrorHandler errorHandler,
final long currentPosition,
final Position subscriberPosition)
{... | @Test
void shouldReadMultipleMessages()
{
final int msgLength = 1;
final int frameLength = HEADER_LENGTH + msgLength;
final int alignedFrameLength = align(frameLength, FRAME_ALIGNMENT);
final int termOffset = 0;
when(termBuffer.getIntVolatile(0)).thenReturn(frameLength);... |
public int getBytesSize(SeaTunnelRowType rowType) {
if (size == 0) {
int s = 0;
for (int i = 0; i < fields.length; i++) {
s += getBytesForValue(fields[i], rowType.getFieldType(i));
}
size = s;
}
return size;
} | @Test
void testForRowSize() {
Map<String, Object> map = new HashMap<>();
map.put(
"key1",
new SeaTunnelRow(
new Object[] {
1, "test", 1L, new BigDecimal("3333.333"),
}));
map.put(
... |
@Override
public void onChangeLogParsed(Run<?, ?> run, SCM scm, TaskListener listener, ChangeLogSet<?> changelog) throws Exception {
try {
JiraSite jiraSite = JiraSite.get(run.getParent());
if (jiraSite == null) {
return;
}
Collection<String> ... | @Test
public void onChangeLogParsed() throws Exception {
JiraSCMListener listener = new JiraSCMListener();
Job job = mock(Job.class);
Run run = mock(Run.class);
ChangeLogSet logSet = mock(ChangeLogSet.class);
final ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class);
... |
@VisibleForTesting
ZonedDateTime parseZoned(final String text, final ZoneId zoneId) {
final TemporalAccessor parsed = formatter.parse(text);
final ZoneId parsedZone = parsed.query(TemporalQueries.zone());
ZonedDateTime resolved = DEFAULT_ZONED_DATE_TIME.apply(
ObjectUtils.defaultIfNull(parsedZone... | @Test
public void shouldParseFullLocalDateWithOptionalElements() {
// Given
final String format = "yyyy-MM-dd[ HH:mm:ss]";
final String timestamp = "1605-11-05";
// When
final ZonedDateTime ts = new StringToTimestampParser(format).parseZoned(timestamp, ZID);
// Then
assertThat(ts, is(sam... |
@Override
public TableDataConsistencyCheckResult swapToObject(final YamlTableDataConsistencyCheckResult yamlConfig) {
if (null == yamlConfig) {
return null;
}
if (!Strings.isNullOrEmpty(yamlConfig.getIgnoredType())) {
return new TableDataConsistencyCheckResult(TableDa... | @Test
void assertSwapToObjectWithString() {
TableDataConsistencyCheckResult actual = yamlTableDataConsistencyCheckResultSwapper.swapToObject("ignoredType: NO_UNIQUE_KEY");
assertThat(actual.getIgnoredType(), is(TableDataConsistencyCheckIgnoredType.NO_UNIQUE_KEY));
assertFalse(actual.isMatche... |
static void askForHardStop(File tmpDir) throws IOException {
writeToShareMemory(tmpDir, 1, (byte) 0xFF);
} | @Test
public void askForHardStop_write_right_bit_with_right_value_in_right_file() throws Exception {
File tempFolder = temporaryFolder.newFolder();
Shutdowner.askForHardStop(tempFolder);
try (RandomAccessFile sharedMemory = new RandomAccessFile(new File(tempFolder, "sharedmemory"), "r")) {
// Using... |
public static <
EventTypeT,
EventKeyTypeT,
ResultTypeT,
StateTypeT extends MutableState<EventTypeT, ResultTypeT>>
OrderedEventProcessor<EventTypeT, EventKeyTypeT, ResultTypeT, StateTypeT> create(
OrderedProcessingHandler<EventTypeT, EventKeyTypeT, StateTypeT, Resu... | @Test
public void testHandlingOfDuplicateSequences() throws CannotProvideCoderException {
Event[] events = {
Event.create(3, "id-1", "d"),
Event.create(2, "id-1", "c"),
// Duplicates to be buffered
Event.create(3, "id-1", "d"),
Event.create(3, "id-1", "d"),
Event.create(0, "id-... |
public static void checkParamsLength(final Integer argsLength, final Integer typesLength) {
if (argsLength < typesLength) {
throw new ShenyuException("args.length < types.length");
}
} | @Test
public void testcheckParamsLength() {
assertDoesNotThrow(() -> ParamCheckUtils.checkParamsLength(2, 2));
} |
@SuppressWarnings("unchecked")
public static <T> NFAFactory<T> compileFactory(
final Pattern<T, ?> pattern, boolean timeoutHandling) {
if (pattern == null) {
// return a factory for empty NFAs
return new NFAFactoryImpl<>(
0,
Collect... | @Test
public void testNoUnnecessaryStateCopiesCreated() {
final Pattern<Event, Event> pattern =
Pattern.<Event>begin("start")
.where(startFilter)
.notFollowedBy("not")
.where(startFilter)
.followe... |
public JobStatsExtended enrich(JobStats jobStats) {
JobStats latestJobStats = getLatestJobStats(jobStats, previousJobStats);
if (lock.tryLock()) {
setFirstRelevantJobStats(latestJobStats);
setJobStatsExtended(latestJobStats);
setPreviousJobStats(latestJobStats);
... | @Test
void firstRelevantJobStatsIsUpdatedAfterWorkIsDone() {
JobStats firstJobStats = getJobStats(0L, 0L, 0L, 100L);
jobStatsEnricher.enrich(firstJobStats);
SleepUtils.sleep(2); //sleeping as JVM is too fast and runs code in the same nanosecond
JobStats secondJobStats = getJobStats(... |
public boolean isEqualTo(Version version) {
return major == version.major && minor == version.minor;
} | @Test
public void isEqualTo() throws Exception {
assertTrue(V3_0.isEqualTo(of(3, 0)));
assertFalse(V3_0.isEqualTo(of(4, 0)));
} |
@Override
public MetadataNode child(String name) {
try {
Integer brokerId = Integer.valueOf(name);
ControllerRegistration registration = image.controllers().get(brokerId);
if (registration == null) return null;
return new MetadataLeafNode(registration.toString... | @Test
public void testNode1Child() {
MetadataNode child = NODE.child("2");
assertNotNull(child);
assertEquals("ControllerRegistration(id=2, " +
"incarnationId=adGo6sTPS0uJshjvdTUmqQ, " +
"zkMigrationReady=false, " +
"listeners=[], " +
"supporte... |
public ClientDetailsEntity() {
} | @Test
public void testClientDetailsEntity() {
Date now = new Date();
ClientDetailsEntity c = new ClientDetailsEntity();
c.setClientId("s6BhdRkqt3");
c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk");
c.setApplicationType(ClientDetailsEntity.AppType.WEB);
c.setRedirectUris(ImmutableSet.of("... |
public Map<String, String> build() {
Map<String, String> builder = new HashMap<>();
configureFileSystem(builder);
configureNetwork(builder);
configureCluster(builder);
configureSecurity(builder);
configureOthers(builder);
LOGGER.info("Elasticsearch listening on [HTTP: {}:{}, TCP: {}:{}]",
... | @Test
public void configureSecurity_whenHttpKeystoreNotProvided_shouldNotAddHttpProperties() throws Exception {
Props props = minProps(true);
File keystore = temp.newFile("keystore.p12");
File truststore = temp.newFile("truststore.p12");
props.set(CLUSTER_SEARCH_PASSWORD.getKey(), "qwerty");
props... |
@SafeVarargs
public final PromiseAggregator<V, F> add(Promise<V>... promises) {
ObjectUtil.checkNotNull(promises, "promises");
if (promises.length == 0) {
return this;
}
synchronized (this) {
if (pendingPromises == null) {
int size;
... | @Test
public void testAddNullFuture() {
@SuppressWarnings("unchecked")
Promise<Void> p = mock(Promise.class);
@SuppressWarnings("deprecation")
final PromiseAggregator<Void, Future<Void>> a =
new PromiseAggregator<Void, Future<Void>>(p);
assertThrows(NullPointe... |
Duration getLockAtLeastFor(AnnotationData annotation) {
return getValue(
annotation.getLockAtLeastFor(),
annotation.getLockAtLeastForString(),
this.defaultLockAtLeastFor,
"lockAtLeastForString");
} | @Test
public void shouldGetPositiveGracePeriodFromAnnotationWithString() throws NoSuchMethodException {
noopResolver();
SpringLockConfigurationExtractor.AnnotationData annotation =
getAnnotation("annotatedMethodWithPositiveGracePeriodWithString");
TemporalAmount gracePeriod =... |
@Override
public boolean next() throws SQLException {
if (orderByValuesQueue.isEmpty()) {
return false;
}
if (isFirstNext) {
isFirstNext = false;
return true;
}
OrderByValue firstOrderByValue = orderByValuesQueue.poll();
if (firstOr... | @Test
void assertNextForMix() throws SQLException {
List<QueryResult> queryResults = Arrays.asList(mock(QueryResult.class), mock(QueryResult.class), mock(QueryResult.class));
for (int i = 0; i < 3; i++) {
QueryResultMetaData metaData = mock(QueryResultMetaData.class);
when(qu... |
@Override
public long extract(
final ConsumerRecord<Object, Object> record,
final long previousTimestamp
) {
return timestampExtractor.extract(record, previousTimestamp);
} | @Test(expected = UnsupportedOperationException.class)
public void shouldThrowUnsupportedExceptionOnExtractGenericRow() {
// when/Then
new MetadataTimestampExtractor(timestampExtractor)
.extract(mock(Struct.class), mock(GenericRow.class));
} |
@Override
public NativeEntity<CacheDto> createNativeEntity(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Object> nativeEntities,
... | @Test
public void createNativeEntity() {
final Entity entity = EntityV1.builder()
.id(ModelId.of("1"))
.type(ModelTypes.LOOKUP_CACHE_V1)
.data(objectMapper.convertValue(LookupCacheEntity.create(
ValueReference.of(DefaultEntityScope.NAME... |
@Override
public KsqlSecurityContext provide(final ApiSecurityContext apiSecurityContext) {
final Optional<KsqlPrincipal> principal = apiSecurityContext.getPrincipal();
final Optional<String> authHeader = apiSecurityContext.getAuthHeader();
final List<Entry<String, String>> requestHeaders = apiSecurityCo... | @Test
public void shouldPassAuthHeaderToDefaultFactory() {
// Given:
when(securityExtension.getUserContextProvider()).thenReturn(Optional.empty());
when(apiSecurityContext.getAuthHeader()).thenReturn(Optional.of("some-auth"));
// When:
ksqlSecurityContextProvider.provide(apiSecurityContext);
... |
@Override
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @Test
public void isEqualTo_WithoutToleranceParameter_Fail_NotEqual() {
expectFailureWhenTestingThat(array(2.2f)).isEqualTo(array(JUST_OVER_2POINT2));
assertFailureKeys("expected", "but was", "differs at index");
assertFailureValue("expected", "[" + floatToString(JUST_OVER_2POINT2) + "]");
assertFailu... |
@VisibleForTesting
static LocalImage cacheDockerImageTar(
BuildContext buildContext,
Path tarPath,
ProgressEventDispatcher.Factory progressEventDispatcherFactory,
TempDirectoryProvider tempDirectoryProvider)
throws IOException, LayerCountMismatchException {
ExecutorService executorSe... | @Test
public void testCacheDockerImageTar_validTar() throws Exception {
Path tarBuild = getResource("core/extraction/jib-image.tar");
LocalImage result =
LocalBaseImageSteps.cacheDockerImageTar(
buildContext, tarBuild, progressEventDispatcherFactory, tempDirectoryProvider);
Mockito.ve... |
public static Parser parser() {
return ParserImpl.INSTANCE;
} | @Test
void testCharsetInputValidation() {
assertThrows(NullPointerException.class, new Executable() {
@Override
public void execute() throws IOException {
HostsFileEntriesProvider.parser().parse((Charset[]) null);
}
});
assertThrows(NullPo... |
String extractStem(String className) {
if (className == null)
return null;
int lastDotIndex = className.lastIndexOf(CoreConstants.DOT);
if (lastDotIndex == -1)
return null;
if ((lastDotIndex + 1) == className.length())
return null;
return clas... | @Test
public void testStemExtraction() {
assertNull(imh.extractStem(null));
assertNull(imh.extractStem(""));
assertNull(imh.extractStem("bla."));
assertEquals("Foo", imh.extractStem("bla.Foo"));
assertEquals("Foo", imh.extractStem("com.titi.bla.Foo"));
} |
public static LevenbergMarquardt fit(DifferentiableMultivariateFunction func, double[] x, double[] y, double[] p) {
return fit(func, x, y, p, 0.0001, 20);
} | @Test
public void test() {
System.out.println("LevenbergMarquardt");
MathEx.setSeed(19650218); // to get repeatable results.
double[] x = new double[100];
double[] y = new double[100];
GaussianDistribution d = new GaussianDistribution(0.0, 1);
for (int i = 0; i < x.l... |
public String reverseResolve(String address) {
if (WalletUtils.isValidAddress(address, addressLength)) {
String reverseName = Numeric.cleanHexPrefix(address) + REVERSE_NAME_SUFFIX;
PublicResolver resolver = obtainOffchainResolver(reverseName);
byte[] nameHash = NameHash.name... | @Test
public void testReverseResolve() throws Exception {
configureSyncing(false);
configureLatestBlock(System.currentTimeMillis() / 1000); // block timestamp is in seconds
NetVersion netVersion = new NetVersion();
netVersion.setResult(Long.toString(ChainIdLong.MAINNET));
S... |
public static DaysWindows weeks(int number, int startDayOfWeek) {
return new DaysWindows(
7 * number, DEFAULT_START_DATE.withDayOfWeek(startDayOfWeek), DateTimeZone.UTC);
} | @Test
public void testWeeks() throws Exception {
Map<IntervalWindow, Set<String>> expected = new HashMap<>();
final List<Long> timestamps =
Arrays.asList(
makeTimestamp(2014, 1, 1, 0, 0).getMillis(),
makeTimestamp(2014, 1, 5, 5, 5).getMillis(),
makeTimestamp(2014, ... |
@Override
@SuppressFBWarnings("PATH_TRAVERSAL_IN") // suppressing because we are using the getValidFilePath
public String getMimeType(String file) {
if (file == null || !file.contains(".")) {
return null;
}
String mimeType = null;
// may not work on Lambda until mai... | @Test
@Disabled
void getMimeType_disabledPath_expectException() {
AwsServletContext ctx = new AwsServletContext(null);
try {
assertNull(ctx.getMimeType("/usr/local/lib/nothing"));
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().startsWith("File pa... |
public static boolean containsLocalIp(List<InetSocketAddress> clusterAddresses,
AlluxioConfiguration conf) {
String localAddressIp = getLocalIpAddress((int) conf.getMs(PropertyKey
.NETWORK_HOST_RESOLUTION_TIMEOUT_MS));
for (InetSocketAddress addr : clusterAddresses) {
String clusterNodeIp;
... | @Test
public void testContainsLocalIP() {
List<InetSocketAddress> clusterAddresses = new ArrayList<>();
InetSocketAddress raftNodeAddress1 = new InetSocketAddress(NetworkAddressUtils
.getLocalHostName(
(int) mConfiguration.getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS)),
10)... |
public String getRealm() {
return realm;
} | @Test
public void testRules() throws Exception {
checkTranslation("omalley@" + KerberosTestUtils.getRealm(), "omalley");
checkTranslation("hdfs/10.0.0.1@" + KerberosTestUtils.getRealm(), "hdfs");
checkTranslation("oom@YAHOO.COM", "oom");
checkTranslation("johndoe/zoo@FOO.COM", "guest");
checkTrans... |
@Override
public boolean markSupported() {
return false;
} | @Test
public void testMarkSupported() throws Exception {
try (InputStream sample = new ByteArrayInputStream(sample1.getBytes());
JsonArrayFixingInputStream instance = new JsonArrayFixingInputStream(sample)) {
boolean result = instance.markSupported();
assertFalse(resu... |
public void init(ScannerReportWriter writer) {
File analysisLog = writer.getFileStructure().analysisLog();
try (BufferedWriter fileWriter = Files.newBufferedWriter(analysisLog.toPath(), StandardCharsets.UTF_8)) {
writePlugins(fileWriter);
writeBundledAnalyzers(fileWriter);
writeGlobalSettings(... | @Test
public void init_splitsPluginsByTypeInTheFile() throws IOException {
DefaultInputModule parent = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder())
.setProperty("sonar.projectKey", "parent")
.setProperty(SONAR_SKIP, "true"));... |
public void updateTopicConfig(final TopicConfig topicConfig) {
updateSingleTopicConfigWithoutPersist(topicConfig);
this.persist(topicConfig.getTopicName(), topicConfig);
} | @Test
public void testAddWrongValueOnCreating() {
Map<String, String> attributes = new HashMap<>();
attributes.put("+" + TopicAttributes.QUEUE_TYPE_ATTRIBUTE.getName(), "wrong-value");
TopicConfig topicConfig = new TopicConfig();
topicConfig.setTopicName("new-topic");
topicC... |
@Override
public <KR, VR> KStream<KR, VR> map(final KeyValueMapper<? super K, ? super V, ? extends KeyValue<? extends KR, ? extends VR>> mapper) {
return map(mapper, NamedInternal.empty());
} | @Test
public void shouldNotAllowNullMapperOnMap() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.map(null));
assertThat(exception.getMessage(), equalTo("mapper can't be null"));
} |
@Override
public void add(long key, String value) {
// fix https://github.com/crossoverJie/cim/issues/79
treeMap.clear();
for (int i = 0; i < VIRTUAL_NODE_SIZE; i++) {
Long hash = super.hash("vir" + key + i);
treeMap.put(hash,value);
}
treeMap.put(key... | @Test
public void getFirstNodeValue2() {
AbstractConsistentHash map = new TreeMapConsistentHash() ;
List<String> strings = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
strings.add("127.0.0." + i) ;
}
String process = map.process(strings,"zhangsan2");
... |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testNonIncreasingOffsetRecordBatchHasMetricsLogged() {
ByteBuffer buf = ByteBuffer.allocate(512);
MemoryRecordsBuilder builder = MemoryRecords.builder(buf, RecordBatch.MAGIC_VALUE_V2, Compression.NONE, TimestampType.CREATE_TIME, 0L);
builder.appendWithOffset(0, RecordBatch.... |
public boolean register(String nodeId, List<ZookeeperNodeInfo> payload) {
if (payload == null || payload.isEmpty()) {
return false;
}
lock.lock();
try {
createPathIfNotExisted();
if (member != null) {
LOG.warn("GroupMember has already r... | @Test
public void testRegister() throws Exception {
List<ZookeeperNodeInfo> payload = new ArrayList<ZookeeperNodeInfo>();
ZookeeperNodeInfo node1 = new ZookeeperNodeInfo();
node1.setPrefix("foo");
node1.setHost("127.0.0.1");
node1.setPort(1234);
node1.setDatabase("foo... |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateJobStatus(Long id, Integer status) throws SchedulerException {
// 校验 status
if (!containsAny(status, JobStatusEnum.NORMAL.getStatus(), JobStatusEnum.STOP.getStatus())) {
throw exception(JOB_CHANGE_STATUS_INVALI... | @Test
public void testUpdateJobStatus_changeStatusInvalid() {
// 调用,并断言异常
assertServiceException(() -> jobService.updateJobStatus(1L, JobStatusEnum.INIT.getStatus()),
JOB_CHANGE_STATUS_INVALID);
} |
@Override
public void setControllers(List<ControllerInfo> controllers) {
DriverHandler handler = handler();
OvsdbClientService clientService = getOvsdbClientService(handler);
if (!clientService.getControllers(handler().data().deviceId())
.equals(ImmutableSet.copyOf(controller... | @Test
public void testSetControllers() throws Exception {
} |
@Override
public Map<String, Object> newMap() {
return new CaseInsensitiveMap<>();
} | @Test
public void testLookupCaseAgnostic() {
Map<String, Object> map = new FastHeadersMapFactory().newMap();
assertNull(map.get("foo"));
map.put("foo", "cheese");
assertEquals("cheese", map.get("foo"));
assertEquals("cheese", map.get("Foo"));
assertEquals("cheese", ... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertConnectionInfo() throws Exception {
String connectionId = "myConnectionId";
String clientId = "myClientId";
ConnectionInfo dataStructure = new ConnectionInfo();
dataStructure.setConnectionId(new ConnectionId(connectionId));
dataStructure.setClientId(clientId);... |
public static Type convertType(TypeInfo typeInfo) {
switch (typeInfo.getOdpsType()) {
case BIGINT:
return Type.BIGINT;
case INT:
return Type.INT;
case SMALLINT:
return Type.SMALLINT;
case TINYINT:
ret... | @Test
public void testConvertTypeCaseSmallint() {
TypeInfo typeInfo = TypeInfoFactory.SMALLINT;
Type result = EntityConvertUtils.convertType(typeInfo);
assertEquals(Type.SMALLINT, result);
} |
@Override
public void profileSet(JSONObject properties) {
} | @Test
public void profileSet() {
mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
Assert.fail();
return false;
}
});
... |
public void maybeAutoCommitOffsetsAsync(long now) {
if (autoCommitEnabled) {
nextAutoCommitTimer.update(now);
if (nextAutoCommitTimer.isExpired()) {
nextAutoCommitTimer.reset(autoCommitIntervalMs);
autoCommitOffsetsAsync();
}
}
} | @Test
public void testAutoCommitAfterCoordinatorBackToService() {
try (ConsumerCoordinator coordinator = buildCoordinator(rebalanceConfig, new Metrics(), assignors, true, subscriptions)) {
subscriptions.assignFromUser(Collections.singleton(t1p));
subscriptions.seek(t1p, 100L);
... |
@Override
public String getGroupKeyString(int rowIndex, int groupKeyColumnIndex) {
return _groupByResults.get(rowIndex).get("group").get(groupKeyColumnIndex).asText();
} | @Test
public void testGetGroupKeyString() {
// Run the test
final String result = _groupByResultSetUnderTest.getGroupKeyString(0, 0);
// Verify the results
assertEquals("testGroup1", result);
} |
@SuppressWarnings({"PMD.AvoidInstantiatingObjectsInLoops"})
public void validate(Workflow workflow, User caller) {
try {
RunProperties runProperties = new RunProperties();
runProperties.setOwner(caller);
Map<String, ParamDefinition> workflowParams = workflow.getParams();
Map<String, ParamD... | @Test
public void testValidatePass() {
when(paramsManager.generateMergedWorkflowParams(any(), any()))
.thenReturn(new LinkedHashMap<>());
when(paramsManager.generateMergedStepParams(any(), any(), any(), any()))
.thenReturn(new LinkedHashMap<>());
dryRunValidator.validate(definition.getWork... |
public FileSystem get(Key key) {
synchronized (mLock) {
Value value = mCacheMap.get(key);
FileSystem fs;
if (value == null) {
// On cache miss, create and insert a new FileSystem instance,
fs = FileSystem.Factory.create(FileSystemContext.create(key.mSubject, key.mConf));
mC... | @Test
public void getSameKey() {
Key key1 = createTestFSKey("user1");
FileSystem fs1 = mFileSystemCache.get(key1);
FileSystem fs2 = mFileSystemCache.get(key1);
assertSame(getDelegatedFileSystem(fs1), getDelegatedFileSystem(fs2));
assertFalse(fs1.isClosed());
assertFalse(fs2.isClosed());
} |
public static ScalarType createUnifiedDecimalType() {
// for mysql compatibility
return createUnifiedDecimalType(10, 0);
} | @Test
public void createUnifiedDecimalTypeWithoutPrecisionAndScale() throws AnalysisException {
ScalarType.createUnifiedDecimalType();
} |
public static String packAttributes(EnumSet<FileAttribute> attributes) {
StringBuilder buffer = new StringBuilder(FileAttribute.values().length);
int len = 0;
for (FileAttribute attribute : attributes) {
buffer.append(attribute.name().charAt(0));
len++;
}
return buffer.substring(0, len);... | @Test
public void testPackAttributes() {
EnumSet<FileAttribute> attributes = EnumSet.noneOf(FileAttribute.class);
assertThat(DistCpUtils.packAttributes(attributes)).isEqualTo("");
attributes.add(FileAttribute.REPLICATION);
assertThat(DistCpUtils.packAttributes(attributes)).isEqualTo("R");
attrib... |
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Version that = (Version) o;
return version.equals(that.getVersion());
} | @Test
public void testEquals() throws Exception {
assertTrue(Version.from(0, 20, 0).equals(Version.from(0, 20, 0)));
assertTrue(Version.from(0, 20, 0, "preview.1").equals(Version.from(0, 20, 0, "preview.1")));
assertTrue(Version.from(1, 2, 3).equals(Version.from(1, 2, 3)));
Version ... |
public ImmutableSet<String> getAllRoleIds() {
// Use a MongoCollection query here to avoid the mongojack deserializing and object creation overhead
final FindIterable<Document> docs = dbCollection.find().projection(Projections.include("_id"));
return StreamSupport.stream(docs.spliterator(), fal... | @Test
void getAllRoleIds() {
assertThat(service.getAllRoleIds()).isEqualTo(ImmutableSet.of(
"564c6707c8306e079f718980",
"56701ac4c8302ff6bee2a65d",
"5b17d7c63f3ab8204eea0589",
"58dbaa158ae4923256dc6266",
"564c6707c8306e079f71897... |
private void validateHmsUri(String catalogHmsUri) {
if (catalogHmsUri == null) {
return;
}
Configuration conf = SparkSession.active().sessionState().newHadoopConf();
String envHmsUri = conf.get(HiveConf.ConfVars.METASTOREURIS.varname, null);
if (envHmsUri == null) {
return;
}
P... | @Test
public void testValidateHmsUri() {
// HMS uris match
Assert.assertTrue(
spark
.sessionState()
.catalogManager()
.v2SessionCatalog()
.defaultNamespace()[0]
.equals("default"));
// HMS uris doesn't match
spark.sessionState().cata... |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testAnalyzePackageJson() throws Exception {
try (Engine engine = new Engine(getSettings())) {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "requirements.txt"));
engine.addDependency(result);
analyzer.analyze(result, engine);
... |
@Override
public List<Object> handle(String targetName, List<Object> instances, RequestData requestData) {
if (requestData == null) {
return super.handle(targetName, instances, null);
}
if (!shouldHandle(instances)) {
return instances;
}
List<Object> r... | @Test
public void testGetTargetInstancesByFlowRulesWithGlobalRules() {
RuleInitializationUtils.initGlobalAndServiceFlowMatchRules();
List<Object> instances = new ArrayList<>();
ServiceInstance instance1 = TestDefaultServiceInstance.getTestDefaultServiceInstance("1.0.0");
instances.ad... |
public static GenericRow getIntermediateRow(final TableRow row) {
final GenericKey key = row.key();
final GenericRow value = row.value();
final List<?> keyFields = key.values();
value.ensureAdditionalCapacity(
1 // ROWTIME
+ keyFields.size() //all the keys
+ row.window(... | @Test
public void shouldReturnIntermediateRowNonWindowed() {
// Given:
final GenericRow intermediateRow1 = aValue.append(aRowtime).append(aKey);
final GenericRow intermediateRow2 = aValue2.append(aRowtime).append(aKey2);
// When:
final GenericRow genericRow1 = KsqlMaterialization.getIntermediateR... |
public MetaDataService getMetaDataService() {
return metaDataService;
} | @Test
public void testGetMetaDataService() {
assertEquals(metaDataService, abstractShenyuClientRegisterService.getMetaDataService());
} |
@Override
public SchemaResult getKeySchema(
final Optional<String> topicName,
final Optional<Integer> schemaId,
final FormatInfo expectedFormat,
final SerdeFeatures serdeFeatures
) {
return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, true);
} | @Test
public void shouldReturnErrorFromGetKeyIfForbidden() throws Exception {
// Given:
when(srClient.getSchemaBySubjectAndId(any(), anyInt()))
.thenThrow(forbiddenException());
// When:
final SchemaResult result = supplier.getKeySchema(Optional.of(TOPIC_NAME),
Optional.of(42), expect... |
static Result coerceUserList(
final Collection<Expression> expressions,
final ExpressionTypeManager typeManager
) {
return coerceUserList(expressions, typeManager, Collections.emptyMap());
} | @Test
public void shouldCoerceMapOfCompatibleLiterals() {
// Given:
final ImmutableList<Expression> expressions = ImmutableList.of(
new CreateMapExpression(
ImmutableMap.of(
new IntegerLiteral(10),
new IntegerLiteral(289476)
)
),
... |
public static List<String> validateXml(InputStream schemaStream, String xmlString) throws Exception {
return validateXml(schemaStream, xmlString, null);
} | @Test
public void testValidXmlAgainstInvalidSchema() throws Exception {
InputStream schemaStream = new FileInputStream("target/test-classes/io/github/microcks/util/invalid-schema.xsd");
String validXml = """
<note>
<to>Tove</to>
<from>Jani</from>
... |
@Override
public int compareTo(ResourceDescription o) {
if (o.getResourceUsage().size() > resourceUsageByName.size()) {
return -1;
}
if (exactlyEquals(o.getResourceUsage())) {
return 0;
}
for (Map.Entry<String, ResourceUsage> entry : o.getResourceUsa... | @Test
public void compareTo() {
PulsarResourceDescription one = new PulsarResourceDescription();
one.put("cpu", new ResourceUsage(0.1, 0.2));
PulsarResourceDescription two = new PulsarResourceDescription();
two.put("cpu", new ResourceUsage(0.1, 0.2));
assertEquals(0, one.comp... |
@JsonIgnore
public LongParamDefinition getCompletedByTsParam() {
if (completedByTs != null) {
return ParamDefinition.buildParamDefinition(PARAM_NAME, completedByTs);
}
if (completedByHour != null) {
String timeZone = tz == null ? "WORKFLOW_CRON_TIMEZONE" : String.format("'%s'", tz);
retu... | @Test
public void testGetCompletedByTsParamWithDurationMinutes() {
Tct tct = new Tct();
tct.setDurationMinutes(60);
tct.setTz("UTC");
LongParamDefinition expected =
LongParamDefinition.builder()
.name("completed_by_ts")
.expression("return new DateTime(RUN_TS).plusMinut... |
public static <T> List<List<T>> groupPartitions(List<T> elements, int numGroups) {
if (numGroups <= 0)
throw new IllegalArgumentException("Number of groups must be positive.");
List<List<T>> result = new ArrayList<>(numGroups);
// Each group has either n+1 or n raw partitions
... | @Test
public void testGroupPartitionsInvalidCount() {
assertThrows(IllegalArgumentException.class,
() -> ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 0));
} |
public static Application getDefaultEditor() {
final Application application = finder.getDescription(
preferences.getProperty("editor.bundleIdentifier"));
if(finder.isInstalled(application)) {
return application;
}
return Application.notfound;
} | @Test
public void testGetDefaultEditor() {
assertSame(Application.notfound, EditorFactory.getDefaultEditor());
} |
public static InExpression bind(final InExpression segment, final SegmentType parentSegmentType, final SQLStatementBinderContext binderContext,
final Map<String, TableSegmentBinderContext> tableBinderContexts, final Map<String, TableSegmentBinderContext> outerTableBinderContexts) {
... | @Test
void assertInExpressionBinder() {
InExpression inExpression = new InExpression(0, 10,
new LiteralExpressionSegment(0, 0, "left"),
new LiteralExpressionSegment(0, 0, "right"), true);
SQLStatementBinderContext binderContext = mock(SQLStatementBinderContext.class);... |
@Override
public void filter(ContainerRequestContext context)
{
if (internalAuthenticationManager.isInternalRequest(context) ||
(internalAuthenticationManager.isInternalJwtEnabled() && isAccessingInternalEndpoint(resourceInfo))) {
Principal authenticatedPrincipal = internalAu... | @Test
public void testJwtAuthenticationRejectsWithNoBearerTokenJwtEnabled()
{
String sharedSecret = "secret";
boolean internalJwtEnabled = true;
InternalAuthenticationManager internalAuthenticationManager = new InternalAuthenticationManager(Optional.of(sharedSecret), "nodeId", internalJ... |
@Override
public int compute(QB batch, boolean flush, boolean shutdown) {
return workerObserver.observeExecutionComputation(batch, () -> execution.compute(batch, flush, shutdown));
} | @Test
public void compute() throws IOException {
final ManualAdvanceClock manualAdvanceClock = new ManualAdvanceClock(Instant.now());
final MetricExt rootMetric = MetricExtFactory.newMetricExtFromTestClock(manualAdvanceClock);
final MockCompiledExecution mockQueueBatchExecution = new MockCom... |
@Override
public String group() {
return Constants.SERVICE_METADATA;
} | @Test
void testGroup() {
String group = serviceMetadataProcessor.group();
assertEquals(Constants.SERVICE_METADATA, group);
} |
public static <T> Set<T> symmetricDifference(Collection<? extends T> c1, Collection<? extends T> c2) {
Set<T> diff1 = new HashSet<>(c1);
diff1.removeAll(c2);
Set<T> diff2 = new HashSet<>(c2);
diff2.removeAll(c1);
diff1.addAll(diff2);
return diff1;
} | @Test
public void testSymmetricDifference() {
assertTrue(CollectionUtil.equalContentsIgnoreOrder(
List.of(1, 2, 3),
CollectionUtil.symmetricDifference(l1, l2)));
} |
@Override
public Map<K, Object> executeOnEntries(com.hazelcast.map.EntryProcessor entryProcessor) {
return map.executeOnEntries(entryProcessor);
} | @Test
public void testExecuteOnEntries() {
map.put(23, "value-23");
map.put(42, "value-42");
Map<Integer, Object> resultMap = adapter.executeOnEntries(new IMapReplaceEntryProcessor("value", "newValue"));
assertEquals(2, resultMap.size());
assertEquals("newValue-23", resultMa... |
@Override
public boolean tryFence(HAServiceTarget target, String args) {
ProcessBuilder builder;
String cmd = parseArgs(target.getTransitionTargetHAStatus(), args);
if (!Shell.WINDOWS) {
builder = new ProcessBuilder("bash", "-e", "-c", cmd);
} else {
builder = new ProcessBuilder("cmd.exe"... | @Test
public void testStdoutLogging() {
assertTrue(fencer.tryFence(TEST_TARGET, "echo hello"));
Mockito.verify(ShellCommandFencer.LOG).info(
Mockito.endsWith("echo hello: hello"));
} |
public synchronized boolean saveNamespace(long timeWindow, long txGap,
FSNamesystem source) throws IOException {
if (timeWindow > 0 || txGap > 0) {
final FSImageStorageInspector inspector = storage.readAndInspectDirs(
EnumSet.of(NameNodeFile.IMAGE, NameNodeFile.IMAGE_ROLLBACK),
Start... | @Test
public void testHasNonEcBlockUsingStripedIDForLoadUCFile()
throws IOException{
// start a cluster
Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(9)
.build();
cluster.waitActive... |
@Override
public V pollLastAndOfferFirstTo(String queueName, long timeout, TimeUnit unit) throws InterruptedException {
return commandExecutor.getInterrupted(pollLastAndOfferFirstToAsync(queueName, timeout, unit));
} | @Test
public void testPollLastAndOfferFirstTo() throws InterruptedException {
final RBlockingQueue<Integer> queue1 = redisson.getBlockingQueue("{queue}1");
Executors.newSingleThreadScheduledExecutor().schedule(() -> {
try {
queue1.put(3);
} catch (InterruptedE... |
private PlantUmlDiagram createDiagram(List<String> rawDiagramLines) {
List<String> diagramLines = filterOutComments(rawDiagramLines);
Set<PlantUmlComponent> components = parseComponents(diagramLines);
PlantUmlComponents plantUmlComponents = new PlantUmlComponents(components);
List<Parse... | @Test
public void parses_component_name_that_clashes_with_alias_definition() {
PlantUmlDiagram diagram = createDiagram(TestDiagram.in(temporaryFolder)
.component("tricky as hell cause of as keyword").withAlias("alias").withStereoTypes("..any..")
.write());
PlantUmlCo... |
public static String s2(int v) {
char[] result = new char[5];
if (v < 0) {
result[0] = '-';
v = -v;
} else {
result[0] = '+';
}
for (int i = 0; i < 4; i++) {
result[4 - i] = Character.forDigit(v & 0x0f, 16);
v >>= 4;
... | @Test
public void testS2() {
Assert.assertEquals("+0000", Hex.s2(0));
Assert.assertEquals("-0000", Hex.s2(-2147483648));
Assert.assertEquals("+3039", Hex.s2(12345));
Assert.assertEquals("+02d2", Hex.s2(1234567890));
} |
public int minValue()
{
final int initialValue = this.initialValue;
int min = 0 == size ? initialValue : Integer.MAX_VALUE;
for (final int value : values)
{
if (initialValue != value)
{
min = Math.min(min, value);
}
}
... | @Test
void shouldHaveNoMinValueForEmptyCollection()
{
assertEquals(INITIAL_VALUE, map.minValue());
} |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlySingleElementNoEqualsMagic() {
expectFailureWhenTestingThat(asList(1)).containsExactly(1L);
assertFailureValueIndexed("an instance of", 0, "java.lang.Long");
} |
@Override
public MaterialPollResult responseMessageForLatestRevisionsSince(String responseBody) {
if (isEmpty(responseBody)) return new MaterialPollResult();
Map responseBodyMap = getResponseMap(responseBody);
return new MaterialPollResult(toMaterialDataMap(responseBodyMap), toSCMRevisions(r... | @Test
public void shouldBuildSCMRevisionsFromLatestRevisionsSinceResponse() throws Exception {
String r1 = "{\"revision\":\"r1\",\"timestamp\":\"2011-07-14T19:43:37.100Z\",\"user\":\"some-user\",\"revisionComment\":\"comment\",\"data\":{\"dataKeyTwo\":\"data-value-two\",\"dataKeyOne\":\"data-value-one\"}," ... |
@Override
public Health check(Set<NodeHealth> nodeHealths) {
ClusterHealthResponse esClusterHealth = this.getEsClusterHealth();
if (esClusterHealth != null) {
Health minimumNodes = checkMinimumNodes(esClusterHealth);
Health clusterStatus = extractStatusHealth(esClusterHealth);
return HealthR... | @Test
public void check_returns_RED_with_cause_if_ES_cluster_has_less_than_three_nodes_and_status_is_RED() {
Set<NodeHealth> nodeHealths = ImmutableSet.of(newNodeHealth(GREEN));
when(esClient.clusterHealth(any()).getStatus()).thenReturn(ClusterHealthStatus.RED);
when(esClient.clusterHealth(any()).getNumbe... |
public static RowCoder of(Schema schema) {
return new RowCoder(schema);
} | @Test
public void testEncodingPositionRemoveFields() throws Exception {
Schema schema1 =
Schema.builder()
.addNullableField("f_int32", FieldType.INT32)
.addNullableField("f_string", FieldType.STRING)
.addNullableField("f_boolean", FieldType.BOOLEAN)
.build()... |
@Override
@Deprecated
public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNul... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullTransformerSupplierOnFlatTransformWithNamedAndStores() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransform(null, Named.as("flatTransformer"), "storeN... |
public static List<URL> parseConfigurators(String rawConfig) {
// compatible url JsonArray, such as [ "override://xxx", "override://xxx" ]
List<URL> compatibleUrls = parseJsonArray(rawConfig);
if (CollectionUtils.isNotEmpty(compatibleUrls)) {
return compatibleUrls;
}
... | @Test
void parseConfiguratorsAppAnyServicesTest() throws IOException {
try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppAnyServices.yml")) {
List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream));
Assertions.assertNotNull(urls);
... |
public static void printIfErrorEnabled(Logger logger, String s, Object... args) {
if (logger.isErrorEnabled()) {
logger.error(s, args);
}
} | @Test
void testPrintIfErrorEnabled() {
Logger logger = Mockito.mock(Logger.class);
Mockito.when(logger.isErrorEnabled()).thenReturn(true);
LoggerUtils.printIfErrorEnabled(logger, "test", "arg1", "arg2", "arg3");
Mockito.verify(logger, Mockito.times(1)).error("test", "arg1", "arg2", "... |
@Override
public Optional<ClusterHealthStatus> getClusterHealthStatus() {
try {
ClusterHealthResponse healthResponse = getRestHighLevelClient().cluster()
.health(new ClusterHealthRequest().waitForYellowStatus().timeout(timeValueSeconds(30)), RequestOptions.DEFAULT);
return Optional.of(healthRe... | @Test
public void newInstance_whenKeyStorePassed_shouldCreateClient() throws GeneralSecurityException, IOException {
mockServerResponse(200, JSON_SUCCESS_RESPONSE);
Path keyStorePath = temp.newFile("keystore.p12").toPath();
String password = "password";
HandshakeCertificates certificate = createCert... |
@Override
public Map<String, PluginMetadataSummary> test(ViewDTO view) {
final Optional<Search> optionalSearch = searchDbService.get(view.searchId());
return optionalSearch.map(searchRequiresParameterSupport::test)
.orElseThrow(() -> new IllegalStateException("Search " + view.searchI... | @Test
public void returnsEmptyCapabilitiesIfViewDoesNotHaveParameters() {
final Search search = Search.builder().parameters(ImmutableSet.of()).build();
when(searchDbService.get("searchId")).thenReturn(Optional.of(search));
final Map<String, PluginMetadataSummary> result = this.requiresPara... |
public boolean overlaps(final BoundingBox pBoundingBox, double pZoom) {
//FIXME this is a total hack but it works around a number of issues related to vertical map
//replication and horiztonal replication that can cause polygons to completely disappear when
//panning
if (pZoom < 3)
... | @Test
public void testOverlaps() {
// ________________
// | | |
// | | |
// |------+-------|
// | | |
// | | |
// ----------------
//box is notated as *
//test area is notated as &
/... |
public static List<Annotation> scanMetaAnnotation(Class<? extends Annotation> annotationType) {
return AnnotationScanner.DIRECTLY_AND_META_ANNOTATION.getAnnotationsIfSupport(annotationType);
} | @Test
public void scanMetaAnnotationTest() {
// RootAnnotation -> RootMetaAnnotation1 -> RootMetaAnnotation2 -> RootMetaAnnotation3
// -> RootMetaAnnotation3
final List<Annotation> annotations = AnnotationUtil.scanMetaAnnotation(RootAnnotation.class);
assertEquals(4, annotations.size());
asser... |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowStatement) {
return Optional.of(new PostgreSQLShowVariableExecutor((ShowStatement) s... | @Test
void assertCreateWithOtherSQLStatementContextOnly() {
assertThat(new PostgreSQLAdminExecutorCreator().create(new UnknownSQLStatementContext(new PostgreSQLInsertStatement())), is(Optional.empty()));
} |
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 testSubmitReservationNormal() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 5, 3);
Plan plan = null;
try {
plan =
rrValidator.validateReservationSubmissionRequest(rSystem, request,
ReservationSystemTestUti... |
@Override
public String toString() {
return "ResourceConfig{" +
"url=" + url +
", id='" + id + '\'' +
", resourceType=" + resourceType +
'}';
} | @Test
public void when_addNonexistentResourceWithFileAndId_then_throwsException() {
// Given
String id = "exist";
String path = Paths.get("/i/do/not/" + id).toString();
File file = new File(path);
// Then
expectedException.expect(JetException.class);
expected... |
public SequenceFile.Writer createWriter(File file) throws IOException {
return createWriter(toPath(file));
} | @Test
public void testCreateWriteReadFileOneEntry() throws Throwable {
final FileEntry source = ENTRY;
// do an explicit close to help isolate any failure.
SequenceFile.Writer writer = createWriter();
writer.append(NullWritable.get(), source);
writer.flush();
writer.close();
FileEntry r... |
@Override
public AwsProxyResponse handle(Throwable ex) {
log.error("Called exception handler for:", ex);
// adding a print stack trace in case we have no appender or we are running inside SAM local, where need the
// output to go to the stderr.
ex.printStackTrace();
if (ex i... | @Test
void streamHandle_InvalidResponseObjectException_jsonContentTypeHeader()
throws IOException {
ByteArrayOutputStream respStream = new ByteArrayOutputStream();
exceptionHandler.handle(new InvalidResponseObjectException(INVALID_RESPONSE_MESSAGE, null), respStream);
assertNotN... |
public static IOD load(String uri) throws IOException {
if (uri.startsWith("resource:")) {
try {
uri = ResourceLocator.getResource(uri.substring(9), IOD.class);
} catch (NullPointerException npe) {
throw new FileNotFoundException(uri);
}
... | @Test
public void testValidateCode() throws Exception {
IOD iod = IOD.load("resource:code-iod.xml");
Attributes attrs = new Attributes(2);
attrs.newSequence(Tag.ConceptNameCodeSequence, 1).add(
new Code("CV-9991", "99DCM4CHE", null, "CM-9991").toItem());
Attributes co... |
public static String keywordOf(int tag, String privateCreator) {
return getElementDictionary(privateCreator).keywordOf(tag);
} | @Test
public void testKeywordOf() {
for (int i = 0; i < TAGS.length; i++)
assertEquals(KEYWORDS[i],
ElementDictionary.keywordOf(TAGS[i], null));
} |
@Override
public Number lookup(String name) {
int t = dictionary.getOrDefault(name, -1);
if (t < 0) {
t = dictionary.getOrDefault("default", -1);
}
if (t < 0) {
log.warn("Pick up system reserved threshold {}ms because of config missing", SYSTEM_RESERVED_THRESH... | @Test
@Timeout(20)
public void testLookupOfDynamicUpdate() throws InterruptedException {
ConfigWatcherRegister register = new MockConfigWatcherRegister(3);
when(provider.name()).thenReturn("default");
ApdexThresholdConfig config = new ApdexThresholdConfig(provider);
register.regi... |
@Override
public Producer createProducer() throws Exception {
return new FopProducer(this, fopFactory, outputType.getFormatExtended());
} | @Test
public void setPDFRenderingMetadataPerDocument() throws Exception {
if (!canTest()) {
// cannot run on CI
return;
}
Endpoint endpoint = context().getEndpoint("fop:pdf");
Producer producer = endpoint.createProducer();
Exchange exchange = new Defa... |
public static boolean matchAnyInterface(String address, Collection<String> interfaces) {
if (interfaces == null || interfaces.isEmpty()) {
return false;
}
for (String interfaceMask : interfaces) {
if (matchInterface(address, interfaceMask)) {
return true;
... | @Test
public void testMatchAnyInterface() {
assertTrue(AddressUtil.matchAnyInterface("10.235.194.23", asList("10.235.194.23", "10.235.193.121")));
assertFalse(AddressUtil.matchAnyInterface("10.235.194.23", null));
assertFalse(AddressUtil.matchAnyInterface("10.235.194.23", Collections.emptyL... |
public static String cloudIdEncode(String... args) {
final String joinedArgs = String.join("$", args);
return Base64.getUrlEncoder().encodeToString(joinedArgs.getBytes());
} | @Test
public void testThrowExceptionWhenAtLeatOneSegmentIsEmpty() {
String[] raw = new String[] {"first", "", "third"};
String encoded = CloudSettingId.cloudIdEncode(raw);
Exception thrownException = assertThrows(org.jruby.exceptions.ArgumentError.class, () -> {
new CloudSetting... |
public static StreamDescriptor createStreamDescriptor(List<OrcType> types, OrcDataSource dataSource)
{
ImmutableMap.Builder<Integer, StreamProperty> propertiesBuilder = ImmutableMap.builderWithExpectedSize(types.size());
addOrcType("", "", ROOT_ID, types, propertiesBuilder);
AllStreams allSt... | @Test
public void testBuilder()
{
List<OrcType> orcTypes = getOrcTypes();
StreamDescriptor streamDescriptor = createStreamDescriptor(orcTypes, DUMMY_ORC_DATA_SOURCE);
StreamProperty rootProperty = new StreamProperty("", orcTypes.get(0), "", ImmutableList.of(1, 2));
StreamPropert... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.