focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer,
final Merger<? super K, V> sessionMerger) {
return aggregate(initializer, sessionMerger, Materialized.with(null, null));
} | @Test
public void shouldNotHaveNullNamedOnAggregate() {
assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT,
sessionMerger, null, Materialized.as("test")));
} |
public static Set<ConfigKey<?>> getAllConfigsProduced(Class<? extends ConfigProducer> producerClass, String configId) {
// TypeToken is @Beta in guava, so consider implementing a simple recursive method instead.
TypeToken<? extends ConfigProducer>.TypeSet interfaces = TypeToken.of(producerClass).getType... | @Test
void getAllConfigsProduced_includes_configs_produced_by_super_class() {
Set<ConfigKey<?>> configs = getAllConfigsProduced(ConcreteProducer.class, "foo");
assertEquals(1, configs.size());
assertTrue(configs.contains(new ConfigKey<>(SimpletypesConfig.CONFIG_DEF_NAME, "foo", SimpletypesCo... |
public static int checkPositive(int i, String name) {
if (i <= INT_ZERO) {
throw new IllegalArgumentException(name + " : " + i + " (expected: > 0)");
}
return i;
} | @Test
public void testCheckPositiveLongString() {
Exception actualEx = null;
try {
ObjectUtil.checkPositive(POS_ONE_LONG, NUM_POS_NAME);
} catch (Exception e) {
actualEx = e;
}
assertNull(actualEx, TEST_RESULT_NULLEX_NOK);
actualEx = null;
... |
public String[] decodeStringArray(final byte[] parameterBytes, final boolean isBinary) {
ShardingSpherePreconditions.checkState(!isBinary, () -> new UnsupportedSQLOperationException("binary mode"));
String parameterValue = new String(parameterBytes, StandardCharsets.UTF_8);
Collection<String> pa... | @Test
void assertParseStringArrayNormalTextMode() {
String[] actual = DECODER.decodeStringArray("{\"a\",\"b\"}".getBytes(), false);
assertThat(actual.length, is(2));
assertThat(actual[0], is("a"));
assertThat(actual[1], is("b"));
} |
@Override
public void addTaskExecutionLogs(List<TaskExecLog> logs) {
if (logs == null || logs.isEmpty()) {
return;
}
Set<TaskExecLog> taskLogs = new HashSet<>(logs);
try {
int cnt =
withRetryableStatement(
CREATE_TASK_EXECUTION_LOGS_STATEMENT,
stateme... | @Test
public void addTaskExecutionLogsTest() {
List<TaskExecLog> logs = new ArrayList<>();
logs.add(createLog(TEST_TASK_ID_1, "log1"));
logs.add(createLog(TEST_TASK_ID_1, "log2"));
logs.add(createLog(TEST_TASK_ID_1, "log3"));
dao.addTaskExecutionLogs(logs);
List<TaskExecLog> indexedLogs =
... |
public static FileMetadata fromJson(String json) {
return JsonUtil.parse(json, FileMetadataParser::fromJson);
} | @Test
public void testFieldNumberOutOfRange() {
assertThatThrownBy(
() ->
FileMetadataParser.fromJson(
"{\n"
+ " \"blobs\" : [ {\n"
+ " \"type\" : \"type-a\",\n"
+ " \"fields\" : [ "
... |
public void notify(PluginJarChangeListener listener, Collection<BundleOrPluginFileDetails> knowPluginFiles, Collection<BundleOrPluginFileDetails> currentPluginFiles) {
List<BundleOrPluginFileDetails> oldPlugins = new ArrayList<>(knowPluginFiles);
subtract(oldPlugins, currentPluginFiles).forEach(listene... | @Test
void shouldNotifyRemovedBeforeAddWhenPluginJarIsRenamed() {
final PluginJarChangeListener listener = mock(PluginJarChangeListener.class);
File pluginJarOne = mock(File.class);
File pluginJarTwo = mock(File.class);
File pluginWorkDir = mock(File.class);
BundleOrPluginFil... |
public List<T> getUnmodifiableData() {
return Collections.unmodifiableList(scesimData);
} | @Test
public void getUnmodifiableData() {
assertThat(model.getUnmodifiableData()).isNotNull().hasSize(SCENARIO_DATA);
} |
public List<Entry> getEntries() {
return new ArrayList<>(actions.values());
} | @Test
public void actions_with_multiple_clusters_of_same_type() {
ConfigChangeActions actions = new ConfigChangeActionsBuilder().
restart(CHANGE_MSG, CLUSTER, CLUSTER_TYPE, SERVICE_TYPE, SERVICE_NAME).
restart(CHANGE_MSG, CLUSTER_2, CLUSTER_TYPE, SERVICE_TYPE, SERVICE_NAME).b... |
public static void checkMrzCheckDigit(String mrz) {
final char checkDigit = calculateCheckDigit(mrz.substring(0, mrz.length() - 1));
if (checkDigit != mrz.charAt(mrz.length() - 1)) {
throw new VerificationException(String.format(
"The check digit of MRZ is not correct [%c... | @Test
public void checkMrzCheckDigit() {
MrzUtils.checkMrzCheckDigit("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");
MrzUtils.checkMrzCheckDigit("PPPPPPPPP");
assertThrows(VerificationException.class, () -> {
MrzUtils.checkMrzCheckDigit("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");
});
} |
public static void main(String[] args) {
ParameterObject params = ParameterObject.newBuilder()
.withType("sneakers")
.sortBy("brand")
.build();
LOGGER.info(params.toString());
LOGGER.info(new SearchService().search(params));
} | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
public static void upgradeConfigurationAndVersion(RuleNode node, RuleNodeClassInfo nodeInfo) {
JsonNode oldConfiguration = node.getConfiguration();
int configurationVersion = node.getConfigurationVersion();
int currentVersion = nodeInfo.getCurrentVersion();
var configClass = nodeInfo.ge... | @Test
public void testUpgradeRuleNodeConfigurationWithNullNodeConfig() throws Exception {
// GIVEN
var node = new RuleNode();
node.setConfiguration(NullNode.instance);
var nodeInfo = mock(RuleNodeClassInfo.class);
var nodeConfigClazz = TbGetAttributesNodeConfiguration.class;
... |
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
String[] lines = splitAndRemoveEmpty(st, "\n");
return interpret(lines, context);
} | @Test
void catTest() throws IOException {
FileSystemTestUtils.createByteFile(fs, "/testFile", WritePType.MUST_CACHE, 10, 10);
InterpreterResult output = alluxioInterpreter.interpret("cat /testFile", null);
byte[] expected = BufferUtils.getIncreasingByteArray(10);
assertEquals(Code.SUCCESS, output.co... |
public static String stripTrailingSlash(String str) {
if (isNullOrEmpty(str)) {
return str;
}
if (str.charAt(str.length() - 1) == '/') {
return str.substring(0, str.length() - 1);
}
return str;
} | @Test
void testStripTrailingSlash() {
assertNull(StringUtil.stripTrailingSlash(null));
assertEquals("", StringUtil.stripTrailingSlash(""));
assertEquals("a", StringUtil.stripTrailingSlash("a"));
assertEquals("a", StringUtil.stripTrailingSlash("a/"));
assertEquals("a/a", Strin... |
@SuppressWarnings("deprecation")
@Override
public Handle newHandle() {
return new HandleImpl(minIndex, maxIndex, initialIndex, minCapacity, maxCapacity);
} | @Test
public void doesNotExceedMaximum() {
AdaptiveRecvByteBufAllocator recvByteBufAllocator = new AdaptiveRecvByteBufAllocator(64, 9000, 9000);
RecvByteBufAllocator.ExtendedHandle handle =
(RecvByteBufAllocator.ExtendedHandle) recvByteBufAllocator.newHandle();
handle.reset(c... |
@Udf
public String lpad(
@UdfParameter(description = "String to be padded") final String input,
@UdfParameter(description = "Target length") final Integer targetLen,
@UdfParameter(description = "Padding string") final String padding) {
if (input == null) {
return null;
}
if (paddi... | @Test
public void shouldReturnNullForNullInputString() {
final String result = udf.lpad(null, 4, "foo");
assertThat(result, is(nullValue()));
} |
@Override
@Nullable
public final Data readData() throws IOException {
byte[] bytes = readByteArray();
return bytes == null ? null : new HeapData(bytes);
} | @Test
public void testReadData() throws Exception {
byte[] bytesBE = {0, 0, 0, 0, 0, 0, 0, 8, -1, -1, -1, -1, 0, 0, 0, 0, 0, 1, -1, -1, -1, -1};
byte[] bytesLE = {0, 0, 0, 0, 8, 0, 0, 0, -1, -1, -1, -1, 0, 0, 0, 0, 0, 1, -1, -1, -1, -1};
in.init((byteOrder == BIG_ENDIAN ? bytesBE : bytesLE),... |
public TreeSelection[] getTreeObjects( final Tree tree, Tree selectionTree, Tree coreObjectsTree ) {
List<TreeSelection> objects = new ArrayList<TreeSelection>();
if ( selectionTree != null && !selectionTree.isDisposed() && tree.equals( selectionTree ) ) {
TreeItem[] selection = selectionTree.getSelectio... | @Test
public void getTreeObjects_getStepByName() {
SpoonTreeDelegate std = spy( new SpoonTreeDelegate( spoon ) );
Tree selection = mock( Tree.class );
Tree core = mock( Tree.class );
TreeItem item = mock( TreeItem.class );
PluginInterface step = mock( PluginInterface.class );
PluginRegistry r... |
@Override
public boolean supportsMultipleTransactions() {
return false;
} | @Test
void assertSupportsMultipleTransactions() {
assertFalse(metaData.supportsMultipleTransactions());
} |
@Around(SYNC_UPDATE_CONFIG_ALL)
public Object aroundSyncUpdateConfigAll(ProceedingJoinPoint pjp, HttpServletRequest request,
HttpServletResponse response, String dataId, String group, String content, String appName, String srcUser,
String tenant, String tag) throws Throwable {
if (!P... | @Test
void testAroundSyncUpdateConfigAllForInsertAspect3Tenant() throws Throwable {
//test with insert
//condition:
// 1. has tenant: true
// 2. capacity limit check: true
// 3. over cluster quota: false
// 4. tenant capacity: not null
// 5. over tenant m... |
@Override
public boolean isIn(String ipAddress) {
if (ipAddress == null || addressList == null) {
return false;
}
return addressList.includes(ipAddress);
} | @Test
public void testSubnetsAndIPs() throws IOException {
String[] ips = {"10.119.103.112", "10.221.102.0/23"};
createFileWithEntries ("ips.txt", ips);
IPList ipList = new FileBasedIPList("ips.txt");
assertTrue ("10.119.103.112 is not in the list",
ipList.isIn("10.119.103.112"));
asse... |
public DiscardObject markAsDiscardedOnShutdown(JobStatus jobStatus) {
return shouldBeDiscardedOnShutdown(jobStatus) ? markAsDiscarded() : NOOP_DISCARD_OBJECT;
} | @Test
void testCompletedCheckpointStatsCallbacks() throws Exception {
Map<JobVertexID, TaskStateStats> taskStats = new HashMap<>();
JobVertexID jobVertexId = new JobVertexID();
taskStats.put(jobVertexId, new TaskStateStats(jobVertexId, 1));
CompletedCheckpointStats checkpointStats =
... |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.SMS_TEMPLATE,
allEntries = true) // allEntries 清空所有缓存,因为可能修改到 code 字段,不好清理
public void updateSmsTemplate(SmsTemplateSaveReqVO updateReqVO) {
// 校验存在
validateSmsTemplateExists(updateReqVO.getId());
// 校验短信渠道
SmsChann... | @Test
public void testUpdateSmsTemplate_notExists() {
// 准备参数
SmsTemplateSaveReqVO reqVO = randomPojo(SmsTemplateSaveReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> smsTemplateService.updateSmsTemplate(reqVO), SMS_TEMPLATE_NOT_EXISTS);
} |
@Override
public void finished(boolean allStepsExecuted) {
if (postProjectAnalysisTasks.length == 0) {
return;
}
ProjectAnalysisImpl projectAnalysis = createProjectAnalysis(allStepsExecuted ? SUCCESS : FAILED);
for (PostProjectAnalysisTask postProjectAnalysisTask : postProjectAnalysisTasks) {
... | @Test
public void branch_comes_from_AnalysisMetadataHolder_when_set() {
analysisMetadataHolder.setBranch(new Branch() {
@Override
public BranchType getType() {
return BranchType.BRANCH;
}
@Override
public boolean isMain() {
return false;
}
@Override
... |
@Override
public KeyValueIterator<K, V> reverseRange(final K from,
final K to) {
final byte[] serFrom = from == null ? null : serdes.rawKey(from);
final byte[] serTo = to == null ? null : serdes.rawKey(to);
return new MeteredKeyValueIterator(
... | @Test
public void shouldThrowNullPointerOnReverseRangeIfToIsNull() {
setUpWithoutContext();
assertThrows(NullPointerException.class, () -> metered.reverseRange("from", null));
} |
public <T> Map<String, Object> schemas(Class<? extends T> cls) {
return this.schemas(cls, false);
} | @SuppressWarnings({"unchecked", "deprecation"})
@Test
void echoTask() throws URISyntaxException {
Helpers.runApplicationContext((applicationContext) -> {
JsonSchemaGenerator jsonSchemaGenerator = applicationContext.getBean(JsonSchemaGenerator.class);
Map<String, Object> returnSc... |
@Override
public HealthCheckResponse call() {
final HealthCheckResponseBuilder healthResponseBuilder = HealthCheckResponse.named("JobRunr");
if (!jobRunrBuildTimeConfiguration.backgroundJobServer().enabled()) {
healthResponseBuilder
.up()
.withData... | @Test
void givenEnabledBackgroundJobServerAndBackgroundJobServerStopped_ThenHealthIsDown() {
when(backgroundJobServerConfiguration.enabled()).thenReturn(true);
when(backgroundJobServer.isRunning()).thenReturn(false);
assertThat(jobRunrHealthCheck.call().getStatus()).isEqualTo(HealthCheckRes... |
public abstract VoiceInstructionValue getConfigForDistance(
double distance,
String turnDescription,
String thenVoiceInstruction); | @Test
public void conditionalDistanceVICShouldReturnFirstFittingMetricValues() {
ConditionalDistanceVoiceInstructionConfig config = new ConditionalDistanceVoiceInstructionConfig(IN_LOWER_DISTANCE_PLURAL.metric, trMap, locale, new int[]{400, 200}, new int[]{400, 200});
compareVoiceInstructionValues(... |
@PostMapping("/order")
public ResponseEntity<String> processOrder(@RequestBody(required = false) String request) {
LOGGER.info("Received order request: {}", request);
var result = orderService.processOrder();
LOGGER.info("Order processed result: {}", result);
return ResponseEntity.ok(result);
} | @Test
void processOrderShouldReturnSuccessStatus() {
// Arrange
when(orderService.processOrder()).thenReturn("Order processed successfully");
// Act
ResponseEntity<String> response = orderController.processOrder("test order");
// Assert
assertEquals("Order processed successfully", response.get... |
public static <K, E, V> Collector<E, ImmutableSetMultimap.Builder<K, V>, ImmutableSetMultimap<K, V>> unorderedFlattenIndex(
Function<? super E, K> keyFunction, Function<? super E, Stream<V>> valueFunction) {
verifyKeyAndValueFunctions(keyFunction, valueFunction);
BiConsumer<ImmutableSetMultimap.Builder<K, ... | @Test
public void unorderedFlattenIndex_with_valueFunction_fails_if_key_function_returns_null() {
assertThatThrownBy(() -> SINGLE_ELEMENT2_LIST.stream().collect(unorderedFlattenIndex(s -> null, MyObj2::getTexts)))
.isInstanceOf(NullPointerException.class)
.hasMessage("Key function can't return null");... |
public static String getContainerExecutorExecutablePath(Configuration conf) {
String yarnHomeEnvVar =
System.getenv(ApplicationConstants.Environment.HADOOP_YARN_HOME.key());
File hadoopBin = new File(yarnHomeEnvVar, "bin");
String defaultPath =
new File(hadoopBin, "container-executor").getAb... | @Test
public void testExecutorPath() {
String containerExePath = PrivilegedOperationExecutor
.getContainerExecutorExecutablePath(nullConf);
//In case HADOOP_YARN_HOME isn't set, CWD is used. If conf is null or
//NM_LINUX_CONTAINER_EXECUTOR_PATH is not set, then a defaultPath is
//constructed.... |
@Operation(summary = "queryAuthorizedUser", description = "QUERY_AUTHORIZED_USER_NOTES")
@Parameters({
@Parameter(name = "projectCode", description = "PROJECT_CODE", schema = @Schema(implementation = long.class, example = "100", required = true))
})
@GetMapping(value = "/authed-user")
@Respo... | @Test
public void testQueryAuthorizedUser() {
Result result = new Result();
this.putMsg(result, Status.SUCCESS);
Mockito.when(this.projectService.queryAuthorizedUser(this.user, 3682329499136L)).thenReturn(result);
Result response = this.projectV2Controller.queryAuthorizedUser(this.u... |
@Override public void pluginRemoved( Object serviceObject ) {
SpoonPluginInterface spoonPluginInterface = plugins.get( serviceObject );
if ( spoonPluginInterface == null ) {
return;
}
SpoonPluginCategories categories = spoonPluginInterface.getClass().getAnnotation( SpoonPluginCategories.class );
... | @Test
public void testPluginRemoved() throws Exception {
spoonPluginManager.pluginAdded( plugin1 );
spoonPluginManager.pluginRemoved( plugin1 );
verify( spoonPerspectiveManager ).removePerspective( spoonPerspective );
} |
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
} | @Test
public void testNameAndLabelsFromPattern() throws Exception {
new JmxCollector(
"\n---\nrules:\n- pattern: `^hadoop<(service)=(DataNode), name=DataNodeActivity-ams-hdd001-50010><>(replaceBlockOpMinTime):`\n name: hadoop_$3\n labels:\n `$1`: `$2`"
... |
@Override
public CloseableIterator<ScannerReport.Duplication> readComponentDuplications(int componentRef) {
ensureInitialized();
return delegate.readComponentDuplications(componentRef);
} | @Test
public void readComponentDuplications_returns_empty_list_if_file_does_not_exist() {
assertThat(underTest.readComponentDuplications(COMPONENT_REF)).isExhausted();
} |
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
... | @Test
public void testEqualsAndHashCode() throws Exception {
ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap());
Simple proxy = handler.as(Simple.class);
JLSDefaults sameAsProxy = proxy.as(JLSDefaults.class);
ProxyInvocationHandler handler2 = new ProxyInvocationHandler(Maps... |
public Resource getIncrementAllocation() {
Long memory = null;
Integer vCores = null;
Map<String, Long> others = new HashMap<>();
ResourceInformation[] resourceTypes = ResourceUtils.getResourceTypesArray();
for (int i=0; i < resourceTypes.length; ++i) {
String name = resourceTypes[i].getName()... | @Test
public void testAllocationIncrementMemoryNonDefaultUnit() throws Exception {
Configuration conf = new Configuration();
conf.set(YarnConfiguration.RESOURCE_TYPES + "." +
ResourceInformation.MEMORY_MB.getName() +
FairSchedulerConfiguration.INCREMENT_ALLOCATION, "1 Gi");
FairSchedulerCo... |
public static boolean isComplete(Object obj) throws IllegalArgumentException {
requireNonNull(obj);
Field[] fields = obj.getClass().getDeclaredFields();
StringBuilder error = new StringBuilder();
for (Field field : fields) {
if (field.isAnnotationPresent(FieldContext.class)) ... | @Test
public void testIncomplete() throws IllegalAccessException {
assertThrows(IllegalArgumentException.class, () -> isComplete(new TestInCompleteObjectRequired()));
assertThrows(IllegalArgumentException.class, () -> isComplete(new TestInCompleteObjectMin()));
assertThrows(IllegalArgumentEx... |
public static ConditionStatus create(EvaluationStatus status, String value) {
requireNonNull(status, "status can not be null");
checkArgument(status != EvaluationStatus.NO_VALUE, "EvaluationStatus 'NO_VALUE' can not be used with this method, use constant ConditionStatus.NO_VALUE_STATUS instead.");
requireNo... | @Test
@UseDataProvider("allStatusesButNO_VALUE")
public void create_throws_NPE_if_value_is_null_and_status_argument_is_not_NO_VALUE(ConditionStatus.EvaluationStatus status) {
assertThatThrownBy(() -> ConditionStatus.create(status, null))
.isInstanceOf(NullPointerException.class)
.hasMessage("value c... |
public static TimeLock ofTimestamp(Instant time) {
long secs = time.getEpochSecond();
if (secs < THRESHOLD)
throw new IllegalArgumentException("timestamp too low: " + secs);
return new TimeLock(secs);
} | @Test
public void timestampSubtype() {
LockTime timestamp = LockTime.ofTimestamp(Instant.now());
assertTrue(timestamp instanceof TimeLock);
assertTrue(((TimeLock) timestamp).timestamp().isAfter(Instant.EPOCH));
} |
public RuntimeOptionsBuilder parse(Map<String, String> properties) {
return parse(properties::get);
} | @Test
void should_parse_glue_list() {
properties.put(Constants.GLUE_PROPERTY_NAME, "com.example.app.steps, com.example.other.steps");
RuntimeOptions options = cucumberPropertiesParser.parse(properties).build();
assertThat(options.getGlue(), contains(
URI.create("classpath:/com/ex... |
public static int readVInt(ByteData arr, long position) {
byte b = arr.get(position++);
if(b == (byte) 0x80)
throw new RuntimeException("Attempting to read null value as int");
int value = b & 0x7F;
while ((b & 0x80) != 0) {
b = arr.get(position++);
valu... | @Test
public void testReadVIntHollowBlobInput() throws IOException {
HollowBlobInput hbi = HollowBlobInput.serial(BYTES_VALUE_129);
Assert.assertEquals(129l, VarInt.readVInt(hbi));
} |
public static Statement sanitize(
final Statement node,
final MetaStore metaStore) {
return sanitize(node, metaStore, true);
} | @Test
public void shouldThrowOnUnknownSource() {
// Given:
final Statement stmt = givenQuery("SELECT * FROM Unknown;");
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> AstSanitizer.sanitize(stmt, META_STORE)
);
// Then:
assertThat(e.getMessage(), con... |
@Override
public Decision onResultPartitionClosed(HsSpillingInfoProvider spillingInfoProvider) {
Decision.Builder builder = Decision.builder();
for (int subpartitionId = 0;
subpartitionId < spillingInfoProvider.getNumSubpartitions();
subpartitionId++) {
bu... | @Test
void testOnResultPartitionClosed() {
final int subpartition1 = 0;
final int subpartition2 = 1;
List<BufferIndexAndChannel> subpartitionBuffer1 =
createBufferIndexAndChannelsList(subpartition1, 0, 1, 2, 3);
List<BufferIndexAndChannel> subpartitionBuffer2 =
... |
@Override
public Optional<HealthStatus> health() {
return clusterHealth().map(response -> healthStatusFrom(response.getStatus()));
} | @Test
void returnsEmptyOptionalForHealthWhenElasticsearchExceptionThrown() {
when(client.execute(any())).thenThrow(new ElasticsearchException("Exception"));
final Optional<HealthStatus> healthStatus = clusterAdapter.health();
assertThat(healthStatus).isEmpty();
} |
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testNullableField() {
assertDeterministic(AvroCoder.of(NullableField.class));
} |
@SuppressWarnings("unchecked")
public static <K1,V1,K2,V2> Mapper<K1,V1,K2,V2>.Context
cloneMapContext(MapContext<K1,V1,K2,V2> context,
Configuration conf,
RecordReader<K1,V1> reader,
RecordWriter<K2,V2> writer
) throws... | @Test
public void testCloneMapContext() throws Exception {
TaskID taskId = new TaskID(jobId, TaskType.MAP, 0);
TaskAttemptID taskAttemptid = new TaskAttemptID(taskId, 0);
MapContext<IntWritable, IntWritable, IntWritable, IntWritable> mapContext =
new MapContextImpl<IntWritable, IntWritable, IntWritabl... |
public static byte[] toArray(ByteBuffer bytebuffer) {
if (bytebuffer.hasArray()) {
return Arrays.copyOfRange(bytebuffer.array(), bytebuffer.position(), bytebuffer.limit());
} else {
int oldPosition = bytebuffer.position();
bytebuffer.position(0);
int size = bytebuffer.limit();
byte[] buffers = new by... | @Test
public void toArrayTest() {
final ArrayList<String> list = CollUtil.newArrayList("A", "B", "C", "D");
final String[] array = ArrayUtil.toArray(list, String.class);
assertEquals("A", array[0]);
assertEquals("B", array[1]);
assertEquals("C", array[2]);
assertEquals("D", array[3]);
} |
public static JsonNode getHostLifePacket() {
var jsonMapper = Jackson.mapper();
ObjectNode jsonObject = jsonMapper.createObjectNode();
jsonObject.put("timestamp", Instant.now().getEpochSecond());
jsonObject.put("application", "host_life");
ObjectNode metrics = jsonMapper.createOb... | @Test
void host_is_alive() {
JsonNode packet = HostLifeGatherer.getHostLifePacket();
JsonNode metrics = packet.get("metrics");
assertEquals("host_life", packet.get("application").textValue());
assertEquals(1, metrics.get("alive").intValue());
assertTrue(packet.get("dimensions... |
protected void setCharsetWithContentType(Exchange camelExchange) {
// setup the charset from content-type header
String contentTypeHeader = ExchangeHelper.getContentType(camelExchange);
if (contentTypeHeader != null) {
String charset = HttpHeaderHelper.findCharset(contentTypeHeader);... | @Test
public void testSetCharsetWithContentType() {
DefaultCxfRsBinding cxfRsBinding = new DefaultCxfRsBinding();
Exchange exchange = new DefaultExchange(context);
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/xml;charset=ISO-8859-1");
cxfRsBinding.setCharsetWithContentType... |
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
gauges.put("loaded", (Gauge<Long>) mxBean::getTotalLoadedClassCount);
gauges.put("unloaded", (Gauge<Long>) mxBean::getUnloadedClassCount);
return gauges;
} | @Test
public void unLoadedGauge() {
final Gauge gauge = (Gauge) gauges.getMetrics().get("unloaded");
assertThat(gauge.getValue()).isEqualTo(1L);
} |
@Override
public void cancel() {
synchronized (monitor) {
if (!periodicExecutionCancellation.isPresent()) {
throw new IllegalStateException("setPeriodicExecutionCancellationCallback has not been called before cancel");
}
cancelled = true;
if (... | @Test
public void testCancelWhileIdle() {
// Cancel while runlet is not running and verify closure and executor cancellation
cancellable.cancel();
assertFalse(executor.isExecutionRunning());
assertTrue(runlet.isClosed());
// Ensure a spurious run is ignored.
executor... |
@Override
public ConfigFileList getConfigFiles(String pluginId, final String destinationFolder, final Collection<CRConfigurationProperty> configurations) {
String resolvedExtensionVersion = pluginManager.resolveExtensionVersion(pluginId, CONFIG_REPO_EXTENSION, goSupportedVersions);
if (resolvedExten... | @Test
public void shouldGracefullyHandleV1AndV2Incompatability() {
ConfigFileList expected = ConfigFileList.withError("Unsupported Operation", "This plugin version does not support list config files");
when(pluginManager.resolveExtensionVersion(PLUGIN_ID, CONFIG_REPO_EXTENSION, new ArrayList<>(List... |
public String get(String key) {
return properties.getProperty(key);
} | @Test
public void testGet_whenKeyExisting() {
Properties props = new Properties();
props.setProperty("key1", "value1");
props.setProperty("key2", "value2");
HazelcastProperties properties = new HazelcastProperties(props);
assertEquals("value1", properties.get("key1"));
} |
public static void validateCardSecurityVsCardAccess(SecurityInfos cardSecurity, int caKeyReference, int paceVersion,
int taVersion) {
Assert.notNull(cardSecurity, "cardSecurity may not be null");
if (caKeyReference != cardSecurity.getCaKeyId() || ... | @Test
public void validateCardSecurityVsCardAccessCaFail() {
ClientException thrown = assertThrows(ClientException.class, () -> CardValidations.validateCardSecurityVsCardAccess(efCardSecurity, 2, 1, 1));
assertEquals("The card info and the card security do not match.", thrown.getMessage());
} |
@Override
public List<?> deserialize(final String topic, final byte[] bytes) {
if (bytes == null) {
return null;
}
try {
final String recordCsvString = new String(bytes, StandardCharsets.UTF_8);
final List<CSVRecord> csvRecords = CSVParser.parse(recordCsvString, csvFormat)
.ge... | @Test
public void shouldThrowOnNegativeTime() {
// Given:
KsqlDelimitedDeserializer deserializer = createDeserializer(persistenceSchema(
column(
"ids",
SqlTypes.TIME
)
));
final byte[] bytes = "-5".getBytes(StandardCharsets.UTF_8);
// When:
final Except... |
public static TrackPair of(Track track1, Track track2) {
return new TrackPair(track1, track2);
} | @Test
public void testOf_nullInput_1st() {
assertThrows(
NullPointerException.class,
() -> TrackPair.of(null, A_TRACK)
);
} |
@Override
public void execute(SensorContext context) {
Set<String> reportPaths = loadReportPaths();
Map<String, SarifImportResults> filePathToImportResults = new HashMap<>();
for (String reportPath : reportPaths) {
try {
SarifImportResults sarifImportResults = processReport(context, reportP... | @Test
public void execute_whenMultipleFilesAreSpecified_shouldImportResults() throws NoSuchFileException {
sensorSettings.setProperty("sonar.sarifReportPaths", SARIF_REPORT_PATHS_PARAM);
ReportAndResults reportAndResults1 = mockSuccessfulReportAndResults(FILE_1);
ReportAndResults reportAndResults2 = mockS... |
@Override
public void validate(Context context) {
context.model().getContainerClusters().forEach((id, cluster) -> {
Http http = cluster.getHttp();
if (http != null) {
if (http.getAccessControl().isPresent()) {
verifyAccessControlFilterPresent(conte... | @Test
void validator_accepts_non_empty_access_control_filter_chain() throws IOException, SAXException {
DeployState deployState = createDeployState();
VespaModel model = new VespaModel(
MapConfigModelRegistry.createFromList(new ModelBuilderAddingAccessControlFilter()),
... |
public static TraceTransferBean encoderFromContextBean(TraceContext ctx) {
if (ctx == null) {
return null;
}
//build message trace of the transferring entity content bean
TraceTransferBean transferBean = new TraceTransferBean();
StringBuilder sb = new StringBuilder(25... | @Test
public void testSubBeforeTraceDataFormatTest() {
TraceContext subBeforeContext = new TraceContext();
subBeforeContext.setTraceType(TraceType.SubBefore);
subBeforeContext.setTimeStamp(time);
subBeforeContext.setRegionId("Default-region");
subBeforeContext.setGroupName("G... |
public AbstractRequestBuilder<K, V, R> addReqParam(String key, Object value)
{
ArgumentUtil.notNull(value, "value");
return addParam(key, value);
} | @Test
public void testAddReqParamWithNullValue()
{
final AbstractRequestBuilder<?, ?, ?> builder = new DummyAbstractRequestBuilder();
try
{
builder.addReqParam("a", null);
Assert.fail("addReqParam should not allow null values");
}
catch (NullPointerException e)
{
}
} |
@Override
public PageData<WidgetTypeInfo> findSystemWidgetTypes(WidgetTypeFilter widgetTypeFilter, PageLink pageLink) {
boolean deprecatedFilterEnabled = !DeprecatedFilter.ALL.equals(widgetTypeFilter.getDeprecatedFilter());
boolean deprecatedFilterBool = DeprecatedFilter.DEPRECATED.equals(widgetType... | @Test
public void testTagsSearchInFindBySystemWidgetTypes() {
for (var entry : SHOULD_FIND_SEARCH_TO_TAGS_MAP.entrySet()) {
String searchText = entry.getKey();
String[] tags = entry.getValue();
WidgetTypeDetails savedWidgetType = createAndSaveWidgetType(TenantId.SYS_TENA... |
@Override
public void close() {
super.close();
// close other classloader in the list
for (FlinkUserCodeClassLoader classLoader : originClassLoaders) {
try {
classLoader.close();
} catch (IOException e) {
LOG.error("Failed to close the ... | @Test
public void testClassLoadingByAddURL() throws Exception {
Configuration configuration = new Configuration();
final ClientWrapperClassLoader classLoader =
new ClientWrapperClassLoader(
ClientClassloaderUtil.buildUserClassLoader(
... |
public static Builder newBuilder() {
return new Builder();
} | @Test void noRulesOk() {
HttpRuleSampler.newBuilder().build();
} |
public static <T> T createRMProxy(final Configuration configuration,
final Class<T> protocol) throws IOException {
long rmConnectWait =
configuration.getLong(
YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_MS,
YarnConfiguration.DEFAULT_RESOURCEMANAGER_CONNECT_MAX_WAIT_MS);
... | @Test
public void testDistributedProtocol() {
YarnConfiguration conf = new YarnConfiguration();
try {
ServerRMProxy.createRMProxy(conf, DistributedSchedulingAMProtocol.class);
} catch (Exception e) {
Assert.fail("DistributedSchedulingAMProtocol fail in non HA");
}
// HA is enabled
... |
public static ClusterAllocationDiskSettings create(boolean enabled, String low, String high, String floodStage) {
if (!enabled) {
return ClusterAllocationDiskSettings.create(enabled, null);
}
return ClusterAllocationDiskSettings.create(enabled, createWatermarkSettings(low, high, floo... | @Test
public void createAbsoluteValueWatermarkSettingsWithoutFloodStage() throws Exception {
ClusterAllocationDiskSettings clusterAllocationDiskSettings = ClusterAllocationDiskSettingsFactory.create(true, "10Gb", "5Gb", "");
assertThat(clusterAllocationDiskSettings).isInstanceOf(ClusterAllocationDi... |
@SuppressWarnings("checkstyle:MissingSwitchDefault")
@Override
protected void doCommit(TableMetadata base, TableMetadata metadata) {
int version = currentVersion() + 1;
CommitStatus commitStatus = CommitStatus.FAILURE;
/* This method adds no fs scheme, and it persists in HTS that way. */
final Stri... | @Test
void testDoCommitAppendSnapshotsInitialVersion() throws IOException {
List<Snapshot> testSnapshots = IcebergTestUtil.getSnapshots();
Map<String, String> properties = new HashMap<>(BASE_TABLE_METADATA.properties());
try (MockedStatic<TableMetadataParser> ignoreWriteMock =
Mockito.mockStatic(T... |
@GetMapping("/find/username")
@PreAuthorize("isAnonymous()")
public ResponseEntity<?> findUsername(@Validated PhoneVerificationDto.VerifyCodeReq request) {
return ResponseEntity.ok(SuccessResponse.from("user", authCheckUseCase.findUsername(request)));
} | @Test
@DisplayName("일반 회원의 휴대폰 번호로 아이디를 찾을 때 200 응답을 반환한다.")
void findUsername() throws Exception {
// given
given(authCheckUseCase.findUsername(new PhoneVerificationDto.VerifyCodeReq(inputPhone, code))).willReturn(
new AuthFindDto.FindUsernameRes(expectedUsername));
// ... |
public String[] getFunctions() {
return getFunctions(
catalogManager.getCurrentCatalog(), catalogManager.getCurrentDatabase());
} | @Test
void testGetBuiltInFunctions() {
Set<String> actual = new HashSet<>();
Collections.addAll(actual, functionCatalog.getFunctions());
Set<String> expected = new ModuleManager().listFunctions();
assertThat(actual.containsAll(expected)).isTrue();
} |
@Override
public BufferedReader getReader() {
try {
return source.getReader();
} catch (IOException e) {
throw new IllegalStateException("Failed to read", e);
}
} | @Test
public void getReader() throws IOException {
BufferedReader reader = new BufferedReader(new StringReader("foo"));
when(source.getReader()).thenReturn(reader);
assertThat(underTest.getReader()).isEqualTo(reader);
} |
@Internal
public void replaceAll(List<PTransformOverride> overrides) {
for (PTransformOverride override : overrides) {
replace(override);
}
checkNoMoreMatches(overrides);
} | @Test
public void testReplaceAll() {
pipeline.enableAbandonedNodeEnforcement(false);
pipeline.apply("unbounded", GenerateSequence.from(0));
pipeline.apply("bounded", GenerateSequence.from(0).to(100));
pipeline.replaceAll(
ImmutableList.of(
PTransformOverride.of(
ap... |
@Override
public OAuth2CodeDO consumeAuthorizationCode(String code) {
OAuth2CodeDO codeDO = oauth2CodeMapper.selectByCode(code);
if (codeDO == null) {
throw exception(OAUTH2_CODE_NOT_EXISTS);
}
if (DateUtils.isExpired(codeDO.getExpiresTime())) {
throw exceptio... | @Test
public void testConsumeAuthorizationCode_expired() {
// 准备参数
String code = "test_code";
// mock 数据
OAuth2CodeDO codeDO = randomPojo(OAuth2CodeDO.class).setCode(code)
.setExpiresTime(LocalDateTime.now().minusDays(1));
oauth2CodeMapper.insert(codeDO);
... |
public static SourceConfig validateUpdate(SourceConfig existingConfig, SourceConfig newConfig) {
SourceConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!ex... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Namespaces differ")
public void testMergeDifferentNamespace() {
SourceConfig sourceConfig = createSourceConfig();
SourceConfig newSourceConfig = createUpdatedSourceConfig("namespace", "Different");
... |
@Override
public void createNode(K8sNode node) {
checkNotNull(node, ERR_NULL_NODE);
K8sNode intNode;
K8sNode extNode;
K8sNode localNode;
K8sNode tunNode;
if (node.intgBridge() == null) {
String deviceIdStr = genDpid(deviceIdCounter.incrementAndGet());
... | @Test(expected = IllegalArgumentException.class)
public void testCreateDuplicateNode() {
target.createNode(MINION_1);
target.createNode(MINION_1);
} |
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (readError == null) {
try {
processSymbols(lineBuilder);
} catch (RangeOffsetConverter.RangeOffsetConverterException e) {
readError = new ReadError(Data.SYMBOLS, lineBuilder.getLine());
LOG.w... | @Test
public void read_symbols_with_two_references_on_the_same_line() {
SymbolsLineReader symbolsLineReader = newReader(newSymbol(
newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_2, OFFSET_3, RANGE_LABEL_1),
newSingleLineTextRangeWithExpectedLabel(LINE_2, OFFSET_0, OFFSET_1, RANGE_LABEL_2),
... |
public void convertQueueHierarchy(FSQueue queue) {
List<FSQueue> children = queue.getChildQueues();
final String queueName = queue.getName();
emitChildQueues(queueName, children);
emitMaxAMShare(queueName, queue);
emitMaxParallelApps(queueName, queue);
emitMaxAllocations(queueName, queue);
... | @Test
public void testQueueOrderingPolicy() throws Exception {
converter = builder.build();
String absolutePath =
new File("src/test/resources/fair-scheduler-orderingpolicy.xml")
.getAbsolutePath();
yarnConfig.set(FairSchedulerConfiguration.ALLOCATION_FILE,
FILE_PREFIX + absolute... |
static boolean isLocalhost(String hostname, String ipAddress) {
try {
return isLocalhostWithLoopbackIpAddress(hostname, ipAddress) || isLocalhostWithNonLoopbackIpAddress(ipAddress);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | @Test
public void shouldDetermineIfAddressIsLocal() throws UnknownHostException {
InetAddress local;
try {
local = InetAddress.getLocalHost();
}
catch (UnknownHostException e) {
local = InetAddress.getByName("localhost");
}
assertThat("Localh... |
@Override
public Long dbSize(RedisClusterNode node) {
return execute(node, RedisCommands.DBSIZE);
} | @Test
public void testDbSize() {
RedisClusterNode master = getFirstMaster();
Long size = connection.dbSize(master);
assertThat(size).isZero();
} |
public static Comparator<StructLike> forType(Types.StructType struct) {
return new StructLikeComparator(struct);
} | @Test
public void testList() {
assertComparesCorrectly(
Comparators.forType(Types.ListType.ofRequired(18, Types.IntegerType.get())),
ImmutableList.of(1, 1, 1),
ImmutableList.of(1, 1, 2));
assertComparesCorrectly(
Comparators.forType(Types.ListType.ofRequired(18, Types.IntegerT... |
public boolean isProactiveSupportEnabled() {
if (properties == null) {
return false;
}
return getMetricsEnabled();
} | @Test
public void isProactiveSupportEnabledHTTPSOnly() {
// Given
Properties serverProperties = new Properties();
serverProperties.setProperty(
BaseSupportConfig.CONFLUENT_SUPPORT_METRICS_ENDPOINT_SECURE_ENABLE_CONFIG, "true");
BaseSupportConfig supportConfig = new TestSupportConfig(serverProp... |
@Override
public int read(ByteBuffer dst) throws IOException {
if (state == State.CLOSING) return -1;
else if (!ready()) return 0;
//if we have unread decrypted data in appReadBuffer read that into dst buffer.
int read = 0;
if (appReadBuffer.position() > 0) {
rea... | @Test
public void testScatteringRead() throws IOException {
SSLEngine sslEngine = mock(SSLEngine.class);
SelectionKey selectionKey = mock(SelectionKey.class);
SslTransportLayer sslTransportLayer = spy(new SslTransportLayer(
"test-channel",
selectionKey,
... |
@Override
public Ingress ingress(String uid) {
checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_INGRESS_UID);
return k8sIngressStore.ingress(uid);
} | @Test
public void testGetIngressByUid() {
createBasicIngresses();
assertNotNull("Ingress did not match", target.ingress(INGRESS_UID));
assertNull("Ingress did not match", target.ingress(UNKNOWN_UID));
} |
@Override
public TypeDescriptor<Collection<T>> getEncodedTypeDescriptor() {
return new TypeDescriptor<Collection<T>>() {}.where(
new TypeParameter<T>() {}, getElemCoder().getEncodedTypeDescriptor());
} | @Test
public void testEncodedTypeDescriptor() throws Exception {
TypeDescriptor<Collection<Integer>> expectedTypeDescriptor =
new TypeDescriptor<Collection<Integer>>() {};
assertThat(TEST_CODER.getEncodedTypeDescriptor(), equalTo(expectedTypeDescriptor));
} |
@Field
public void setExtractFontNames(boolean extractFontNames) {
defaultConfig.setExtractFontNames(extractFontNames);
} | @Test
public void testFontNameExtraction() throws Exception {
PDFParserConfig config = new PDFParserConfig();
config.setExtractFontNames(true);
ParseContext pc = new ParseContext();
pc.set(PDFParserConfig.class, config);
XMLResult r = getXML("testPDFVarious.pdf", pc);
... |
@Override
public ValidationException getOrThrowException() throws ValidationException {
// We skip schema field validation errors because they are CDAP oriented and don't affect
// anything in our case
List<ValidationFailure> schemaValidationFailures = new ArrayList<>();
for (ValidationFailure failur... | @Test
public void getOrThrowException() {
/** arrange */
FailureCollectorWrapper failureCollectorWrapper = new FailureCollectorWrapper();
String errorMessage = "An error has occurred";
String expectedMessage = "Errors were encountered during validation. An error has occurred";
FailureCollectorWra... |
@Override
public AwsProxyResponse handle(Throwable ex) {
log.error("Called exception handler for:", ex);
// adding a print stack trace in case we have no appender or we are running inside SAM local, where need the
// output to go to the stderr.
ex.printStackTrace();
if (ex i... | @Test
void typedHandle_InvalidRequestEventException_500State() {
AwsProxyResponse resp = exceptionHandler.handle(new InvalidRequestEventException(INVALID_REQUEST_MESSAGE, null));
assertNotNull(resp);
assertEquals(500, resp.getStatusCode());
} |
@Override
public SessionStore<K, V> build() {
return new MeteredSessionStore<>(
maybeWrapCaching(maybeWrapLogging(storeSupplier.get())),
storeSupplier.metricsScope(),
keySerde,
valueSerde,
time);
} | @Test
public void shouldHaveChangeLoggingStoreWhenLoggingEnabled() {
setUp();
final SessionStore<String, String> store = builder
.withLoggingEnabled(Collections.emptyMap())
.build();
final StateStore wrapped = ((WrappedStateStore) store).wrapped();
ass... |
@Override
public boolean isGenerateSQLToken(final SQLStatementContext sqlStatementContext) {
return sqlStatementContext instanceof InsertStatementContext && (((InsertStatementContext) sqlStatementContext).getSqlStatement()).getOnDuplicateKeyColumns().isPresent();
} | @Test
void assertIsNotGenerateSQLTokenWithNotInsertStatement() {
assertFalse(generator.isGenerateSQLToken(mock(SelectStatementContext.class)));
} |
public void executeTaskLater(final Runnable r, final long timeDelay) {
if (!isStopped()) {
this.scheduledExecutorService.schedule(r, timeDelay, TimeUnit.MILLISECONDS);
} else {
logger.warn("PullMessageServiceScheduledThread has shutdown");
}
} | @Test
public void testExecuteTaskLater() {
Runnable runnable = mock(Runnable.class);
pullMessageService.executeTaskLater(runnable, defaultTimeout);
pullMessageService.makeStop();
pullMessageService.executeTaskLater(runnable, defaultTimeout);
verify(executorService, times(1))
... |
@Override
public boolean isSubTypeOf(Class<?> ancestor) {
checkNotNull(ancestor);
return id.isSubTypeOf(ancestor);
} | @Test
public void testSubTypeOf() {
DiscreteResource discrete = Resources.discrete(D1, P1, VLAN1).resource();
assertThat(discrete.isSubTypeOf(DeviceId.class), is(true));
assertThat(discrete.isSubTypeOf(PortNumber.class), is(true));
assertThat(discrete.isSubTypeOf(VlanId.class), is(t... |
public static String[] intersection(String[] arr1, String[] arr2) {
if (arr1 == null || arr2 == null) {
return null;
}
if (arr1.length == 0 || arr2.length == 0) {
return new String[0];
}
List<String> list = new ArrayList<>(Arrays.asList(arr1));
lis... | @Test
void testArrayIntersection() {
assertArrayEquals(arr("test"), StringUtil.intersection(arr("x", "test", "y", "z"), arr("a", "b", "test")));
assertArrayEquals(arr(""), StringUtil.intersection(arr("", "z"), arr("a", "")));
assertArrayEquals(arr(), StringUtil.intersection(arr("", "z"), arr... |
@Override
public ConnectClusterDetails clusterDetails() {
return clusterDetails;
} | @Test
public void kafkaClusterId() {
assertEquals(KAFKA_CLUSTER_ID, connectClusterState.clusterDetails().kafkaClusterId());
} |
public StepInstance getStepInstance(
String workflowId,
long workflowInstanceId,
long workflowRunId,
String stepId,
String stepAttempt) {
return getStepInstanceFieldByIds(
StepInstanceField.ALL,
workflowId,
workflowInstanceId,
workflowRunId,
step... | @Test
public void testGetStepInstanceWithInvalidAttempt() {
AssertHelper.assertThrows(
"cannot cast an invalid attempt id",
NumberFormatException.class,
"For input string: \"first\"",
() -> stepDao.getStepInstance(TEST_WORKFLOW_ID, 1, 1, "job1", "first"));
} |
@Udf
public <T> Boolean contains(
@UdfParameter final String jsonArray,
@UdfParameter final T val
) {
try (JsonParser parser = PARSER_FACTORY.createParser(jsonArray)) {
if (parser.nextToken() != START_ARRAY) {
return false;
}
while (parser.nextToken() != null) {
fi... | @Test
public void shouldReturnFalseOnEmptyArray() {
assertEquals(false, jsonUdf.contains("[]", true));
assertEquals(false, jsonUdf.contains("[]", false));
assertEquals(false, jsonUdf.contains("[]", null));
assertEquals(false, jsonUdf.contains("[]", 1.0));
assertEquals(false, ... |
@Override
public Collection<SQLToken> generateSQLTokens(final AlterTableStatementContext sqlStatementContext) {
String tableName = sqlStatementContext.getSqlStatement().getTable().getTableName().getIdentifier().getValue();
EncryptTable encryptTable = encryptRule.getEncryptTable(tableName);
C... | @Test
void assertChangeEncryptColumnGenerateSQLTokens() {
assertThrows(UnsupportedOperationException.class, () -> generator.generateSQLTokens(mockChangeColumnStatementContext()));
} |
public static boolean shouldLoadInIsolation(String name) {
return !(EXCLUDE.matcher(name).matches() && !INCLUDE.matcher(name).matches());
} | @Test
public void testAllowedRuntimeClasses() {
List<String> jsonConverterClasses = Arrays.asList(
"org.apache.kafka.connect.connector.policy.",
"org.apache.kafka.connect.connector.policy.AbstractConnectorClientConfigOverridePolicy",
"org.apache.kafka.connect.connector.po... |
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext,
final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon... | @Test
void assertNewInstanceForTCL() {
TCLStatement tclStatement = mock(TCLStatement.class);
when(sqlStatementContext.getSqlStatement()).thenReturn(tclStatement);
QueryContext queryContext = new QueryContext(sqlStatementContext, "", Collections.emptyList(), new HintValueContext(), mockConnec... |
public UUID getPhoneNumberIdentifier(final String phoneNumber) {
final GetItemResponse response = GET_PNI_TIMER.record(() -> dynamoDbClient.getItem(GetItemRequest.builder()
.tableName(tableName)
.key(Map.of(KEY_E164, AttributeValues.fromString(phoneNumber)))
.projectionExpression(ATTR_PHONE_... | @Test
void getPhoneNumberIdentifier() {
final String number = "+18005551234";
final String differentNumber = "+18005556789";
final UUID firstPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
final UUID secondPni = phoneNumberIdentifiers.getPhoneNumberIdentifier(number);
assertEquals... |
public FEELFnResult<List<BigDecimal>> invoke(@ParameterName( "list" ) List list, @ParameterName( "match" ) Object match) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
final List<BigDecimal> result = new A... | @Test
void invokeListNull() {
FunctionTestUtil.assertResultError(indexOfFunction.invoke((List) null, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(indexOfFunction.invoke(null, new Object()), InvalidParametersEvent.class);
} |
@Override
public Optional<WindowExpression> getWindowExpression() {
final Optional<WindowExpression> windowExpression = original.getWindowExpression();
final Optional<RefinementInfo> refinementInfo = original.getRefinementInfo();
// we only need to rewrite if we have a window expression and if we use emi... | @Test
public void shouldCreateNewSessionWindowWithZeroGracePeriodDefault() {
// Given:
when(windowExpression.getKsqlWindowExpression()).thenReturn(sessionWindow);
when(sessionWindow.getGracePeriod()).thenReturn(gracePeriodOptional);
when(gracePeriodOptional.isPresent()).thenReturn(false);
when(ses... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.