focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void transform(Message message, DataType fromType, DataType toType) {
AvroSchema schema = message.getExchange().getProperty(SchemaHelper.CONTENT_SCHEMA, AvroSchema.class);
if (schema == null) {
throw new CamelExecutionException("Missing proper avro schema for data type ... | @Test
void shouldHandleExplicitContentClass() throws Exception {
Exchange exchange = new DefaultExchange(camelContext);
AvroSchema avroSchema = getSchema();
exchange.setProperty(SchemaHelper.CONTENT_SCHEMA, avroSchema);
exchange.setProperty(SchemaHelper.CONTENT_CLASS, Person.class.g... |
public boolean removeNode(String key, String group) {
return zkClient.removeConfig(key, group);
} | @Test
public void testRemoveNode() {
int index = CHILD_ONE_PATH.lastIndexOf("/");
String parentPath = CHILD_ONE_PATH.substring(0, index);
String key = CHILD_ONE_PATH.substring(index + 1);
boolean deleteChileOne = zooKeeperBufferedClient.removeNode(key, parentPath);
Assert.ass... |
@VisibleForTesting
static Estimate calculateDataSize(String column, Collection<PartitionStatistics> partitionStatistics, double totalRowCount)
{
List<PartitionStatistics> statisticsWithKnownRowCountAndDataSize = partitionStatistics.stream()
.filter(statistics -> {
if ... | @Test
public void testCalculateDataSize()
{
assertEquals(calculateDataSize(COLUMN, ImmutableList.of(), 0), Estimate.unknown());
assertEquals(calculateDataSize(COLUMN, ImmutableList.of(), 1000), Estimate.unknown());
assertEquals(calculateDataSize(COLUMN, ImmutableList.of(PartitionStatisti... |
@Override
public void doRegister(URL url) {
try {
checkDestroyed();
zkClient.create(toUrlPath(url), url.getParameter(DYNAMIC_KEY, true), true);
} catch (Throwable e) {
throw new RpcException(
"Failed to register " + url + " to zookeeper " + get... | @Test
void testDoRegisterWithException() {
Assertions.assertThrows(RpcException.class, () -> {
URL errorUrl = URL.valueOf("multicast://0.0.0.0/");
zookeeperRegistry.doRegister(errorUrl);
});
} |
public static void ensureCorrectArgs(
final FunctionName functionName, final Object[] args, final Class<?>... argTypes
) {
if (args == null) {
throw new KsqlFunctionException("Null argument list for " + functionName.text() + ".");
}
if (args.length != argTypes.length) {
throw new KsqlFu... | @Test(expected = KsqlException.class)
public void shouldFailIfArgCountIsTooMany() {
final Object[] args = new Object[]{"TtestArg1", 10L};
UdfUtil.ensureCorrectArgs(FUNCTION_NAME, args, String.class);
} |
public static String clientTagPrefix(final String clientTagKey) {
return CLIENT_TAG_PREFIX + clientTagKey;
} | @Test
public void shouldThrowExceptionWhenClientTagKeyExceedMaxLimit() {
final String key = String.join("", nCopies(MAX_RACK_AWARE_ASSIGNMENT_TAG_KEY_LENGTH + 1, "k"));
props.put(StreamsConfig.clientTagPrefix(key), "eu-central-1a");
final ConfigException exception = assertThrows(ConfigExcept... |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyWithOnlyNullPassedAsNullArray() {
// Truth is tolerant of this erroneous varargs call.
Iterable<Object> actual = asList((Object) null);
assertThat(actual).containsExactly((Object[]) null);
} |
public static Object getMessageAnnotation(String key, Message message) {
if (message != null && message.getMessageAnnotations() != null) {
Map<Symbol, Object> annotations = message.getMessageAnnotations().getValue();
return annotations.get(AmqpMessageSupport.getSymbol(key));
}
... | @Test
public void testGetMessageAnnotationWhenMessageHasEmptyAnnotationsMap() {
Map<Symbol, Object> messageAnnotationsMap = new HashMap<Symbol,Object>();
Message message = Proton.message();
message.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap));
assertNull(Amqp... |
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, String issuerCommonName,
String subjectCommonName, String domain,
String signAlgoritm)
... | @Test
public void testGenerateCertificateIssuer() throws Exception
{
// Setup fixture.
final KeyPair keyPair = subjectKeyPair;
final int days = 2;
final String issuerCommonName = "issuer common name";
final String subjectCommonName = "subject common name";
final S... |
@SqlInvokedScalarFunction(value = "array_average", deterministic = true, calledOnNullInput = false)
@Description("Returns the average of all array elements, or null if the array is empty. Ignores null elements.")
@SqlParameter(name = "input", type = "array<double>")
@SqlType("double")
public static Stri... | @Test
public void testArrayAverage()
{
assertFunctionWithError("array_average(array[1, 2])", DOUBLE, 1.5);
assertFunctionWithError("array_average(array[1, bigint '2', smallint '3', tinyint '4', 5.0])", DOUBLE, 3.0);
assertFunctionWithError("array_average(array[1, null, 2, null])", DOUBL... |
@Override
public Object evaluate(final ProcessingDTO processingDTO) {
Number input = (Number) getFromPossibleSources(name, processingDTO)
.orElse(null);
if (input == null) {
return mapMissingTo;
}
return getFromDiscretizeBins(input).orElse(defaultValue);
... | @Test
void evaluateDefaultValue() {
KiePMMLDiscretize kiePMMLDiscretize = getKiePMMLDiscretize(null, null);
ProcessingDTO processingDTO = getProcessingDTO(List.of(new KiePMMLNameValue(NAME, 20)));
Object retrieved = kiePMMLDiscretize.evaluate(processingDTO);
assertThat(retrieved).is... |
public static void onGeTuiNotificationClicked(Object gtNotificationMessage) {
if (gtNotificationMessage == null) {
SALog.i(TAG, "gtNotificationMessage is null");
return;
}
if (!isTrackPushEnabled()) return;
try {
String msgId = ReflectUtil.callMethod(g... | @Test
public void onGeTuiNotificationClicked() {
PushAutoTrackHelper.onGeTuiNotificationClicked(new GetTuiData());
} |
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testLeavingMemberBumpsGroupEpoch() {
String groupId = "fooup";
// Use a static member id as it makes the test easier.
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
Uuid fooTopicId = Uuid.randomUuid();
... |
public static String buildFormPostContent(final WebContext context) {
val requestedUrl = context.getFullRequestURL();
val parameters = context.getRequestParameters();
val buffer = new StringBuilder();
buffer.append("<html>\n");
buffer.append("<body>\n");
buffer.append("<f... | @Test
public void testBuildFormPostContentWithData() {
val content = HttpActionHelper
.buildFormPostContent(MockWebContext.create().setFullRequestURL(CALLBACK_URL).addRequestParameter(NAME, VALUE));
assertEquals("<html>\n<body>\n<form action=\"" + CALLBACK_URL + "\" name=\"f\" method=\"p... |
public static ScanReport fromJson(String json) {
return JsonUtil.parse(json, ScanReportParser::fromJson);
} | @Test
public void invalidTableName() {
assertThatThrownBy(() -> ScanReportParser.fromJson("{\"table-name\":23}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse to a string value: table-name: 23");
} |
@Override
public void processElement(StreamRecord<MergeOnReadInputSplit> element) {
splits.add(element.getValue());
enqueueProcessSplits();
} | @Test
void testWriteRecords() throws Exception {
TestData.writeData(TestData.DATA_SET_INSERT, conf);
try (OneInputStreamOperatorTestHarness<MergeOnReadInputSplit, RowData> harness = createReader()) {
harness.setup();
harness.open();
SteppingMailboxProcessor processor = createLocalMailbox(ha... |
public boolean isExist(final String key) {
try {
return null != client.checkExists().forPath(key);
} catch (Exception e) {
throw new ShenyuException(e);
}
} | @Test
void isExist() throws Exception {
assertThrows(ShenyuException.class, () -> client.isExist("/test"));
ExistsBuilderImpl existsBuilder = mock(ExistsBuilderImpl.class);
when(curatorFramework.checkExists()).thenReturn(existsBuilder);
when(existsBuilder.forPath(anyString())).thenRe... |
public static MessageExtBrokerInner buildTransactionalMessageFromHalfMessage(MessageExt msgExt) {
final MessageExtBrokerInner msgInner = new MessageExtBrokerInner();
msgInner.setWaitStoreMsgOK(false);
msgInner.setMsgId(msgExt.getMsgId());
msgInner.setTopic(msgExt.getProperty(MessageConst... | @Test
public void testBuildTransactionalMessageFromHalfMessage() {
MessageExt halfMessage = new MessageExt();
halfMessage.setTopic(TransactionalMessageUtil.buildHalfTopic());
MessageAccessor.putProperty(halfMessage, MessageConst.PROPERTY_REAL_TOPIC, "real-topic");
halfMessage.setMsgI... |
Record convert(Object data) {
return convert(data, null);
} | @Test
public void testMapConvert() {
Table table = mock(Table.class);
when(table.schema()).thenReturn(SCHEMA);
RecordConverter converter = new RecordConverter(table, config);
Map<String, Object> data = createMapData();
Record record = converter.convert(data);
assertRecordValues(record);
} |
@Override
public void monitor(RedisServer master) {
connection.sync(RedisCommands.SENTINEL_MONITOR, master.getName(), master.getHost(),
master.getPort().intValue(), master.getQuorum().intValue());
} | @Test
public void testMonitor() {
Collection<RedisServer> masters = connection.masters();
RedisServer master = masters.iterator().next();
master.setName(master.getName() + ":");
connection.monitor(master);
} |
public static Map<String, String> getProps(String properties) {
Map<String, String> configs = new HashMap<>();
if (StringUtils.isNotEmpty(properties)) {
for (String property : properties.split(";")) {
if (StringUtils.isNotEmpty(property)) {
int delimiterPo... | @Test
void givenKafkaTopicProperties_whenGetConfig_thenReturnMappedValues() {
assertThat(PropertyUtils.getProps("retention.ms:604800000;segment.bytes:52428800;retention.bytes:1048576000;partitions:1;min.insync.replicas:1"))
.isEqualTo(Map.of(
"retention.ms", "60480000... |
static void readFullyDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException {
int nextReadLength = Math.min(buf.remaining(), temp.length);
int bytesRead = 0;
while (nextReadLength > 0 && (bytesRead = f.read(temp, 0, nextReadLength)) >= 0) {
buf.put(temp, 0, bytesRead);
next... | @Test
public void testDirectReadFullyJustRight() throws Exception {
final ByteBuffer readBuffer = ByteBuffer.allocateDirect(10);
MockInputStream stream = new MockInputStream();
// reads all of the bytes available without EOFException
DelegatingSeekableInputStream.readFullyDirectBuffer(stream, readBu... |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
@SuppressWarnings("unchecked")
public void testDecodeStaticStructStaticArray() {
String rawInput =
"0x0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000000"
... |
@Override
public HttpRestResult<String> httpDelete(String path, Map<String, String> headers, Map<String, String> paramValues,
String encode, long readTimeoutMs) throws Exception {
final long endTime = System.currentTimeMillis() + readTimeoutMs;
String currentServerAddr = serverListMgr.ge... | @Test
void testHttpDeleteFailed() throws Exception {
assertThrows(ConnectException.class, () -> {
when(nacosRestTemplate.<String>delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult);... |
@Override
public Processor<K, Change<V>, KO, SubscriptionWrapper<K>> get() {
return new UnbindChangeProcessor();
} | @Test
public void leftJoinShouldPropagateChangeOfFKFromNonNullToNonNullValue() {
final MockInternalNewProcessorContext<String, SubscriptionWrapper<String>> context = new MockInternalNewProcessorContext<>();
leftJoinProcessor.init(context);
context.setRecordMetadata("topic", 0, 0);
f... |
@Deprecated
public String getJSON() {
return getJSON(Long.MAX_VALUE);
} | @Test
public void testGetJSONFromZLIBCompressedMessage() throws Exception {
for (int level = -1; level <= 9; level++) {
final GELFMessage msg = new GELFMessage(TestHelper.zlibCompress(GELF_JSON, level));
assertEquals(GELF_JSON, msg.getJSON(1024));
}
} |
public RingbufferStoreConfig setFactoryImplementation(@Nonnull RingbufferStoreFactory factoryImplementation) {
this.factoryImplementation = checkNotNull(factoryImplementation, "Ringbuffer store factory cannot be null");
this.factoryClassName = null;
return this;
} | @Test
public void setFactoryImplementation() {
RingbufferStoreFactory factory = new RingbufferStoreFactory() {
@Override
public RingbufferStore newRingbufferStore(String name, Properties properties) {
return null;
}
};
config.setFactoryImp... |
public void incrCounter(Enum<?> key, long amount) {
findCounter(key).increment(amount);
} | @SuppressWarnings("deprecation")
@Test
public void testCounterIteratorConcurrency() {
Counters counters = new Counters();
counters.incrCounter("group1", "counter1", 1);
Iterator<Group> iterator = counters.iterator();
counters.incrCounter("group2", "counter2", 1);
iterator.next();
} |
public CompletableFuture<QueryAssignmentResponse> queryAssignment(ProxyContext ctx,
QueryAssignmentRequest request) {
CompletableFuture<QueryAssignmentResponse> future = new CompletableFuture<>();
try {
validateTopicAndConsumerGroup(request.getTopic(), request.getGroup());
... | @Test
public void testQueryAssignmentWithNoReadPerm() throws Throwable {
when(this.messagingProcessor.getTopicRouteDataForProxy(any(), any(), anyString()))
.thenReturn(createProxyTopicRouteData(2, 2, PermName.PERM_WRITE));
QueryAssignmentResponse response = this.routeActivity.queryAssig... |
@Override
public MutableNetwork<Node, Edge> apply(MapTask mapTask) {
List<ParallelInstruction> parallelInstructions = Apiary.listOrEmpty(mapTask.getInstructions());
MutableNetwork<Node, Edge> network =
NetworkBuilder.directed()
.allowsSelfLoops(false)
.allowsParallelEdges(true)... | @Test
public void testFlatten() {
// ReadA --\
// |--> Flatten
// ReadB --/
InstructionOutput readOutputA = createInstructionOutput("ReadA.out");
ParallelInstruction readA = createParallelInstruction("ReadA", readOutputA);
readA.setRead(new ReadInstruction());
InstructionOutput r... |
@Override
public Object apply(Object input) {
return PropertyOrFieldSupport.EXTRACTION.getValueOf(propertyOrFieldName, input);
} | @Test
void should_throw_exception_if_no_object_is_given() {
// GIVEN
ByNameSingleExtractor underTest = new ByNameSingleExtractor("id");
// WHEN
Throwable thrown = catchThrowable(() -> underTest.apply(null));
// THEN
then(thrown).isInstanceOf(IllegalArgumentException.class);
} |
@VisibleForTesting
static SwitchGenerationCase checkSwitchGenerationCase(Type type, List<RowExpression> values)
{
if (values.size() > 32) {
// 32 is chosen because
// * SET_CONTAINS performs worst when smaller than but close to power of 2
// * Benchmark shows performa... | @Test
public void testBigint()
{
FunctionAndTypeManager functionAndTypeManager = createTestMetadataManager().getFunctionAndTypeManager();
List<RowExpression> values = new ArrayList<>();
values.add(constant(Integer.MAX_VALUE + 1L, BIGINT));
values.add(constant(Integer.MIN_VALUE - ... |
@Override
public SparkTable loadTable(Identifier ident) throws NoSuchTableException {
Pair<Table, Long> table = load(ident);
return new SparkTable(table.first(), table.second(), false /* refresh eagerly */);
} | @TestTemplate
public void testTimeTravel() {
sql("CREATE TABLE %s (id INT, dep STRING) USING iceberg", tableName);
Table table = validationCatalog.loadTable(tableIdent);
sql("INSERT INTO TABLE %s VALUES (1, 'hr')", tableName);
table.refresh();
Snapshot firstSnapshot = table.currentSnapshot();
... |
protected void notify(List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
return;
}
for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) {
URL url = entry.getKey();
if (!UrlUtils.isMatch(url, urls.get(0))) {
continu... | @Test
void testNotify() {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
NotifyListener listener1 = urls -> notified.set(Boolean.TRUE);
URL url1 = new ServiceConfigURL("dubbo", "192.168.0.1", 2200, parametersConsumer);
abstractRegistry.subscribe(url1, ... |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowFunctionStatusStatement) {
return Optional.of(new ShowFunctionStatusExecutor((ShowFu... | @Test
void assertCreateWithShowTables() {
when(sqlStatementContext.getSqlStatement()).thenReturn(new MySQLShowTablesStatement());
Optional<DatabaseAdminExecutor> actual = new MySQLAdminExecutorCreator().create(sqlStatementContext);
assertTrue(actual.isPresent());
assertThat(actual.ge... |
static ByteBuffer epochEntriesAsByteBuffer(List<EpochEntry> epochEntries) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) {
CheckpointFile.CheckpointWrite... | @Test
public void testEpochEntriesAsByteBuffer() throws Exception {
int expectedEpoch = 0;
long expectedStartOffset = 1L;
int expectedVersion = 0;
List<EpochEntry> epochs = Arrays.asList(new EpochEntry(expectedEpoch, expectedStartOffset));
ByteBuffer buffer = RemoteLogManager... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DelegatingScheduledFutureStripper<?> that = (DelegatingScheduledFutureStripper<?>) o;
return original.e... | @Test
public void equals() {
ScheduledFuture<Future<Integer>> original = taskScheduler.schedule(new SimpleCallableTestTask(), 0, TimeUnit.SECONDS);
ScheduledFuture<Future<Integer>> joker = taskScheduler.schedule(new SimpleCallableTestTask(), 1, TimeUnit.SECONDS);
ScheduledFuture testA = new... |
public List<PartitionInfo> getTopicMetadata(String topic, boolean allowAutoTopicCreation, Timer timer) {
MetadataRequest.Builder request = new MetadataRequest.Builder(Collections.singletonList(topic), allowAutoTopicCreation);
Map<String, List<PartitionInfo>> topicMetadata = getTopicMetadata(request, tim... | @Test
public void testGetTopicMetadataUnknownTopic() {
buildFetcher();
assignFromUser(singleton(tp0));
client.prepareResponse(newMetadataResponse(Errors.UNKNOWN_TOPIC_OR_PARTITION));
List<PartitionInfo> topicMetadata = topicMetadataFetcher.getTopicMetadata(topicName, true, time.time... |
@Override
public void reconcileExecutionDeployments(
ResourceID taskExecutorHost,
ExecutionDeploymentReport executionDeploymentReport,
Map<ExecutionAttemptID, ExecutionDeploymentState> expectedDeployedExecutions) {
final Set<ExecutionAttemptID> unknownExecutions =
... | @Test
void testMissingDeployments() {
TestingExecutionDeploymentReconciliationHandler handler =
new TestingExecutionDeploymentReconciliationHandler();
DefaultExecutionDeploymentReconciler reconciler =
new DefaultExecutionDeploymentReconciler(handler);
Resour... |
@Override
public Date getDate(final int columnIndex) throws SQLException {
return (Date) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, Date.class), Date.class);
} | @Test
void assertGetDateWithColumnIndex() throws SQLException {
when(mergeResultSet.getValue(1, Date.class)).thenReturn(new Date(0L));
assertThat(shardingSphereResultSet.getDate(1), is(new Date(0L)));
} |
public static SqlMap of(final SqlType keyType, final SqlType valueType) {
return new SqlMap(keyType, valueType);
} | @SuppressWarnings("UnstableApiUsage")
@Test
public void shouldImplementHashCodeAndEqualsProperly() {
new EqualsTester()
.addEqualityGroup(SqlMap.of(SOME_TYPE, SOME_TYPE), SqlMap.of(SOME_TYPE, SOME_TYPE))
.addEqualityGroup(SqlMap.of(OTHER_TYPE, SOME_TYPE))
.addEqualityGroup(SqlMap.of(SOME... |
public static boolean isValidSigned(byte[] signedContent, byte[] signature, Certificate[] signingCertificateChain) {
if (signedContent == null || signature == null || signingCertificateChain == null) {
return false;
}
try {
CMSSignedData signedData
= ... | @Test
public void isValidSignedTest() throws Exception {
AS2SignedDataGenerator gen = SigningUtils.createSigningGenerator(AS2SignatureAlgorithm.SHA1WITHRSA,
new Certificate[] { signingCert }, signingKP.getPrivate());
CMSProcessableByteArray sData = new CMSProcessableByteArray(MESSAGE... |
public Future<?> scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit) {
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
ScheduledFuture<?> scheduledFuture =
scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, d... | @Test
public void testCloseableScheduleWithFixedDelay() throws InterruptedException {
CloseableScheduledExecutorService service = new CloseableScheduledExecutorService(executorService);
final CountDownLatch latch = new CountDownLatch(QTY);
service.scheduleWithFixedDelay(
new... |
@Override
public void append(final LogEvent event) {
if(null == event.getMessage()) {
return;
}
final StringBuilder buffer = new StringBuilder();
buffer.append(new String(getLayout().toByteArray(event), StandardCharsets.UTF_8));
if(ignoreExceptions()) {
... | @Test
public void testAppend() {
final SystemLogAppender a = new SystemLogAppender(PatternLayout.newBuilder().withPattern("%level - %m%n").build());
a.append(new Log4jLogEvent.Builder().setLoggerName(SystemLogAppender.class.getCanonicalName()).setLevel(Level.ERROR).setThrown(new RuntimeException()).... |
public List<URL> getCacheUrls(URL url) {
Map<String, List<URL>> categoryNotified = notified.get(url);
if (CollectionUtils.isNotEmptyMap(categoryNotified)) {
List<URL> urls = categoryNotified.values().stream()
.flatMap(Collection::stream)
.collect(Colle... | @Test
void getCacheUrlsTest() {
List<URL> urls = new ArrayList<>();
urls.add(testUrl);
// check if notify successfully
Assertions.assertFalse(notifySuccess);
abstractRegistry.notify(testUrl, listener, urls);
Assertions.assertTrue(notifySuccess);
List<URL> cach... |
public List<T> pollAll() {
List<T> retList = new ArrayList<T>(size);
for (int i = 0; i < entries.length; i++) {
LinkedElement<T> current = entries[i];
while (current != null) {
retList.add(current.element);
current = current.next;
}
}
this.clear();
return retList;
... | @Test
public void testPollAll() {
LOG.info("Test poll all");
for (Integer i : list) {
assertTrue(set.add(i));
}
// remove all elements by polling
List<Integer> poll = set.pollAll();
assertEquals(0, set.size());
assertTrue(set.isEmpty());
// the deleted elements should not be the... |
public static IntArrayList shuffle(IntArrayList list, Random random) {
int maxHalf = list.size() / 2;
for (int x1 = 0; x1 < maxHalf; x1++) {
int x2 = random.nextInt(maxHalf) + maxHalf;
int tmp = list.buffer[x1];
list.buffer[x1] = list.buffer[x2];
list.buff... | @Test
public void testShuffle() {
assertEquals(from(4, 1, 3, 2), ArrayUtil.shuffle(from(1, 2, 3, 4), new Random(0)));
assertEquals(from(4, 3, 2, 1, 5), ArrayUtil.shuffle(from(1, 2, 3, 4, 5), new Random(1)));
} |
@Override
protected List<Object[]> rows() {
List<Object[]> rows = new ArrayList<>(dataConnectionCatalogEntries.size());
for (DataConnectionCatalogEntry dl : dataConnectionCatalogEntries) {
final Map<String, String> options;
if (!securityEnabled) {
options = dl... | @Test
public void test_rows_enabledSecurity() {
when(connectorCache.forType("Kafka")).thenReturn(new KafkaSqlConnector());
// given
DataConnectionCatalogEntry dc = new DataConnectionCatalogEntry(
"dc-name",
"Kafka",
false,
Map.... |
@Override
public void print(Iterator<RowData> it, PrintWriter printWriter) {
if (!it.hasNext()) {
printEmptyResult(it, printWriter);
return;
}
long numRows = printTable(it, printWriter);
printFooter(printWriter, numRows);
} | @Test
void testPrintWithEmptyResultAndRowKind() {
PrintStyle.tableauWithTypeInferredColumnWidths(
getSchema(),
getConverter(),
PrintStyle.DEFAULT_MAX_COLUMN_WIDTH,
true,
true)
... |
void commitOffsetsOrTransaction(final Map<Task, Map<TopicPartition, OffsetAndMetadata>> offsetsPerTask) {
log.debug("Committing task offsets {}", offsetsPerTask.entrySet().stream().collect(Collectors.toMap(t -> t.getKey().id(), Entry::getValue))); // avoid logging actual Task objects
final Set<TaskId> ... | @Test
public void testCommitWithOpenTransactionButNoOffsetsEOSV2() {
final Tasks tasks = mock(Tasks.class);
final TaskManager taskManager = mock(TaskManager.class);
final ConsumerGroupMetadata groupMetadata = mock(ConsumerGroupMetadata.class);
when(taskManager.consumerGroupMetadata()... |
public static String addUUID(String pathStr, String uuid) {
Preconditions.checkArgument(StringUtils.isNotEmpty(pathStr), "empty path");
Preconditions.checkArgument(StringUtils.isNotEmpty(uuid), "empty uuid");
// In some cases, Spark will add the UUID to the filename itself.
if (pathStr.contains(uuid)) {... | @Test
public void testEmptyUUID() throws Throwable {
intercept(IllegalArgumentException.class,
() -> addUUID("part-0000.gz", ""));
} |
@JsonCreator
public static StageSource create(@JsonProperty("stage") @Min(0) int stage,
@JsonProperty("match") @Nullable Stage.Match match,
@JsonProperty("rules") List<String> rules) {
return builder()
.stage(stage)
... | @Test
public void testSerialization() throws Exception {
final StageSource stageSource = StageSource.create(23, Stage.Match.ALL, Collections.singletonList("some-rule"));
final JsonNode json = objectMapper.convertValue(stageSource, JsonNode.class);
assertThat(json.path("stage").asInt()).isEq... |
@Override
public Object adapt(final HttpAction action, final WebContext context) {
if (action != null) {
var code = action.getCode();
val response = ((JEEContext) context).getNativeResponse();
if (code < 400) {
response.setStatus(code);
} else... | @Test
public void testActionWithContent() {
JEEHttpActionAdapter.INSTANCE.adapt(new OkAction(TestsConstants.VALUE), context);
verify(response).setStatus(200);
verify(writer).write(TestsConstants.VALUE);
} |
public static void validate(ProjectMeasuresQuery query) {
validateFilterKeys(query.getMetricCriteria().stream().map(MetricCriterion::getMetricKey).collect(Collectors.toSet()));
validateSort(query.getSort());
} | @Test
public void query_with_empty_metrics_is_valid() {
ProjectMeasuresQueryValidator.validate(new ProjectMeasuresQuery());
} |
@Override public SlotAssignmentResult ensure(long key1, int key2) {
return super.ensure0(key1, key2);
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void testPut_whenDisposed() {
hsa.dispose();
hsa.ensure(1, 1);
} |
SortMergeSubpartitionReader createSubpartitionReader(
BufferAvailabilityListener availabilityListener,
int targetSubpartition,
PartitionedFile resultFile)
throws IOException {
synchronized (lock) {
checkState(!isReleased, "Partition is already released... | @Test
@Timeout(60)
void testCreateSubpartitionReader() throws Exception {
ManuallyTriggeredScheduledExecutorService ioExecutor =
new ManuallyTriggeredScheduledExecutorService();
readScheduler =
new SortMergeResultPartitionReadScheduler(bufferPool, ioExecutor, new ... |
public ZMsg append(String stringValue)
{
add(stringValue);
return this;
} | @Test
public void testAppend()
{
ZMsg msg = new ZMsg().append((ZMsg) null).append(ZMsg.newStringMsg("123"));
assertThat(msg.popString(), is("123"));
msg.append(ZMsg.newStringMsg("123")).append(msg);
assertThat(msg.size(), is(2));
assertThat(msg.contentSize(), is(6L));
... |
public boolean isAlive(E endpoint) {
AtomicInteger attempts = pingAttempts.get(endpoint);
return attempts != null && attempts.get() < maxPingAttempts;
} | @Test
public void member_isNotAlive_whenNoHeartbeat() {
Member member = newMember(5000);
assertFalse(failureDetector.isAlive(member));
} |
static <T, R> CheckedFunction<T, R> decorateCheckedFunction(Observation observation,
CheckedFunction<T, R> function) {
return (T t) -> observation.observeChecked(() -> function.apply(t));
} | @Test
public void shouldDecorateCheckedFunctionAndReturnWithSuccess() throws Throwable {
given(helloWorldService.returnHelloWorldWithNameWithException("Tom"))
.willReturn("Hello world Tom");
CheckedFunction<String, String> function = Observations.decorateCheckedFunction(observation,
... |
private Values() {} | @Test
@Category(NeedsRunner.class)
public void testValues() {
PCollection<KV<String, Integer>> input =
p.apply(
Create.of(Arrays.asList(TABLE))
.withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of())));
PCollection<Integer> output = input.apply(Values.cr... |
static int evaluateLevenshteinDistanceAllHits(LevenshteinDistance levenshteinDistance, List<String> terms,
List<String> texts) {
logger.debug("evaluateLevenshteinDistanceAllHits {} {}", terms, texts);
int batchSize = terms.size();
int limit = tex... | @Test
void evaluateLevenshteinDistanceAllHits() {
String wordSeparatorCharacterRE = "\\s+"; // brown-foxy does not match
Pattern pattern = Pattern.compile(wordSeparatorCharacterRE);
List<String> terms = KiePMMLTextIndex.splitText(TERM_0, pattern);
List<String> texts = KiePMMLTextInde... |
ValidationResult getElasticProfileValidationResultResponseFromBody(String responseBody) {
return new JSONResultMessageHandler().toValidationResult(responseBody);
} | @Test
public void shouldHandleValidationResponse() {
String responseBody = "[{\"key\":\"key-one\",\"message\":\"error on key one\"}, {\"key\":\"key-two\",\"message\":\"error on key two\"}]";
ValidationResult result = new ElasticAgentExtensionConverterV4().getElasticProfileValidationResultResponseFro... |
public static String sign(String metadata, String key) throws RuntimeException {
return sign(metadata.getBytes(StandardCharsets.UTF_8), key);
} | @Test
void testEncryptWithNoParameters() {
String encryptWithNoParams = SignatureUtils.sign(null, "TestMethod#hello", "TOKEN");
Assertions.assertEquals(encryptWithNoParams, "2DGkTcyXg4plU24rY8MZkEJwOMRW3o+wUP3HssRc3EE=");
} |
@Override
public UnregisterBrokerResult unregisterBroker(int brokerId, UnregisterBrokerOptions options) {
final KafkaFutureImpl<Void> future = new KafkaFutureImpl<>();
final long now = time.milliseconds();
final Call call = new Call("unregisterBroker", calcDeadlineMs(now, options.timeoutMs()... | @Test
public void testUnregisterBrokerTimeoutAndSuccessRetry() throws ExecutionException, InterruptedException {
int nodeId = 1;
try (final AdminClientUnitTestEnv env = mockClientEnv()) {
env.kafkaClient().setNodeApiVersions(
NodeApiVersions.create(ApiKeys.UNREGISTER_... |
private AlarmEntityId(final URI uri) {
super(uri);
} | @Test(expected = IllegalArgumentException.class)
public void verifyCorruptSchemaRejected() {
alarmEntityId("other:");
} |
@Override
public void editSchedule() {
// grab all changed metrics and update bindings
collector.clear();
queueMetrics.getMetrics(collector, false);
jvmMetrics.getMetrics(collector, false);
for (MetricsRecord record : collector.getRecords()) {
for (AbstractMetric am : record.metrics()) {
... | @Test(timeout = 5000)
public void testManyRuns() {
QueueMetrics qm =
QueueMetrics.forQueue(metricsSystem, "root", null, false, conf);
qm.setAvailableResourcesToQueue(RMNodeLabelsManager.NO_LABEL,
Resource.newInstance(1, 1));
int numIterations = 1000;
long start = System.currentTimeMi... |
public boolean isWatchStart() {
return isWatchStart;
} | @Test
public void isWatchStartTest() {
PlainPermissionManager plainPermissionManager = new PlainPermissionManager();
Assert.assertTrue(plainPermissionManager.isWatchStart());
} |
public static List<String> getAllConfiguredLoggers() {
LoggerContext context = (LoggerContext) LogManager.getContext(false);
Configuration config = context.getConfiguration();
return config.getLoggers().values().stream().map(LoggerConfig::toString).collect(Collectors.toList());
} | @Test
public void testGetAllConfiguredLoggers() {
List<String> allLoggers = LoggerUtils.getAllConfiguredLoggers();
assertEquals(allLoggers.size(), 2);
assertTrue(allLoggers.contains(ROOT));
assertTrue(allLoggers.contains(PINOT));
} |
@Override
public synchronized T getValue(int index) {
BarSeries series = getBarSeries();
if (series == null) {
// Series is null; the indicator doesn't need cache.
// (e.g. simple computation of the value)
// --> Calculating the value
T result = calcul... | @Test
public void recursiveCachedIndicatorOnMovingBarSeriesShouldNotCauseStackOverflow() {
// Added to check issue #120: https://github.com/mdeverdelhan/ta4j/issues/120
// See also: CachedIndicator#getValue(int index)
series = new MockBarSeries(numFunction);
series.setMaximumBarCount... |
public CompletableFuture<Triple<MessageExt, String, Boolean>> getMessageAsync(String topic, long offset, int queueId, String brokerName, boolean deCompressBody) {
MessageStore messageStore = brokerController.getMessageStoreByBrokerName(brokerName);
if (messageStore != null) {
return messageS... | @Test
public void getMessageAsyncTest_localStore_decodeNothing_TieredMessageStore() throws Exception {
when(brokerController.getMessageStoreByBrokerName(any())).thenReturn(tieredMessageStore);
for (GetMessageStatus status : GetMessageStatus.values()) {
GetMessageResult getMessageResult =... |
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
//set OfficeParserConfig if the user hasn't specified one
configure(context);
// Have the OOXML file processed
OO... | @Test
public void testNoFormat() throws Exception {
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
try (InputStream stream = getResourceAsStream("/test-documents/testWORD_no_format.docx")) {
new OOXMLParser().parse(stream, handler, metadat... |
@Override
public int read() throws EOFException {
return (pos < size) ? (data[pos++] & 0xff) : -1;
} | @Test(expected = IndexOutOfBoundsException.class)
public void testReadForBOffLen_negativeOffset() throws Exception {
in.read(INIT_DATA, -10, 1);
} |
@Override
public Object saveContent(@NonNull StaplerRequest staplerRequest, @NonNull Item item) {
JSONObject body;
try {
body = JSONObject.fromObject(IOUtils.toString(staplerRequest.getReader()));
} catch (IOException e) {
throw new ServiceException.UnexpectedErrorExc... | @Test
public void unauthorizedSaveContentToMbpGHEShouldFail() throws UnirestException, IOException {
User alice = User.get("alice");
alice.setFullName("Alice Cooper");
alice.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
String aliceCredentialId = createGithubEnterpri... |
@Override
public List<ImportValidationFeedback> verifyRule( Object subject ) {
List<ImportValidationFeedback> feedback = new ArrayList<>();
if ( !isEnabled() || !( subject instanceof JobMeta ) ) {
return feedback;
}
JobMeta jobMeta = (JobMeta) subject;
String description = jobMeta.getDesc... | @Test
public void testVerifyRule_ShortDescription_DisabledRule() {
JobHasDescriptionImportRule importRule = getImportRule( 10, false );
JobMeta jobMeta = new JobMeta();
jobMeta.setDescription( "short" );
List<ImportValidationFeedback> feedbackList = importRule.verifyRule( null );
assertNotNull( ... |
public static long elapsed(long started, long finished) {
return Times.elapsed(started, finished, true);
} | @Test
void testPositiveStartandFinishTimes() {
long elapsed = Times.elapsed(5, 10, true);
assertEquals(5, elapsed, "Elapsed time is not 5");
elapsed = Times.elapsed(5, 10, false);
assertEquals(5, elapsed, "Elapsed time is not 5");
} |
Record deserialize(Object data) {
return (Record) fieldDeserializer.value(data);
} | @Test
public void testSchemaDeserialize() {
StandardStructObjectInspector schemaObjectInspector =
ObjectInspectorFactory.getStandardStructObjectInspector(
Arrays.asList("0:col1", "1:col2"),
Arrays.asList(
PrimitiveObjectInspectorFactory.writableLongObjectInspector,
... |
public static void resetDeepLinkProcessor() {
mDeepLinkProcessor = null;
} | @Test
public void resetDeepLinkProcessor() {
DeepLinkManager.resetDeepLinkProcessor();
} |
@SafeVarargs
public static void rethrowFromCollection(Collection<?> values, Class<? extends Throwable> ... ignored) throws Throwable {
outerLoop:
for (Object value : values) {
if (value instanceof Throwable throwable) {
for (Class<? extends Throwable> ignoredClass : ignor... | @Test
public void testRethrowFromCollection_when_notIgnoredThrowableOnList_then_isRethrown() {
assertThatExceptionOfType(TestException.class)
.isThrownBy(() -> rethrowFromCollection(Collections.singleton(new TestException())));
assertThatExceptionOfType(TestException.class)
... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertLong() {
Column column = PhysicalColumn.builder().name("test").dataType(BasicType.LONG_TYPE).build();
BasicTypeDefine typeDefine = PostgresTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName());
Assert... |
public static String getS3EncryptionContextBase64Encoded(
String bucket,
Configuration conf,
boolean propagateExceptions) throws IOException {
try {
final String encryptionContextValue = getS3EncryptionContext(bucket, conf);
if (StringUtils.isBlank(encryptionContextValue)) {
re... | @Test
public void testGetS3EncryptionContextBase64Encoded() throws IOException {
Configuration configuration = new Configuration(false);
configuration.set(S3_ENCRYPTION_CONTEXT, GLOBAL_CONTEXT);
final String result = S3AEncryption.getS3EncryptionContextBase64Encoded("bucket",
configuration, true);... |
@ConstantFunction(name = "milliseconds_add", argTypes = {DATETIME, INT}, returnType = DATETIME, isMonotonic = true)
public static ConstantOperator millisecondsAdd(ConstantOperator date, ConstantOperator millisecond) {
return ConstantOperator.createDatetimeOrNull(date.getDatetime().plus(millisecond.getInt(),... | @Test
public void millisecondsAdd() {
assertEquals("2015-03-23T09:23:55.010",
ScalarOperatorFunctions.millisecondsAdd(O_DT_20150323_092355, O_INT_10).getDatetime().toString());
} |
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersion.class) ||
resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersions.class)) {
checkVersion(... | @Test
public void testFilterWithInvalidDistribution() throws Exception {
final Method resourceMethod = TestResourceWithMethodAnnotation.class.getMethod("methodWithAnnotation");
when(resourceInfo.getResourceMethod()).thenReturn(resourceMethod);
when(versionProvider.get()).thenReturn(elasticSe... |
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 testAbaloneHuber() {
test(Loss.huber(0.9), "abalone", Abalone.formula, Abalone.train, 2.2228);
} |
public static List<String> parseFilterColumnNameList(String filterExpression) {
if (isNullOrWhitespaceOnly(filterExpression)) {
return new ArrayList<>();
}
SqlSelect sqlSelect = parseFilterExpression(filterExpression);
if (!sqlSelect.hasWhere()) {
return new Array... | @Test
public void testParseFilterColumnNameList() {
List<String> computedColumnNames =
TransformParser.parseFilterColumnNameList(" uniq_id > 10 and id is not null");
Assertions.assertThat(computedColumnNames.toArray())
.isEqualTo(new String[] {"uniq_id", "id"});
} |
public static Formatter forDates(@Nonnull String format) {
return new DateFormat(format);
} | @Test
public void testWeekDates() {
Formatter f = forDates("IYYY-\"W\"IW-FMID");
check(LocalDate.of(2022, 10, 25), f, "2022-W43-2");
check(LocalDate.of(2019, 12, 30), f, "2020-W01-1");
f = forDates("YYYY-MM-DD \"is the\" FMIDDDth \"day of week-year\" FMIYYY.");
check(LocalDa... |
@Override
public boolean canFastDuplicate(StreamStateHandle stateHandle) throws IOException {
if (!(stateHandle instanceof FileStateHandle)) {
return false;
}
final Path srcPath = ((FileStateHandle) stateHandle).getFilePath();
final Path dst = getNewDstPath(srcPath.getNam... | @Test
void testCanDuplicate() throws IOException {
final FsCheckpointStateToolset stateToolset =
new FsCheckpointStateToolset(
new Path("test-path"), new TestDuplicatingFileSystem());
final boolean canFastDuplicate =
stateToolset.canFastDuplic... |
CompletableFuture<Void> beginExecute(
@Nonnull List<? extends Tasklet> tasklets,
@Nonnull CompletableFuture<Void> cancellationFuture,
@Nonnull ClassLoader jobClassLoader
) {
final ExecutionTracker executionTracker = new ExecutionTracker(tasklets.size(), cancellationFuture... | @Test
public void when_tryCancelOnReturnedFuture_then_fails() {
// Given
final MockTasklet t = new MockTasklet().callsBeforeDone(Integer.MAX_VALUE);
CompletableFuture<Void> f = tes.beginExecute(singletonList(t), cancellationFuture, classLoader);
// When - Then
assertThrows(U... |
@Override
public boolean overlap(final Window other) throws IllegalArgumentException {
if (getClass() != other.getClass()) {
throw new IllegalArgumentException("Cannot compare windows of different type. Other window has type "
+ other.getClass() + ".");
}
final Ti... | @Test
public void shouldNotOverlapIfOtherWindowIsBeforeThisWindow() {
/*
* This: [-------)
* Other: [-----)
*/
assertFalse(window.overlap(new TimeWindow(0, 25)));
assertFalse(window.overlap(new TimeWindow(0, start - 1)));
assertFalse(window.overlap(n... |
public OpenAPI read(Class<?> cls) {
return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
} | @Test(description = "RequestBody with filter")
public void testRequestBodyWithFilter() {
Components components = new Components();
components.addRequestBodies("User", new RequestBody());
OpenAPI oas = new OpenAPI()
.info(new Info().description("info"))
.compon... |
@Override
public Predicate negate() {
return new NotEqualPredicate(attributeName, value);
} | @Test
public void negate_thenReturnNotEqualPredicate() {
EqualPredicate equalPredicate = new EqualPredicate("foo", 1);
NotEqualPredicate negate = (NotEqualPredicate) equalPredicate.negate();
assertEquals("foo", negate.attributeName);
assertEquals(1, negate.value);
} |
public String lookup(final String name, final String uriParamName, final boolean isReLookup)
{
final long beginNs = clock.nanoTime();
maxTimeTracker.update(beginNs);
String resolvedName = null;
try
{
resolvedName = delegateResolver.lookup(name, uriParamName, isReL... | @Test
void lookupShouldMeasureExecutionTimeEvenIfExceptionIsThrown()
{
final NameResolver delegateResolver = mock(NameResolver.class);
final Error error = new Error("broken");
when(delegateResolver.lookup(anyString(), anyString(), anyBoolean())).thenThrow(error);
final NanoClock ... |
@VisibleForTesting
static Optional<Catalog> loadCatalog(Configuration conf, String catalogName) {
String catalogType = getCatalogType(conf, catalogName);
if (NO_CATALOG_TYPE.equalsIgnoreCase(catalogType)) {
return Optional.empty();
} else {
String name = catalogName == null ? ICEBERG_DEFAULT_C... | @Test
public void testLoadCatalogUnknown() {
String catalogName = "barCatalog";
conf.set(
InputFormatConfig.catalogPropertyConfigKey(catalogName, CatalogUtil.ICEBERG_CATALOG_TYPE),
"fooType");
assertThatThrownBy(() -> Catalogs.loadCatalog(conf, catalogName))
.isInstanceOf(Unsuppor... |
static InvokerResult convertToResult(Query query, SearchProtocol.SearchReply protobuf,
DocumentDatabase documentDatabase, int partId, int distKey)
{
InvokerResult result = new InvokerResult(query, protobuf.getHitsCount());
result.getResult().setTotalHitCount... | @Test
void testSearchReplyDecodingWithSortData() {
Query q = new Query("search/?query=test");
InvokerResult result = ProtobufSerialization.convertToResult(q, createSearchReply(5, true), null, 1, 2);
assertEquals(result.getResult().getTotalHitCount(), 7);
List<LeanHit> hits = result.g... |
static Properties adminClientConfiguration(String bootstrapHostnames, PemTrustSet kafkaCaTrustSet, PemAuthIdentity authIdentity, Properties config) {
if (config == null) {
throw new InvalidConfigurationException("The config parameter should not be null");
}
config.setProperty(Adm... | @Test
public void testCustomConfig() {
Properties customConfig = new Properties();
customConfig.setProperty(AdminClientConfig.RETRIES_CONFIG, "5"); // Override a value we have default for
customConfig.setProperty(AdminClientConfig.RECONNECT_BACKOFF_MS_CONFIG, "13000"); // Override a value we... |
public FEELFnResult<List<Object>> invoke(@ParameterName("list") Object[] lists) {
if ( lists == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
// spec requires us to return a new list
final List<Object> result = n... | @Test
void invokeNull() {
FunctionTestUtil.assertResultError(concatenateFunction.invoke(null), InvalidParametersEvent.class);
} |
public boolean isValid(String value) {
if (value == null) {
return false;
}
URI uri; // ensure value is a valid URI
try {
uri = new URI(value);
} catch (URISyntaxException e) {
return false;
}
// OK, perfom additional validatio... | @Test
public void testValidator467() {
UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES);
assertTrue(validator.isValid("https://example.com/some_path/path/"));
assertTrue(validator.isValid("https://example.com//somepath/path/"));
assertTrue(validator.isValid("https://exa... |
public void putDefaultNullValue(String fieldName, Object defaultNullValue) {
_fieldToValueMap.put(fieldName, defaultNullValue);
_nullValueFields.add(fieldName);
} | @Test
public void testNullValueFieldsNotEqual() {
GenericRow first = new GenericRow();
first.putDefaultNullValue("one", 1);
GenericRow second = new GenericRow();
second.putDefaultNullValue("one", 2);
Assert.assertNotEquals(first, second);
first = new GenericRow();
first.putDefaultNullValu... |
public void validate(ExternalIssueReport report, Path reportPath) {
if (report.rules != null && report.issues != null) {
Set<String> ruleIds = validateRules(report.rules, reportPath);
validateIssuesCctFormat(report.issues, ruleIds, reportPath);
} else if (report.rules == null && report.issues != nul... | @Test
public void validate_whenContainsDeprecatedTypeEntry_shouldThrowException() throws IOException {
ExternalIssueReport report = read(REPORTS_LOCATION);
report.issues[0].type = "BUG";
assertThatThrownBy(() -> validator.validate(report, reportPath))
.isInstanceOf(IllegalStateException.class)
... |
public DataPoint addDataPoint(Object label) {
DataPoint dp = new DataPoint();
labels.add(label);
dataPoints.add(dp);
return dp;
} | @Test(expected = IllegalArgumentException.class)
public void dataPointBandSeries() {
cm = new ChartModel(FOO, BAR);
cm.addDataPoint(System.currentTimeMillis())
.data(ZOO, VALUES3[0]);
} |
@Override
public CompletableFuture<JobResult> requestJobResult(JobID jobId, Time timeout) {
final CompletableFuture<JobResult> jobResultFuture = super.requestJobResult(jobId, timeout);
if (executionMode == ClusterEntrypoint.ExecutionMode.NORMAL) {
// terminate the MiniDispatcher once we... | @Test
public void testJobResultRetrieval() throws Exception {
final MiniDispatcher miniDispatcher =
createMiniDispatcher(ClusterEntrypoint.ExecutionMode.NORMAL);
miniDispatcher.start();
try {
// wait until we have submitted the job
final TestingJobMa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.