focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
static String headerLine(CSVFormat csvFormat) {
return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader());
} | @Test
public void givenIgnoreEmptyLines_shouldSkip() {
CSVFormat csvFormat = csvFormat().withIgnoreEmptyLines(true);
PCollection<String> input =
pipeline.apply(Create.of(headerLine(csvFormat), "a,1,1.1", "", "b,2,2.2", "", "c,3,3.3"));
CsvIOStringToCsvRecord underTest = new CsvIOStringToCsvRecord... |
public static String substVars(String val, PropertyContainer pc1) {
return substVars(val, pc1, null);
} | @Test
public void detectCircularReferences5() {
context.putProperty("A", "${B} and ${C}");
context.putProperty("B", "${B1}");
context.putProperty("B1", "B1-value");
context.putProperty("C", "${C1}");
context.putProperty("C1", "here's the loop: ${A}");
expectedException.expect(IllegalArgumentE... |
public static long parseDuration(final String propertyName, final String propertyValue)
{
final char lastCharacter = propertyValue.charAt(propertyValue.length() - 1);
if (Character.isDigit(lastCharacter))
{
return Long.parseLong(propertyValue);
}
if (lastCharacte... | @Test
void shouldParseTimesWithSuffix()
{
assertEquals(1L, parseDuration("", "1"));
assertEquals(1L, parseDuration("", "1ns"));
assertEquals(1L, parseDuration("", "1NS"));
assertEquals(1000L, parseDuration("", "1us"));
assertEquals(1000L, parseDuration("", "1US"));
... |
public static Map<String, String> parseUriPattern(String pattern, String url) {
int qpos = url.indexOf('?');
if (qpos != -1) {
url = url.substring(0, qpos);
}
List<String> leftList = StringUtils.split(pattern, '/', false);
List<String> rightList = StringUtils.split(ur... | @Test
void testParseUriPathPatterns() {
Map<String, String> map = HttpUtils.parseUriPattern("/cats/{id}", "/cats/1");
match(map, "{ id: '1' }");
map = HttpUtils.parseUriPattern("/cats/{id}/", "/cats/1"); // trailing slash
match(map, "{ id: '1' }");
map = HttpUtils.parseUriPat... |
@Override
public int ndoc() {
return docs.size();
} | @Test
public void testGetNumDocuments() {
System.out.println("getNumDocuments");
assertEquals(5000, corpus.ndoc());
} |
@Override
public void pluginJarRemoved(BundleOrPluginFileDetails bundleOrPluginFileDetails) {
GoPluginDescriptor existingDescriptor = registry.getPluginByIdOrFileName(null, bundleOrPluginFileDetails.file().getName());
if (existingDescriptor == null) {
return;
}
try {
... | @Test
void shouldRemovePluginFromBundlePathAndInformRegistryWhenAPluginIsRemoved() throws Exception {
File pluginJarFile = new File(pluginWorkDir, PLUGIN_JAR_FILE_NAME);
File removedBundleDirectory = new File(bundleDir, PLUGIN_JAR_FILE_NAME);
String pluginJarFileLocation = pluginJarFile.get... |
static List<String> parseEtcResolverSearchDomains() throws IOException {
return parseEtcResolverSearchDomains(new File(ETC_RESOLV_CONF_FILE));
} | @Test
public void searchDomainsPrecedence(@TempDir Path tempDir) throws IOException {
File f = buildFile(tempDir, "domain linecorp.local\n" +
"search squarecorp.local\n" +
"nameserver 127.0.0.2\n");
List<String> domains = UnixResolverDnsServerAdd... |
@Override
public Iterator<E> iterator() {
return new ElementIterator();
} | @Test
public void testIteratorHasNextReturnsTrueIfNotIteratedOverAll() {
final OAHashSet<Integer> set = new OAHashSet<>(8);
populateSet(set, 2);
final Iterator<Integer> iterator = set.iterator();
iterator.next();
assertTrue(iterator.hasNext());
} |
public static Set<Metric> mapFromDataProvider(TelemetryDataProvider<?> provider) {
switch (provider.getDimension()) {
case INSTALLATION -> {
return mapInstallationMetric(provider);
} case PROJECT -> {
return mapProjectMetric(provider);
} case USER -> {
return mapUserMetric(... | @Test
void mapFromDataProvider_whenLanguageProvider() {
TelemetryDataProvider<String> provider = new TestTelemetryBean(Dimension.LANGUAGE);
Set<Metric> metrics = TelemetryMetricsMapper.mapFromDataProvider(provider);
List<LanguageMetric> list = retrieveList(metrics);
assertThat(list)
.extractin... |
@Override
public FileObject[] findJarFiles() throws KettleFileException {
return findJarFiles( searchLibDir );
} | @Test
public void testFindJarFiles_DirWithKettleIgnoreFileIgnored() throws IOException, KettleFileException {
Files.createDirectories( PATH_TO_TEST_DIR_NAME );
Files.createFile( PATH_TO_JAR_FILE2 );
Files.createFile( PATH_TO_KETTLE_IGNORE_FILE );
FileObject[] findJarFiles = plFolder.findJarFiles();
... |
public static UForAll create(List<UTypeVar> typeVars, UType quantifiedType) {
return new AutoValue_UForAll(ImmutableList.copyOf(typeVars), quantifiedType);
} | @Test
public void equality() {
UType objectType = UClassType.create("java.lang.Object", ImmutableList.<UType>of());
UTypeVar eType = UTypeVar.create("E", objectType);
UTypeVar tType = UTypeVar.create("T", objectType);
UType listOfEType = UClassType.create("java.util.List", ImmutableList.<UType>of(eTyp... |
public Map<String, HivePartitionStats> getPartitionStatistics(Table table, List<String> partitionNames) {
String catalogName = ((HiveMetaStoreTable) table).getCatalogName();
String dbName = ((HiveMetaStoreTable) table).getDbName();
String tblName = ((HiveMetaStoreTable) table).getTableName();
... | @Test
public void testGetPartitionStatistics() {
com.starrocks.catalog.Table hiveTable = hmsOps.getTable("db1", "table1");
Map<String, HivePartitionStats> statistics = hmsOps.getPartitionStatistics(
hiveTable, Lists.newArrayList("col1=1", "col1=2"));
Assert.assertEquals(0, st... |
@Override
protected Release findLatestActiveRelease(String appId, String clusterName, String namespaceName,
ApolloNotificationMessages clientMessages) {
String messageKey = ReleaseMessageKeyGenerator.generate(appId, clusterName, namespaceName);
String cacheKey = mes... | @Test
public void testFindLatestActiveReleaseWithReleaseNotFound() throws Exception {
when(releaseMessageService.findLatestReleaseMessageForMessages(Lists.newArrayList(someKey))).thenReturn(null);
when(releaseService.findLatestActiveRelease(someAppId, someClusterName, someNamespaceName)).thenReturn(null);
... |
public boolean updateQuota(String tenant, Integer quota) {
return updateTenantCapacity(tenant, quota, null, null, null);
} | @Test
void testUpdateQuota() {
List<Object> argList = CollectionUtils.list();
Integer quota = 2;
argList.add(quota);
String tenant = "test2";
argList.add(tenant);
when(jdbcTemplate.update(anyString(), any(Object.class))).thenAnswer((Answer<I... |
public void addCwe(String cwe) {
if (cwe != null) {
this.cwes.add(cwe);
}
} | @Test
public void testAddCwe() {
System.out.println("addCwe");
String cwe = "CWE-89";
CweSet instance = new CweSet();
instance.addCwe(cwe);
assertFalse(instance.getEntries().isEmpty());
} |
public AppResponse startFlow(String flowName, Action action, AppRequest request) throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException {
Flow flow = flowFactoryFactory.getFactory(ActivationFlowFactory.TYPE).getFlow(flowName);
A... | @Test
void startFlowNOKTest() throws FlowNotDefinedException, FlowStateNotDefinedException, IOException, NoSuchAlgorithmException, SharedServiceClientException {
AppSession appSession = new AppSession();
appSession.setState(State.INITIALIZED.name());
appSession.setActivationMethod(Activation... |
public static Expression convert(Predicate[] predicates) {
Expression expression = Expressions.alwaysTrue();
for (Predicate predicate : predicates) {
Expression converted = convert(predicate);
Preconditions.checkArgument(
converted != null, "Cannot convert Spark predicate to Iceberg expres... | @Test
public void testNotIn() {
NamedReference namedReference = FieldReference.apply("col");
LiteralValue v1 = new LiteralValue(1, DataTypes.IntegerType);
LiteralValue v2 = new LiteralValue(2, DataTypes.IntegerType);
org.apache.spark.sql.connector.expressions.Expression[] attrAndValue =
new or... |
public static BigDecimal cast(final Integer value, final int precision, final int scale) {
if (value == null) {
return null;
}
return cast(value.longValue(), precision, scale);
} | @Test
public void shouldNotCastIntTooBig() {
// When:
final Exception e = assertThrows(
ArithmeticException.class,
() -> cast(10, 2, 1)
);
// Then:
assertThat(e.getMessage(), containsString("Numeric field overflow"));
} |
@Override
public void setConfig(RedisClusterNode node, String param, String value) {
RedisClient entry = getEntry(node);
RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_SET, param, value);
syncFuture(f);
} | @Test
public void testSetConfig() {
RedisClusterNode master = getFirstMaster();
connection.setConfig(master, "timeout", "10");
} |
public Object resolve(final Expression expression) {
return new Visitor().process(expression, null);
} | @Test
public void shouldResolveArbitraryExpressions() {
// Given:
final SqlType type = SqlTypes.struct().field("FOO", SqlTypes.STRING).build();
final Expression exp = new CreateStructExpression(ImmutableList.of(
new Field("FOO", new FunctionCall(
FunctionName.of("CONCAT"),
... |
@Override
protected void runTask() {
LOGGER.debug("Updating currently processed jobs... ");
convertAndProcessJobs(new ArrayList<>(backgroundJobServer.getJobSteward().getJobsInProgress()), this::updateCurrentlyProcessingJob);
} | @Test
void jobsThatAreBeingProcessedButHaveBeenDeletedViaDashboardWillBeInterrupted() {
// GIVEN
final Job job = anEnqueuedJob().withId().build();
doThrow(new ConcurrentJobModificationException(job)).when(storageProvider).save(singletonList(job));
when(storageProvider.getJobById(job.... |
public Schema getSchema() {
return context.getSchema();
} | @Test
public void testRepeatedSchema() {
ProtoDynamicMessageSchema schemaProvider =
schemaFromDescriptor(RepeatPrimitive.getDescriptor());
Schema schema = schemaProvider.getSchema();
assertEquals(REPEATED_SCHEMA, schema);
} |
@Override
public void createEvents(EventFactory eventFactory, EventProcessorParameters processorParameters, EventConsumer<List<EventWithContext>> eventsConsumer) throws EventProcessorException {
final AggregationEventProcessorParameters parameters = (AggregationEventProcessorParameters) processorParameters;... | @Test
public void createEventsWithFilter() throws Exception {
when(eventProcessorDependencyCheck.hasMessagesIndexedUpTo(any(TimeRange.class))).thenReturn(true);
final DateTime now = DateTime.now(DateTimeZone.UTC);
final AbsoluteRange timerange = AbsoluteRange.create(now.minusHours(1), now.m... |
public static double log2(double x) {
return Math.log(x) / LOG2;
} | @Test
public void testLog2() {
System.out.println("log2");
assertEquals(0, MathEx.log2(1), 1E-6);
assertEquals(1, MathEx.log2(2), 1E-6);
assertEquals(1.584963, MathEx.log2(3), 1E-6);
assertEquals(2, MathEx.log2(4), 1E-6);
} |
@Override
public CompletableFuture<T> getFuture() {
final CompletableFuture<T> currentGatewayFuture = atomicGatewayFuture.get();
if (currentGatewayFuture.isCompletedExceptionally()) {
try {
currentGatewayFuture.get();
} catch (ExecutionException | Interrupted... | @Test
void testGatewayRetrievalFailures() throws Exception {
final String address = "localhost";
final UUID leaderId = UUID.randomUUID();
RpcGateway rpcGateway = TestingRpcGateway.newBuilder().build();
TestingLeaderGatewayRetriever leaderGatewayRetriever =
new Testi... |
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
List<AclEntry> foundAclSpecEntries =
... | @Test(expected=AclException.class)
public void testMergeAclEntriesResultTooLarge() throws AclException {
ImmutableList.Builder<AclEntry> aclBuilder =
new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL));
for (int i = 1; i <= 28; ++i) {
aclBuilder.add(aclEntry(ACCESS, USE... |
@Override
protected void handleRemove(final String listenTo)
{
ClusterInfoItem clusterInfoRemoved = _simpleLoadBalancerState.getClusterInfo().remove(listenTo);
_simpleLoadBalancerState.notifyListenersOnClusterInfoRemovals(clusterInfoRemoved);
_simpleLoadBalancerState.notifyClusterListenersOnRemove(liste... | @Test
public void testHandleRemove()
{
String clusterName = "mock-cluster-foo";
ClusterLoadBalancerSubscriberFixture fixture = new ClusterLoadBalancerSubscriberFixture();
ClusterInfoItem clusterInfoItemToRemove =
new ClusterInfoItem(fixture._simpleLoadBalancerState, new ClusterProperties(cluster... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldThrowOnAmbiguousImplicitCastWithoutGenerics() {
// Given:
givenFunctions(
function(FIRST_FUNC, -1, LONG, LONG),
function(SECOND_FUNC, -1, DOUBLE, DOUBLE)
);
// When:
final KsqlException e = assertThrows(KsqlException.class,
() -> udfIndex
... |
@Override
public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
String taskType = MinionConstants.UpsertCompactionTask.TASK_TYPE;
List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
for (TableConfig tableConfig : tableConfigs) {
if (!validate(tableConfig)) {
LO... | @Test
public void testGenerateTasksWithNoSegments() {
when(_mockClusterInfoAccessor.getSegmentsZKMetadata(REALTIME_TABLE_NAME)).thenReturn(
Lists.newArrayList(Collections.emptyList()));
when(_mockClusterInfoAccessor.getIdealState(REALTIME_TABLE_NAME)).thenReturn(
getIdealState(REALTIME_TABLE_N... |
public boolean isFreshRun() {
return currentPolicy == null || currentPolicy.isFreshRun();
} | @Test
public void testIsFreshRun() {
RunRequest runRequest =
RunRequest.builder()
.initiator(new ManualInitiator())
.currentPolicy(RestartPolicy.RESTART_FROM_BEGINNING)
.build();
Assert.assertFalse(runRequest.isFreshRun());
runRequest =
RunRequest.builde... |
@Override
public void close() throws UnavailableException {
// JournalContext is closed before block deletion context so that file system master changes
// are written before block master changes. If a failure occurs between deleting an inode and
// remove its blocks, it's better to have an orphaned block... | @Test
public void order() throws Throwable {
List<Object> order = new ArrayList<>();
doAnswer(unused -> order.add(mMockJC)).when(mMockJC).close();
doAnswer(unused -> order.add(mMockBDC)).when(mMockBDC).close();
mRpcContext.close();
assertEquals(Arrays.asList(mMockJC, mMockBDC), order);
} |
public synchronized LogAction record(double... values) {
return record(DEFAULT_RECORDER_NAME, timer.monotonicNow(), values);
} | @Test
public void testInfrequentPrimaryAndDependentLoggers() {
helper = new LogThrottlingHelper(LOG_PERIOD, "foo", timer);
assertTrue(helper.record("foo", 0).shouldLog());
assertTrue(helper.record("bar", 0).shouldLog());
// Both should log once the period has elapsed
assertTrue(helper.record("fo... |
public static <T> T[] reverse(T[] array, final int startIndexInclusive, final int endIndexExclusive) {
if (isEmpty(array)) {
return array;
}
int i = Math.max(startIndexInclusive, 0);
int j = Math.min(array.length, endIndexExclusive) - 1;
T tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
... | @Test
public void reverseTest2s() {
Object[] a = {"1", '2', "3", 4};
final Object[] reverse = ArrayUtil.reverse(a);
assertArrayEquals(new Object[]{4, "3", '2', "1"}, reverse);
} |
@Override
public int[] computeMatchingLines(Component component) {
List<String> database = getDBLines(component);
List<String> report = getReportLines(component);
return new SourceLinesDiffFinder().findMatchingLines(database, report);
} | @Test
void all_file_is_modified_if_no_source_in_db() {
periodHolder.setPeriod(null);
Component component = fileComponent(FILE_REF);
setLineHashesInReport(component, CONTENT);
assertThat(underTest.computeMatchingLines(component)).containsExactly(0, 0, 0, 0, 0, 0, 0);
} |
@Override
@Cacheable(cacheNames = RedisKeyConstants.SMS_TEMPLATE, key = "#code",
unless = "#result == null")
public SmsTemplateDO getSmsTemplateByCodeFromCache(String code) {
return smsTemplateMapper.selectByCode(code);
} | @Test
public void testGetSmsTemplateByCodeFromCache() {
// mock 数据
SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO();
smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
String code = dbSmsTemplate.getCode();
// 调用
SmsTemplateDO smsTemplate... |
static CharSource asCharSource(ZipFile file, ZipEntry entry, Charset charset) {
return asByteSource(file, entry).asCharSource(charset);
} | @Test
public void testAsCharSource() throws Exception {
File zipDir = new File(tmpDir, "zip");
assertTrue(zipDir.mkdirs());
createFileWithContents(zipDir, "myTextFile.txt", "Simple Text");
ZipFiles.zipDirectory(tmpDir, zipFile);
try (ZipFile zip = new ZipFile(zipFile)) {
ZipEntry entry = z... |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testMultipleFinishBundleMethods() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Found multiple methods annotated with @FinishBundle");
thrown.expectMessage("bar(FinishBundleContext)");
thrown.expectMessage("baz(FinishBundleContext)");
thr... |
public static String replaceByCodePoint(CharSequence str, int startInclude, int endExclude, char replacedChar) {
if (isEmpty(str)) {
return str(str);
}
final String originalStr = str(str);
int[] strCodePoints = originalStr.codePoints().toArray();
final int strLength = strCodePoints.length;
if (startInclu... | @Test
public void replaceByStrTest() {
String replace = "SSM15930297701BeryAllen";
String result = CharSequenceUtil.replaceByCodePoint(replace, 5, 12, "***");
assertEquals("SSM15***01BeryAllen", result);
} |
@SuppressWarnings("unchecked")
public static <T extends InputSplit> void createSplitFiles(Path jobSubmitDir,
Configuration conf, FileSystem fs, List<InputSplit> splits)
throws IOException, InterruptedException {
T[] array = (T[]) splits.toArray(new InputSplit[splits.size()]);
createSplitFiles(jobSub... | @Test
public void testMaxBlockLocationsOldSplits() throws Exception {
TEST_DIR.mkdirs();
try {
Configuration conf = new Configuration();
conf.setInt(MRConfig.MAX_BLOCK_LOCATIONS_KEY, 4);
Path submitDir = new Path(TEST_DIR.getAbsolutePath());
FileSystem fs = FileSystem.getLocal(conf);
... |
@Override
public String toString() {
return String.format(
"IcebergStagedScan(table=%s, type=%s, taskSetID=%s, caseSensitive=%s)",
table(), expectedSchema().asStruct(), taskSetId, caseSensitive());
} | @TestTemplate
public void testTaskSetPlanning() throws NoSuchTableException, IOException {
sql("CREATE TABLE %s (id INT, data STRING) USING iceberg", tableName);
List<SimpleRecord> records =
ImmutableList.of(new SimpleRecord(1, "a"), new SimpleRecord(2, "b"));
Dataset<Row> df = spark.createDataFr... |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
throw new UnsupportedOperationException("MultiMessageCodec " + getClass() + " does not support decode()");
} | @Test
public void decodeThrowsUnsupportedOperationException() throws Exception {
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> codec.decode(new RawMessage(new byte[0])))
.withMessage("MultiMessageCodec " + NetFlowCodec.class + " does not sup... |
public static PointList sample(PointList input, double maxDistance, DistanceCalc distCalc, ElevationProvider elevation) {
PointList output = new PointList(input.size() * 2, input.is3D());
if (input.isEmpty()) return output;
int nodes = input.size();
double lastLat = input.getLat(0), last... | @Test
public void addsExtraPointBelowSecondThreshold() {
PointList in = new PointList(2, true);
in.add(0, 0, 0);
in.add(0.8, 0, 0);
PointList out = EdgeSampling.sample(
in,
DistanceCalcEarth.METERS_PER_DEGREE / 3,
new DistanceCalcEarth... |
@Override
protected void transmitRpcContext(final Map<String, String> rpcContext) {
RpcContext.getClientAttachment().setAttachments(rpcContext);
} | @Test
public void testTransmitRpcContext() {
Map<String, String> stringStringMap = Maps.newHashMapWithExpectedSize(1);
stringStringMap.put("test", "test");
apacheDubboPlugin.transmitRpcContext(stringStringMap);
assertEquals(RpcContext.getContext().getAttachment("test"), "test");
... |
public static void checkDrivingLicenceMrz(String mrz) {
if (mrz.charAt(0) != 'D') {
throw new VerificationException("MRZ should start with D");
}
if (mrz.charAt(1) != '1') {
throw new VerificationException("Only BAP configuration is supported (1)");
}
if (... | @Test
public void checkDrivingLicenceMrzPositive() {
MrzUtils.checkDrivingLicenceMrz("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");
} |
@Override
public synchronized Multimap<String, String> findBundlesForUnloading(final LoadData loadData,
final ServiceConfiguration conf) {
selectedBundlesCache.clear();
final double threshold = conf.getLoadBalancerBrokerThresho... | @Test
public void testLowerBoundaryShedding() {
int numBundles = 10;
int brokerNum = 11;
int lowLoadNode = 10;
LoadData loadData = new LoadData();
double throughput = 100 * 1024 * 1024;
//There are 11 Brokers, of which 10 are loaded at 80% and 1 is loaded at 0%.
... |
public static org.apache.pinot.common.utils.regex.Pattern compile(String regex) {
// un-initialized factory will use java.util.regex to avoid requiring initialization in tests
if (_regexClass == null) {
return new JavaUtilPattern(regex);
}
switch (_regexClass) {
case RE2J:
return new... | @Test
public void testNonInitializedPatternFactory() {
Pattern pattern = PatternFactory.compile("pattern");
Assert.assertTrue(pattern instanceof JavaUtilPattern);
} |
public static double cov(int[] x, int[] y) {
if (x.length != y.length) {
throw new IllegalArgumentException("Arrays have different length.");
}
if (x.length < 3) {
throw new IllegalArgumentException("array length has to be at least 3.");
}
double mx = me... | @Test
public void testCov_doubleArr_doubleArr() {
System.out.println("cov");
double[] x = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515};
double[] y = {-1.7781325, -0.6659839, 0.9526148, -0.9460919, -0.3925300};
assertEquals(0.5894983, MathEx.cov(x, y), 1E-7);
} |
public ArtifactResolveRequest startArtifactResolveProcess(HttpServletRequest httpServletRequest) throws SamlParseException {
try {
final var artifactResolveRequest = validateRequest(httpServletRequest);
final var samlSession = updateArtifactResolveRequestWithSamlSession(artifactResolveRe... | @Test
void parseArtifactResolveSuccessfulBVDRequest() throws Exception {
samlSession.setProtocolType(ProtocolType.SAML_ROUTERINGSDIENST);
samlSession.setTransactionId("transactionId");
when(samlSessionServiceMock.loadSession(anyString())).thenReturn(samlSession);
ArtifactResolveRequ... |
public static <T> Serde<Windowed<T>> sessionWindowedSerdeFrom(final Class<T> type) {
return new SessionWindowedSerde<>(Serdes.serdeFrom(type));
} | @Test
public void shouldWrapForSessionWindowedSerde() {
final Serde<Windowed<String>> serde = WindowedSerdes.sessionWindowedSerdeFrom(String.class);
assertInstanceOf(SessionWindowedSerializer.class, serde.serializer());
assertInstanceOf(SessionWindowedDeserializer.class, serde.deserializer()... |
public static void mkdir(
final HybridFile parentFile,
@NonNull final HybridFile file,
final Context context,
final boolean rootMode,
@NonNull final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
... | @Test
public void testMkdirDuplicate() throws InterruptedException {
File newFolder = new File(storageRoot, "test");
HybridFile newFolderHF = new HybridFile(OpenMode.FILE, newFolder.getAbsolutePath());
CountDownLatch waiter1 = new CountDownLatch(1);
Operations.mkdir(
newFolderHF,
newF... |
@Override
public void start() {
DatabaseVersion.Status status = version.getStatus();
checkState(status == UP_TO_DATE || status == FRESH_INSTALL, "Compute Engine can't start unless Database is up to date");
} | @Test
public void start_has_no_effect_if_status_is_UP_TO_DATE() {
when(databaseVersion.getStatus()).thenReturn(UP_TO_DATE);
underTest.start();
verify(databaseVersion).getStatus();
verifyNoMoreInteractions(databaseVersion);
} |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (!authConfigs.isAuthEnabled()) {
chain.doFilter(request, response);
return;
}
HttpServletRequest... | @Test
void testDoFilter() {
try {
FilterChain filterChain = new MockFilterChain();
Mockito.when(authConfigs.isAuthEnabled()).thenReturn(true);
MockHttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResp... |
private void failoverServiceCntMetrics() {
try {
for (Map.Entry<String, ServiceInfo> entry : serviceMap.entrySet()) {
String serviceName = entry.getKey();
List<Tag> tags = new ArrayList<>();
tags.add(new ImmutableTag("service_name", serviceName));
... | @Test
void testFailoverServiceCntMetrics()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method method = FailoverReactor.class.getDeclaredMethod("failoverServiceCntMetrics");
method.setAccessible(true);
method.invoke(failoverReactor);
/... |
@Override
public boolean putRowWait( RowMetaInterface rowMeta, Object[] rowData, long time, TimeUnit tu ) {
return putRow( rowMeta, rowData );
} | @Test
public void testPutRowWait() throws Exception {
rowSet.putRowWait( new RowMeta(), row, 1, TimeUnit.SECONDS );
assertSame( row, rowSet.getRowWait( 1, TimeUnit.SECONDS ) );
} |
@ApiOperation(value = "Delete widget type (deleteWidgetType)",
notes = "Deletes the Widget Type. Referencing non-existing Widget Type Id will cause an error." + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/widgetType/{... | @Test
public void testDeleteWidgetType() throws Exception {
WidgetTypeDetails widgetType = new WidgetTypeDetails();
widgetType.setName("Widget Type");
widgetType.setDescriptor(JacksonUtil.fromString("{ \"someKey\": \"someValue\" }", JsonNode.class));
WidgetTypeDetails savedWidgetType... |
@Override
@Deprecated
public void setFullName(final String fullname) {
fields.put(FULL_NAME, fullname);
} | @Test
public void testSetFullName() {
user = createUserImpl(null, null, null);
user.setFullName("Full Name");
assertEquals("Full Name", user.getFullName());
assertFalse(user.getFirstName().isPresent());
assertFalse(user.getLastName().isPresent());
} |
public String opensslDn() {
StringBuilder bldr = new StringBuilder();
if (organizationName != null) {
bldr.append(String.format("/O=%s", organizationName));
}
if (commonName != null) {
bldr.append(String.format("/CN=%s", commonName));
}
retu... | @Test
public void testSubjectOpensslDn() {
Subject.Builder subject = new Subject.Builder()
.withCommonName("joe");
assertThat(subject.build().opensslDn(), is("/CN=joe"));
subject = new Subject.Builder()
.withOrganizationName("MyOrg");
assertThat(subject.bui... |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testSpdySynReplyFrame() throws Exception {
short type = 2;
byte flags = 0;
int length = 4;
int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, leng... |
@SuppressWarnings("DataFlowIssue")
public static CommandExecutor newInstance(final MySQLCommandPacketType commandPacketType, final CommandPacket commandPacket, final ConnectionSession connectionSession) throws SQLException {
if (commandPacket instanceof SQLReceivedPacket) {
log.debug("Execute pa... | @Test
void assertNewInstanceWithComStmtClose() throws SQLException {
assertThat(MySQLCommandExecutorFactory.newInstance(MySQLCommandPacketType.COM_STMT_CLOSE,
mock(MySQLComStmtClosePacket.class), connectionSession), instanceOf(MySQLComStmtCloseExecutor.class));
} |
public static boolean getIncludeNullsProperty() {
return "Y".equalsIgnoreCase( System.getProperty( Const.KETTLE_JSON_INPUT_INCLUDE_NULLS, "N" ) );
} | @Test
public void testGetIncludeNullsProperty_Y() {
System.setProperty( Const.KETTLE_JSON_INPUT_INCLUDE_NULLS, "Y" );
assertTrue( JsonInputMeta.getIncludeNullsProperty() );
} |
public static void notEmpty(Collection<?> collection, String message) {
if (CollectionUtil.isEmpty(collection)) {
throw new IllegalArgumentException(message);
}
} | @Test(expected = IllegalArgumentException.class)
public void assertNotEmptyByListAndMessageIsNull() {
Assert.notEmpty(Collections.emptyList());
} |
@Override
public boolean equals( Object o )
{
return o instanceof COSFloat &&
Float.floatToIntBits(((COSFloat)o).value) == Float.floatToIntBits(value);
} | @Test
void testEquals()
{
new BaseTester()
{
@Override
@SuppressWarnings({"java:S5863"}) // don't flag tests for reflexivity
void runTest(float num)
{
COSFloat test1 = new COSFloat(num);
COSFloat test2 = new COSFloa... |
@Override
public Consumer createConsumer(Processor processor) throws Exception {
Plc4XConsumer consumer = new Plc4XConsumer(this, processor);
configureConsumer(consumer);
return consumer;
} | @Test
public void createConsumer() throws Exception {
assertThat(sut.createConsumer(mock(Processor.class)), notNullValue());
} |
public static int damerau(String a, String b) {
// switch parameters to use the shorter one as b to save space.
if (a.length() < b.length()) {
String swap = a;
a = b;
b = swap;
}
int[][] d = new int[3][b.length() + 1];
for (int j = 0; j <= b.... | @Test
public void testPlainDamerauSpeedTest() {
System.out.println("Plain Damerau speed test");
for (int i = 0; i < 100; i++) {
EditDistance.damerau(H1N1, H1N5);
}
} |
@Override
public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) {
String accessKey = context.getAccessKey();
String secretKey = context.getSecretKey();
// STS 临时凭证鉴权的优先级高于 AK/SK 鉴权
if (StsConfig.getInstance().isStsOn()) {
StsCrede... | @Test
void testDoInjectForV4Sign() {
LoginIdentityContext actual = new LoginIdentityContext();
ramContext.setRegionId("cn-hangzhou");
configResourceInjector.doInject(resource, ramContext, actual);
assertEquals(4, actual.getAllKey().size());
assertEquals(PropertyKeyConst.ACCES... |
public void retain(IndexSet indexSet, IndexLifetimeConfig config, RetentionExecutor.RetentionAction action, String actionName) {
final Map<String, Set<String>> deflectorIndices = indexSet.getAllIndexAliases();
// Account for DST and time zones in determining age
final DateTime now = clock.nowUT... | @Test
public void timeBasedNoDates() {
when(indices.indexClosingDate("test_1")).thenReturn(Optional.empty());
when(indices.indexCreationDate("test_1")).thenReturn(Optional.empty());
underTest.retain(indexSet, getIndexLifetimeConfig(14, 16), action, "action");
verify(action, times(1... |
public static CallRoutingTable fromTsv(final Reader inputReader) throws IOException {
try (final BufferedReader reader = new BufferedReader(inputReader)) {
// use maps to silently dedupe CidrBlocks
Map<CidrBlock.IpV4CidrBlock, List<String>> ipv4Map = new HashMap<>();
Map<CidrBlock.IpV6CidrBlock, L... | @Test
public void testParserMissingSection() throws IOException {
var input =
"""
192.1.12.0/24\t \tdatacenter-1\t\t datacenter-2 datacenter-3
193.123.123.0/24\tdatacenter-1\tdatacenter-2
1.123.123.0/24\t datacenter-1
SA-SR-v4 datacenter-3
... |
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
// 入栈
DataPermission dataPermission = this.findAnnotation(methodInvocation);
if (dataPermission != null) {
DataPermissionContextHolder.add(dataPermission);
}
try {
// ... | @Test // 在 Class 上有 @DataPermission 注解
public void testInvoke_class() throws Throwable {
// 参数
mockMethodInvocation(TestClass.class);
// 调用
Object result = interceptor.invoke(methodInvocation);
// 断言
assertEquals("class", result);
assertEquals(1, interceptor.... |
@Override
public boolean contains(CharSequence name, CharSequence value) {
return contains(name, value, false);
} | @Test
public void testContainsNameAndValue() {
Http2Headers headers = newHeaders();
assertTrue(headers.contains("name1", "value2"));
assertFalse(headers.contains("name1", "Value2"));
assertTrue(headers.contains("2name", "Value3", true));
assertFalse(headers.contains("2name", ... |
public EntityShareResponse prepareShare(GRN ownedEntity,
EntityShareRequest request,
User sharingUser,
Subject sharingSubject) {
requireNonNull(ownedEntity, "ownedEntity cannot be ... | @DisplayName("Don't run validation on initial empty request")
@Test
void noValidationOnEmptyRequest() {
final GRN entity = grnRegistry.newGRN(GRNTypes.DASHBOARD, "54e3deadbeefdeadbeefaffe");
final EntityShareRequest shareRequest = EntityShareRequest.create(null);
final User user = creat... |
@Override
public String pluginNamed() {
return PluginEnum.SENTINEL.getName();
} | @Test
public void pluginNamedTest() {
assertEquals(PluginEnum.SENTINEL.getName(), sentinelRuleHandle.pluginNamed());
} |
@Override
public IndexRange calculateRange(String index) {
checkIfHealthy(indices.waitForRecovery(index),
(status) -> new RuntimeException("Unable to calculate range for index <" + index + ">, index is unhealthy: " + status));
final DateTime now = DateTime.now(DateTimeZone.UTC);
... | @Test
@MongoDBFixtures("MongoIndexRangeServiceTest-EmptyCollection.json")
public void testCalculateRangeWithEmptyIndex() throws Exception {
final String index = "graylog";
when(indices.indexRangeStatsOfIndex(index)).thenReturn(IndexRangeStats.EMPTY);
when(indices.waitForRecovery(index)).... |
@Override
public boolean match(Message msg, StreamRule rule) {
if(msg.getField(Message.FIELD_GL2_SOURCE_INPUT) == null) {
return rule.getInverted();
}
final String value = msg.getField(Message.FIELD_GL2_SOURCE_INPUT).toString();
return rule.getInverted() ^ value.trim().equal... | @Test
public void testSuccessfulMatch() {
StreamRule rule = getSampleRule();
rule.setValue("input-id-beef");
Message msg = getSampleMessage();
msg.addField(Message.FIELD_GL2_SOURCE_INPUT, "input-id-beef");
StreamRuleMatcher matcher = getMatcher(rule);
assertTrue(mat... |
@Override
public Future<RestResponse> restRequest(RestRequest request)
{
return restRequest(request, new RequestContext());
} | @Test
public void testRestRetryOverLimit() throws Exception
{
SimpleLoadBalancer balancer = prepareLoadBalancer(Arrays.asList("http://test.linkedin.com/retry1", "http://test.linkedin.com/retry2"),
HttpClientFactory.UNLIMITED_CLIENT_REQUEST_RETRY_RATIO);
DynamicClient dynamicClient = new DynamicClie... |
static void parseTargetAddress(HttpHost target, Span span) {
if (span.isNoop()) return;
if (target == null) return;
InetAddress address = target.getAddress();
if (address != null) {
if (span.remoteIpAndPort(address.getHostAddress(), target.getPort())) return;
}
span.remoteIpAndPort(target.... | @Test void parseTargetAddress_IpAndPortFromHost() {
when(span.isNoop()).thenReturn(false);
when(span.remoteIpAndPort("1.2.3.4", 9999)).thenReturn(true);
HttpHost host = new HttpHost("1.2.3.4", 9999);
TracingHttpAsyncClientBuilder.parseTargetAddress(host, span);
verify(span).isNoop();
verify(s... |
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
if (bizConfig.isAdminServiceAccessControlEnabled()) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res... | @Test
public void testWithAccessControlEnabledWithTokenSpecifiedWithValidTokenPassed()
throws Exception {
String someValidToken = "someToken";
when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true);
when(bizConfig.getAdminServiceAccessTokens()).thenReturn(someValidToken);
when(se... |
@Override
public void putAll(Map<String, ?> vars) {
throw new UnsupportedOperationException();
} | @Test
public void testPutAllMapOfStringQ() {
assertThrowsUnsupportedOperation(
() -> unmodifiables.putAll(Collections.emptyMap()));
} |
public Timer add(long interval, Handler handler, Object... args)
{
if (handler == null) {
return null;
}
Utils.checkArgument(interval > 0, "Delay of a timer has to be strictly greater than 0");
final Timer timer = new Timer(this, interval, handler, args);
final bo... | @Test
public void testAddFaultyHandler()
{
Timers.Timer timer = timers.add(10, null);
assertThat(timer, nullValue());
} |
@Override
public String resolveStaticUri(Exchange exchange, DynamicAwareEntry entry) {
String optimizedUri = null;
String uri = entry.getUri();
if (DynamicRouterControlConstants.SHOULD_OPTIMIZE.test(uri)) {
optimizedUri = URISupport.stripQuery(uri);
}
return optim... | @Test
void resolveStaticUri() throws Exception {
String originalUri = "dynamic-router-control:subscribe?subscriptionId=testSub1";
String uri = "dynamic-router-control://subscribe?subscriptionId=testSub1";
try (DynamicRouterControlChannelSendDynamicAware testSubject = new DynamicRouterControl... |
public ImmutableSet<GrantDTO> getForGranteeWithCapability(GRN grantee, Capability capability) {
return streamQuery(DBQuery.and(
DBQuery.is(GrantDTO.FIELD_GRANTEE, grantee),
DBQuery.is(GrantDTO.FIELD_CAPABILITY, capability)
)).collect(ImmutableSet.toImmutableSet());
} | @Test
@MongoDBFixtures("grants.json")
public void getForGranteeWithCapability() {
final GRN jane = grnRegistry.newGRN("user", "jane");
final GRN john = grnRegistry.newGRN("user", "john");
assertThat(dbService.getForGranteeWithCapability(jane, Capability.MANAGE)).hasSize(1);
asse... |
public static DateTime dateTimeFromDouble(double x) {
return new DateTime(Math.round(x * 1000), DateTimeZone.UTC);
} | @Test
public void testTimeFromDouble() {
assertTrue(Tools.dateTimeFromDouble(1381076986.306509).toString().startsWith("2013-10-06T"));
assertTrue(Tools.dateTimeFromDouble(1381076986).toString().startsWith("2013-10-06T"));
assertTrue(Tools.dateTimeFromDouble(1381079085.6).toString().startsWit... |
@Override
protected void doRefresh(final List<PluginData> dataList) {
pluginDataSubscriber.refreshPluginDataSelf(dataList);
dataList.forEach(pluginDataSubscriber::onSubscribe);
} | @Test
public void testDoRefresh() {
List<PluginData> pluginDataList = createFakePluginDataObjects(3);
pluginDataHandler.doRefresh(pluginDataList);
verify(subscriber).refreshPluginDataSelf(pluginDataList);
pluginDataList.forEach(verify(subscriber)::onSubscribe);
} |
public void update(Map<String, NamespaceBundleStats> bundleStats, int topk) {
arr.clear();
try {
var isLoadBalancerSheddingBundlesWithPoliciesEnabled =
pulsar.getConfiguration().isLoadBalancerSheddingBundlesWithPoliciesEnabled();
for (var etr : bundleStats.ent... | @Test
public void testLoadBalancerSheddingBundlesWithPoliciesEnabledConfig() throws MetadataStoreException {
setIsolationPolicy();
setAntiAffinityGroup();
configuration.setLoadBalancerSheddingBundlesWithPoliciesEnabled(true);
Map<String, NamespaceBundleStats> bundleStats = new Has... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testReceiveFailedBatchTwiceWithTransactions() throws Exception {
ProducerIdAndEpoch producerIdAndEpoch = new ProducerIdAndEpoch(123456L, (short) 0);
apiVersions.update("0", NodeApiVersions.create(ApiKeys.INIT_PRODUCER_ID.id, (short) 0, (short) 3));
TransactionManager txnMan... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatResumeQuery() {
// Given:
final ResumeQuery query = ResumeQuery.query(Optional.empty(), new QueryId(
"FOO"));
// When:
final String formatted = SqlFormatter.formatSql(query);
// Then:
assertThat(formatted, is("RESUME FOO"));
} |
T call() throws IOException, RegistryException {
String apiRouteBase = "https://" + registryEndpointRequestProperties.getServerUrl() + "/v2/";
URL initialRequestUrl = registryEndpointProvider.getApiRoute(apiRouteBase);
return call(initialRequestUrl);
} | @Test
public void testCall_credentialsForcedOverHttp() throws IOException, RegistryException {
ResponseException unauthorizedException =
mockResponseException(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
setUpRegistryResponse(unauthorizedException);
System.setProperty(JibSystemProperties.SEND_CREDEN... |
static String resolveLocalRepoPath(String localRepoPath) {
// todo decouple home folder resolution
// find homedir
String home = System.getenv("ZEPPELIN_HOME");
if (home == null) {
home = System.getProperty("zeppelin.home");
}
if (home == null) {
home = "..";
}
return Paths.... | @Test
void should_throw_exception_for_null() {
assertThrows(NullPointerException.class, () -> {
Booter.resolveLocalRepoPath(null);
});
} |
void start(Iterable<ShardCheckpoint> checkpoints) {
LOG.info(
"Pool {} - starting for stream {} consumer {}. Checkpoints = {}",
poolId,
read.getStreamName(),
consumerArn,
checkpoints);
for (ShardCheckpoint shardCheckpoint : checkpoints) {
checkState(
!stat... | @Test
public void poolReSubscribesWhenRecoverableErrorOccurs() throws Exception {
kinesis = new EFOStubbedKinesisAsyncClient(10);
kinesis
.stubSubscribeToShard("shard-000", eventWithRecords(3))
.failWith(new ReadTimeoutException());
kinesis.stubSubscribeToShard("shard-000", eventWithRecor... |
public static void main(String[] args) {
var queriesOr = new String[]{"many", "Annabel"};
var finder = Finders.expandedFinder(queriesOr);
var res = finder.find(text());
LOGGER.info("the result of expanded(or) query[{}] is {}", queriesOr, res);
var queriesAnd = new String[]{"Annabel", "my"};
fin... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> CombinatorApp.main(new String[]{}));
} |
public void parse(DataByteArrayInputStream input, int readSize) throws Exception {
if (currentParser == null) {
currentParser = initializeHeaderParser();
}
// Parser stack will run until current incoming data has all been consumed.
currentParser.parse(input, readSize);
} | @Test
public void testProcessInChunks() throws Exception {
CONNECT connect = new CONNECT();
connect.cleanSession(false);
connect.clientId(new UTF8Buffer("test"));
connect.userName(new UTF8Buffer("user"));
connect.password(new UTF8Buffer("pass"));
DataByteArrayOutput... |
@Override
public Collection<Integer> getOutboundPorts(EndpointQualifier endpointQualifier) {
final AdvancedNetworkConfig advancedNetworkConfig = node.getConfig().getAdvancedNetworkConfig();
if (advancedNetworkConfig.isEnabled()) {
EndpointConfig endpointConfig = advancedNetworkConfig.get... | @Test
public void testGetOutboundPorts_zeroTakesPrecedenceInRange() {
networkConfig.addOutboundPortDefinition("0-100");
Collection<Integer> outboundPorts = serverContext.getOutboundPorts(MEMBER);
assertEquals(0, outboundPorts.size());
} |
public boolean addItem(Item item) {
if (items.size() < inventorySize) {
lock.lock();
try {
if (items.size() < inventorySize) {
items.add(item);
var thread = Thread.currentThread();
LOGGER.info("{}: items.size()={}, inventorySize={}", thread, items.size(), inventoryS... | @Test
void testAddItem() {
assertTimeout(ofMillis(10000), () -> {
// Create a new inventory with a limit of 1000 items and put some load on the add method
final var inventory = new Inventory(INVENTORY_SIZE);
final var executorService = Executors.newFixedThreadPool(THREAD_COUNT);
IntStream.... |
@Override
public String toString() {
return toString(false);
} | @Test
public void testToStringNoQuota() {
QuotaUsage quotaUsage = new QuotaUsage.Builder().
fileAndDirectoryCount(1234).build();
String expected = " none inf none"
+ " inf ";
assertEquals(expected, quotaUsage.toString());
} |
public static <T> WithTimestamps<T> of(SerializableFunction<T, Instant> fn) {
return new WithTimestamps<>(fn, Duration.ZERO);
} | @Test
@Category(ValidatesRunner.class)
public void withTimestampsWithNullFnShouldThrowOnConstruction() {
SerializableFunction<String, Instant> timestampFn = null;
thrown.expect(NullPointerException.class);
thrown.expectMessage("WithTimestamps fn cannot be null");
p.apply(Create.of("1234", "0", In... |
@Override
public CRParseResult responseMessageForParseDirectory(String responseBody) {
ErrorCollection errors = new ErrorCollection();
try {
ResponseScratch responseMap = parseResponseForMigration(responseBody);
ParseDirectoryResponseMessage parseDirectoryResponseMessage;
... | @Test
public void shouldErrorWhenTargetVersionOfPluginIsHigher() {
int targetVersion = JsonMessageHandler1_0.CURRENT_CONTRACT_VERSION + 1;
String json = "{\n" +
" \"target_version\" : " + targetVersion + ",\n" +
" \"pipelines\" : [],\n" +
" \"errors... |
@GetMapping(
path = "/api/{namespace}/{extension}",
produces = MediaType.APPLICATION_JSON_VALUE
)
@CrossOrigin
@Operation(summary = "Provides metadata of the latest version of an extension")
@ApiResponses({
@ApiResponse(
responseCode = "200",
description =... | @Test
public void testPreReleaseExtensionVersionNonDefaultTarget() throws Exception {
var extVersion = mockExtension("web");
extVersion.setPreRelease(true);
extVersion.setDisplayName("Foo Bar (web)");
Mockito.when(repositories.findExtensionVersion("foo", "bar", null, VersionAlias.PRE... |
@Override
public MastershipTerm getTermFor(NetworkId networkId, DeviceId deviceId) {
Map<DeviceId, NodeId> masterMap = getMasterMap(networkId);
Map<DeviceId, AtomicInteger> termMap = getTermMap(networkId);
if ((termMap.get(deviceId) == null)) {
return MastershipTerm.of(masterMap... | @Test
public void getTermFor() {
put(VNID1, VDID1, N1, true, true);
assertEquals("wrong term", MastershipTerm.of(N1, 0),
sms.getTermFor(VNID1, VDID1));
//switch to N2 and back - 2 term switches
sms.setMaster(VNID1, N2, VDID1);
sms.setMaster(VNID1, N1, VD... |
public CompiledPipeline.CompiledExecution buildExecution() {
return buildExecution(false);
} | @SuppressWarnings({"unchecked"})
@Test
public void equalityCheckOnCompositeField() throws Exception {
final ConfigVariableExpander cve = ConfigVariableExpander.withoutSecret(EnvironmentVariableProvider.defaultProvider());
final PipelineIR pipelineIR = ConfigCompiler.configToPipelineIR(
... |
@SuppressWarnings({"unchecked", "rawtypes"})
public static Collection<ShardingSphereRule> build(final String databaseName, final DatabaseType protocolType, final DatabaseConfiguration databaseConfig,
final ComputeNodeInstanceContext computeNodeInstanceContext, ... | @Test
void assertBuild() {
Iterator<ShardingSphereRule> actual = DatabaseRulesBuilder.build("foo_db", new MySQLDatabaseType(),
new DataSourceProvidedDatabaseConfiguration(Collections.emptyMap(), Collections.singleton(new FixtureRuleConfiguration())), mock(ComputeNodeInstanceContext.class),
... |
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
String returnCommand = null;
String subCommand = safeReadLine(reader, false);
if (subCommand.equals(FIELD_GET_SUB_COMMAND_NAME)) {
returnCommand = getField(reader);
} else ... | @Test
public void testPrivateMember() {
String inputCommand = "g\n" + target + "\nfield1\ne\n";
try {
command.execute("f", new BufferedReader(new StringReader(inputCommand)), writer);
assertEquals("!yo\n", sWriter.toString());
} catch (Exception e) {
e.printStackTrace();
fail();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.