focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static RepositoryMetadataStore getInstance() {
return repositoryMetadataStore;
} | @Test
public void shouldReturnNullForMetadataIfPluginIdIsNonExistent() {
assertNull(RepositoryMetadataStore.getInstance().getMetadata("non-existent-plugin-id"));
} |
@Override
public GcsResourceId resolve(String other, ResolveOptions resolveOptions) {
checkState(
isDirectory(),
String.format("Expected the gcsPath is a directory, but had [%s].", gcsPath));
checkArgument(
resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE)
|| resol... | @Test
public void testResolve() {
// Tests for common gcs paths.
assertEquals(
toResourceIdentifier("gs://bucket/tmp/aa"),
toResourceIdentifier("gs://bucket/tmp/")
.resolve("aa", StandardResolveOptions.RESOLVE_FILE));
assertEquals(
toResourceIdentifier("gs://bucket/tmp/... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(0L == status.getLength()) {
return new NullInputStream(0L);
}
final Storage.Objects.Get request = sessi... | @Test
public void testReadCloseReleaseEntity() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final ... |
@Override
public synchronized void handle(ResourceEvent event) {
LocalResourceRequest req = event.getLocalResourceRequest();
LocalizedResource rsrc = localrsrc.get(req);
switch (event.getType()) {
case LOCALIZED:
if (useLocalCacheDirectoryManager) {
inProgressLocalResourcesMap.remove(req... | @Test
@SuppressWarnings("unchecked")
public void testReleaseWhileDownloading() throws Exception {
String user = "testuser";
DrainDispatcher dispatcher = null;
try {
Configuration conf = new Configuration();
dispatcher = createDispatcher(conf);
EventHandler<LocalizerEvent> localizerEven... |
public long identifier() {
return identifier;
} | @Test
void identifier() {
LocalComponentIdDrlSession retrieved = new LocalComponentIdDrlSession(basePath, identifier);
assertThat(retrieved.identifier()).isEqualTo(identifier);
} |
@Override
public MapperResult selectGroupInfoBySize(MapperContext context) {
String sql = "SELECT id, group_id FROM group_capacity WHERE id > ? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY";
return new MapperResult(sql,
CollectionUtils.list(context.getWhereParameter(FieldConstant.ID), contex... | @Test
void testSelectGroupInfoBySize() {
Object id = 1;
context.putWhereParameter(FieldConstant.ID, id);
MapperResult mapperResult = groupCapacityMapperByDerby.selectGroupInfoBySize(context);
assertEquals("SELECT id, group_id FROM group_capacity WHERE id > ? OFFSET 0 ROWS FETCH NEXT ... |
@Override
public ResponseHeader execute() throws SQLException {
switch (operationType) {
case BEGIN:
handleBegin();
break;
case SAVEPOINT:
handleSavepoint();
break;
case ROLLBACK_TO_SAVEPOINT:
... | @Test
void assertExecute() throws SQLException {
ProxyDatabaseConnectionManager databaseConnectionManager = mock(ProxyDatabaseConnectionManager.class);
when(connectionSession.getDatabaseConnectionManager()).thenReturn(databaseConnectionManager);
when(databaseConnectionManager.getConnectionSe... |
private ExitStatus run() {
try {
init();
return new Processor().processNamespace().getExitStatus();
} catch (IllegalArgumentException e) {
System.out.println(e + ". Exiting ...");
return ExitStatus.ILLEGAL_ARGUMENTS;
} catch (IOException e) {
System.out.println(e + ". Exiting... | @Test
public void testMoverFailedRetry() throws Exception {
// HDFS-8147
final Configuration conf = new HdfsConfiguration();
initConf(conf);
conf.set(DFSConfigKeys.DFS_MOVER_RETRY_MAX_ATTEMPTS_KEY, "2");
final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(3)
... |
public void restore(final List<Pair<byte[], byte[]>> backupCommands) {
// Delete the command topic
deleteCommandTopicIfExists();
// Create the command topic
KsqlInternalTopicUtils.ensureTopic(commandTopicName, serverConfig, topicClient);
// Restore the commands
restoreCommandTopic(backupComman... | @Test
public void shouldThrowWhenRestoreIsInterrupted() throws Exception {
// Given:
when(topicClient.isTopicExists(COMMAND_TOPIC_NAME)).thenReturn(false);
doThrow(new InterruptedException("fail")).when(future2).get();
// When:
final Exception e = assertThrows(
KsqlException.class,
... |
public void createControlFile( String filename, Object[] row, OraBulkLoaderMeta meta ) throws KettleException {
FileWriter fw = null;
try {
File controlFile = new File( getFileObject( filename, getTransMeta() ).getURL().getFile() );
// Need to ensure that the parent directory they set exists for th... | @Test
public void testCreateControlFile() throws Exception {
// Create a tempfile, so we can use the temp file path when we run the createControlFile method
String tempTrueControlFilepath = tempControlFile.getAbsolutePath() + "A.txt";
String expectedControlContents = "test";
OraBulkLoaderMeta oraBulkL... |
public static Validator mapWithDoubleValue() {
return (name, val) -> {
if (!(val instanceof String)) {
throw new ConfigException(name, val, "Must be a string");
}
final String str = (String) val;
final Map<String, String> map = KsqlConfig.parseStringAsMap(name, str);
map.forEa... | @Test
public void shouldThrowOnBadDoubleValueInMap() {
// Given:
final Validator validator = ConfigValidators.mapWithDoubleValue();
// When:
final Exception e = assertThrows(
ConfigException.class,
() -> validator.ensureValid("propName", "foo:abc")
);
// Then:
assertThat(... |
@Override
public ProcResult fetchResult()
throws AnalysisException {
BaseProcResult result = new BaseProcResult();
result.setNames(getMetadata());
final List<List<String>> computeNodesInfos = getClusterComputeNodesInfos();
for (List<String> computeNodesInfo : computeNode... | @Test
public void testWarehouse(@Mocked WarehouseManager warehouseManager) throws AnalysisException {
new Expectations() {
{
systemInfoService.getComputeNodeIds(anyBoolean);
result = Lists.newArrayList(1000L, 1001L);
}
};
new Expectati... |
@Override
public Set<Class<?>> classes() {
Set<Class<?>> output = new HashSet<>();
if (application != null) {
Set<Class<?>> clzs = application.getClasses();
if (clzs != null) {
for (Class<?> clz : clzs) {
if (!isIgnored(clz.getName())) {
... | @Test(description = "scan classes from Application only")
public void shouldScanClassesApplicationOnly() throws Exception {
assertEquals(scanner.classes().size(), 1);
assertTrue(scanner.classes().contains(ResourceInPackageA.class));
} |
@VisibleForTesting
static boolean[] parseOSName() {
boolean[] result = new boolean[] { false, false, false };
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("windows")) {
result[0] = true;
} else if (osName.contains("linux")) {
... | @Test
public void parseOSName() {
String old = System.getProperty("os.name");
try {
System.setProperty("os.name", "windows7");
Assert.assertTrue(SystemInfo.parseOSName()[0]);
System.setProperty("os.name", "linux123");
Assert.assertTrue(SystemInfo.parse... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(!session.getClient().setFileType(FTP.BINARY_FILE_TYPE)) {
throw new FTPException(session.getClient().getReplyCode(), session.ge... | @Test
public void testReadRange() throws Exception {
final Path test = new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
new FTPTouchFeature(session).touch(test, new TransferStatus());
final byte[] content = RandomUtils.nextBytes(2048)... |
public void cacheRuleData(final RuleData ruleData) {
Optional.ofNullable(ruleData).ifPresent(this::ruleAccept);
} | @Test
public void testCacheRuleData() throws NoSuchFieldException, IllegalAccessException {
RuleData firstCachedRuleData = RuleData.builder().id("1").selectorId(mockSelectorId1).sort(1).build();
BaseDataCache.getInstance().cacheRuleData(firstCachedRuleData);
ConcurrentHashMap<String, List<Ru... |
private MessageRouter getMessageRouter() {
MessageRouter messageRouter;
MessageRoutingMode messageRouteMode = conf.getMessageRoutingMode();
switch (messageRouteMode) {
case CustomPartition:
messageRouter = Objects.requireNonNull(conf.getCustomMessageRouter());
... | @Test
public void testRoundRobinPartitionMessageRouterImplInstance() throws NoSuchFieldException, IllegalAccessException {
ProducerConfigurationData producerConfigurationData = new ProducerConfigurationData();
producerConfigurationData.setMessageRoutingMode(MessageRoutingMode.RoundRobinPartition);
... |
public static void notNull(Object obj, String message) {
if (obj == null) {
throw new IllegalArgumentException(message);
}
} | @Test
void testNotNull2() {
Assertions.assertThrows(
IllegalStateException.class, () -> notNull(null, new IllegalStateException("null object")));
} |
@Override public HashSlotCursor16byteKey cursor() {
return new CursorLongKey2();
} | @Test
public void testCursor_advance_whenEmpty() {
HashSlotCursor16byteKey cursor = hsa.cursor();
assertFalse(cursor.advance());
} |
@Override
public TopicAssignment place(
PlacementSpec placement,
ClusterDescriber cluster
) throws InvalidReplicationFactorException {
RackList rackList = new RackList(random, cluster.usableBrokers());
throwInvalidReplicationFactorIfNonPositive(placement.numReplicas());
t... | @Test
public void testAllBrokersFenced() {
MockRandom random = new MockRandom();
StripedReplicaPlacer placer = new StripedReplicaPlacer(random);
assertEquals("All brokers are currently fenced.",
assertThrows(InvalidReplicationFactorException.class,
() -> place(pla... |
public static <T> CheckedSupplier<T> recover(CheckedSupplier<T> supplier,
CheckedFunction<Throwable, T> exceptionHandler) {
return () -> {
try {
return supplier.get();
} catch (Throwable throwable) {
return ... | @Test(expected = RuntimeException.class)
public void shouldRethrowException2() throws Throwable {
CheckedSupplier<String> callable = () -> {
throw new RuntimeException("BAM!");
};
CheckedSupplier<String> callableWithRecovery = CheckedFunctionUtils.recover(callable, IllegalArgumen... |
private void initialize() {
// NOTE: Do not create a new model or use the default application/module model here!
// Only the visible and only matching scope model can be injected, that is, module -> application -> framework.
// The converse is a one-to-many relationship and cannot be injected.
... | @Test
void testInitialize() {
ScopeModelAwareExtensionProcessor processor1 = new ScopeModelAwareExtensionProcessor(frameworkModel);
Assertions.assertEquals(processor1.getFrameworkModel(), frameworkModel);
Assertions.assertEquals(processor1.getScopeModel(), frameworkModel);
Assertions... |
public Plan validateReservationUpdateRequest(
ReservationSystem reservationSystem, ReservationUpdateRequest request)
throws YarnException {
ReservationId reservationId = request.getReservationId();
Plan plan = validateReservation(reservationSystem, reservationId,
AuditConstants.UPDATE_RESERV... | @Test
public void testUpdateReservationNormal() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 3);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
} catch (YarnException e) {
Assert.fail(e.getMess... |
private <T> RestResponse<T> get(final String path, final Class<T> type) {
return executeRequestSync(HttpMethod.GET,
path,
null,
r -> deserialize(r.getBody(), type),
Optional.empty());
} | @Test
public void shouldPostQueryRequest_chunkHandler_nonOkStatusCode() {
when(httpClientResponse.statusCode()).thenReturn(BAD_REQUEST.code());
ksqlTarget = new KsqlTarget(httpClient, socketAddress, localProperties, authHeader, HOST,
Collections.emptyMap(), RequestOptions.DEFAULT_TIMEOUT);
executo... |
@JsonIgnore
public List<Tag> deriveRuntimeTagPermits(StepRuntimeSummary runtimeSummary) {
List<Tag> runtimeTagPermits = new ArrayList<>();
Long stepConcurrency = runProperties.getStepConcurrency();
if (instanceStepConcurrency != null) { // instance_step_concurrency is enabled.
// if step_concurrency... | @Test
public void testDeriveRuntimeTagPermits() throws Exception {
WorkflowSummary summary =
loadObject("fixtures/parameters/sample-wf-summary-params.json", WorkflowSummary.class);
summary.setCorrelationId("correlation_id");
Tag t1 = new Tag();
t1.setName(Constants.MAESTRO_PREFIX + summary.ge... |
@Override
public List<Instance> getAllInstances(String serviceName) throws NacosException {
return getAllInstances(serviceName, new ArrayList<>());
} | @Test
void testGetAllInstances8() throws NacosException {
//given
String serviceName = "service1";
String groupName = "group1";
List<String> clusterList = Arrays.asList("cluster1", "cluster2");
//when
client.getAllInstances(serviceName, groupName, clusterList, false);... |
@Override
public void shutdown() {
scheduledExecutorService.shutdown();
try {
web3jService.close();
} catch (IOException e) {
throw new RuntimeException("Failed to close web3j service", e);
}
} | @Test
public void testStopExecutorOnShutdown() throws Exception {
web3j.shutdown();
verify(scheduledExecutorService).shutdown();
verify(service).close();
} |
@VisibleForTesting
protected KeyQueryMetadata getKeyQueryMetadata(final KsqlKey key) {
if (sharedRuntimesEnabled && kafkaStreams instanceof KafkaStreamsNamedTopologyWrapper) {
return ((KafkaStreamsNamedTopologyWrapper) kafkaStreams)
.queryMetadataForKey(storeName, key.getKey(), keySerializer, quer... | @Test
public void shouldUseNamedTopologyWhenSharedRuntimeIsEnabledForQueryMetadataForKey() {
// Given:
final KsLocator locator = new KsLocator(STORE_NAME, kafkaStreamsNamedTopologyWrapper, topology,
keySerializer, LOCAL_HOST_URL, true, "queryId");
// When:
locator.getKeyQueryMetadata(KEY);
... |
List<AlternativeInfo> calcAlternatives(final int s, final int t) {
// First, do a regular bidirectional route search
checkAlreadyRun();
init(s, 0, t, 0);
runAlgo();
final Path bestPath = extractPath();
if (!bestPath.isFound()) {
return Collections.emptyList();... | @Test
public void testCalcAlternatives() {
BaseGraph g = createTestGraph(em);
PMap hints = new PMap();
hints.putObject("alternative_route.max_weight_factor", 4);
hints.putObject("alternative_route.local_optimality_factor", 0.5);
hints.putObject("alternative_route.max_paths", ... |
public static String generateInstanceId(Instance instance) {
String instanceIdGeneratorType = instance.getInstanceIdGenerator();
if (StringUtils.isBlank(instanceIdGeneratorType)) {
instanceIdGeneratorType = Constants.DEFAULT_INSTANCE_ID_GENERATOR;
}
return INSTANCE.getInstanc... | @Test
void testGenerateInstanceId() {
Instance instance = new Instance();
instance.setServiceName("service");
instance.setClusterName("cluster");
instance.setIp("1.1.1.1");
instance.setPort(1000);
assertThat(InstanceIdGeneratorManager.generateInstanceId(instance), is(... |
@CheckForNull
public String get() {
// branches will be empty in CE
if (branchConfiguration.isPullRequest() || branches.isEmpty()) {
return null;
}
return Optional.ofNullable(getFromProperties()).orElseGet(this::loadWs);
} | @Test
public void get_uses_scanner_property_with_higher_priority() {
when(branchConfiguration.branchType()).thenReturn(BranchType.BRANCH);
when(branchConfiguration.branchName()).thenReturn(BRANCH_KEY);
when(newCodePeriodLoader.load(PROJECT_KEY, BRANCH_KEY)).thenReturn(createResponse(NewCodePeriods.NewCode... |
@Override
public void pluginJarAdded(BundleOrPluginFileDetails bundleOrPluginFileDetails) {
final GoPluginBundleDescriptor bundleDescriptor = goPluginBundleDescriptorBuilder.build(bundleOrPluginFileDetails);
try {
LOGGER.info("Plugin load starting: {}", bundleOrPluginFileDetails.file())... | @Test
void shouldCopyPluginToBundlePathAndInformRegistryAndUpdateTheOSGiManifestWhenAPluginIsAdded() throws Exception {
String pluginId = "testplugin.descriptorValidator";
File pluginJarFile = new File(pluginWorkDir, PLUGIN_JAR_FILE_NAME);
File expectedBundleDirectory = new File(bundleDir, P... |
public static String buildSplitScanQuery(
TableId tableId, SeaTunnelRowType rowType, boolean isFirstSplit, boolean isLastSplit) {
return buildSplitQuery(tableId, rowType, isFirstSplit, isLastSplit, -1, true);
} | @Test
public void testSplitScanQuery() {
String splitScanSQL =
SqlServerUtils.buildSplitScanQuery(
TableId.parse("db1.schema1.table1"),
new SeaTunnelRowType(
new String[] {"id"}, new SeaTunnelDataType[] {BasicTyp... |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
InvokeMode invokeMode = RpcUtils.getInvokeMode(invoker.getUrl(), invocation);
if (InvokeMode.SYNC == invokeMode) {
return syncInvoke(invoker, invocation);
} else {
return a... | @Test
public void testInvokeAsync() {
Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
Invoker invoker = DubboTestUtil.getDefaultMockInvoker();
when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString());
final Result result = mock(Result.class... |
public static MetricName name(Class<?> klass, String... names) {
return name(klass.getName(), names);
} | @Test
@SuppressWarnings("NullArgumentToVariableArgMethod")
public void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() throws Exception {
assertThat(name("one", (String)null))
.isEqualTo(MetricName.build("one"));
} |
public boolean isEmpty() {
if (isTailFirstUsage(currentTailPtr)) {
return currentHeadPtr.compareTo(currentTailPtr) == 0;
} else {
return currentHeadPtr.moveForward(1).compareTo(currentTailPtr) == 0;
}
} | @Test
public void newlyQueueIsEmpty() throws QueueException {
final QueuePool queuePool = QueuePool.loadQueues(tempQueueFolder, PAGE_SIZE, SEGMENT_SIZE);
final Queue queue = queuePool.getOrCreate("test");
assertTrue(queue.isEmpty(), "Freshly created queue must be empty");
} |
public static <T> @Nullable String getClassNameOrNull(@Nullable T value) {
if (value != null) {
return value.getClass().getName();
}
return null;
} | @Test
public void testGetClassNameOrNullClassName() {
assertEquals("java.lang.String", SingleStoreUtil.getClassNameOrNull("asd"));
} |
@Override
public void add(long key, String value) {
// fix https://github.com/crossoverJie/cim/issues/79
sortArrayMap.clear();
for (int i = 0; i < VIRTUAL_NODE_SIZE; i++) {
Long hash = super.hash("vir" + key + i);
sortArrayMap.add(hash,value);
}
sortAr... | @Test
public void getFirstNodeValue2() {
AbstractConsistentHash map = new SortArrayMapConsistentHash() ;
List<String> strings = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
strings.add("127.0.0." + i) ;
}
String process = map.process(strings,"zhangsan2... |
public void setSendIfNoneMatch(boolean sendIfNoneMatch) {
kp.put("sendIfNoneMatch",sendIfNoneMatch);
} | @Test
public void testSendIfNoneMatch() throws Exception {
fetcher().setSendIfNoneMatch(true);
CrawlURI curi = makeCrawlURI("http://localhost:7777/if-none-match");
fetcher().process(curi);
assertFalse(httpRequestString(curi).toLowerCase().contains("if-none-match: "));
... |
@Override
public int hashCode() {
return Objects.hash(
Arrays.hashCode(salt),
Arrays.hashCode(storedKey),
Arrays.hashCode(serverKey),
iterations
);
} | @Test
public void testEqualsAndHashCode() {
byte[] salt1 = {1, 2, 3};
byte[] storedKey1 = {4, 5, 6};
byte[] serverKey1 = {7, 8, 9};
int iterations1 = 1000;
byte[] salt2 = {1, 2, 3};
byte[] storedKey2 = {4, 5, 6};
byte[] serverKey2 = {7, 8, 9};
int ite... |
@BuildStep
AdditionalBeanBuildItem addMetrics(Optional<MetricsCapabilityBuildItem> metricsCapability, JobRunrBuildTimeConfiguration jobRunrBuildTimeConfiguration) {
if (metricsCapability.isPresent() && metricsCapability.get().metricsSupported(MetricsFactory.MICROMETER)) {
final AdditionalBeanBui... | @Test
void addMetricsDoesNotAddMetricsIfEnabledButNoMicroMeterSupport() {
final AdditionalBeanBuildItem metricsBeanBuildItem = jobRunrExtensionProcessor.addMetrics(Optional.of(new MetricsCapabilityBuildItem(toSupport -> false)), jobRunrBuildTimeConfiguration);
assertThat(metricsBeanBuildItem).isNul... |
public ImmutableSet<EntityDescriptor> resolve(GRN entity) {
// TODO: Replace entity excerpt usage with GRNDescriptors once we implemented GRN descriptors for every entity
final ImmutableMap<GRN, Optional<String>> entityExcerpts = contentPackService.listAllEntityExcerpts().stream()
// TOD... | @Test
@DisplayName("Try a regular depency resolve")
void resolve() {
final String TEST_TITLE = "Test Stream Title";
final EntityExcerpt streamExcerpt = EntityExcerpt.builder()
.type(ModelTypes.STREAM_V1)
.id(ModelId.of("54e3deadbeefdeadbeefaffe"))
... |
public static Logger verboseLogger() {
return VERBOSE_ANDROID_LOGGER;
} | @Test
public void verboseLoggerReturnsSameInstance() {
Logger logger1 = Loggers.verboseLogger();
Logger logger2 = Loggers.verboseLogger();
assertThat(logger1, sameInstance(logger2));
} |
private Main() {
// Utility Class.
} | @Test
public void runsAgainstRelease() throws Exception {
final File pwd = temp.newFolder();
Main.main(
String.format("--%s=5.5.0", UserInput.DISTRIBUTION_VERSION_PARAM),
String.format("--workdir=%s", pwd.getAbsolutePath())
);
} |
public static ShadowRouteEngine newInstance(final QueryContext queryContext) {
SQLStatement sqlStatement = queryContext.getSqlStatementContext().getSqlStatement();
if (sqlStatement instanceof InsertStatement) {
return createShadowInsertStatementRoutingEngine(queryContext);
}
... | @Test
void assertNewInstance() {
ShadowRouteEngine shadowInsertRouteEngine = ShadowRouteEngineFactory.newInstance(
new QueryContext(createInsertSqlStatementContext(), "", Collections.emptyList(), new HintValueContext(), mockConnectionContext(), mock(ShardingSphereMetaData.class)));
a... |
@Override
public void trace(String msg) {
logger.trace(msg);
} | @Test
void testMarkerTraceWithFormat() {
jobRunrDashboardLogger.trace(marker, "trace with {}", "format");
verify(slfLogger).trace(marker, "trace with {}", "format");
} |
@Override
public <T> @Nullable Schema schemaFor(TypeDescriptor<T> typeDescriptor) {
checkForDynamicType(typeDescriptor);
return ProtoSchemaTranslator.getSchema((Class<Message>) typeDescriptor.getRawType());
} | @Test
public void testRequiredPrimitiveSchema() {
Schema schema = new ProtoMessageSchema().schemaFor(TypeDescriptor.of(RequiredPrimitive.class));
assertEquals(REQUIRED_PRIMITIVE_SCHEMA, schema);
} |
public static String cleanHtmlTag(String content) {
return content.replaceAll(RE_HTML_MARK, "");
} | @Test
public void cleanHtmlTagTest() {
//非闭合标签
String str = "pre<img src=\"xxx/dfdsfds/test.jpg\">";
String result = HtmlUtil.cleanHtmlTag(str);
assertEquals("pre", result);
//闭合标签
str = "pre<img>";
result = HtmlUtil.cleanHtmlTag(str);
assertEquals("pre", result);
//闭合标签
str = "pre<img src=\"xxx/... |
public static List<String> computeNameParts(String loggerName) {
List<String> partList = new ArrayList<String>();
int fromIndex = 0;
while (true) {
int index = getSeparatorIndexOf(loggerName, fromIndex);
if (index == -1) {
partList.add(loggerName.substrin... | @Test
public void supportNestedClasses() {
List<String> witnessList = new ArrayList<String>();
witnessList.add("com");
witnessList.add("foo");
witnessList.add("Bar");
witnessList.add("Nested");
List<String> partList = LoggerNameUtil.computeNameParts("com.foo.Bar$Nest... |
@Override
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
//if (!descriptor.equals("Lorg/pf4j/Extension;")) {
if (!Type.getType(descriptor).getClassName().equals(Extension.class.getName())) {
return super.visitAnnotation(descriptor, visible);
}
... | @Test
void visitAnnotationShouldReturnExtensionAnnotationVisitor() {
ExtensionInfo extensionInfo = new ExtensionInfo("org.pf4j.asm.ExtensionInfo");
ClassVisitor extensionVisitor = new ExtensionVisitor(extensionInfo);
AnnotationVisitor returnedVisitor = extensionVisitor.visitAnnotation("Lorg... |
private JobMetrics getJobMetrics() throws IOException {
if (cachedMetricResults != null) {
// Metric results have been cached after the job ran.
return cachedMetricResults;
}
JobMetrics result = dataflowClient.getJobMetrics(dataflowPipelineJob.getJobId());
if (dataflowPipelineJob.getState().... | @Test
public void testIgnoreDistributionButGetCounterUpdates() throws IOException {
AppliedPTransform<?, ?, ?> myStep = mock(AppliedPTransform.class);
when(myStep.getFullName()).thenReturn("myStepName");
BiMap<AppliedPTransform<?, ?, ?>, String> transformStepNames = HashBiMap.create();
transformStepNa... |
public static String buildURIFromPattern(String pattern, List<Parameter> parameters) {
if (parameters != null) {
// Browse parameters and choose between template or query one.
for (Parameter parameter : parameters) {
String wadlTemplate = "{" + parameter.getName() + "}";
... | @Test
void testBuildURIFromPatternWithNoParameters() {
String pattern = "http://localhost:8080/blog/{year}/{month}";
try {
String uri = URIBuilder.buildURIFromPattern(pattern, new ArrayList<Parameter>());
} catch (NullPointerException npe) {
fail("buildURIFromPattern should not fa... |
@Override
public void publish(ScannerReportWriter writer) {
AbstractProjectOrModule rootProject = moduleHierarchy.root();
ScannerReport.Metadata.Builder builder = ScannerReport.Metadata.newBuilder()
.setAnalysisDate(projectInfo.getAnalysisDate().getTime())
// Here we want key without branch
... | @Test
public void should_not_crash_when_scm_provider_does_not_support_relativePathFromScmRoot() {
ScmProvider fakeScmProvider = new ScmProvider() {
@Override
public String key() {
return "foo";
}
};
when(scmConfiguration.provider()).thenReturn(fakeScmProvider);
underTest.pub... |
@Override
public Map<String, String> getSourcesMap(final CompilationDTO<RegressionModel> compilationDTO) {
logger.trace("getKiePMMLModelWithSources {} {} {} {}", compilationDTO.getPackageName(),
compilationDTO.getFields(),
compilationDTO.getModel(),
... | @Test
void getKiePMMLModelWithSources() throws Exception {
final PMML pmml = TestUtils.loadFromFile(SOURCE_1);
assertThat(pmml).isNotNull();
assertThat(pmml.getModels()).hasSize(1);
assertThat(pmml.getModels().get(0)).isInstanceOf(RegressionModel.class);
RegressionModel regre... |
static List<Order> getImplicitOrderBy(StructuredQuery query) {
List<OrderByFieldPath> expectedImplicitOrders = new ArrayList<>();
if (query.hasWhere()) {
fillInequalityFields(query.getWhere(), expectedImplicitOrders);
}
Collections.sort(expectedImplicitOrders);
if (expectedImplicitOrders.strea... | @Test
public void getImplicitOrderBy_nameInWhere() {
StructuredQuery.Builder builder = testQuery.toBuilder();
builder
.getWhereBuilder()
.getCompositeFilterBuilder()
.addFilters(
Filter.newBuilder()
.setFieldFilter(
FieldFilter.newBuilder... |
@Override
public <E extends Exception> Job getOrCreateJob(
JobID jobId,
SupplierWithException<? extends JobTable.JobServices, E> jobServicesSupplier)
throws E {
JobOrConnection job = jobs.get(jobId);
if (job == null) {
job = new JobOrConnection(jobId,... | @Test
void connectJob_Connected_Fails() {
final JobTable.Job job = jobTable.getOrCreateJob(jobId, DEFAULT_JOB_SERVICES_SUPPLIER);
connectJob(job, ResourceID.generate());
assertThatThrownBy(() -> connectJob(job, ResourceID.generate()))
.isInstanceOf(IllegalStateException.cla... |
public static TermQueryBuilder termQuery(String name, String value) {
return new TermQueryBuilder(name, value);
} | @Test
public void testTermQuery() throws Exception {
assertEquals("{\"term\":{\"k\":\"aaaa\"}}",
toJson(QueryBuilders.termQuery("k", "aaaa")));
assertEquals("{\"term\":{\"aaaa\":\"k\"}}",
toJson(QueryBuilders.termQuery("aaaa", "k")));
assertEquals("{\"term\":{... |
BrokerResponse getQueueResponse(String queueName) throws IOException {
String queryUrl = getQueueEndpoint(messageVpn, queueName);
HttpResponse response = executeGet(new GenericUrl(baseUrl + queryUrl));
return BrokerResponse.fromHttpResponse(response);
} | @Test
public void testExecuteStatus3xx() {
MockHttpTransport transport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttp... |
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 SessionWindow ot... | @Test
public void shouldOverlapIfOtherWindowStartIsWithinThisWindow() {
/*
* This: [-------]
* Other: [-------]
*/
assertTrue(window.overlap(new SessionWindow(start, end + 1)));
assertTrue(window.overlap(new SessionWindow(start, 150)));
ass... |
@Override
public void register(ThreadPoolPlugin plugin) {
} | @Test
public void testRegister() {
manager.register(new TestPlugin());
Assert.assertTrue(isEmpty(manager));
} |
@Nullable
public static EpoxyModel<?> getModelFromPayload(List<Object> payloads, long modelId) {
if (payloads.isEmpty()) {
return null;
}
for (Object payload : payloads) {
DiffPayload diffPayload = (DiffPayload) payload;
if (diffPayload.singleModel != null) {
if (diffPayload.si... | @Test
public void getSingleModelsFromMultipleDiffPayloads() {
TestModel model1 = new TestModel();
DiffPayload diffPayload1 = diffPayloadWithModels(model1);
TestModel model2 = new TestModel();
DiffPayload diffPayload2 = diffPayloadWithModels(model2);
List<Object> payloads = payloadsWithDiffPayloa... |
@Override
public void doWork() {
pollOnce(Long.MAX_VALUE);
} | @Test
public void testShouldCallCompletionHandlerWithDisconnectedResponseWhenNodeNotReady() {
final AbstractRequest.Builder<?> request = new StubRequestBuilder<>();
final Node node = new Node(1, "", 8080);
final RequestAndCompletionHandler handler =
new RequestAndCompletionHandle... |
public void start() {
configService.addListener(configListener);
interfaceService.addListener(interfaceListener);
setUpConnectivity();
} | @Test
public void testConnectionSetup() {
reset(intentSynchronizer);
// Setup the expected intents
for (Intent intent : intentList) {
intentSynchronizer.submit(eqExceptId(intent));
}
replay(intentSynchronizer);
// Running the interface to be tested.
... |
public static String getPathWithoutScheme(Path path) {
return path.toUri().getPath();
} | @Test
public void testGetPathWithoutSchemaThatContainsSchema() {
final Path path = new Path("file:///foo/bar/baz");
final String output = HadoopUtils.getPathWithoutScheme(path);
assertEquals("/foo/bar/baz", output);
} |
public void inject(Inspector inspector, Inserter inserter) {
if (inspector.valid()) {
injectValue(inserter, inspector, null);
}
} | @Test
public void injectIntoArray() {
f2.slime1.setArray();
inject(f1.empty.get(), new ArrayInserter(f2.slime1.get()));
inject(f1.nixValue.get(), new ArrayInserter(f2.slime1.get()));
inject(f1.boolValue.get(), new ArrayInserter(f2.slime1.get()));
inject(f1.longValue.get(), ne... |
public List<String> getPoints() {
return Collections.unmodifiableList(points);
} | @Test
void getPointsShouldReturnEmptyListWhenNotSet() {
ExtensionInfo info = new ExtensionInfo("org.pf4j.asm.ExtensionInfo");
assertTrue(info.getPoints().isEmpty());
} |
@Override
public JobManagerRunner get(JobID jobId) {
assertJobRegistered(jobId);
return this.jobManagerRunners.get(jobId);
} | @Test
void testGetOnNonExistingJobManagerRunner() {
assertThatThrownBy(() -> testInstance.get(new JobID()))
.isInstanceOf(NoSuchElementException.class);
} |
@Override
public Result apply(String action, Class<? extends Validatable> aClass, String resource, String resourceToOperateWithin) {
if (matchesAction(action) && matchesType(aClass) && matchesResource(resource)) {
return Result.DENY;
}
if (isRequestForElasticAgentProfiles(aClass... | @Test
void forAdministerOfWildcardDefinedClusterProfile() {
Deny directive = new Deny("administer", "cluster_profile", "team1_*");
Result viewAllElasticAgentProfiles = directive.apply("view", ElasticProfile.class, "*", null);
Result viewAllElasticAgentProfilesUnderTeam1 = directive.apply("v... |
@Override
public RemotingCommand processRequest(final ChannelHandlerContext ctx, RemotingCommand request)
throws RemotingCommandException {
final long beginTimeMills = this.brokerController.getMessageStore().now();
request.addExtFieldIfNotExist(BORN_TIME, String.valueOf(System.currentTimeMil... | @Test
public void testProcessRequest_whenTimerWheelIsFalse() throws RemotingCommandException {
MessageStoreConfig messageStoreConfig = new MessageStoreConfig();
messageStoreConfig.setTimerWheelEnable(false);
when(messageStore.getMessageStoreConfig()).thenReturn(messageStoreConfig);
f... |
@VisibleForTesting
boolean applyRaisingException() throws Exception {
Boolean outcome = apply();
if (thrown != null) {
throw thrown;
}
return outcome;
} | @Test
public void testReadFailure() throws Throwable {
int threshold = 50;
SDKStreamDrainer drainer = new SDKStreamDrainer("s3://example/",
new FakeSDKInputStream(BYTES, threshold),
false,
BYTES,
EMPTY_INPUT_STREAM_STATISTICS, "test");
intercept(IOException.class, "", () ->... |
@Override
public String getFileChecksum(Path sourceFile)
throws IOException {
FileSystem fs = sourceFile.getFileSystem(this.conf);
try (FSDataInputStream in = fs.open(sourceFile)) {
return this.checksum.computeChecksum(in);
}
} | @Test(expected = FileNotFoundException.class)
public void testNonexistantFileChecksum() throws Exception {
Path file = new Path(TEST_ROOT_DIR, "non-existant-file");
client.getFileChecksum(file);
} |
public static InMemorySorter create(Options options) {
return new InMemorySorter(options);
} | @Test
public void testSingleElement() throws Exception {
SorterTestUtils.testSingleElement(InMemorySorter.create(new InMemorySorter.Options()));
} |
@Override
public void start() {
if (embeddedDatabase == null) {
String jdbcUrl = config.get(JDBC_URL.getKey()).get();
if (startsWith(jdbcUrl, URL_PREFIX)) {
embeddedDatabase = createEmbeddedDatabase();
embeddedDatabase.start();
}
}
} | @Test
public void should_not_start_mem_h2_database() {
settings.setProperty(JDBC_URL.getKey(), "jdbc:h2:mem");
EmbeddedDatabase embeddedDatabase = mock(EmbeddedDatabase.class);
EmbeddedDatabaseFactory databaseFactory = new EmbeddedDatabaseFactory(settings.asConfig(), system2) {
@Override
Emb... |
public static Optional<Object> getAdjacentValue(Type type, Object value, boolean isPrevious)
{
if (!type.isOrderable()) {
throw new IllegalStateException("Type is not orderable: " + type);
}
requireNonNull(value, "value is null");
if (type.equals(BIGINT) || type instance... | @Test
public void testNextValueForOtherType()
{
assertThat(getAdjacentValue(VARCHAR, "anystr", false))
.isEmpty();
assertThat(getAdjacentValue(BOOLEAN, true, false))
.isEmpty();
assertThat(getAdjacentValue(TIME, 123L, false))
.isEmpty();
... |
@WithSpan
@Override
public QueryResult doRun(SearchJob job, Query query, ESGeneratedQueryContext queryContext) {
if (query.searchTypes().isEmpty()) {
return QueryResult.builder()
.query(query)
.searchTypes(Collections.emptyMap())
.e... | @Test
public void executesSearchForEmptySearchTypes() {
final Query query = Query.builder()
.id("query1")
.query(ElasticsearchQueryString.of(""))
.timerange(RelativeRange.create(300))
.build();
final Search search = Search.builder().que... |
public static String buildPopRetryTopic(String topic, String cid, boolean enableRetryV2) {
if (enableRetryV2) {
return buildPopRetryTopicV2(topic, cid);
}
return buildPopRetryTopicV1(topic, cid);
} | @Test
public void testBuildPopRetryTopic() {
assertThat(KeyBuilder.buildPopRetryTopicV2(topic, group)).isEqualTo(MixAll.RETRY_GROUP_TOPIC_PREFIX + group + "+" + topic);
} |
@Override
public String getKeyId() {
return this.keyId;
} | @Test
void shouldGetKeyIdFromJwk() {
assertTrue(StringUtils.hasText(service.getKeyId()));
} |
public void watch(File file) throws IOException {
String dirString;
if (file.isFile()) {
dirString = file.getParentFile().getAbsolutePath();
} else {
throw new IOException(file.getName() + " is not a file");
}
if (dirString == null) {
dirString = "/";
}
Path dir = FileSys... | @Test
void test() throws IOException, InterruptedException {
assertNull(fileChanged);
assertEquals(0, numChanged.get());
// create new file
File file1 = new File(tmpDir.toFile(), "test1");
file1.createNewFile();
File file2 = new File(tmpDir.toFile(), "test2");
file2.createNewFile();
... |
void startup(@Observes StartupEvent event) {
if (storageProviderMetricsBinderInstance.isResolvable()) {
storageProviderMetricsBinderInstance.get();
LOGGER.debug("JobRunr StorageProvider MicroMeter Metrics enabled");
}
if (backgroundJobServerMetricsBinderInstance.isResolva... | @Test
void metricsStarterDoesNotStartBackgroundJobServerMetricsBinderIfNotAvailable() {
jobRunrMetricsStarter.startup(new StartupEvent());
verify(backgroundJobServerMetricsBinderInstance, never()).get();
} |
@Override
public Optional<CompletableFuture<TaskManagerLocation>> getTaskManagerLocation(
ExecutionVertexID executionVertexId) {
return inputsLocationsRetriever
.getTaskManagerLocation(executionVertexId)
.filter(future -> future.isDone() && !future.isCompletedExce... | @Test
void testNoInputLocation() {
TestingInputsLocationsRetriever originalLocationRetriever = getOriginalLocationRetriever();
InputsLocationsRetriever availableInputsLocationsRetriever =
new AvailableInputsLocationsRetriever(originalLocationRetriever);
assertThat(availableIn... |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final String msg = new String(rawMessage.getPayload(), charset);
try (Timer.Context ignored = this.decodeTime.time()) {
final ResolvableInetSocketAddress address = rawMessage.getRemoteAddress();
f... | @Test
public void testIssue3502() throws Exception {
// https://github.com/Graylog2/graylog2-server/issues/3502
final RawMessage rawMessage = buildRawMessage("<6>0 2017-02-15T16:01:07.000+01:00 hostname test - - - test 4");
final Message message = codec.decode(rawMessage);
assertNo... |
@Override
public void write(Object object) throws IOException {
objectOutputStream.writeObject(object);
objectOutputStream.flush();
preventMemoryLeak();
} | @Test
public void writesToUnderlyingObjectOutputStream() throws IOException {
// given
ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2);
String object = "foo";
// when
objectWriter.write(object);
// then
verify(objectOutputStream).writeObjectOverride(objec... |
public static CharSequence escapeCsv(CharSequence value) {
return escapeCsv(value, false);
} | @Test
public void escapeCsvWithCarriageReturn() {
CharSequence value = "some text\r more text";
CharSequence expected = "\"some text\r more text\"";
escapeCsv(value, expected);
} |
public static void main(String[] args) throws Exception {
String usage = "Usage: MapFile inFile outFile";
if (args.length != 2) {
System.err.println(usage);
System.exit(-1);
}
String in = args[0];
String out = args[1];
Configuration conf = new Configuration();
File... | @Test
public void testMainMethodMapFile() {
String inFile = "mainMethodMapFile.mapfile";
String path = new Path(TEST_DIR, inFile).toString();
String[] args = { path, path };
MapFile.Writer writer = null;
try {
writer = createWriter(inFile, IntWritable.class, Text.class);
writer.append(... |
@Override
protected boolean isStepCompleted(@NonNull Context context) {
return SetupSupport.isThisKeyboardSetAsDefaultIME(context);
} | @Test
public void testKeyboardEnabledButNotDefault() {
final String flatASKComponent =
new ComponentName(BuildConfig.APPLICATION_ID, SoftKeyboard.class.getName())
.flattenToString();
Settings.Secure.putString(
getApplicationContext().getContentResolver(),
Settings.Secure.EN... |
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) {
FunctionConfig mergedConfig = existingConfig.toBuilder().build();
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
... | @Test
public void testMergeDifferentParallelism() {
FunctionConfig functionConfig = createFunctionConfig();
FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("parallelism", 101);
FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig);... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() != 2) {
onInvalidDataReceived(device, data);
return;
}
final int interval = data.getIntValue(Data.FORMAT_UINT16_LE, 0);
onMeasurementIntervalRece... | @Test
public void onInvalidDataReceived() {
final ProfileReadResponse response = new MeasurementIntervalDataCallback() {
@Override
public void onMeasurementIntervalReceived(@NonNull final BluetoothDevice device, final int interval) {
called = true;
}
};
called = false;
final Data data = new Data(... |
@Override
public boolean isGenerateSQLToken(final SQLStatementContext sqlStatementContext) {
return sqlStatementContext instanceof UpdateStatementContext
&& encryptRule.findEncryptTable(((TableAvailable) sqlStatementContext).getTablesContext().getSimpleTables().iterator().next().getTableName... | @Test
void assertIsGenerateSQLTokenUpdateSQLSuccess() {
assertTrue(tokenGenerator.isGenerateSQLToken(updateStatementContext));
} |
public static String generateResourceId(
String baseString,
Pattern illegalChars,
String replaceChar,
int targetLength,
DateTimeFormatter timeFormat) {
// first, make sure the baseString, typically the test ID, is not empty
checkArgument(baseString.length() != 0, "baseString cannot... | @Test
public void testGenerateResourceIdShouldReplaceUpperCaseLettersWithLowerCase() {
String testBaseString = "Test-Instance";
String actual =
generateResourceId(
testBaseString,
ILLEGAL_INSTANCE_CHARS,
REPLACE_INSTANCE_CHAR,
MAX_INSTANCE_ID_LENGTH,
... |
public Rectangle getBounds() {
double minX = Double.MAX_VALUE;
double minY = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
double maxY = Double.MIN_VALUE;
for (LineSegment segment : this.segments) {
minX = Math.min(minX, Math.min(segment.start.x, segment.end.x));... | @Test
public void boundsTest() {
Point point1 = new Point(0, 0);
Point point2 = new Point(1, 0);
Point point3 = new Point(1, 1);
LineString lineString = new LineString();
lineString.segments.add(new LineSegment(point1, point2));
lineString.segments.add(new LineSegmen... |
public SampleResult mergeSampleResult(SampleResult sampleCollectResult, List<SampleResult> sampleResults) {
SampleResult mergeResult = new SampleResult();
Map<String, String> listenersGroupkeyStatus;
if (sampleCollectResult.getLisentersGroupkeyStatus() == null || sampleCollectResult.getLisenters... | @Test
void testMergeSampleResult() throws Exception {
SampleResult sampleResult1 = new SampleResult();
Map<String, String> listener1 = new HashMap<>();
listener1.put("config1", "md51123");
listener1.put("config11", "md5123123");
sampleResult1.setLisentersGroupkeyStatus(listen... |
public BackgroundException map(HttpResponse response) throws IOException {
final S3ServiceException failure;
if(null == response.getEntity()) {
failure = new S3ServiceException(response.getStatusLine().getReasonPhrase());
}
else {
EntityUtils.updateEntity(response... | @Test
public void testAlgorithmFailure() {
assertEquals("EC AlgorithmParameters not available. Please contact your web hosting service provider for assistance.",
new S3ExceptionMappingService().map(new S3ServiceException(
new SSLException(
new RuntimeException... |
public static String formatLocalizedErrorMessage(Message localizedErrorMessage, Locale locale) {
var bundle = ResourceBundle.getBundle(BUNDLE, locale);
var localizedMessage = bundle.getString(localizedErrorMessage.messageKey());
var key = localizedErrorMessage.messageKey();
if (!key.isBlank()) {
... | @Test
void test_negotiatePreferredLocales_errorWithContent() {
var errorMessage = new Message("error.badRedirect", String.valueOf(BASE_URI));
var locale = Locale.GERMANY;
var result = LocaleUtils.formatLocalizedErrorMessage(errorMessage, locale);
var expected =
"Ungültige redirect_uri='%s'.... |
@Override
public TokenIdent cancelToken(Token<TokenIdent> token,
String canceller) throws IOException {
ByteArrayInputStream buf = new ByteArrayInputStream(token.getIdentifier());
DataInputStream in = new DataInputStream(buf);
TokenIdent id = createIdentifier();
id.readFields(in);
syncLocal... | @SuppressWarnings("unchecked")
@Test
public void testNodeUpAferAWhile() throws Exception {
for (int i = 0; i < TEST_RETRIES; i++) {
String connectString = zkServer.getConnectString();
Configuration conf = getSecretConf(connectString);
DelegationTokenManager tm1 = new DelegationTokenManager(con... |
@Override
public <T> Future<T> submit(Callable<T> callable) {
return schedule(callable, 0, TimeUnit.SECONDS);
} | @Test
public void submit() throws Exception {
CountTask task = new CountTask();
ControllableScheduler scheduler = new ControllableScheduler();
scheduler.submit(task);
assertFalse(scheduler.schedulerIsIdle());
scheduler.runNextPendingCommand();
assertEquals(1, task.runTimes());
assertTrue(s... |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldHandleAllSortsOfLiterals() {
// Given:
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
ImmutableList.of(COL1, COL0),
ImmutableList.of(
new LongLiteral(2L),
new StringLiteral("str"))
);
// When:
executor.execute... |
@VisibleForTesting
static boolean hasEnoughCurvature(final int[] xs, final int[] ys, final int middlePointIndex) {
// Calculate the radianValue formed between middlePointIndex, and one point in either
// direction
final int startPointIndex = middlePointIndex - CURVATURE_NEIGHBORHOOD;
final int startX ... | @Test
public void testHasEnoughCurvature9Degrees() {
final int[] Xs = new int[3];
final int[] Ys = new int[3];
// https://www.triangle-calculator.com/?what=&q=A%3D171%2C+b%3D100%2C+c%3D100&submit=Solve
// A[100; 0] B[0; 0] C[198.769; 15.643]
Xs[0] = 0;
Ys[0] = 0;
Xs[1] = 100;
Ys[1] ... |
public static String getMaskedStatement(final String query) {
try {
final ParseTree tree = DefaultKsqlParser.getParseTree(query);
return new Visitor().visit(tree);
} catch (final Exception | StackOverflowError e) {
return fallbackMasking(query);
}
} | @Test
public void shouldMaskInsertStatement() {
// Given
final String query = "--this is a comment. \n"
+ "INSERT INTO foo (KEY_COL, COL_A) VALUES (\"key\", \"A\");";
// When
final String maskedQuery = QueryMask.getMaskedStatement(query);
// Then
final String expected = "INSERT INTO ... |
public String getTopicName(AsyncMockDefinition definition, EventMessage eventMessage) {
logger.debugf("AsyncAPI Operation {%s}", definition.getOperation().getName());
// Produce service name part of topic name.
String serviceName = definition.getOwnerService().getName().replace(" ", "");
servic... | @Test
void testTopicNameWithPart() {
AmazonSNSProducerManager producerManager = new AmazonSNSProducerManager();
Service service = new Service();
service.setName("Pastry orders API");
service.setVersion("0.1.0");
Operation operation = new Operation();
operation.setName("SUBSCRIBE... |
public static Sensor processLatencySensor(final String threadId,
final StreamsMetricsImpl streamsMetrics) {
final Sensor sensor =
streamsMetrics.threadLevelSensor(threadId, PROCESS + LATENCY_SUFFIX, RecordingLevel.INFO);
final Map<String, String>... | @Test
public void shouldGetProcessLatencySensor() {
final String operationLatency = "process" + LATENCY_SUFFIX;
final String avgLatencyDescription = "The average process latency";
final String maxLatencyDescription = "The maximum process latency";
when(streamsMetrics.threadLevelSenso... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.