focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public void setSendIfModifiedSince(boolean sendIfModifiedSince) {
kp.put("sendIfModifiedSince",sendIfModifiedSince);
} | @Test
public void testSendIfModifiedSince() throws Exception {
fetcher().setSendIfModifiedSince(true);
CrawlURI curi = makeCrawlURI("http://localhost:7777/if-modified-since");
fetcher().process(curi);
assertFalse(httpRequestString(curi).toLowerCase().contains("if-modified-since: "))... |
public ConcurrentLongHashMap<CompletableFuture<Producer>> getProducers() {
return producers;
} | @Test(timeOut = 30000)
public void testProducerFailureOnEncryptionRequiredTopic() throws Exception {
resetChannel();
setChannelConnected();
// Set encryption_required to true
Policies policies = mock(Policies.class);
policies.encryption_required = true;
policies.topi... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final Instant lower = calculateLowerBound(windowSt... | @Test
@SuppressWarnings("unchecked")
public void shouldReturnValuesForClosedStartBounds_fetchAll() {
// Given:
final Range<Instant> start = Range.closed(
Instant.ofEpochMilli(System.currentTimeMillis()),
NOW.plusSeconds(10)
);
final StateQueryResult<KeyValueIterator<Windowed<GenericKey>... |
public void processGv01(Gv01 gv01){
String oldBsn = CategorieUtil.findBsnOudeWaarde(gv01.getCategorie());
if (oldBsn != null && CategorieUtil.findBsn(gv01.getCategorie()) != null){
digidXClient.remoteLogSpontaneVerstrekking(Log.BSN_CHANGED, "Gv01", gv01.getANummer(), oldBsn);
}
... | @Test
public void testProcessGv01() {
String testAnummer = "SSSSSSSSSS";
String testBsnOud = "SSSSSSSSS";
String testBsnNieuw = "SSSSSSSSS";
Gv01 testGv01 = TestDglMessagesUtil.createTestGv01(testAnummer, "O", testBsnOud, testBsnNieuw);
classUnderTest.processGv01(testGv01);
... |
@Override
public @Nullable V putIfAbsent(K key, V value) {
return put(key, value, expiry(), /* onlyIfAbsent */ true);
} | @CheckMaxLogLevel(ERROR)
@Test(dataProvider = "caches")
@CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG)
public void brokenEquality_putIfAbsent(
BoundedLocalCache<MutableInt, Int> cache, CacheContext context) {
testForBrokenEquality(cache, context, key -> {
var value = cache.... |
public static Instant garbageCollectionTime(
BoundedWindow window, WindowingStrategy windowingStrategy) {
return garbageCollectionTime(window, windowingStrategy.getAllowedLateness());
} | @Test
public void garbageCollectionTimeAfterEndOfGlobalWindowWithLateness() {
FixedWindows windowFn = FixedWindows.of(Duration.standardMinutes(5));
Duration allowedLateness = Duration.millis(Long.MAX_VALUE);
WindowingStrategy<?, ?> strategy =
WindowingStrategy.globalDefault()
.withWind... |
@Override
public List<TaskProperty> getPropertiesForDisplay() {
ArrayList<TaskProperty> taskProperties = new ArrayList<>();
if (PluggableTaskConfigStore.store().hasPreferenceFor(pluginConfiguration.getId())) {
TaskPreference preference = taskPreference();
List<? extends Prope... | @Test
public void shouldGetOnlyConfiguredPropertiesIfACertainPropertyDefinedByPluginIsNotConfiguredByUser() throws Exception {
Task taskDetails = mock(Task.class);
TaskConfig taskConfig = new TaskConfig();
addProperty(taskConfig, "KEY2", "Key 2", 1);
addProperty(taskConfig, "KEY1", "... |
@Override
public String[] split(String text) {
boundary.setText(text);
List<String> words = new ArrayList<>();
int start = boundary.first();
int end = boundary.next();
while (end != BreakIterator.DONE) {
String word = text.substring(start, end).trim();
... | @Test
public void testSplitAbbreviation() {
System.out.println("tokenize");
String text = "Here are some examples of abbreviations: A.B., abbr., "
+ "acad., A.D., alt., A.M., B.C., etc.";
String[] expResult = {"Here", "are", "some", "examples", "of",
"abbreviatio... |
public static DataSourceProvider tryGetDataSourceProviderOrNull(Configuration hdpConfig) {
final String configuredPoolingType = MetastoreConf.getVar(hdpConfig,
MetastoreConf.ConfVars.CONNECTION_POOLING_TYPE);
return Iterables.tryFind(FACTORIES, factory -> {
String poolingType = factory.getPoolingT... | @Test
public void testSetHikariCpBooleanProperty() throws SQLException {
MetastoreConf.setVar(conf, ConfVars.CONNECTION_POOLING_TYPE, HikariCPDataSourceProvider.HIKARI);
conf.set(HikariCPDataSourceProvider.HIKARI + ".allowPoolSuspension", "false");
conf.set(HikariCPDataSourceProvider.HIKARI + ".initializ... |
@VisibleForTesting
void forceFreeMemory()
{
memoryManager.close();
} | @Test
public void testForceFreeMemory()
throws Throwable
{
BroadcastOutputBuffer buffer = createBroadcastBuffer(
createInitialEmptyOutputBuffers(BROADCAST)
.withBuffer(FIRST, BROADCAST_PARTITION_ID)
.withNoMoreBufferIds(),
... |
public static Optional<ScalablePushRegistry> create(
final LogicalSchema logicalSchema,
final Supplier<List<PersistentQueryMetadata>> allPersistentQueries,
final boolean isTable,
final Map<String, Object> streamsProperties,
final Map<String, Object> consumerProperties,
final String s... | @Test
public void shouldCreate_badApplicationServer() {
// When
final Exception e = assertThrows(
IllegalArgumentException.class,
() -> ScalablePushRegistry.create(SCHEMA, Collections::emptyList, false,
ImmutableMap.of(StreamsConfig.APPLICATION_SERVER_CONFIG, 123),
Immu... |
@Nullable
public String getStorageClass() {
return _storageClass;
} | @Test
public void testDefaultStorageClassIsNull() {
PinotConfiguration pinotConfig = new PinotConfiguration();
S3Config cfg = new S3Config(pinotConfig);
Assert.assertNull(cfg.getStorageClass());
} |
public static Dependency parseDependency(String dependency) {
List<String> dependencyAndExclusions = Arrays.asList(dependency.split("\\^"));
Collection<Exclusion> exclusions = new ArrayList<>();
for (int idx = 1 ; idx < dependencyAndExclusions.size() ; idx++) {
exclusions.add(AetherU... | @Test
public void parseDependency() {
String testDependency = "testgroup:testartifact:1.0.0^testgroup:testexcartifact^testgroup:*";
Dependency dependency = AetherUtils.parseDependency(testDependency);
assertEquals("testgroup", dependency.getArtifact().getGroupId());
assertEquals("t... |
public static void main(String[] args) {
Map<Integer, Instance> instanceMap = new HashMap<>();
var messageManager = new RingMessageManager(instanceMap);
var instance1 = new RingInstance(messageManager, 1, 1);
var instance2 = new RingInstance(messageManager, 2, 1);
var instance3 = new RingInstance(... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> RingApp.main(new String[]{}));
} |
public static long validateMillisecondDuration(final Duration duration, final String messagePrefix) {
try {
if (duration == null) {
throw new IllegalArgumentException(messagePrefix + VALIDATE_MILLISECOND_NULL_SUFFIX);
}
return duration.toMillis();
} c... | @Test
public void shouldReturnMillisecondsOnValidDuration() {
final Duration sampleDuration = Duration.ofDays(MAX_ACCEPTABLE_DAYS_FOR_DURATION_TO_MILLIS);
assertEquals(sampleDuration.toMillis(), validateMillisecondDuration(sampleDuration, "sampleDuration"));
} |
@Override
public List<? extends Instance> listInstances(String namespaceId, String groupName, String serviceName,
String clusterName) throws NacosException {
Service service = Service.newService(namespaceId, groupName, serviceName);
if (!ServiceManager.getInstance().containSingleton(serv... | @Test
void testListInstancesNonExistCluster() throws NacosException {
assertThrows(NacosException.class, () -> {
catalogServiceV2Impl.listInstances("A", "B", "C", "DD");
});
} |
@Override
public void start() {
client = new ScClient();
client.init();
} | @Test
public void start() {
scRegister.start();
} |
public static NamingSelector newMetadataSelector(Map<String, String> metadata) {
return newMetadataSelector(metadata, false);
} | @Test
public void testNewMetadataSelector2() {
Instance ins1 = new Instance();
ins1.addMetadata("a", "1");
ins1.addMetadata("c", "3");
Instance ins2 = new Instance();
ins2.addMetadata("b", "2");
Instance ins3 = new Instance();
ins3.addMetadata("c", "3");
... |
public static List<MusicProtocol.MusicArtist> convertMusicGroupsToMusicArtists(Collection<MusicGroup> musicGroups) {
if (musicGroups == null || musicGroups.isEmpty()) {
return Collections.emptyList();
}
List<MusicProtocol.MusicArtist> musicArtists = new ArrayList<>();
for (... | @Test
public void testConvertMusicGroupsToMusicArtists() {
String expectedName = "Expected Artist Name";
String expectedName2 = "Expected Second Artist Name";
MusicGroup musicGroup = new MusicGroup(expectedName);
MusicGroup secondMusicGroup = new MusicGroup(expectedName2);
/... |
public Map<String, String> subjectAltNames() {
Map<String, String> san = new HashMap<>();
int i = 0;
for (String name : dnsNames()) {
san.put("DNS." + (i++), name);
}
i = 0;
for (String ip : ipAddresses()) {
san.put("IP." + (i++), ip);
}
... | @Test
public void testIPV6() {
Subject subject = new Subject.Builder()
.withCommonName("joe")
.addIpAddress("fc01::8d1c")
.addIpAddress("1762:0000:0000:00:0000:0B03:0001:AF18")
.addIpAddress("1974:0:0:0:0:B03:1:AF74")
.build()... |
public List<IssueDto> sort() {
String sort = query.sort();
Boolean asc = query.asc();
if (sort != null && asc != null) {
return getIssueProcessor(sort).sort(issues, asc);
}
return issues;
} | @Test
public void should_sort_by_close_date() {
Date date = new Date();
Date date1 = DateUtils.addDays(date, -3);
Date date2 = DateUtils.addDays(date, -2);
Date date3 = DateUtils.addDays(date, -1);
IssueDto issue1 = new IssueDto().setKee("A").setIssueCloseDate(date1);
IssueDto issue2 = new Iss... |
@Override
protected double maintain() {
if (!nodeRepository().nodes().isWorking()) return 0.0;
if (!nodeRepository().zone().environment().isProduction()) return 1.0;
NodeList allNodes = nodeRepository().nodes().list(); // Lockless as strong consistency is not needed
if (!zoneIsStable... | @Test
public void rebalance() {
ClusterSpec.Id cluster1 = ClusterSpec.Id.from("c1");
ClusterSpec.Id cluster2 = ClusterSpec.Id.from("c2");
ProvisioningTester tester = new ProvisioningTester.Builder().zone(new Zone(Environment.prod, RegionName.from("us-east")))
... |
@Override
public boolean contains(Object o) {
for (M member : members) {
if (selector.select(member) && o.equals(member)) {
return true;
}
}
return false;
} | @Test
public void testDoesNotContainOtherMemberWhenLiteMembersSelected() {
Collection<MemberImpl> collection = new MemberSelectingCollection<>(members, LITE_MEMBER_SELECTOR);
assertFalse(collection.contains(nonExistingMember));
} |
@JsonProperty("status")
public Status status() {
if (indices.isEmpty() || indices.stream().allMatch(i -> i.status() == Status.NOT_STARTED)) {
return Status.NOT_STARTED;
} else if (indices.stream().allMatch(RemoteReindexIndex::isCompleted)) {
// all are now completed, either f... | @Test
void testStatusCompletedWithError() {
final RemoteReindexMigration migration = withIndices(
index("one", RemoteReindexingMigrationAdapter.Status.FINISHED),
index("two", RemoteReindexingMigrationAdapter.Status.ERROR)
);
Assertions.assertThat(migration.sta... |
public void finish(Promise<Void> aggregatePromise) {
ObjectUtil.checkNotNull(aggregatePromise, "aggregatePromise");
checkInEventLoop();
if (this.aggregatePromise != null) {
throw new IllegalStateException("Already finished");
}
this.aggregatePromise = aggregatePromise... | @Test
public void testNullArgument() {
try {
combiner.finish(null);
fail();
} catch (NullPointerException expected) {
// expected
}
combiner.finish(p1);
verify(p1).trySuccess(null);
} |
public static PredicateTreeAnnotations createPredicateTreeAnnotations(Predicate predicate) {
PredicateTreeAnalyzerResult analyzerResult = PredicateTreeAnalyzer.analyzePredicateTree(predicate);
// The tree size is used as the interval range.
int intervalEnd = analyzerResult.treeSize;
Anno... | @Test
void require_that_or_intervals_are_the_same() {
Predicate p =
or(
feature("key1").inSet("value1"),
feature("key2").inSet("value2"));
PredicateTreeAnnotations r = PredicateTreeAnnotator.createPredicateTreeAnnotations(p);
as... |
@Override
public <K, T_OTHER, OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> connectAndProcess(
KeyedPartitionStream<K, T_OTHER> other,
TwoInputBroadcastStreamProcessFunction<T_OTHER, T, OUT> processFunction) {
// no state redistribution mode check is required here, since al... | @Test
void testConnectKeyedStreamWithOutputKeySelector() throws Exception {
ExecutionEnvironmentImpl env = StreamTestUtils.getEnv();
BroadcastStreamImpl<Integer> stream =
new BroadcastStreamImpl<>(env, new TestingTransformation<>("t1", Types.INT, 1));
NonKeyedPartitionStreamI... |
public synchronized boolean maybeUpdateGetRequestTimestamp(long currentTime) {
long lastRequestTimestamp = Math.max(lastGetRequestTimestamp, lastPushRequestTimestamp);
long timeElapsedSinceLastMsg = currentTime - lastRequestTimestamp;
if (timeElapsedSinceLastMsg >= pushIntervalMs) {
... | @Test
public void testMaybeUpdateGetRequestAfterElapsedTimeValid() {
assertTrue(clientInstance.maybeUpdateGetRequestTimestamp(System.currentTimeMillis() - ClientMetricsConfigs.DEFAULT_INTERVAL_MS));
// Second request should be accepted as time since last request is greater than the push interval.
... |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String c... | @Test
public void testAggregateSingleStat() throws MetaException {
List<String> partitions = Collections.singletonList("part1");
long[] values = { TS_1.getSecondsSinceEpoch(), TS_3.getSecondsSinceEpoch() };
ColumnStatisticsData data1 = new ColStatsBuilder<>(Timestamp.class).numNulls(1).numDVs(2).low(TS_1... |
@JsonIgnore
public boolean isForeachIterationRestartable(long iterationId) {
if (restartInfo != null && restartInfo.contains(iterationId)) {
return false;
}
if (details == null) {
return false;
}
return details.isForeachIterationRestartable(iterationId);
} | @Test
public void testisForeachIterationRestartable() throws Exception {
ForeachStepOverview overview =
loadObject(
"fixtures/instances/sample-foreach-step-overview.json", ForeachStepOverview.class);
assertFalse(overview.isForeachIterationRestartable(123L));
overview.addOne(123L, Workf... |
@Override
public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan,
final boolean restoreInProgress) {
try {
final ExecuteResult result = EngineExecutor
.create(primaryContext, serviceContext, plan.getConfig())
.execut... | @Test
public void shouldThrowOnInsertIntoStreamWithTableResult() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
KsqlEngineTestUtil.execute(
serviceContext,
ksqlEngine,
"create stream bar as select ordertime, itemid, orderid from orders;",
ksqlConfig,
Collec... |
@Override
public ExecuteContext doAfter(ExecuteContext context) {
final Object result = context.getResult();
if (result instanceof Boolean) {
final boolean heartbeatResult = (Boolean) result;
if (heartbeatResult) {
RegisterContext.INSTANCE.compareAndSet(false,... | @Test
public void doAfter() throws NoSuchMethodException {
final ExecuteContext context = buildContext();
context.changeResult(true);
interceptor.doAfter(context);
Assert.assertTrue(RegisterContext.INSTANCE.isAvailable());
context.changeResult(false);
interceptor.doAf... |
public Certificate add(CvCertificate cert) {
final Certificate db = Certificate.from(cert);
if (repository.countByIssuerAndSubject(db.getIssuer(), db.getSubject()) > 0) {
throw new ClientException(String.format(
"Certificate of subject %s and issuer %s already exists", db.ge... | @Test
public void shouldNotAddCertificateIfFirstButNotSelfSigned() {
ClientException thrown = assertThrows(ClientException.class, () -> service.add(readCvCertificate("rdw/acc/dvca.cvcert")));
assertEquals("Could not find trust chain", thrown.getMessage());
} |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testPuma8nhHuber() {
test(Loss.huber(0.9), "puma8nh", Puma8NH.formula, Puma8NH.data, 3.2429);
} |
public static void processEnvVariables(Map<String, String> inputProperties) {
processEnvVariables(inputProperties, System.getenv());
} | @Test
void throwIfInvalidFormat() {
var inputProperties = new HashMap<String, String>();
var env = Map.of("SONAR_SCANNER_JSON_PARAMS", "{garbage");
var thrown = assertThrows(IllegalArgumentException.class, () -> EnvironmentConfig.processEnvVariables(inputProperties, env));
assertThat(thrown).hasMessa... |
public static Collection<MdbValidityStatus> assertEjbClassValidity(final ClassInfo mdbClass) {
Collection<MdbValidityStatus> mdbComplianceIssueList = new ArrayList<>(MdbValidityStatus.values().length);
final String className = mdbClass.name().toString();
verifyModifiers(className, mdbClass.flags... | @Test
public void mdbWithInterface() {
assertTrue(assertEjbClassValidity(buildClassInfoForClass(InvalidMdbInterface.class.getName())).contains(
MdbValidityStatus.MDB_CANNOT_BE_AN_INTERFACE));
} |
public static Application mergeApplication(Application first, Application second) {
if (!first.getName().equals(second.getName())) {
throw new IllegalArgumentException("Cannot merge applications with different names");
}
Application merged = copyApplication(first);
for (Insta... | @Test
public void testMergeApplicationIfActionTypeModifiedReturnApplication() {
Application application = createSingleInstanceApp("foo", "foo",
InstanceInfo.ActionType.MODIFIED);
Assert.assertEquals(application.getInstances(),
EurekaEntityFunctions.mergeApplication(
... |
@Override
public ValidationTaskResult validateImpl(Map<String, String> optionMap)
throws InterruptedException {
String hadoopVersion;
try {
hadoopVersion = getHadoopVersion();
} catch (IOException e) {
return new ValidationTaskResult(ValidationUtils.State.FAILED, getName(),
... | @Test
public void minorVersionConflict() throws Exception {
PowerMockito.mockStatic(ShellUtils.class);
String[] cmd = new String[]{"hadoop", "version"};
// Alluxio defines a different minor version, which should not work
BDDMockito.given(ShellUtils.execCommand(cmd)).willReturn("Hadoop 2.6.2");
CON... |
@Override
public FetchedAppReport getApplicationReport(ApplicationId appId)
throws YarnException, IOException {
SubClusterId scid = federationFacade.getApplicationHomeSubCluster(appId);
createSubclusterIfAbsent(scid);
ApplicationClientProtocol applicationsManager = subClusters.get(scid).getRight();
... | @Test
public void testFetchReportAHSDisabled() throws Exception {
testHelper(false);
/* RM will not know of the app and Application History Service is disabled
* So we will not try to get the report from AHS and RM will throw
* ApplicationNotFoundException
*/
LambdaTestUtils.intercept(Appl... |
public static MemberSelector and(MemberSelector... selectors) {
return new AndMemberSelector(selectors);
} | @Test
public void testAndMemberSelector2() {
MemberSelector selector = MemberSelectors.and(LOCAL_MEMBER_SELECTOR, LITE_MEMBER_SELECTOR);
assertFalse(selector.select(member));
verify(member).localMember();
verify(member, never()).isLiteMember();
} |
@Override
public void processElement(RowData input, Context ctx, Collector<RowData> out)
throws Exception {
processFirstRowOnProcTime(input, state, out);
} | @Test
public void testWithStateTtl() throws Exception {
ProcTimeDeduplicateKeepFirstRowFunction func =
new ProcTimeDeduplicateKeepFirstRowFunction(minTime.toMilliseconds());
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createTestHarness(func);
testHarness... |
public void send(String body) {
if (isStopped) {
throw new IllegalStateException(String.format(
"Producer %s was stopped and fail to deliver requested message [%s].", body, name));
}
var msg = new SimpleMessage();
msg.addHeader(Headers.DATE, new Date().toString());
msg.addHeader(Head... | @Test
void testSend() throws Exception {
final var publishPoint = mock(MqPublishPoint.class);
final var producer = new Producer("producer", publishPoint);
verifyNoMoreInteractions(publishPoint);
producer.send("Hello!");
final var messageCaptor = ArgumentCaptor.forClass(Message.class);
verify... |
public Future<Collection<Integer>> resizeAndReconcilePvcs(KafkaStatus kafkaStatus, List<PersistentVolumeClaim> pvcs) {
Set<Integer> podIdsToRestart = new HashSet<>();
List<Future<Void>> futures = new ArrayList<>(pvcs.size());
for (PersistentVolumeClaim desiredPvc : pvcs) {
Future<V... | @Test
public void testVolumesBoundNonExpandableStorageClass(VertxTestContext context) {
List<PersistentVolumeClaim> pvcs = List.of(
createPvc("data-pod-0"),
createPvc("data-pod-1"),
createPvc("data-pod-2")
);
ResourceOperatorSupplier supplier... |
@SuppressWarnings("unchecked")
public static <S, F> S visit(final SqlType type, final SqlTypeWalker.Visitor<S, F> visitor) {
final BiFunction<SqlTypeWalker.Visitor<?, ?>, SqlType, Object> handler = HANDLER
.get(type.baseType());
if (handler == null) {
throw new UnsupportedOperationException("Un... | @Test
public void shouldVisitTimestamp() {
// Given:
final SqlPrimitiveType type = SqlTypes.TIMESTAMP;
when(visitor.visitTimestamp(any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitTimestamp(same(type));
a... |
@Override
@NonNull public Iterable<String> getNextWords(
@NonNull String currentWord, int maxResults, int minWordUsage) {
if (mNextNameParts.containsKey(currentWord)) {
return Arrays.asList(mNextNameParts.get(currentWord));
} else {
return Collections.emptyList();
}
} | @Test
public void testGetNextWords() throws Exception {
Iterator<String> nextWords = mDictionaryUnderTest.getNextWords("Menny", 2, 1).iterator();
Assert.assertTrue(nextWords.hasNext());
Assert.assertEquals("Even-Danan", nextWords.next());
Assert.assertFalse(nextWords.hasNext());
nextWords = mDict... |
@ApiOperation(value = "Get Widget Type (getWidgetType)",
notes = "Get the Widget Type by FQN. " + WIDGET_TYPE_DESCRIPTION + AVAILABLE_FOR_ANY_AUTHORIZED_USER, hidden = true)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/widgetType", params =... | @Test
public void testGetWidgetType() throws Exception {
WidgetTypeDetails widgetType = new WidgetTypeDetails();
widgetType.setName("Widget Type");
widgetType.setDescriptor(JacksonUtil.fromString("{ \"someKey\": \"someValue\" }", JsonNode.class));
WidgetTypeDetails savedWidgetType = ... |
@Override
public void write(final PostgreSQLPacketPayload payload, final Object value) {
throw new UnsupportedSQLOperationException("PostgreSQLFloat4ArrayBinaryProtocolValue.write()");
} | @Test
void assertWrite() {
assertThrows(UnsupportedSQLOperationException.class, () -> newInstance().write(new PostgreSQLPacketPayload(null, StandardCharsets.UTF_8), "val"));
} |
@Override
public int read() throws IOException {
throttle();
int data = rawStream.read();
if (data != -1) {
bytesRead++;
}
return data;
} | @Test
public void testRead() {
File tmpFile;
File outFile;
try {
tmpFile = createFile(1024);
outFile = createFile();
tmpFile.deleteOnExit();
outFile.deleteOnExit();
// Correction: we should use CB.ONE_C mode to calculate the maxBandwidth,
// because CB.ONE_C's speed i... |
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) {
if (statsEnabled) {
stats.log(deviceStateServiceMsg);
}
stateService.onQueueMsg(deviceStateServiceMsg, callback);
} | @Test
public void givenStatsDisabled_whenForwardingDeviceStateMsgToStateService_thenStatsAreNotRecorded() {
// GIVEN
ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "stats", statsMock);
ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "statsEnabled", false);
... |
public final void isPositiveInfinity() {
isEqualTo(Double.POSITIVE_INFINITY);
} | @Test
public void isPositiveInfinity() {
assertThat(Double.POSITIVE_INFINITY).isPositiveInfinity();
assertThatIsPositiveInfinityFails(1.23);
assertThatIsPositiveInfinityFails(Double.NEGATIVE_INFINITY);
assertThatIsPositiveInfinityFails(Double.NaN);
assertThatIsPositiveInfinityFails(null);
} |
public static DiskValidator
getInstance(Class<? extends DiskValidator> clazz) {
DiskValidator diskValidator;
if (INSTANCES.containsKey(clazz)) {
diskValidator = INSTANCES.get(clazz);
} else {
diskValidator = ReflectionUtils.newInstance(clazz, null);
// check the return of putIfAbsent... | @Test(expected = DiskErrorException.class)
public void testGetInstanceOfNonExistClass() throws DiskErrorException {
DiskValidatorFactory.getInstance("non-exist");
} |
@Override
public void setOutputBuffers(OutputBuffers newOutputBuffers)
{
requireNonNull(newOutputBuffers, "newOutputBuffers is null");
checkArgument(outputBuffers.getType() == SPOOLING, "Invalid output buffers type");
checkArgument(outputBuffers.isNoMoreBufferIds(), "invalid noMoreBuffer... | @Test
public void testSetOutputBuffers()
{
SpoolingOutputBuffer buffer = createSpoolingOutputBuffer();
OutputBuffers newBuffers = new OutputBuffers(SPOOLING, 1, true, ImmutableMap.of());
buffer.setOutputBuffers(newBuffers);
OutputBuffers invalidBuffers = new OutputBuffers(PARTI... |
public static <EventT> Write<EventT> write() {
return new AutoValue_JmsIO_Write.Builder<EventT>().build();
} | @Test
public void testWriteMessageWithRetryPolicy() throws Exception {
int waitingSeconds = 5;
// Margin of the pipeline execution in seconds that should be taken into consideration
int pipelineDuration = 5;
Instant now = Instant.now();
String messageText = now.toString();
List<String> data = ... |
@VisibleForTesting
static Duration parseToDuration(String timeStr) {
final Matcher matcher = Pattern.compile("(?<value>\\d+)\\s*(?<time>[dhms])").matcher(timeStr);
if (!matcher.matches()) {
throw new IllegalArgumentException("Expected a time specification in the form <number>[d,h,m,s], e... | @Test(expected = IllegalArgumentException.class)
public void testParseToDurationWithUnrecognizedTimeUnitThrowsAnError() {
AbstractPipelineExt.parseToDuration("3y");
} |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testGreaterThanOrEqual() {
Evaluator evaluator = new Evaluator(STRUCT, greaterThanOrEqual("x", 7));
assertThat(evaluator.eval(TestHelpers.Row.of(7, 8, null))).as("7 >= 7 => true").isTrue();
assertThat(evaluator.eval(TestHelpers.Row.of(6, 8, null))).as("6 >= 7 => false").isFalse();
as... |
@Override
public Connection getConnection(final String databaseName, final ContextManager contextManager) {
return new CircuitBreakerConnection();
} | @Test
void assertGetConnection() {
Connection actual = new CircuitBreakDriverState().getConnection(DefaultDatabase.LOGIC_NAME, mock(ContextManager.class, RETURNS_DEEP_STUBS));
assertThat(actual, instanceOf(CircuitBreakerConnection.class));
} |
@Override
public String resolveContentType(String resourceName) {
if (resourceName != null && !resourceName.isEmpty()) {
String lowerResourceName = resourceName.toLowerCase();
String fileExtension = StringUtils.substringAfterLast(lowerResourceName, '.');
return fileExtens... | @Test
void missingResourceName() {
ContentTypeResolver contentTypeResolver = new DefaultContentTypeResolver();
assertThat(contentTypeResolver.resolveContentType(null)).isNull();
assertThat(contentTypeResolver.resolveContentType("")).isNull();
} |
public static InetSocketAddress createUnresolved(String hostname, int port) {
return createInetSocketAddress(hostname, port, false);
} | @Test
void shouldAlwaysCreateResolvedNumberIPAddress() {
InetSocketAddress socketAddress = AddressUtils.createUnresolved("127.0.0.1", 8080);
assertThat(socketAddress.isUnresolved()).isFalse();
assertThat(socketAddress.getAddress().getHostAddress()).isEqualTo("127.0.0.1");
assertThat(socketAddress.getPort()).is... |
private static void network(XmlGenerator gen, ClientNetworkConfig network) {
gen.open("network")
.node("cluster-routing", null,
"mode", network.getClusterRoutingConfig().getRoutingMode().name())
.node("redo-operation", network.isRedoOperation())
.node("connect... | @Test
public void network() {
ClientNetworkConfig expected = new ClientNetworkConfig();
expected.setRedoOperation(true)
.setConnectionTimeout(randomInt())
.addAddress(randomString())
.setOutboundPortDefinitions(Collections.singleton(randomString()))
... |
public ConvertedTime getConvertedTime(long duration) {
Set<Seconds> keys = RULES.keySet();
for (Seconds seconds : keys) {
if (duration <= seconds.getSeconds()) {
return RULES.get(seconds).getConvertedTime(duration);
}
}
return new TimeConverter.Ove... | @Test
public void testShouldReportAbout2HoursHourFor89Minutes30Seconds() throws Exception {
assertEquals(TimeConverter.ABOUT_X_HOURS_AGO.argument(2), timeConverter
.getConvertedTime(1 * TimeConverter.HOUR_IN_SECONDS + 29 * 60 + 30));
} |
public ProcessingExceptionHandler processingExceptionHandler() {
return getConfiguredInstance(PROCESSING_EXCEPTION_HANDLER_CLASS_CONFIG, ProcessingExceptionHandler.class);
} | @Test
public void shouldOverrideDefaultProcessingExceptionHandler() {
props.put(StreamsConfig.PROCESSING_EXCEPTION_HANDLER_CLASS_CONFIG, "org.apache.kafka.streams.errors.LogAndContinueProcessingExceptionHandler");
final StreamsConfig streamsConfig = new StreamsConfig(props);
assertEquals("o... |
@Override
public void onEvent(Event e) {
LOGGER.info("Received event from the King's Hand: {}", e.toString());
} | @Test
void testOnEvent() {
final var kingJoffrey = new KingJoffrey();
IntStream.range(0, Event.values().length).forEach(i -> {
assertEquals(i, appender.getLogSize());
var event = Event.values()[i];
kingJoffrey.onEvent(event);
final var expectedMessage = "Received event from the King's... |
public static void validateFineGrainedAuth(Method endpointMethod, UriInfo uriInfo, HttpHeaders httpHeaders,
FineGrainedAccessControl accessControl) {
if (endpointMethod.isAnnotationPresent(Authorize.class)) {
final Authorize auth = endpointMethod.getAnnotation(Authorize.class);
String targetId = n... | @Test
public void testValidateFineGrainedAuthDenied() {
FineGrainedAccessControl ac = Mockito.mock(FineGrainedAccessControl.class);
Mockito.when(ac.hasAccess(Mockito.any(HttpHeaders.class), Mockito.any(), Mockito.any(), Mockito.any()))
.thenReturn(false);
UriInfo mockUriInfo = Mockito.mock(UriInf... |
RegistryEndpointProvider<Void> committer(URL location) {
return new Committer(location);
} | @Test
public void testCommitter_getApiRoute() throws MalformedURLException {
Assert.assertEquals(
new URL("https://someurl?somequery=somevalue&digest=" + fakeDescriptorDigest),
testBlobPusher.committer(new URL("https://someurl?somequery=somevalue")).getApiRoute(""));
} |
public static List<AwsEndpoint>[] splitByZone(List<AwsEndpoint> eurekaEndpoints, String myZone) {
if (eurekaEndpoints.isEmpty()) {
return new List[]{Collections.emptyList(), Collections.emptyList()};
}
if (myZone == null) {
return new List[]{Collections.emptyList(), new A... | @Test
public void testSplitByZone() throws Exception {
List<AwsEndpoint> endpoints = SampleCluster.merge(SampleCluster.UsEast1a, SampleCluster.UsEast1b, SampleCluster.UsEast1c);
List<AwsEndpoint>[] parts = ResolverUtils.splitByZone(endpoints, "us-east-1b");
List<AwsEndpoint> myZoneServers =... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldHandleQualifiedSelect() {
// Given:
final SingleStatementContext stmt = givenQuery("SELECT TEST1.COL0 FROM TEST1;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
assertThat(result.getSelect(), is(new Select(ImmutableList.of(
new... |
public static void init(final Map<String, PluginConfiguration> pluginConfigs, final Collection<JarFile> pluginJars, final ClassLoader pluginClassLoader, final boolean isEnhancedForProxy) {
if (STARTED_FLAG.compareAndSet(false, true)) {
start(pluginConfigs, pluginClassLoader, isEnhancedForProxy);
... | @Test
void assertInitPluginLifecycleServiceWithMockHandler() throws MalformedURLException {
URLStreamHandlerFactory urlStreamHandlerFactory = mock(URLStreamHandlerFactory.class);
PluginLifecycleServiceManager.init(Collections.emptyMap(), Collections.emptyList(),
new PrivateMLet(new U... |
public static Builder builder() {
return new Builder();
} | @Test
public void testBackOffWithMaxAttempts() {
final BackOff backOff = BackOff.builder().maxAttempts(5L).build();
final BackOffTimerTask context = new BackOffTimerTask(backOff, null, t -> true);
long delay;
for (int i = 1; i <= 5; i++) {
delay = context.next();
... |
@Nullable
public static <T extends Annotation> T extract(Class<?> targetClass, Class<T> annotationClass) {
T annotation = null;
if (targetClass.isAnnotationPresent(annotationClass)) {
annotation = targetClass.getAnnotation(annotationClass);
if (annotation == null && logger.is... | @Test
public void testExtract2() {
CircuitBreaker circuitBreaker = AnnotationExtractor
.extract(NotAnnotatedClass.class, CircuitBreaker.class);
assertThat(circuitBreaker).isNull();
} |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final CloudBlob blob = session.getClient().getContainerReference(containerService.getContainer(file).getName())
.getBlobRefere... | @Test
public void testReadZeroLength() throws Exception {
final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new AzureTouchFeature(... |
@Override
public RouteContext route(final ShardingRule shardingRule) {
Collection<String> bindingTableNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
Collection<RouteContext> routeContexts = new LinkedList<>();
for (String each : logicTables) {
Optional<ShardingTable> shard... | @Test
void assertRoutingForShardingTableJoinWithUpperCase() {
ShardingComplexRoutingEngine complexRoutingEngine = new ShardingComplexRoutingEngine(ShardingRoutingEngineFixtureBuilder.createShardingConditions("T_ORDER"),
mock(SQLStatementContext.class), new HintValueContext(), new Configurati... |
@Override
public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) {
return execute(commands, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getNewKey(), "New name must not be null!");
byte[] k... | @Test
public void testRename_keyNotExist() {
testInClusterReactive(connection -> {
Integer originalSlot = getSlotForKey(originalKey, (RedissonReactiveRedisClusterConnection) connection);
newKey = getNewKeyForSlot(new String(originalKey.array()), getTargetSlot(originalSlot), connectio... |
@Override
public void truncate(final Long length) {
this.length = length;
if(temporary.exists()) {
try {
final RandomAccessFile file = random();
if(length < file.length()) {
// Truncate current
file.setLength(length)... | @Test
public void testTruncate() throws Exception {
final FileBuffer buffer = new FileBuffer();
assertEquals(0L, buffer.length(), 0L);
final byte[] chunk = RandomUtils.nextBytes(100);
buffer.write(chunk, 0L);
assertEquals(100L, buffer.length(), 0L);
buffer.truncate(1L... |
public String getFragmentByLines(int startLine, int endLine) {
Preconditions.checkArgument(startLine <= endLine);
return Joiner.on("\n").join(getLines(startLine, endLine)) + "\n";
} | @Test
public void getFragmentByLines() {
assertThat(sourceFile.getFragmentByLines(2, 2))
.isEqualTo("// eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut\n");
assertThat(sourceFile.getFragmentByLines(8, 8)).isEqualTo("// est laborum.\n");
assertThat(sourceFile.getFragmentByLines(2, 3)... |
public FindTemplateResponse findByIdAndMember(MemberDto memberDto, Long id) {
Member member = memberRepository.fetchById(memberDto.id());
Template template = templateRepository.fetchById(id);
validateTemplateAuthorizeMember(template, member);
List<SourceCode> sourceCodes = sourceCodeRep... | @Test
@DisplayName("템플릿 단건 조회 실패: 권한 없음")
void findOneTemplateFailWithUnauthorized() {
// given
MemberDto memberDto = MemberDtoFixture.getFirstMemberDto();
Member member = memberRepository.fetchById(memberDto.id());
CreateTemplateRequest createdTemplate = makeTemplateRequest("tit... |
public static void verifyHybridTableConfigs(String rawTableName, TableConfig offlineTableConfig,
TableConfig realtimeTableConfig) {
Preconditions.checkNotNull(offlineTableConfig,
"Found null offline table config in hybrid table check for table: %s", rawTableName);
Preconditions.checkNotNull(realti... | @Test
public void testValidateHybridTableConfig() {
TableConfig realtimeTableConfig = new TableConfigBuilder(TableType.REALTIME).setTableName(TABLE_NAME).build();
TableConfig offlineTableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName(TABLE_NAME).build();
try {
// Call validate hybri... |
public static FunctionTypeInfo getFunctionTypeInfo(
final ExpressionTypeManager expressionTypeManager,
final FunctionCall functionCall,
final UdfFactory udfFactory,
final Map<String, SqlType> lambdaMapping
) {
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
final List<Expression> argument... | @Test
public void shouldResolveGenericsInLambdaFunction() {
// Given:
givenUdfWithNameAndReturnType("ComplexFunction", SqlTypes.DOUBLE);
when(function.parameters()).thenReturn(
ImmutableList.of(
ArrayType.of(GenericType.of("X")),
MapType.of(GenericType.of("K"), GenericType.... |
public static String fastUUID() {
return UUID.fastUUID().toString();
} | @Test
public void fastUUIDTest() {
String simpleUUID = IdUtil.fastSimpleUUID();
assertEquals(32, simpleUUID.length());
String randomUUID = IdUtil.fastUUID();
assertEquals(36, randomUUID.length());
} |
public static <K, V>
PTransform<PCollection<KV<K, TimestampedValue<V>>>, PCollection<KV<K, V>>>
extractTimestampsFromValues() {
return new ExtractTimestampsFromValues<>();
} | @Test
@Category(NeedsRunner.class)
public void extractFromValuesSucceeds() {
PCollection<KV<String, TimestampedValue<Integer>>> preified =
pipeline.apply(
Create.of(
KV.of("foo", TimestampedValue.of(0, new Instant(0))),
KV.of("foo", TimestampedValue.of(1, new ... |
@Override
public void preCommit(TransactionState txnState, List<TabletCommitInfo> finishedTablets,
List<TabletFailInfo> failedTablets) throws TransactionException {
Preconditions.checkState(txnState.getTransactionStatus() != TransactionStatus.COMMITTED);
txnState.clearAut... | @Test
public void testCommitRateLimiterDisabled() throws TransactionException {
new MockUp<LakeTableTxnStateListener>() {
@Mock
boolean enableIngestSlowdown() {
return false;
}
};
LakeTable table = buildLakeTable();
DatabaseTransac... |
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> rule... | @Test
public void param_componentUuids_enables_search_by_test_file() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project).setQualifier(Qualifiers.UNIT_TEST_FILE));
SearchRequest request = new Searc... |
public boolean isSuccess() {
return applicationStatus == ApplicationStatus.SUCCEEDED
|| (applicationStatus == ApplicationStatus.UNKNOWN && serializedThrowable == null);
} | @Test
void testIsNotSuccess() {
final JobResult jobResult =
new JobResult.Builder()
.jobId(new JobID())
.serializedThrowable(new SerializedThrowable(new RuntimeException()))
.netRuntime(Long.MAX_VALUE)
... |
private RemotingCommand updateUser(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
RemotingCommand response = RemotingCommand.createResponseCommand(null);
UpdateUserRequestHeader requestHeader = request.decodeCommandCustomHeader(UpdateUserRequestHeader.clas... | @Test
public void testUpdateUser() throws RemotingCommandException {
when(authenticationMetadataManager.updateUser(any(User.class)))
.thenReturn(CompletableFuture.completedFuture(null));
when(authenticationMetadataManager.getUser(eq("abc"))).thenReturn(CompletableFuture.completedFuture(U... |
@SqlInvokedScalarFunction(value = "array_duplicates", alias = {"array_dupes"}, deterministic = true, calledOnNullInput = false)
@Description("Returns set of elements that have duplicates")
@SqlParameter(name = "input", type = "array(T)")
@TypeParameter("T")
@SqlType("array(T)")
public static String ... | @Test
public void testArrayDuplicates()
{
assertFunction("array_duplicates(cast(null as array(varchar)))", new ArrayType(VARCHAR), null);
assertFunction("array_duplicates(cast(array[] as array(varchar)))", new ArrayType(VARCHAR), ImmutableList.of());
assertFunction("array_duplicates(arr... |
public boolean release(final ResourceProfile reservation) {
checkResourceProfileNotNullOrUnknown(reservation);
ResourceProfile newAvailableBudget = availableBudget.merge(reservation);
if (!totalBudget.allFieldsNoLessThan(newAvailableBudget)) {
return false;
}
availab... | @Test
void testRelease() {
ResourceBudgetManager budgetManager =
new ResourceBudgetManager(createResourceProfile(1.0, 100));
assertThat(budgetManager.reserve(createResourceProfile(0.7, 70))).isEqualTo(true);
assertThat(budgetManager.release(createResourceProfile(0.5, 50))).i... |
public static Builder newBuilder() {
return new Builder();
} | @Test
public void largeLimitIncrease() {
VegasLimit limit = VegasLimit.newBuilder()
.initialLimit(10000)
.maxConcurrency(20000)
.build();
limit.onSample(0, TimeUnit.SECONDS.toNanos(10), 5000, false);
Assert.assertEquals(10000, limit.getLimit())... |
public static void mergeMap(boolean decrypt, Map<String, Object> config) {
merge(decrypt, config);
} | @Test(expected = ConfigException.class)
public void testMap_key_mergeWhenFieldNotInValues_throwsException() {
Map<String, Object> testMap = new HashMap<>();
testMap.put("${TEST.somethingNotInValues}", "value");
CentralizedManagement.mergeMap(true, testMap);
} |
@Operation(summary = "update", description = "Update a cluster")
@PutMapping("/{id}")
public ResponseEntity<ClusterVO> update(@PathVariable Long id, @RequestBody @Validated ClusterReq clusterReq) {
ClusterDTO clusterDTO = ClusterConverter.INSTANCE.fromReq2DTO(clusterReq);
return ResponseEntity.s... | @Test
void updateModifiesCluster() {
Long id = 1L;
ClusterReq clusterReq = new ClusterReq();
ClusterVO updatedCluster = new ClusterVO();
when(clusterService.update(eq(id), any())).thenReturn(updatedCluster);
ResponseEntity<ClusterVO> response = clusterController.update(id, c... |
public static Number parseNumber(String numberStr) throws NumberFormatException {
if (StrUtil.startWithIgnoreCase(numberStr, "0x")) {
// 0x04表示16进制数
return Long.parseLong(numberStr.substring(2), 16);
} else if (StrUtil.startWith(numberStr, '+')) {
// issue#I79VS7
numberStr = StrUtil.subSuf(numberStr, 1)... | @Test
public void issue3636Test() {
final Number number = NumberUtil.parseNumber("12,234,456");
assertEquals(new BigDecimal(12234456), number);
} |
public void putValue(String fieldName, @Nullable Object value) {
_fieldToValueMap.put(fieldName, value);
} | @Test
public void testNullAndNonNullValuesNotEqual() {
GenericRow first = new GenericRow();
first.putValue("one", null);
GenericRow second = new GenericRow();
second.putValue("one", 1);
Assert.assertNotEquals(first, second);
first = new GenericRow();
first.putValue("one", 1);
second =... |
public void registerHandlerMethods(String pluginId, Object handler) {
Class<?> handlerType = (handler instanceof String beanName
? obtainApplicationContext().getType(beanName) : handler.getClass());
if (handlerType != null) {
final Class<?> userType = ClassUtils.getUserClass(han... | @Test
public void getHandlerDirectMatch() {
// register handler methods first
handlerMapping.registerHandlerMethods("fakePlugin", new TestController());
// resolve an expected method from TestController
Method expected =
ResolvableMethod.on(TestController.class).annot(ge... |
@Override
public MetricType getType() {
return MetricType.COUNTER_LONG;
} | @Test
public void getType() {
assertEquals(MetricType.COUNTER_LONG, new UptimeMetric().getType());
} |
public static int compose(final int major, final int minor, final int patch)
{
if (major < 0 || major > 255)
{
throw new IllegalArgumentException("major must be 0-255: " + major);
}
if (minor < 0 || minor > 255)
{
throw new IllegalArgumentException("m... | @Test
void shouldDetectZeroVersion()
{
assertThrows(IllegalArgumentException.class, () -> SemanticVersion.compose(0, 0, 0));
} |
static Callback create(@Nullable Callback delegate, Span span, CurrentTraceContext current) {
if (delegate == null) return new FinishSpan(span);
return new DelegateAndFinishSpan(delegate, span, current);
} | @Test void on_completion_should_forward_then_tag_if_exception() {
Span span = tracing.tracer().nextSpan().start();
Callback delegate = mock(Callback.class);
Callback tracingCallback = TracingCallback.create(delegate, span, currentTraceContext);
RecordMetadata md = createRecordMetadata();
tracingCal... |
public static String format(String source, Object... parameters) {
String current = source;
for (Object parameter : parameters) {
if (!current.contains("{}")) {
return current;
}
current = current.replaceFirst("\\{\\}", String.valueOf(parameter));
... | @Test
public void testFormatMissingBracket() {
String fmt = "Some string 1 2 3";
assertEquals("Some string 1 2 3", format(fmt, 7));
} |
@Override
public int hashCode()
{
return Long.hashCode(numberAndGeneration);
} | @Test
void checkHashCode()
{
// same object number 100 0
assertEquals(new COSObjectKey(100, 0).hashCode(),
new COSObjectKey(100, 0).hashCode());
// different object numbers/same generation numbers 100 0 vs. 200 0
assertNotEquals(new COSObjectKey(100, 0).hashCode(... |
@Override
public void doAlarm(List<AlarmMessage> alarmMessages) throws Exception {
Map<String, SlackSettings> settingsMap = alarmRulesWatcher.getSlackSettings();
if (settingsMap == null || settingsMap.isEmpty()) {
return;
}
Map<String, List<AlarmMessage>> groupedMessages... | @Test
public void testWechatWebhook() throws Exception {
List<String> remoteEndpoints = new ArrayList<>();
remoteEndpoints.add("http://127.0.0.1:" + SERVER.httpPort() + "/services/x/y/zssss");
Rules rules = new Rules();
String template = "{\"type\":\"section\",\"text\":{\"type\":\"mr... |
public void convert(FSConfigToCSConfigConverterParams params)
throws Exception {
validateParams(params);
this.clusterResource = getClusterResource(params);
this.convertPlacementRules = params.isConvertPlacementRules();
this.outputDirectory = params.getOutputDirectory();
this.rulesToFile = para... | @Test
public void testConvertFSConfigurationUndefinedYarnSiteConfig()
throws Exception {
FSConfigToCSConfigConverterParams params =
FSConfigToCSConfigConverterParams.Builder.create()
.withYarnSiteXmlConfig(null)
.withOutputDirectory(FSConfigConverterTestCommons.OUTPUT_DIR)
... |
public static KeyValueBytesStoreSupplier lruMap(final String name, final int maxCacheSize) {
Objects.requireNonNull(name, "name cannot be null");
if (maxCacheSize < 0) {
throw new IllegalArgumentException("maxCacheSize cannot be negative");
}
return new KeyValueBytesStoreSupp... | @Test
public void shouldThrowIfILruMapStoreNameIsNull() {
final Exception e = assertThrows(NullPointerException.class, () -> Stores.lruMap(null, 0));
assertEquals("name cannot be null", e.getMessage());
} |
public List<DataRecord> merge(final List<DataRecord> dataRecords) {
Map<DataRecord.Key, DataRecord> result = new HashMap<>();
dataRecords.forEach(each -> {
if (PipelineSQLOperationType.INSERT == each.getType()) {
mergeInsert(each, result);
} else if (PipelineSQLOp... | @Test
void assertUpdateBeforeInsert() {
DataRecord beforeDataRecord = mockUpdateDataRecord(1, 2, 2);
DataRecord afterDataRecord = mockInsertDataRecord(1, 1, 1);
assertThrows(PipelineUnexpectedDataRecordOrderException.class, () -> groupEngine.merge(Arrays.asList(beforeDataRecord, afterDataRec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.