focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void close() throws IOException {
State prevState = state;
if (state == State.CLOSING) return;
state = State.CLOSING;
sslEngine.closeOutbound();
try {
if (prevState != State.NOT_INITIALIZED && isConnected()) {
if (!flush(netWriteBu... | @Test
public void testSSLEngineCloseInboundInvokedOnClose() throws IOException {
// Given
SSLEngine sslEngine = mock(SSLEngine.class);
Socket socket = mock(Socket.class);
SocketChannel socketChannel = mock(SocketChannel.class);
SelectionKey selectionKey = mock(SelectionKey.cl... |
@Override
public void acknowledge(OutputBufferId outputBufferId, long sequenceId)
{
requireNonNull(outputBufferId, "bufferId is null");
partitions.get(outputBufferId.getId()).acknowledgePages(sequenceId);
} | @Test
public void testAcknowledge()
{
int partitionId = 0;
PartitionedOutputBuffer buffer = createPartitionedBuffer(
createInitialEmptyOutputBuffers(PARTITIONED)
.withBuffer(FIRST, partitionId)
.withNoMoreBufferIds(),
... |
@Override
// Camel calls this method if the endpoint isSynchronous(), as the
// KafkaEndpoint creates a SynchronousDelegateProducer for it
public void process(Exchange exchange) throws Exception {
// is the message body a list or something that contains multiple values
Message message = exch... | @Test
public void processSendsMessageWithTopicHeaderAndEndPoint() throws Exception {
endpoint.getConfiguration().setTopic("sometopic");
Mockito.when(exchange.getIn()).thenReturn(in);
Mockito.when(exchange.getMessage()).thenReturn(in);
in.setHeader(KafkaConstants.PARTITION_KEY, 4);
... |
public ConfigOperateResult insertOrUpdate(String srcIp, String srcUser, ConfigInfo configInfo,
Map<String, Object> configAdvanceInfo) {
try {
ConfigInfoStateWrapper configInfoState = findConfigInfoState(configInfo.getDataId(), configInfo.getGroup(),
configInfo.getTena... | @Test
void testInsertOrUpdateOfInsertConfigSuccess() {
String dataId = "dataId";
String group = "group";
String tenant = "tenant";
String appName = "appNameNew";
String content = "content132456";
Map<String, Object> configAdvanceInfo = new HashMap<>();
... |
@Override
public ArrayList<Character> read(String charactersString) throws Exception {
return null;
} | @Test
public void testRead() throws Exception {
Controlador controlador = new Controlador();
try {
ArrayList<Character> result = controlador.read("12345");
// Verificar que el resultado no sea null
// Resto del código de verificación
} catch (Exception e) {
fai... |
@Override
public <T> ListState<T> getListState(ListStateDescriptor<T> stateProperties) {
KeyedStateStore keyedStateStore = checkPreconditionsAndGetKeyedStateStore(stateProperties);
stateProperties.initializeSerializerUnlessSet(this::createSerializer);
return keyedStateStore.getListState(stat... | @Test
void testV2ListStateInstantiation() throws Exception {
final ExecutionConfig config = new ExecutionConfig();
SerializerConfig serializerConfig = config.getSerializerConfig();
serializerConfig.registerKryoType(Path.class);
final AtomicReference<Object> descriptorCapture = new A... |
public static <K, V> Read<K, V> read() {
return new AutoValue_KafkaIO_Read.Builder<K, V>()
.setTopics(new ArrayList<>())
.setTopicPartitions(new ArrayList<>())
.setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN)
.setConsumerConfig(KafkaIOUtils.DEFAULT_CONSUMER_PROPERTIES)
... | @Test
public void testResolveDefaultApiTimeout() {
final String defaultApiTimeoutConfig = "default.api.timeout.ms";
assertEquals(
Duration.millis(20),
KafkaUnboundedReader.resolveDefaultApiTimeout(
KafkaIO.<Integer, Long>read()
.withConsumerConfigUpdates(
... |
public static String getElasticJobNamespace() {
// ElasticJob will persist job to namespace
return getJobsPath();
} | @Test
void assertGetElasticJobNamespace() {
assertThat(PipelineMetaDataNode.getElasticJobNamespace(), is(jobsPath));
} |
@Override
protected Object createObject(ValueWrapper<Object> initialInstance, String className, Map<List<String>, Object> params, ClassLoader classLoader) {
return fillBean(initialInstance, className, params, classLoader);
} | @Test
public void createObjectDirectMappingComplexType() {
Map<List<String>, Object> params = new HashMap<>();
Person directMappingComplexTypeValue = new Person();
directMappingComplexTypeValue.setFirstName("TestName");
params.put(List.of(), directMappingComplexTypeValue);
pa... |
@VisibleForTesting
public Optional<ProcessContinuation> run(
PartitionMetadata partition,
ChildPartitionsRecord record,
RestrictionTracker<TimestampRange, Timestamp> tracker,
ManualWatermarkEstimator<Instant> watermarkEstimator) {
final String token = partition.getPartitionToken();
L... | @Test
public void testRestrictionClaimedAnsIsSplitCaseAndChildExists() {
final String partitionToken = "partitionToken";
final long heartbeat = 30L;
final Timestamp startTimestamp = Timestamp.ofTimeMicroseconds(10L);
final Timestamp endTimestamp = Timestamp.ofTimeMicroseconds(20L);
final Partition... |
synchronized void ensureTokenInitialized() throws IOException {
// we haven't inited yet, or we used to have a token but it expired
if (!hasInitedToken || (action != null && !action.isValid())) {
//since we don't already have a token, go get one
Token<?> token = fs.getDelegationToken(null);
//... | @Test
public void testInitWithUGIToken() throws IOException, URISyntaxException {
Configuration conf = new Configuration();
DummyFs fs = spy(new DummyFs());
doReturn(null).when(fs).getDelegationToken(anyString());
Token<TokenIdentifier> token = new Token<TokenIdentifier>(new byte[0],
new byte... |
Mono<ServerResponse> getComment(ServerRequest request) {
String name = request.pathVariable("name");
return Mono.defer(() -> Mono.justOrEmpty(commentPublicQueryService.getByName(name)))
.subscribeOn(Schedulers.boundedElastic())
.flatMap(comment -> ServerResponse.ok().bodyValue(co... | @Test
void getComment() {
when(commentPublicQueryService.getByName(any()))
.thenReturn(null);
webTestClient.get()
.uri("/comments/test-comment")
.exchange()
.expectStatus()
.isOk();
verify(commentPublicQueryService, times(1)).getB... |
@Override
public <T> T persist(T detachedObject) {
Map<Object, Object> alreadyPersisted = new HashMap<Object, Object>();
return persist(detachedObject, alreadyPersisted, RCascadeType.PERSIST);
} | @Test
public void testObjectShouldNotBeAttached() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
Customer customer = new Customer("12");
customer = redisson.getLiveObjectService().persist(customer);
Order order = new Order();
customer.getOrd... |
@Override
public boolean matches(Job localJob, Job storageProviderJob) {
return AllowedConcurrentStateChange.super.matches(localJob, storageProviderJob)
&& localJob.getVersion() == storageProviderJob.getVersion() - 1
&& localJob.getLastJobStateOfType(FailedState.class).isPres... | @Test
void ifLocalJobHasOtherThanEnqueuedStateItWillNotMatch() {
final Job scheduledJob = aScheduledJob().build();
final Job enqueuedJob = aCopyOf(scheduledJob).withEnqueuedState(Instant.now()).build();
boolean matchesAllowedStateChange = allowedStateChange.matches(scheduledJob, enqueuedJob... |
@Subscribe
public void inputUpdated(InputUpdated inputUpdatedEvent) {
final String inputId = inputUpdatedEvent.id();
LOG.debug("Input updated: {}", inputId);
final Input input;
try {
input = inputService.find(inputId);
} catch (NotFoundException e) {
L... | @Test
@SuppressWarnings("unchecked")
public void inputUpdatedDoesNotStopInputIfItIsNotRunning() throws Exception {
final String inputId = "input-id";
final Input input = mock(Input.class);
when(inputService.find(inputId)).thenReturn(input);
when(inputRegistry.getInputState(inputI... |
void validateLogLevelConfigs(Collection<AlterableConfig> ops) {
ops.forEach(op -> {
String loggerName = op.name();
switch (OpType.forId(op.configOperation())) {
case SET:
validateLoggerNameExists(loggerName);
String logLevel = op.va... | @Test
public void testValidateSetRootLogLevelConfig() {
MANAGER.validateLogLevelConfigs(Arrays.asList(new AlterableConfig().
setName(Log4jController.ROOT_LOGGER()).
setConfigOperation(OpType.SET.id()).
setValue("TRACE")));
} |
@Override
public String getPrefix() {
return String.format("%s.%s", DriveProtocol.class.getPackage().getName(), "Drive");
} | @Test
public void testPrefix() {
assertEquals("ch.cyberduck.core.googledrive.Drive", new DriveProtocol().getPrefix());
} |
public static String protectXMLCDATA( String content ) {
if ( Utils.isEmpty( content ) ) {
return content;
}
return "<![CDATA[" + content + "]]>";
} | @Test
public void testProtectXMLCDATA() {
assertEquals( null, Const.protectXMLCDATA( null ) );
assertEquals( "", Const.protectXMLCDATA( "" ) );
assertEquals( "<![CDATA[foo]]>", Const.protectXMLCDATA( "foo" ) );
} |
@Override
public boolean hasResourcesAvailable(Container container) {
return hasResourcesAvailable(container.getResource());
} | @Test
public void testHasResourcesAvailable() {
AllocationBasedResourceUtilizationTracker tracker =
new AllocationBasedResourceUtilizationTracker(mockContainerScheduler);
Container testContainer = mock(Container.class);
when(testContainer.getResource()).thenReturn(Resource.newInstance(512, 4));
... |
public void clearCookies() { parent.headers().remove(HttpHeaders.Names.COOKIE); } | @Test
void testClearCookies() {
URI uri = URI.create("http://example.yahoo.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
httpReq.headers().put(HttpHeaders.Names.COOKIE, "XYZ=value");
DiscFilterRequest request = new DiscFilter... |
public static <T> PrefetchableIterable<T> emptyIterable() {
return (PrefetchableIterable<T>) EMPTY_ITERABLE;
} | @Test
public void testEmptyIterable() {
verifyIterable(PrefetchableIterables.emptyIterable());
} |
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 show_different_types_of_not_intervals() {
{
Predicate p =
and(
or(
and(
feature("key").inSet("A"),
not(feature("k... |
public static FileSystem write(final FileSystem fs, final Path path,
final byte[] bytes) throws IOException {
Objects.requireNonNull(path);
Objects.requireNonNull(bytes);
try (FSDataOutputStream out = fs.createFile(path).overwrite(true).build()) {
out.write(bytes);
}
return fs;
} | @Test
public void testWriteStringFileContext() throws IOException {
URI uri = tmp.toURI();
Configuration conf = new Configuration();
FileContext fc = FileContext.getFileContext(uri, conf);
Path testPath = new Path(new Path(uri), "writestring.out");
String write = "A" + "\u00ea" + "\u00f1" + "\u00... |
public int getDefaultSelectedSchemaIndex() {
List<String> schemaNames;
try {
schemaNames = schemasProvider.getPartitionSchemasNames( transMeta );
} catch ( KettleException e ) {
schemaNames = Collections.emptyList();
}
PartitionSchema partitioningSchema = stepMeta.getStepPartitioningMet... | @Test
public void defaultSelectedSchemaIndexWhenSchemaNameIsNotDefined() throws Exception {
PartitionSchema schema = new PartitionSchema( );
StepPartitioningMeta meta = mock( StepPartitioningMeta.class );
when( meta.getPartitionSchema() ).thenReturn( schema );
when( stepMeta.getStepPartitioningMeta() ... |
@ConstantFunction(name = "time_slice", argTypes = {DATETIME, INT, VARCHAR}, returnType = DATETIME, isMonotonic = true)
public static ConstantOperator timeSlice(ConstantOperator datetime, ConstantOperator interval,
ConstantOperator unit) throws AnalysisException {
... | @Test
public void timeSlice() throws AnalysisException {
class Param {
final LocalDateTime dateTime;
final int interval;
final String unit;
final String boundary;
LocalDateTime expect;
String e;
public Param(LocalDateTime ... |
public static boolean shouldStartHazelcast(AppSettings appSettings) {
return isClusterEnabled(appSettings.getProps()) && toNodeType(appSettings.getProps()).equals(NodeType.APPLICATION);
} | @Test
@UseDataProvider("validIPv4andIPv6Addresses")
public void shouldStartHazelcast_should_return_true_on_AppNode(String host) {
assertThat(ClusterSettings.shouldStartHazelcast(newSettingsForAppNode(host))).isTrue();
} |
public boolean setLocations(DefaultIssue issue, @Nullable Object locations) {
if (!locationsEqualsIgnoreHashes(locations, issue.getLocations())) {
issue.setLocations(locations);
issue.setChanged(true);
issue.setLocationsChanged(true);
return true;
}
return false;
} | @Test
void change_locations_if_secondary_message_changed() {
DbIssues.Locations locations = DbIssues.Locations.newBuilder()
.addFlow(DbIssues.Flow.newBuilder()
.addLocation(DbIssues.Location.newBuilder().setMsg("msg1"))
.build())
.build();
issue.setLocations(locations);
DbIssue... |
@Override
@Deprecated
public void process(final org.apache.kafka.streams.processor.ProcessorSupplier<? super K, ? super V> processorSupplier,
final String... stateStoreNames) {
process(processorSupplier, Named.as(builder.newProcessorName(PROCESSOR_NAME)), stateStoreNames);
} | @SuppressWarnings("deprecation")
@Test
public void shouldBindStateWithOldProcessorSupplier() {
final Consumed<String, String> consumed = Consumed.with(Serdes.String(), Serdes.String());
final StreamsBuilder builder = new StreamsBuilder();
final String input = "input";
builder.... |
public boolean createTable(CreateTableStmt stmt, List<Column> partitionColumns) throws DdlException {
String dbName = stmt.getDbName();
String tableName = stmt.getTableName();
Map<String, String> properties = stmt.getProperties() != null ? stmt.getProperties() : new HashMap<>();
Path tab... | @Test
public void testCreateTableForExternal() throws DdlException {
new MockUp<HiveWriteUtils>() {
@Mock
public void createDirectory(Path path, Configuration conf) {
}
};
HiveMetastoreOperations mockedHmsOps = new HiveMetastoreOperations(cachingHiveMetas... |
public FEELFnResult<Boolean> invoke(@ParameterName( "range1" ) Range range1, @ParameterName( "range2" ) Range range2) {
if ( range1 == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "range1", "cannot be null"));
}
if ( range2 == null ) {
r... | @Test
void invokeParamIsNull() {
FunctionTestUtil.assertResultError(metByFunction.invoke(null, new RangeImpl()), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(metByFunction.invoke(new RangeImpl(), null), InvalidParametersEvent.class);
} |
@Override
public boolean test(Pickle pickle) {
URI picklePath = pickle.getUri();
if (!lineFilters.containsKey(picklePath)) {
return true;
}
for (Integer line : lineFilters.get(picklePath)) {
if (Objects.equals(line, pickle.getLocation().getLine())
... | @Test
void matches_first_example() {
LinePredicate predicate = new LinePredicate(singletonMap(
featurePath,
singletonList(7)));
assertTrue(predicate.test(firstPickle));
assertFalse(predicate.test(secondPickle));
assertFalse(predicate.test(thirdPickle));
... |
@Override
public void unregister(@NonNull SchemeWatcher watcher) {
Assert.notNull(watcher, "Scheme watcher must not be null");
watchers.remove(watcher);
} | @Test
void shouldThrowExceptionWhenUnregisterNullWatcher() {
assertThrows(IllegalArgumentException.class, () -> watcherManager.unregister(null));
} |
@Override
public ColumnStatistics buildColumnStatistics()
{
return new ColumnStatistics(nonNullValueCount, null, rawSize, storageSize);
} | @Test
public void testNoValues()
{
CountStatisticsBuilder statisticsBuilder = new CountStatisticsBuilder();
ColumnStatistics columnStatistics = statisticsBuilder.buildColumnStatistics();
assertEquals(columnStatistics.getNumberOfValues(), 0);
} |
public ParseResult parse(File file) throws IOException, SchemaParseException {
return parse(file, null);
} | @Test
void testMultipleParseErrors() {
SchemaParseException parseException = assertThrows(SchemaParseException.class,
() -> new SchemaParser().parse(DummySchemaParser.SCHEMA_TEXT_ERROR).mainSchema());
assertTrue(parseException.getMessage().startsWith("Could not parse the schema"));
Throwable[] sup... |
static DwrfStripeCacheMode toStripeCacheMode(DwrfProto.StripeCacheMode mode)
{
switch (mode) {
case INDEX:
return DwrfStripeCacheMode.INDEX;
case FOOTER:
return DwrfStripeCacheMode.FOOTER;
case BOTH:
return DwrfStripeCacheMo... | @Test
public void testToStripeCacheMode()
{
assertEquals(DwrfMetadataReader.toStripeCacheMode(DwrfProto.StripeCacheMode.INDEX), DwrfStripeCacheMode.INDEX);
assertEquals(DwrfMetadataReader.toStripeCacheMode(DwrfProto.StripeCacheMode.FOOTER), DwrfStripeCacheMode.FOOTER);
assertEquals(DwrfM... |
@Override
public void init(HttpRequest request, HttpResponse response) {
String returnTo = request.getParameter(RETURN_TO_PARAMETER);
Map<String, String> parameters = new HashMap<>();
Optional<String> sanitizeRedirectUrl = sanitizeRedirectUrl(returnTo);
sanitizeRedirectUrl.ifPresent(s -> parameters.pu... | @Test
public void init_does_not_create_cookie_when_no_parameter() {
underTest.init(request, response);
verify(response, never()).addCookie(any(Cookie.class));
} |
public Template getIndexTemplate(IndexSet indexSet) {
final IndexSetMappingTemplate indexSetMappingTemplate = getTemplateIndexSetConfig(indexSet, indexSet.getConfig(), profileService);
return indexMappingFactory.createIndexMapping(indexSet.getConfig())
.toTemplate(indexSetMappingTemplate... | @Test
void testUsesCustomMappingsAndProfileWhileGettingTemplate() {
final TestIndexSet testIndexSet = indexSetConfig("test",
"test-template-profiles",
"custom",
"000000000000000000000013",
new CustomFieldMappings(List.of(
... |
@Udf
public String concat(@UdfParameter(
description = "The varchar fields to concatenate") final String... inputs) {
if (inputs == null) {
return null;
}
return Arrays.stream(inputs)
.filter(Objects::nonNull)
.collect(Collectors.joining());
} | @Test
public void shouldIgnoreNullInputs() {
assertThat(udf.concat(null, "this ", null, "should ", null, "work!", null),
is("this should work!"));
assertThat(udf.concat(null, ByteBuffer.wrap(new byte[] {1}), null, ByteBuffer.wrap(new byte[] {2}), null),
is(ByteBuffer.wrap(new byte[] {1, 2})));... |
@CanIgnoreReturnValue
public final Ordered containsExactlyEntriesIn(Multimap<?, ?> expectedMultimap) {
checkNotNull(expectedMultimap, "expectedMultimap");
checkNotNull(actual);
ListMultimap<?, ?> missing = difference(expectedMultimap, actual);
ListMultimap<?, ?> extra = difference(actual, expectedMult... | @Test
public void containsExactlyInOrderFailureValuesOnly() {
ImmutableMultimap<Integer, String> actual =
ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four");
ImmutableMultimap<Integer, String> expected =
ImmutableMultimap.of(3, "six", 3, "two", 3, "one", 4, "five", 4, "fo... |
@Override
public String arguments() {
ArrayList<String> args = new ArrayList<>();
if (buildFile != null) {
args.add("-f \"" + FilenameUtils.separatorsToUnix(buildFile) + "\"");
}
if (target != null) {
args.add(target);
}
return StringUtils.jo... | @Test
public void shouldReturnEmptyStringForDefault() throws Exception {
RakeTask rakeTask = new RakeTask();
assertThat(rakeTask.arguments(), is(""));
} |
public static boolean isListEqual(List<String> firstList, List<String> secondList) {
if (firstList == null && secondList == null) {
return true;
}
if (firstList == null || secondList == null) {
return false;
}
if (firstList == secondList) {
... | @Test
void testIsListEqualForNull() {
assertTrue(CollectionUtils.isListEqual(null, null));
assertFalse(CollectionUtils.isListEqual(Collections.emptyList(), null));
assertFalse(CollectionUtils.isListEqual(null, Collections.emptyList()));
} |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 3) {
onInvalidDataReceived(device, data);
return;
}
final int responseCode = data.getIntValue(Data.FORMAT_UINT8, 0);
final int requestCode = da... | @Test
public void onSupportedSensorLocationsReceived() {
final MutableData data = new MutableData(new byte[] { 0x10, 0x04, 0x01, 1, 2, 3});
response.onDataReceived(null, data);
assertTrue(success);
assertEquals(0, errorCode);
assertEquals(4, requestCode);
assertNotNull(locations);
assertEquals(3, locatio... |
byte[] removeEscapedEnclosures( byte[] field, int nrEnclosuresFound ) {
byte[] result = new byte[field.length - nrEnclosuresFound];
int resultIndex = 0;
for ( int i = 0; i < field.length; i++ ) {
result[resultIndex++] = field[i];
if ( field[i] == enclosure[0] && i + 1 < field.length && field[i +... | @Test
public void testRemoveEscapedEnclosuresWithOneEscapedInMiddle() {
CsvInputData csvInputData = new CsvInputData();
csvInputData.enclosure = "\"".getBytes();
String result = new String( csvInputData.removeEscapedEnclosures( "abcd \"\" defg".getBytes(), 1 ) );
assertEquals( "abcd \" defg", result )... |
public String filterNamespaceName(String namespaceName) {
if (namespaceName.toLowerCase().endsWith(".properties")) {
int dotIndex = namespaceName.lastIndexOf(".");
return namespaceName.substring(0, dotIndex);
}
return namespaceName;
} | @Test
public void testFilterNamespaceNameWithRandomCase() throws Exception {
String someName = "AbC.ProPErties";
assertEquals("AbC", namespaceUtil.filterNamespaceName(someName));
} |
public static boolean isUnclosedQuote(final String line) {
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
int quoteStart = -1;
for (int i = 0; i < line.length(); ++i) {
if (quoteStart < 0 && isQuoteChar(line, i)) {
quoteStart = i;
} else if (quoteStart >= 0 && isTwoQuoteStart(line, i) && !... | @Test
public void shouldNotFindUnclosedQuote_commentAfterQuote() {
// Given:
final String line = "some line 'quoted text' -- this is a comment";
// Then:
assertThat(UnclosedQuoteChecker.isUnclosedQuote(line), is(false));
} |
@Override
public void beginCommit(Long txId) {
if (txId <= lastSeenTxn.txnid) {
LOG.info("txID {} is already processed, lastSeenTxn {}. Triggering recovery.", txId, lastSeenTxn);
long start = System.currentTimeMillis();
options.recover(lastSeenTxn.dataFilePath, lastSeenTx... | @Test
public void testIndexFileCreation() {
HdfsState state = createHdfsState();
state.beginCommit(1L);
Collection<File> files = FileUtils.listFiles(new File(TEST_OUT_DIR), null, false);
File hdfsIndexFile = Paths.get(TEST_OUT_DIR, INDEX_FILE_PREFIX + TEST_TOPOLOGY_NAME + ".0").toFil... |
public ProcessContinuation run(
RestrictionTracker<TimestampRange, Timestamp> tracker,
OutputReceiver<PartitionMetadata> receiver,
ManualWatermarkEstimator<Instant> watermarkEstimator) {
final Timestamp readTimestamp = tracker.currentRestriction().getFrom();
// Updates the current watermark a... | @Test
public void testTerminatesWhenAllPartitionsAreFinished() {
final Timestamp from = Timestamp.ofTimeMicroseconds(10L);
when(restriction.getFrom()).thenReturn(from);
when(dao.getUnfinishedMinWatermark()).thenReturn(null);
final ProcessContinuation continuation = action.run(tracker, receiver, water... |
@Deprecated
public RegistryBuilder wait(Integer wait) {
this.wait = wait;
return getThis();
} | @Test
void testWait() {
RegistryBuilder builder = new RegistryBuilder();
builder.wait(Integer.valueOf(1000));
Assertions.assertEquals(1000, builder.build().getWait());
} |
@Override
protected String buildUndoSQL() {
return super.buildUndoSQL();
} | @Test
public void buildUndoSQL() {
String sql = executor.buildUndoSQL().toLowerCase();
Assertions.assertNotNull(sql);
Assertions.assertTrue(sql.contains("update"));
Assertions.assertTrue(sql.contains("id"));
Assertions.assertTrue(sql.contains("age"));
} |
public static Predicate parse(String expression)
{
final Stack<Predicate> predicateStack = new Stack<>();
final Stack<Character> operatorStack = new Stack<>();
final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll("");
final StringTokenizer tokenizer = new StringTokenizer(tr... | @Test
public void testAndOr()
{
final Predicate parsed = PredicateExpressionParser.parse("com.linkedin.data.it.AlwaysTruePredicate & com.linkedin.data.it.AlwaysTruePredicate | com.linkedin.data.it.AlwaysFalsePredicate");
Assert.assertEquals(parsed.getClass(), OrPredicate.class);
final List<Predicate> o... |
public static boolean isEmpty(String value) {
return StringUtils.isEmpty(value)
|| "false".equalsIgnoreCase(value)
|| "0".equalsIgnoreCase(value)
|| "null".equalsIgnoreCase(value)
|| "N/A".equalsIgnoreCase(value);
} | @Test
void testIsEmpty() throws Exception {
assertThat(ConfigUtils.isEmpty(null), is(true));
assertThat(ConfigUtils.isEmpty(""), is(true));
assertThat(ConfigUtils.isEmpty("false"), is(true));
assertThat(ConfigUtils.isEmpty("FALSE"), is(true));
assertThat(ConfigUtils.isEmpty("... |
public synchronized boolean autoEnterPureIncrementPhaseIfAllowed() {
if (!enterPureIncrementPhase
&& maxSnapshotSplitsHighWatermark.compareTo(startupOffset) == 0) {
split.asIncrementalSplit().getCompletedSnapshotSplitInfos().clear();
enterPureIncrementPhase = true;
... | @Test
public void testAutoEnterPureIncrementPhaseIfAllowed() {
Offset startupOffset = new TestOffset(100);
List<CompletedSnapshotSplitInfo> snapshotSplits = Collections.emptyList();
IncrementalSplit split = createIncrementalSplit(startupOffset, snapshotSplits);
IncrementalSplitState ... |
@VisibleForTesting
Collection<NumaNodeResource> getNumaNodesList() {
return numaNodesList;
} | @Test
public void testReadNumaTopologyFromConfigurations() throws Exception {
Collection<NumaNodeResource> nodesList = numaResourceAllocator
.getNumaNodesList();
Collection<NumaNodeResource> expectedNodesList = getExpectedNumaNodesList();
Assert.assertEquals(expectedNodesList, nodesList);
} |
@Override
public void createPort(Port osPort) {
checkNotNull(osPort, ERR_NULL_PORT);
checkArgument(!Strings.isNullOrEmpty(osPort.getId()), ERR_NULL_PORT_ID);
checkArgument(!Strings.isNullOrEmpty(osPort.getNetworkId()), ERR_NULL_PORT_NET_ID);
osNetworkStore.createPort(osPort);
... | @Test(expected = IllegalArgumentException.class)
public void createDuplicatePort() {
target.createPort(PORT);
target.createPort(PORT);
} |
public static Future<?> runClosureInThread(String groupId, final Closure done, final Status status) {
if (done == null) {
return null;
}
return runInThread(groupId, () -> {
try {
done.run(status);
} catch (final Throwable t) {
L... | @Test
public void testRunClosure() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
ThreadPoolsFactory.runClosureInThread(GROUP_ID_001, status -> {
assertTrue(status.isOk());
latch.countDown();
});
latch.await();
} |
@Nonnull
@Override
public Result addChunk(ByteBuf buf, @Nullable SocketAddress remoteAddress) {
if (!buf.isReadable(2)) {
return new Result(null, false);
}
try {
final IpfixParser.MessageDescription messageDescription = shallowParser.shallowParseMessage(buf);
... | @Test
public void dataAndDataTemplate() throws IOException, URISyntaxException {
final IpfixAggregator ipfixAggregator = new IpfixAggregator();
final Map<String, Object> configMap = getIxiaConfigmap();
final Configuration configuration = new Configuration(configMap);
final IpfixCod... |
public EvaluationResult evaluate(Condition condition, Measure measure) {
checkArgument(SUPPORTED_METRIC_TYPE.contains(condition.getMetric().getType()), "Conditions on MetricType %s are not supported", condition.getMetric().getType());
Comparable measureComparable = parseMeasure(measure);
if (measureCompara... | @Test
public void testGreater() {
Metric metric = createMetric(FLOAT);
Measure measure = newMeasureBuilder().create(10.2d, 1, null);
assertThat(underTest.evaluate(createCondition(metric, GREATER_THAN, "10.1"), measure)).hasLevel(ERROR).hasValue(10.2d);
assertThat(underTest.evaluate(createCondition(me... |
ControllerResult<Map<String, ApiError>> updateFeatures(
Map<String, Short> updates,
Map<String, FeatureUpdate.UpgradeType> upgradeTypes,
boolean validateOnly
) {
TreeMap<String, ApiError> results = new TreeMap<>();
List<ApiMessageAndVersion> records =
BoundedL... | @Test
public void testCannotDowngradeToVersionBeforeMinimumSupportedKraftVersion() {
FeatureControlManager manager = TEST_MANAGER_BUILDER1.build();
assertEquals(ControllerResult.of(Collections.emptyList(),
singletonMap(MetadataVersion.FEATURE_NAME, new ApiError(Errors.INVALID_UPDATE_VERS... |
@VisibleForTesting
public static JobGraph createJobGraph(StreamGraph streamGraph) {
return new StreamingJobGraphGenerator(
Thread.currentThread().getContextClassLoader(),
streamGraph,
null,
Runnable::run)
... | @Test
void testResourcesForIteration() throws Exception {
ResourceSpec resource1 = ResourceSpec.newBuilder(0.1, 100).build();
ResourceSpec resource2 = ResourceSpec.newBuilder(0.2, 200).build();
ResourceSpec resource3 = ResourceSpec.newBuilder(0.3, 300).build();
ResourceSpec resource4... |
public static List<AclEntry> filterAclEntriesByAclSpec(
List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
EnumMap<AclEntryScope, AclEntry>... | @Test
public void testFilterAclEntriesByAclSpecAccessMaskPreserved()
throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, USER, "bruce", READ))
.add(aclEntry(ACCESS, USER, "diana", READ_WRITE))
.... |
public static OffsetBasedPagination forStartRowNumber(int startRowNumber, int pageSize) {
checkArgument(startRowNumber >= 1, "startRowNumber must be >= 1");
checkArgument(pageSize >= 1, "page size must be >= 1");
return new OffsetBasedPagination(startRowNumber - 1, pageSize);
} | @Test
void hashcode_whenSameObjects_shouldBeEquals() {
OffsetBasedPagination offsetBasedPagination = OffsetBasedPagination.forStartRowNumber(15, 20);
Assertions.assertThat(offsetBasedPagination).hasSameHashCodeAs(offsetBasedPagination);
} |
@Nonnull
public <K, V> KafkaProducer<K, V> getProducer(@Nullable String transactionalId) {
if (getConfig().isShared()) {
if (transactionalId != null) {
throw new IllegalArgumentException("Cannot use transactions with shared "
+ "KafkaProducer for DataConne... | @Test
public void shared_producer_is_allowed_to_be_created_with_empty_props() {
kafkaDataConnection = createKafkaDataConnection(kafkaTestSupport);
Producer<Object, Object> kafkaProducer = kafkaDataConnection.getProducer(null, new Properties());
assertThat(kafkaProducer).isNotNull();
... |
@Override
public JsonArray deepCopy() {
if (!elements.isEmpty()) {
JsonArray result = new JsonArray(elements.size());
for (JsonElement element : elements) {
result.add(element.deepCopy());
}
return result;
}
return new JsonArray();
} | @Test
public void testDeepCopy() {
JsonArray original = new JsonArray();
JsonArray firstEntry = new JsonArray();
original.add(firstEntry);
JsonArray copy = original.deepCopy();
original.add(new JsonPrimitive("y"));
assertThat(copy).hasSize(1);
firstEntry.add(new JsonPrimitive("z"));
... |
@Override
public StateInstance getStateInstance(String stateInstanceId, String machineInstId) {
StateInstance stateInstance = selectOne(
stateLogStoreSqls.getGetStateInstanceByIdAndMachineInstanceIdSql(dbType), RESULT_SET_TO_STATE_INSTANCE,
machineInstId, stateInstanceId);
... | @Test
public void testGetStateInstance() {
Assertions.assertDoesNotThrow(() -> dbAndReportTcStateLogStore.getStateInstance("test", "test"));
} |
protected int calcAllArgConstructorParameterUnits(Schema record) {
if (record.getType() != Schema.Type.RECORD)
throw new RuntimeException("This method must only be called for record schemas.");
return record.getFields().size();
} | @Test
void calcAllArgConstructorParameterUnitsFailure() {
assertThrows(RuntimeException.class, () -> {
Schema nonRecordSchema = SchemaBuilder.array().items().booleanType();
new SpecificCompiler().calcAllArgConstructorParameterUnits(nonRecordSchema);
});
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("s3.listing.chunksize"));
} | @Test
public void testListFileDot() throws Exception {
final Path container = new SpectraDirectoryFeature(session, new SpectraWriteFeature(session)).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus());
... |
@Override
public Num calculate(BarSeries series, Position position) {
return varianceCriterion.calculate(series, position).sqrt();
} | @Test
public void calculateStandardDeviationPnL() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series, series.one()),
Trade.sellAt(2, series, series.one()), Trade.buyAt(3, seri... |
Mono<Void> dispatchNotification(Reason reason, Subscriber subscriber) {
return getNotifiersBySubscriber(subscriber, reason)
.flatMap(notifierName -> client.fetch(NotifierDescriptor.class, notifierName))
.flatMap(descriptor -> prepareNotificationElement(subscriber, reason, descriptor))
... | @Test
public void testDispatchNotification() {
var spyNotificationCenter = spy(notificationCenter);
doReturn(Flux.just("email-notifier"))
.when(spyNotificationCenter).getNotifiersBySubscriber(any(), any());
NotifierDescriptor notifierDescriptor = mock(NotifierDescriptor.class);... |
@DELETE
@Timed
@ApiOperation(value = "Delete all revisions of a content pack")
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Missing or invalid content pack"),
@ApiResponse(code = 500, message = "Error while saving content pack")
})
@AuditEvent(type = AuditEvent... | @Test
public void deleteContentPack() throws Exception {
final ModelId id = ModelId.of("1");
when(contentPackPersistenceService.deleteById(id)).thenReturn(1);
contentPackResource.deleteContentPack(id);
verify(contentPackPersistenceService, times(1)).deleteById(id);
when(cont... |
@Override
public boolean containsSlots(ResourceID owner) {
return slotsPerTaskExecutor.containsKey(owner);
} | @Test
void testContainsSlots() {
final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool();
final ResourceID owner = ResourceID.generate();
final AllocatedSlot allocatedSlot = createAllocatedSlot(owner);
slotPool.addSlots(Collections.singleton(allocatedSlot), 0);
... |
@Override
protected boolean isInfinite(Short number) {
// Infinity never applies here because only types like Float and Double have Infinity
return false;
} | @Test
void testIsInfinite() {
ShortSummaryAggregator ag = new ShortSummaryAggregator();
// always false for Short
assertThat(ag.isInfinite((short) -1)).isFalse();
assertThat(ag.isInfinite((short) 0)).isFalse();
assertThat(ag.isInfinite((short) 23)).isFalse();
assertTh... |
@Override
protected boolean redirectMatches(String requestedRedirect, String redirectUri) {
if (isStrictMatch()) {
// we're doing a strict string match for all clients
return Strings.nullToEmpty(requestedRedirect).equals(redirectUri);
} else {
// otherwise do the prefix-match from the library
return s... | @Test
public void testRedirectMatches_default() {
// this is not an exact match
boolean res1 = resolver.redirectMatches(pathUri, goodUri);
assertThat(res1, is(false));
// this is an exact match
boolean res2 = resolver.redirectMatches(goodUri, goodUri);
assertThat(res2, is(true));
} |
@ApiOperation(value = "Save user settings (saveUserSettings)",
notes = "Save user settings represented in json format for authorized user. ")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/user/settings")
public JsonNode saveUserSettings(@Re... | @Test
public void testSaveUserSettings() throws Exception {
loginCustomerUser();
JsonNode userSettings = JacksonUtil.toJsonNode("{\"A\":5, \"B\":10, \"E\":18}");
JsonNode savedSettings = doPost("/api/user/settings", userSettings, JsonNode.class);
Assert.assertEquals(userSettings, sa... |
@Override
public CompletableFuture<Acknowledge> requestSlot(
final SlotID slotId,
final JobID jobId,
final AllocationID allocationId,
final ResourceProfile resourceProfile,
final String targetAddress,
final ResourceManagerId resourceManagerId,
... | @Test
void testSlotOfferCounterIsSeparatedByJob() throws Exception {
final OneShotLatch taskExecutorIsRegistered = new OneShotLatch();
final TestingResourceManagerGateway resourceManagerGateway =
createRmWithTmRegisterAndNotifySlotHooks(
new InstanceID(), task... |
@Override
public StorageObject upload(final Path file, final Local local, final BandwidthThrottle throttle,
final StreamListener listener, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final S3Protocol.AuthenticationHeaderSignatu... | @Test(expected = NotfoundException.class)
public void testUploadInvalidContainer() throws Exception {
final S3SingleUploadService m = new S3SingleUploadService(session, new S3WriteFeature(session, new S3AccessControlListFeature(session)));
final Path container = new Path("nosuchcontainer.cyberduck.c... |
public static <K, InputT> GroupIntoBatches<K, InputT> ofByteSize(long batchSizeBytes) {
return new GroupIntoBatches<K, InputT>(BatchingParams.createDefault())
.withByteSize(batchSizeBytes);
} | @Test
@Category({
ValidatesRunner.class,
NeedsRunner.class,
UsesTestStream.class,
UsesTimersInParDo.class,
UsesStatefulParDo.class,
UsesOnWindowExpiration.class
})
public void testInGlobalWindowBatchSizeByteSizeFn() {
SerializableFunction<String, Long> getElementByteSizeFn =
s ... |
public void calculate(IThrowableProxy tp) {
while (tp != null) {
populateFrames(tp.getStackTraceElementProxyArray());
IThrowableProxy[] suppressed = tp.getSuppressed();
if (suppressed != null) {
for (IThrowableProxy current : suppressed) {
... | @Test
// Test http://jira.qos.ch/browse/LBCLASSIC-125
public void noClassDefFoundError_LBCLASSIC_125Test() throws MalformedURLException {
ClassLoader cl = (URLClassLoader) makeBogusClassLoader();
Thread.currentThread().setContextClassLoader(cl);
Throwable t = new Throwable("x");
... |
@SuppressWarnings("unchecked")
static Object extractFromRecordValue(Object recordValue, String fieldName) {
List<String> fields = Splitter.on('.').splitToList(fieldName);
if (recordValue instanceof Struct) {
return valueFromStruct((Struct) recordValue, fields);
} else if (recordValue instanceof Map)... | @Test
public void testExtractFromRecordValueMap() {
Map<String, Object> val = ImmutableMap.of("key", 123L);
Object result = RecordUtils.extractFromRecordValue(val, "key");
assertThat(result).isEqualTo(123L);
} |
public static <NodeT> Iterable<NodeT> topologicalOrder(Network<NodeT, ?> network) {
return computeTopologicalOrder(Graphs.copyOf(network));
} | @Test
public void testTopologicalSortWithSuborder() {
// This cast is required to narrow the type accepted by the comparator
Comparator<String> subOrder = (Comparator<String>) (Comparator) Ordering.arbitrary();
MutableNetwork<String, String> network = createNetwork();
Iterable<String> sortedNodes = N... |
public List<String> getAllExtensions() {
final List<String> extensions = new LinkedList<>();
extensions.add(defaultExtension);
extensions.addAll(Arrays.asList(otherExtensions));
return Collections.unmodifiableList(extensions);
} | @Test
public void testGetAllExtensions() throws Exception {
final ResourceType BPMN2 = ResourceType.BPMN2;
final List<String> extensionsBPMN2 = BPMN2.getAllExtensions();
assertThat(extensionsBPMN2.size()).isEqualTo(3);
assertThat(extensionsBPMN2.contains("bpmn")).isTrue();
a... |
protected void build(C instance) {
if (!StringUtils.isEmpty(id)) {
instance.setId(id);
}
} | @Test
void build() {
Builder builder = new Builder();
builder.id("id");
Config config = builder.build();
Config config2 = builder.build();
Assertions.assertEquals("id", config.getId());
Assertions.assertNotSame(config, config2);
} |
@Override
public T getHollowObject(int ordinal) {
List<T> refCachedItems = cachedItems;
if (refCachedItems == null) {
throw new IllegalStateException(String.format("HollowObjectCacheProvider for type %s has been detached or was not initialized", typeReadState == null ? null : typeReadSta... | @Test
public void preExisting() {
TypeA a0 = typeA(0);
TypeA a1 = typeA(1);
TypeA a2 = typeA(2);
prepopulate(a0, a1, a2);
assertEquals(a0, subject.get().getHollowObject(a0.ordinal));
assertEquals(a1, subject.get().getHollowObject(a1.ordinal));
assertEquals(... |
@Override
public Result analysis(
final Result result,
final StreamAccessLogsMessage.Identifier identifier,
final HTTPAccessLogEntry entry,
final Role role
) {
switch (role) {
case PROXY:
return analyzeProxy(result, entry);
case SID... | @Test
public void testSidecar2SidecarServerMetric() throws IOException {
try (InputStreamReader isr = new InputStreamReader(getResourceAsStream("envoy-mesh-server-sidecar.msg"))) {
StreamAccessLogsMessage.Builder requestBuilder = StreamAccessLogsMessage.newBuilder();
JsonFormat.parse... |
@Override
public double quantile(double p) {
if (p < 0.0 || p > 1.0) {
throw new IllegalArgumentException("Invalid p: " + p);
}
if (p == 0.0) {
return Math.max(0, m+n-N);
}
if (p == 1.0) {
return Math.min(m,n);
}
// Start... | @Test
public void testQuantile() {
System.out.println("quantile");
HyperGeometricDistribution instance = new HyperGeometricDistribution(100, 30, 70);
instance.rand();
assertEquals(0, instance.quantile(0), 1E-30);
assertEquals(14, instance.quantile(0.001), 1E-27);
asse... |
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
if (knownConsumerGroups == null) {
// If knownConsumerGroup is null, it means the initial loading has not finished.
// An exception should be thrown to trigger the retry behavior in the framework.
log.... | @Test
public void testMirrorCheckpointConnectorDisabled() {
// disable the checkpoint emission
MirrorCheckpointConfig config = new MirrorCheckpointConfig(
makeProps("emit.checkpoints.enabled", "false"));
Set<String> knownConsumerGroups = new HashSet<>();
knownConsumerGro... |
public EurekaDataSource(String appId, String instanceId, List<String> serviceUrls, String ruleKey,
Converter<String, T> configParser) {
this(appId, instanceId, serviceUrls, ruleKey, configParser, DEFAULT_REFRESH_MS, DEFAULT_CONNECT_TIMEOUT_MS,
DEFAULT_READ_TIMEOUT_MS);
... | @Test
public void testEurekaDataSource() throws Exception {
String url = "http://localhost:" + port + "/eureka";
EurekaDataSource<List<FlowRule>> eurekaDataSource = new EurekaDataSource(appname, instanceId, Arrays.asList(url)
, SENTINEL_KEY, new Converter<String, List<FlowRule>>() {... |
@Override
public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc,
boolean addFieldName, boolean addCr ) {
return fallback.getFieldDefinition( v, tk, pk, useAutoinc, addFieldName, addCr );
} | @Test
public void testStringFieldDef() throws Exception {
DatabricksDatabaseMeta dbricks = new DatabricksDatabaseMeta();
String fieldDef = dbricks.getFieldDefinition( new ValueMetaString( "name" ), null, null, false, false, false );
assertEquals( "VARCHAR()", fieldDef );
} |
@Override
public void doRegister(ServiceInstance serviceInstance) {
execute(namingService, service -> {
Instance instance = toInstance(serviceInstance);
service.registerInstance(instance.getServiceName(), group, instance);
});
} | @Test
void testDoRegister() throws NacosException {
DefaultServiceInstance serviceInstance =
createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort());
// register
nacosServiceDiscovery.doRegister(serviceInstance);
ArgumentCaptor<Instance> instanceC... |
static void filterProperties(Message message, Set<String> namesToClear) {
List<Object> retainedProperties = messagePropertiesBuffer();
try {
filterProperties(message, namesToClear, retainedProperties);
} finally {
retainedProperties.clear(); // ensure no object references are held due to any exc... | @Test void filterProperties_message_passesFatalOnSetException() throws JMSException {
Message message = mock(Message.class);
when(message.getPropertyNames()).thenReturn(
Collections.enumeration(Collections.singletonList("JMS_SQS_DeduplicationId")));
when(message.getObjectProperty("JMS_SQS_Deduplicatio... |
@Override
protected Map<String, String> getHealthInformation() {
if (!configuration.getBackgroundJobServer().isEnabled()) {
healthStatus = HealthStatus.UP;
return mapOf("backgroundJobServer", "disabled");
} else {
if (backgroundJobServer.isRunning()) {
... | @Test
void givenEnabledBackgroundJobServerAndBackgroundJobServerRunning_ThenHealthIsUp() {
when(backgroundJobServerConfiguration.isEnabled()).thenReturn(true);
when(backgroundJobServer.isRunning()).thenReturn(true);
jobRunrHealthIndicator.getHealthInformation();
assertThat(jobRunrH... |
@Override
public void triggerJob(Long id) throws SchedulerException {
// 校验存在
JobDO job = validateJobExists(id);
// 触发 Quartz 中的 Job
schedulerManager.triggerJob(job.getId(), job.getHandlerName(), job.getHandlerParam());
} | @Test
public void testTriggerJob_success() throws SchedulerException {
// mock 数据
JobDO job = randomPojo(JobDO.class);
jobMapper.insert(job);
// 调用
jobService.triggerJob(job.getId());
// 校验调用
verify(schedulerManager).triggerJob(eq(job.getId()),
... |
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) {
checkArgument(
OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp);
return new AutoValue_UBinary(binaryOp, lhs, rhs);
} | @Test
public void plus() {
assertUnifiesAndInlines(
"4 + 17", UBinary.create(Kind.PLUS, ULiteral.intLit(4), ULiteral.intLit(17)));
} |
@Override
public void start() {
List<FrameworkFactory> frameworkFactories = IteratorUtils.toList(ServiceLoader.load(FrameworkFactory.class).iterator());
if (frameworkFactories.size() != 1) {
throw new RuntimeException("One OSGi framework expected. Got " + frameworkFactories.size() + ": ... | @Test
void shouldRegisterAnInstanceOfEachOfTheRequiredPluginServicesAfterOSGiFrameworkIsInitialized() {
spy.start();
verify(bundleContext).registerService(eq(PluginRegistryService.class), any(DefaultPluginRegistryService.class), isNull());
verify(bundleContext).registerService(eq(LoggingSer... |
@ShellMethod(key = "compactions show all", value = "Shows all compactions that are in active timeline")
public String compactionsAll(
@ShellOption(value = {"--includeExtraMetadata"}, help = "Include extra metadata",
defaultValue = "false") final boolean includeExtraMetadata,
@ShellOption(value =... | @Test
public void testVerifyTableType() throws IOException {
// create COW table.
new TableCommand().createTable(
tablePath, tableName, HoodieTableType.COPY_ON_WRITE.name(),
"", TimelineLayoutVersion.VERSION_1, HoodieAvroPayload.class.getName());
// expect HoodieException for COPY_ON_WRIT... |
@Override
public CompletableFuture<ClusterInfo> getBrokerClusterInfo(String address, long timeoutMillis) {
CompletableFuture<ClusterInfo> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_CLUSTER_INFO, null);
remotingCli... | @Test
public void assertGetBrokerClusterInfoWithError() {
setResponseError();
CompletableFuture<ClusterInfo> actual = mqClientAdminImpl.getBrokerClusterInfo(defaultBrokerAddr, defaultTimeout);
Throwable thrown = assertThrows(ExecutionException.class, actual::get);
assertTrue(thrown.g... |
public static String substringAfter(String s, String splitter) {
final int indexOf = s.indexOf(splitter);
return indexOf >= 0 ? s.substring(indexOf + splitter.length()) : null;
} | @Test
void testSubstringAfterSplitterMultiChar() {
assertThat(substringAfter("this is a test", " is ")).isEqualTo("a test");
assertThat(substringAfter("this is a test", " was ")).isNull();
} |
@Override
public CloseableIterator<ScannerReport.LineCoverage> readComponentCoverage(int fileRef) {
ensureInitialized();
return delegate.readComponentCoverage(fileRef);
} | @Test
public void readComponentCoverage_returns_empty_CloseableIterator_when_file_does_not_exist() {
assertThat(underTest.readComponentCoverage(COMPONENT_REF)).isExhausted();
} |
public void run() {
try {
if ( job.isStopped() || ( job.getParentJob() != null && job.getParentJob().isStopped() ) ) {
return;
}
// This JobEntryRunner is a replacement for the Job thread.
// The job thread is never started because we simply want to wait for the result.
//
... | @Test
public void testRun() throws Exception {
// Call all the NO-OP paths
when( mockJob.isStopped() ).thenReturn( true );
jobRunner.run();
when( mockJob.isStopped() ).thenReturn( false );
when( mockJob.getParentJob() ).thenReturn( null );
when( mockJob.getJobMeta() ).thenReturn( mockJobMeta )... |
public static Timestamp toTimestamp(BigDecimal bigDecimal) {
final BigDecimal nanos = bigDecimal.remainder(BigDecimal.ONE.scaleByPowerOfTen(9));
final BigDecimal seconds = bigDecimal.subtract(nanos).scaleByPowerOfTen(-9).add(MIN_SECONDS);
return Timestamp.ofTimeSecondsAndNanos(seconds.longValue(), nanos.in... | @Test
public void testToTimestampConvertNanosToTimestamp() {
assertEquals(
Timestamp.ofTimeSecondsAndNanos(10L, 9),
TimestampUtils.toTimestamp(new BigDecimal("62135596810000000009")));
} |
@Override
public PathAttributes toAttributes(final StorageObject object) {
final PathAttributes attributes = new PathAttributes();
attributes.setSize(object.getContentLength());
final Date lastmodified = object.getLastModifiedDate();
if(lastmodified != null) {
attributes.... | @Test
public void testMtime() {
final StorageObject object = new StorageObject();
object.addMetadata("ETag", "a43c1b0aa53a0c908810c06ab1ff3967");
object.addMetadata("Mtime", "1647683127.160620746");
assertEquals(1647683127000L, new S3AttributesAdapter(new Host(new S3Protocol())).toAt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.