focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Builder newBuilder() { return new Builder(); }
@Test public void testBuilderThrowsExceptionWhenHeartbeatMillisMissing() { assertThrows( "heartbeatMillis", IllegalStateException.class, () -> PartitionMetadata.newBuilder() .setPartitionToken(PARTITION_TOKEN) .setParentTokens(Sets.newHashSet(PAR...
public static int getXpForLevel(int level) { if (level < 1 || level > MAX_VIRT_LEVEL) { throw new IllegalArgumentException(level + " is not a valid level"); } // XP_FOR_LEVEL[0] is XP for level 1 return XP_FOR_LEVEL[level - 1]; }
@Test(expected = IllegalArgumentException.class) public void testGetXpForHighLevel() { int xp = Experience.getXpForLevel(Integer.MAX_VALUE); }
@GetMapping("") @RequiresPermissions("system:dict:list") public ShenyuAdminResult queryDicts(final String type, final String dictCode, final String dictName, @RequestParam @NotNull final Integer currentPage, @RequestParam @NotNull f...
@Test public void testQueryDicts() throws Exception { final PageParameter pageParameter = new PageParameter(); final ShenyuDictQuery shenyuDictQuery = new ShenyuDictQuery("1", "t", "t_n", pageParameter); final CommonPager<ShenyuDictVO> commonPager = new CommonPager<>(pageParameter, Collectio...
@PATCH @Path("/{connector}/config") public Response patchConnectorConfig(final @PathParam("connector") String connector, final @Context HttpHeaders headers, final @Parameter(hidden = true) @QueryParam("forward") Boolean forward, ...
@Test public void testPatchConnectorConfigLeaderRedirect() throws Throwable { final ArgumentCaptor<Callback<Herder.Created<ConnectorInfo>>> cb = ArgumentCaptor.forClass(Callback.class); expectAndCallbackNotLeaderException(cb) .when(herder).patchConnectorConfig(eq(CONNECTOR_NAME), eq(...
private Map<String, List<URIRegisterDTO>> buildData(final Collection<URIRegisterDTO> dataList) { Map<String, List<URIRegisterDTO>> resultMap = new HashMap<>(8); for (URIRegisterDTO dto : dataList) { String contextPath = dto.getContextPath(); String key = StringUtils.isNotEmpty(co...
@Test public void testBuildData() { try { List<URIRegisterDTO> list = new ArrayList<>(); list.add(URIRegisterDTO.builder().appName("test1").build()); list.add(URIRegisterDTO.builder().appName("test2").build()); Method testMethod = uriRegisterExecutorSubscriber...
@Override public void scanLedgers(OffloadedLedgerMetadataConsumer consumer, Map<String, String> offloadDriverMetadata) throws ManagedLedgerException { BlobStoreLocation bsKey = getBlobStoreLocation(offloadDriverMetadata); String endpoint = bsKey.getEndpoint(); String readBucket =...
@Test(timeOut = 600000) // 10 minutes. public void testScanLedgers() throws Exception { ReadHandle toWrite = buildReadHandle(DEFAULT_BLOCK_SIZE, 3); LedgerOffloader offloader = getOffloader(); UUID uuid = UUID.randomUUID(); offloader.offload(toWrite, uuid, new HashMap<>()).get(); ...
public int[] findMatchingLines(List<String> left, List<String> right) { int[] index = new int[right.size()]; int dbLine = left.size(); int reportLine = right.size(); try { PathNode node = new MyersDiff<String>().buildPath(left, right); while (node.prev != null) { PathNode prevNode ...
@Test public void shouldDetectNewLinesInMiddleOfFile() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); database.add("line - 3"); List<String> report = new ArrayList<>(); report.add("line - 0"); report.add("line...
@Override public String pathPattern() { return buildExtensionPathPattern(scheme) + "/{name}"; }
@Test void shouldBuildPathPatternCorrectly() { var scheme = Scheme.buildFromType(FakeExtension.class); var getHandler = new ExtensionGetHandler(scheme, client); var pathPattern = getHandler.pathPattern(); assertEquals("/apis/fake.halo.run/v1alpha1/fakes/{name}", pathPattern); }
protected void writeDetailsAsHtml(final RouteStatistic routeStatistic, final File outputPath) throws IOException { Map<String, Object> data = new HashMap<>(); data.put("route", routeStatistic); data.put("eips", routeStatistic.getEipStatisticMap().entrySet()); String rendered = Template...
@Test public void testWriteDetailsAsHtml() throws IllegalAccessException, IOException { @SuppressWarnings("unchecked") Map<String, RouteStatistic> routeStatisticMap = (Map<String, RouteStatistic>) FieldUtils.readDeclaredField(processor, "routeStatisticMap", true); File outp...
public void batchOn(Runnable runnable, ParSeqBasedFluentClient... fluentClients) throws Exception { List<ParSeqBasedFluentClient> batchedClients = fluentClients.length > 0 ? new ArrayList<>(Arrays.asList(fluentClients)) : _fluentClientAll; for (ParSeqBasedFluentClient fluentClient : batch...
@Test public void testCallableExecution_Nested() throws Exception { MockBatchableResource client = new MockBatchableResource(); eg.batchOn(() -> { Assert.assertTrue(client.validateExecutionGroupFromContext(eg)); //outer - eg ExecutionGroup eg2 = new ExecutionGroup(_engine); try {...
@Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { try (AutoDetectReader reader = new AutoDetectReader(CloseShieldInputStream.wrap(stream), metadata, getEncod...
@Test public void testNoMarkupInToTextHandler() throws Exception { ContentHandler contentHandler = new ToTextContentHandler(); ParseContext parseContext = new ParseContext(); try (TikaInputStream tis = TikaInputStream .get(getResourceAsStream("/test-documents/testJAVA.java"))...
public FontMetrics parse() throws IOException { return parseFontMetric(false); }
@Test void testHelveticaKernPairs() throws IOException { AFMParser parser = new AFMParser( new FileInputStream("src/test/resources/afm/Helvetica.afm")); FontMetrics fontMetrics = parser.parse(); // KernPairs List<KernPair> kernPairs = fontMetrics.getKernPairs(); ...
public boolean isExcluded(Path absolutePath, Path relativePath, InputFile.Type type) { PathPattern[] exclusionPatterns = InputFile.Type.MAIN == type ? mainExclusionsPattern : testExclusionsPattern; for (PathPattern pattern : exclusionPatterns) { if (pattern.match(absolutePath, relativePath)) { re...
@Test public void should_handleAliasForTestExclusionsProperty() { settings.setProperty(PROJECT_TESTS_EXCLUSIONS_PROPERTY, "**/*Dao.java"); AbstractExclusionFilters filter = new AbstractExclusionFilters(analysisWarnings, settings.asConfig()::getStringArray) { }; IndexedFile indexedFile = new DefaultIn...
@Override public KTable<K, Long> count() { return doCount(NamedInternal.empty(), Materialized.with(keySerde, Serdes.Long())); }
@Test public void shouldThrowNullPointerOnCountWhenMaterializedIsNull() { assertThrows(NullPointerException.class, () -> groupedStream.count((Materialized<String, Long, KeyValueStore<Bytes, byte[]>>) null)); }
static SortKey[] rangeBounds( int numPartitions, Comparator<StructLike> comparator, SortKey[] samples) { // sort the keys first Arrays.sort(samples, comparator); int numCandidates = numPartitions - 1; SortKey[] candidates = new SortKey[numCandidates]; int step = (int) Math.ceil((double) sample...
@Test public void testRangeBoundsSkipDuplicates() { // step is 3 = ceiling(11/4) assertThat( SketchUtil.rangeBounds( 4, SORT_ORDER_COMPARTOR, new SortKey[] { CHAR_KEYS.get("a"), CHAR_KEYS.get("b"), ...
public static synchronized TransformServiceLauncher forProject( @Nullable String projectName, int port, @Nullable String pythonRequirementsFile) throws IOException { if (projectName == null || projectName.isEmpty()) { projectName = DEFAULT_PROJECT_NAME; } if (!launchers.containsKey(project...
@Test public void testLauncherCreatesDependenciesDir() throws IOException { String projectName = UUID.randomUUID().toString(); Path expectedTempDir = Paths.get(System.getProperty("java.io.tmpdir"), projectName); File file = expectedTempDir.toFile(); file.deleteOnExit(); TransformServiceLauncher.fo...
@Override public CloseableIterator<ColumnarBatch> readParquetFiles( CloseableIterator<FileStatus> fileIter, StructType physicalSchema, Optional<Predicate> predicate) { return new CloseableIterator<>() { private int currentReadColumnarBatchIndex = -1; ...
@Test public void testParquetMetadata() { String path = deltaLakePath + "/00000000000000000030.checkpoint.parquet"; DeltaLakeParquetHandler deltaLakeParquetHandler = new DeltaLakeParquetHandler(hdfsConfiguration, checkpointCache); StructType readSchema = LogReplay.getAddRemoveReadSchema(true...
@Bean public RetryRegistry retryRegistry(RetryConfigurationProperties retryConfigurationProperties, EventConsumerRegistry<RetryEvent> retryEventConsumerRegistry, RegistryEventConsumer<Retry> retryRegistryEventConsumer, @Qualifier("compositeRetryCustomizer") CompositeCustomizer<RetryConfigCus...
@Test public void testCreateRetryRegistryWithUnknownConfig() { RetryConfigurationProperties retryConfigurationProperties = new RetryConfigurationProperties(); InstanceProperties instanceProperties = new InstanceProperties(); instanceProperties.setBaseConfig("unknownConfig"); retryCon...
public void prepareIndices(final String idField, final Collection<String> sortFields, final Collection<String> caseInsensitiveStringSortFields) { if (!sortFields.containsAll(caseInsensitiveStringSortFields)) { throw new IllegalArgumentException("Case Insensitive String Sort Fields should be a subset...
@Test void doesNotCreateCollationIndexIfProperOneExists() { rawdb.createIndex(Indexes.ascending("summary"), new IndexOptions().collation(Collation.builder().locale("en").build())); toTest.prepareIndices("id", List.of("summary"), List.of("summary")); verify(db, never()).createIndex(any()); ...
@ScalarOperator(GREATER_THAN_OR_EQUAL) @SqlType(StandardTypes.BOOLEAN) public static boolean greaterThanOrEqual(@SqlType(StandardTypes.INTEGER) long left, @SqlType(StandardTypes.INTEGER) long right) { return left >= right; }
@Test public void testGreaterThanOrEqual() { assertFunction("INTEGER'37' >= INTEGER'37'", BOOLEAN, true); assertFunction("INTEGER'37' >= INTEGER'17'", BOOLEAN, true); assertFunction("INTEGER'17' >= INTEGER'37'", BOOLEAN, false); assertFunction("INTEGER'17' >= INTEGER'17'", BOOLEA...
public void commitLogical(CommittedBundle<?> bundle, MetricUpdates updates) { for (MetricUpdate<Long> counter : updates.counterUpdates()) { counters.get(counter.getKey()).commitLogical(bundle, counter.getUpdate()); } for (MetricUpdate<DistributionData> distribution : updates.distributionUpdates()) { ...
@SuppressWarnings("unchecked") @Test public void testApplyCommittedNoFilter() { metrics.commitLogical( bundle1, MetricUpdates.create( ImmutableList.of( MetricUpdate.create(MetricKey.create("step1", NAME1), 5L), MetricUpdate.create(MetricKey.create("ste...
public void isInStrictOrder() { isInStrictOrder(Ordering.natural()); }
@Test public void iterableIsInStrictOrder() { assertThat(asList()).isInStrictOrder(); assertThat(asList(1)).isInStrictOrder(); assertThat(asList(1, 2, 3, 4)).isInStrictOrder(); }
public void deleteOrder(Long orderId) throws RestClientException { deleteOrderWithHttpInfo(orderId); }
@Test public void deleteOrderTest() { Long orderId = null; api.deleteOrder(orderId); // TODO: test validations }
@Override public boolean implies(Permission permission) { if (permission instanceof RuntimePermission && BLOCKED_RUNTIME_PERMISSIONS.contains(permission.getName())) { return false; } if (permission instanceof SecurityPermission && BLOCKED_SECURITY_PERMISSIONS.contains(permission.getName())) { re...
@Test public void rule_restricts_denied_permissions() { assertThat(rule.implies(deniedSecurity)).isFalse(); assertThat(rule.implies(deniedRuntime)).isFalse(); }
@Override public Object poll() { Object result = queue.poll(); progTracker.madeProgress(result != null); return result; }
@Test public void when_pollNonEmpty_then_getItem() { assertEquals(ITEMS.get(0), inbox.poll()); }
private Function<KsqlConfig, Kudf> getUdfFactory( final Method method, final UdfDescription udfDescriptionAnnotation, final String functionName, final FunctionInvoker invoker, final String sensorName ) { return ksqlConfig -> { final Object actualUdf = FunctionLoaderUtils.instan...
@Test public void shouldLoadFunctionWithNestedDecimalSchema() { // Given: final UdfFactory returnDecimal = FUNC_REG.getUdfFactory(FunctionName.of("decimalstruct")); // When: final KsqlScalarFunction function = returnDecimal.getFunction(ImmutableList.of()); // Then: assertThat( functi...
static DescriptorDigest generateSelector(ImmutableList<FileEntry> layerEntries) throws IOException { return Digests.computeJsonDigest(toSortedJsonTemplates(layerEntries)); }
@Test public void testGenerateSelector_ownersModified() throws IOException { Path layerFile = temporaryFolder.newFolder("testFolder").toPath().resolve("file"); Files.write(layerFile, "hello".getBytes(StandardCharsets.UTF_8)); FileEntry layerEntry111 = new FileEntry( layerFile, ...
@Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { }
@Test public void givenDefaultConfig_whenInit_thenOk() { assertThatNoException().isThrownBy(() -> node.init(ctxMock, nodeConfiguration)); }
@Override public List<String> mapRow(Row element) { List<String> res = new ArrayList<>(); Schema s = element.getSchema(); for (int i = 0; i < s.getFieldCount(); i++) { res.add(convertFieldToString(s.getField(i).getType(), element.getValue(i))); } return res; }
@Test public void testAllDataTypes() { Schema.Builder schemaBuilder = new Schema.Builder(); schemaBuilder.addField("byte", Schema.FieldType.BYTE); schemaBuilder.addField("int16", Schema.FieldType.INT16); schemaBuilder.addField("int32", Schema.FieldType.INT32); schemaBuilder.addField("int64", Schem...
public PickTableLayoutForPredicate pickTableLayoutForPredicate() { return new PickTableLayoutForPredicate(metadata); }
@Test public void nonDeterministicPredicate() { Type orderStatusType = createVarcharType(1); tester().assertThat(pickTableLayout.pickTableLayoutForPredicate()) .on(p -> { p.variable("orderstatus", orderStatusType); return p.filter(p.rowExpr...
@Override public boolean shouldCareAbout(Object entity) { return securityConfigClasses.stream().anyMatch(aClass -> aClass.isAssignableFrom(entity.getClass())); }
@Test public void shouldNotCareAboutEntityWhichIsNotPartOfSecurityConfig() { SecurityConfigChangeListener securityConfigChangeListener = new SecurityConfigChangeListener() { @Override public void onEntityConfigChange(Object entity) { } }; assertThat(sec...
public static <T> Encoder<T> encoderFor(Coder<T> coder) { Encoder<T> enc = getOrCreateDefaultEncoder(coder.getEncodedTypeDescriptor().getRawType()); return enc != null ? enc : binaryEncoder(coder, true); }
@Test public void testBeamEncoderMappings() { BASIC_CASES.forEach( (coder, data) -> { Encoder<?> encoder = encoderFor(coder); serializeAndDeserialize(data.get(0), (Encoder) encoder); Dataset<?> dataset = createDataset(data, (Encoder) encoder); assertThat(dataset.col...
@Override public ImagesAndRegistryClient call() throws IOException, RegistryException, LayerPropertyNotFoundException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException { EventHandlers eventHandlers = buildContext...
@Test public void testCall_offlineMode_cached() throws LayerPropertyNotFoundException, RegistryException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException, InvalidImageReferenceException, IOException { ImageRefer...
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset( RequestContext context, OffsetCommitRequestData request ) throws ApiException { Group group = validateOffsetCommit(context, request); // In the old consumer group protocol, the offset commits maintai...
@Test public void testConsumerGroupOffsetDeleteWithErrors() { OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build(); ConsumerGroup group = context.groupMetadataManager.getOrMaybeCreatePersistedConsumerGroup( "foo", true ); ...
static QueryId buildId( final Statement statement, final EngineContext engineContext, final QueryIdGenerator idGenerator, final OutputNode outputNode, final boolean createOrReplaceEnabled, final Optional<String> withQueryId) { if (withQueryId.isPresent()) { final String que...
@Test public void shouldThrowIfWithQueryIdIsReserved() { // When: final Exception e = assertThrows( Exception.class, () -> QueryIdUtil.buildId(statement, engineContext, idGenerator, plan, false, Optional.of("insertquery_custom")) ); // Then: assertThat(e.getMessage(), ...
@Override public void getConfig(ZookeeperServerConfig.Builder builder) { ConfigServer[] configServers = getConfigServers(); int[] zookeeperIds = getConfigServerZookeeperIds(); if (configServers.length != zookeeperIds.length) { throw new IllegalArgumentException(String.format("Nu...
@Test void zookeeperConfig_default() { ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::hostname, "localhost"); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::id, ...
@Override @CheckForNull public EmailMessage format(Notification notif) { if (!(notif instanceof ChangesOnMyIssuesNotification)) { return null; } ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif; if (notification.getChange() instanceof AnalysisChange) { ...
@Test public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_branch_when_analysis_change() { String branchName = randomAlphabetic(19); Project project = newBranch("1", branchName); String ruleName = randomAlphabetic(8); String host = randomAlphabetic(15); Rule...
@Override public InetSocketAddress resolve(ServerWebExchange exchange) { List<String> xForwardedValues = extractXForwardedValues(exchange); if (!xForwardedValues.isEmpty()) { int index = Math.max(0, xForwardedValues.size() - maxTrustedIndex); return new InetSocketAddress(xForwardedValues.get(index), 0); } ...
@Test public void maxIndexOneReturnsLastForwardedIp() { ServerWebExchange exchange = buildExchange(oneTwoThreeBuilder()); InetSocketAddress address = trustOne.resolve(exchange); assertThat(address.getHostName()).isEqualTo("0.0.0.3"); }
@Override public void reportErrorAndInvalidate(String bundleSymbolicName, List<String> messages) { try { pluginRegistry.markPluginInvalid(bundleSymbolicName, messages); } catch (Exception e) { LOGGER.warn("[Plugin Health Service] Plugin with id '{}' tried to report health wit...
@Test void shouldNotThrowExceptionWhenPluginIsNotFound() { String bundleSymbolicName = "invalid-plugin"; String message = "some msg"; List<String> reasons = List.of(message); doThrow(new RuntimeException()).when(pluginRegistry).markPluginInvalid(bundleSymbolicName, reasons); ...
@Override public Num calculate(BarSeries series, Position position) { return isBreakEvenPosition(position) ? series.one() : series.zero(); }
@Test public void calculateWithNoPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); assertNumEquals(0, getCriterion().calculate(series, new BaseTradingRecord())); }
private void execute(String[] args) throws Exception { String tool = args[0]; String[] subsetArgs = new String[args.length - 1]; System.arraycopy(args, 1, subsetArgs, 0, args.length - 1); switch (tool) { case "Report": handleReport(subsetArgs); ...
@Test @Disabled("use this for development") public void testOneOff() throws Exception { List<String> args = new ArrayList<>(); args.add("Compare"); args.add("-extractsA"); args.add(ProcessUtils.escapeCommandLine(extractsDir .resolve("extractsA") .t...
public static void transform(IntIndexedContainer arr, IntIndexedContainer map) { for (int i = 0; i < arr.size(); ++i) arr.set(i, map.get(arr.get(i))); }
@Test public void testTransform() { IntArrayList arr = from(7, 6, 2); ArrayUtil.transform(arr, ArrayUtil.constant(8, 4)); assertEquals(IntArrayList.from(4, 4, 4), arr); IntArrayList brr = from(3, 0, 1); ArrayUtil.transform(brr, IntArrayList.from(6, 2, 1, 5)); assertE...
@Override public AllocatedSlot reserveFreeSlot(AllocationID allocationId) { LOG.debug("Reserve free slot with allocation id {}.", allocationId); AllocatedSlot slot = registeredSlots.get(allocationId); Preconditions.checkNotNull(slot, "The slot with id %s was not exists.", allocationId); ...
@Test void testReserveFreeSlot() { final DefaultAllocatedSlotPool slotPool = new DefaultAllocatedSlotPool(); final Collection<AllocatedSlot> allSlots = createAllocatedSlots(); final Collection<AllocatedSlot> freeSlots = new ArrayList<>(allSlots); final Iterator<AllocatedSlot> iterato...
public RunResponse restartDirectly( RunResponse restartStepInfo, RunRequest runRequest, boolean blocking) { WorkflowInstance instance = restartStepInfo.getInstance(); String stepId = restartStepInfo.getStepId(); validateStepId(instance, stepId, Actions.StepInstanceAction.RESTART); StepInstance ste...
@Test public void testRestartDirectly() { stepInstance.getRuntimeState().setStatus(StepInstance.Status.FATALLY_FAILED); stepInstance.getStepRetry().setRetryable(false); ((TypedStep) stepInstance.getDefinition()).setFailureMode(FailureMode.FAIL_AFTER_RUNNING); stepInstanceDao.insertOrUpsertStepInstance...
DateRange getRange(String dateRangeString) throws ParseException { if (dateRangeString == null || dateRangeString.isEmpty()) return null; String[] dateArr = dateRangeString.split("-"); if (dateArr.length > 2 || dateArr.length < 1) return null; // throw new Illega...
@Test public void testParseSingleDateRangeWithoutDay() throws ParseException { DateRange dateRange = dateRangeParser.getRange("2014 Sep"); assertFalse(dateRange.isInRange(getCalendar(2014, Calendar.AUGUST, 31))); assertTrue(dateRange.isInRange(getCalendar(2014, Calendar.SEPTEMBER, 1))); ...
public PendingSpan getOrCreate( @Nullable TraceContext parent, TraceContext context, boolean start) { PendingSpan result = get(context); if (result != null) return result; MutableSpan span = new MutableSpan(context, defaultSpan); PendingSpan parentSpan = parent != null ? get(parent) : null; //...
@Test void getOrCreate_cachesReference() { PendingSpan span = pendingSpans.getOrCreate(null, context, false); assertThat(pendingSpans.getOrCreate(null, context, false)).isSameAs(span); }
public Object getProperty( Object root, String propName ) throws Exception { List<Integer> extractedIndexes = new ArrayList<>(); BeanInjectionInfo.Property prop = info.getProperties().get( propName ); if ( prop == null ) { throw new RuntimeException( "Property not found" ); } Object obj = ro...
@Test public void getProperty_NotFound() { BeanInjector bi = new BeanInjector(null ); BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class ); BeanInjectionInfo.Property actualProperty = bi.getProperty( bii, "DOES_NOT_EXIST" ); assertNull(actualProperty); }
public Collection<Integer> getAssignedWorkerIds() { Collection<String> childrenKeys = repository.getChildrenKeys(ComputeNode.getInstanceWorkerIdRootNodePath()); Collection<Integer> result = new LinkedHashSet<>(childrenKeys.size(), 1F); for (String each : childrenKeys) { String worker...
@Test void assertGetUsedWorkerIds() { new ComputeNodePersistService(repository).getAssignedWorkerIds(); verify(repository).getChildrenKeys(ComputeNode.getInstanceWorkerIdRootNodePath()); }
@Override public ElectLeadersResult electLeaders( final ElectionType electionType, final Set<TopicPartition> topicPartitions, ElectLeadersOptions options) { final KafkaFutureImpl<Map<TopicPartition, Optional<Throwable>>> electionFuture = new KafkaFutureImpl<>(); f...
@Test public void testElectLeaders() throws Exception { TopicPartition topic1 = new TopicPartition("topic", 0); TopicPartition topic2 = new TopicPartition("topic", 2); try (AdminClientUnitTestEnv env = mockClientEnv()) { for (ElectionType electionType : ElectionType.values()) { ...
@Override @SuppressWarnings("Slf4jFormatShouldBeConst") protected void logException(long id, JdbiException exception) { final Throwable cause = exception.getCause(); if (cause instanceof SQLException) { for (Throwable throwable : (SQLException) cause) { logger.error(f...
@Test void testPlainJdbiException() throws Exception { JdbiException jdbiException = new TransactionException("Transaction failed for unknown reason"); jdbiExceptionMapper.logException(9812, jdbiException); verify(logger).error("Error handling a request: 0000000000002654", jdbiException); ...
@Override public InvokerWrapper getInvokerWrapper() { return invokerWrapper; }
@Test(expected = IllegalArgumentException.class) public void testInvokerWrapper_invokeOnAllPartitions_whenRequestOfWrongType_thenThrowException() throws Exception { context.getInvokerWrapper().invokeOnAllPartitions(new Object(), false); }
@Override public boolean isEquivalentTo(final AbstractPicker picker) { return picker instanceof EmptyPicker && (Objects.equal(status, ((EmptyPicker) picker).status) || (status.isOk() && ((EmptyPicker) picker).status.isOk())); }
@Test public void testIsEquivalentTo() { EmptyPicker picker = new EmptyPicker(mock(Status.class)); assertTrue(picker.isEquivalentTo(picker)); }
@Override public int hashCode() { return MessageIdAdvUtils.hashCode(this); }
@Test public void hashCodeTest() { BatchMessageIdImpl batchMsgId1 = new BatchMessageIdImpl(0, 0, 0, 0); BatchMessageIdImpl batchMsgId2 = new BatchMessageIdImpl(1, 1, 1, 1); assertEquals(batchMsgId1.hashCode(), batchMsgId1.hashCode()); assertNotEquals(batchMsgId1.hashCode(), batchMsg...
@Override public void check(final String databaseName, final EncryptRuleConfiguration ruleConfig, final Map<String, DataSource> dataSourceMap, final Collection<ShardingSphereRule> builtRules) { checkEncryptors(ruleConfig.getEncryptors()); checkTables(databaseName, ruleConfig.getTables(), ruleConfig....
@SuppressWarnings({"rawtypes", "unchecked"}) @Test void assertCheckWhenConfigInvalidLikeColumn() { EncryptRuleConfiguration config = createInvalidLikeColumnConfiguration(); RuleConfigurationChecker checker = OrderedSPILoader.getServicesByClass(RuleConfigurationChecker.class, Collections.singleto...
@Override protected boolean copyObject(String src, String dst) { try { LOG.debug("Copying {} to {}", src, dst); mClient.copyObject(mBucketNameInternal, src, mBucketNameInternal, dst); return true; } catch (CosClientException e) { LOG.error("Failed to rename file {} to {}", src, dst, e)...
@Test public void testCopyObject() { // test successful copy object Mockito.when(mClient.copyObject(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString())).thenReturn(null); boolean result = mCOSUnderFileSystem.copyObject(SRC, DST); ...
@Override public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) { double priority = edgeToPriorityMapping.get(edgeState, reverse); if (priority == 0) return Double.POSITIVE_INFINITY; final double distance = edgeState.getDistance(); double seconds = calcSeconds(d...
@Test public void bugWithNaNForBarrierEdges() { EdgeIteratorState motorway = graph.edge(0, 1).setDistance(0). set(roadClassEnc, MOTORWAY).set(avSpeedEnc, 80); CustomModel customModel = createSpeedCustomModel(avSpeedEnc) .addToPriority(If("road_class == MOTORWAY", Stat...
public static void toast(Context context, @StringRes int message) { // this is a static method so it is easier to call, // as the context checking and casting is done for you if (context == null) return; if (!(context instanceof Application)) { context = context.getApplicationContext(); } ...
@Test public void testToastWithNullContext() { AppConfig.toast(null, R.string.ok); assertNull(ShadowToast.getLatestToast()); }
static FlowRule toFlowRule(/*@Valid*/ GatewayFlowRule rule) { return new FlowRule(rule.getResource()) .setControlBehavior(rule.getControlBehavior()) .setCount(rule.getCount()) .setGrade(rule.getGrade()) .setMaxQueueingTimeMs(rule.getMaxQueueingTimeoutMs()); }
@Test public void testConvertToFlowRule() { GatewayFlowRule rule = new GatewayFlowRule("routeId1") .setCount(10) .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER) .setMaxQueueingTimeoutMs(1000); FlowRule flowRule = GatewayRuleConverter.toFlowRule(rul...
@Override protected CompletableFuture<JobExecutionResultResponseBody> handleRequest( @Nonnull final HandlerRequest<EmptyRequestBody> request, @Nonnull final RestfulGateway gateway) throws RestHandlerException { final JobID jobId = request.getPathParameter(JobIDPathParame...
@Test void testResultInProgress() throws Exception { final TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder() .setRequestJobStatusFunction( jobId -> CompletableFuture.completedFuture(JobStatus.RUNNING)) ...
public final void doesNotContainEntry(@Nullable Object key, @Nullable Object value) { checkNoNeedToDisplayBothValues("entries()") .that(checkNotNull(actual).entries()) .doesNotContain(immutableEntry(key, value)); }
@Test public void doesNotContainEntryFailure() { ImmutableMultimap<String, String> multimap = ImmutableMultimap.of("kurt", "kluever"); expectFailureWhenTestingThat(multimap).doesNotContainEntry("kurt", "kluever"); assertFailureKeys("value of", "expected not to contain", "but was"); assertFailureValue(...
protected String addDatetimeToFilename( String filename, boolean addDate, String datePattern, boolean addTime, String timePattern, boolean specifyFormat, String datetimeFormat ) { if ( Utils.isEmpty( filename ) ) { return null; } // Replace possible environm...
@Test public void testAddDatetimeToFilename_ZipWithoutDotsInFolderWithDots() { JobEntryBase jobEntryBase = new JobEntryBase(); String fullFilename; String filename = "/folder.with.dots/zip_without_dots_in_folder_with_dots"; String regexFilename = regexDotEscape( filename ); // add nothing ful...
@Override public String getFileId(final Path file) throws BackgroundException { if(StringUtils.isNotBlank(file.attributes().getFileId())) { return file.attributes().getFileId(); } if(file.isRoot() || new SimplePathPredicate(file).test(DriveHomeFinderService.MYDRIV...
@Test public void testGetFileid() throws Exception { final Path test = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final DriveFileIdProvider fileid = new DriveFileIdProvider(session); new DriveTouchFeature(sessi...
@SuppressWarnings("unused") // Required for automatic type inference public static <K> Builder0<K> forClass(final Class<K> type) { return new Builder0<>(); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowIfHandlerSupplierReturnsNullHandler2() { HandlerMaps.forClass(BaseType.class).withArgTypes(String.class, Integer.class) .put(LeafTypeA.class, () -> null) .build(); }
public static Transcript parse(String str) { if (StringUtils.isBlank(str)) { return null; } str = str.replaceAll("\r\n", "\n"); Transcript transcript = new Transcript(); List<String> lines = Arrays.asList(str.split("\n")); Iterator<String> iter = lines.iterat...
@Test public void testParse() { String type = "application/srr"; Transcript result; result = TranscriptParser.parse(srtStr, type); // There isn't a segment at 800L, so go backwards and get the segment at 0L assertEquals(result.getSegmentAtTime(800L).getWords(), "Promoting yo...
public Certificate add(X509Certificate cert) { final Certificate db; try { db = Certificate.from(cert); } catch (CertificateEncodingException e) { logger.error("Encoding error in certificate", e); throw new ClientException("Encoding error in certificate", e); ...
@Test public void shouldDisallowToAddCertificateIfFirstOfDocumentTypeButNotSelfSigned() throws IOException { final X509Certificate cert = readCertificate("test/intermediate.crt"); assertThrows(ClientException.class, () -> service.add(cert)); }
@Override public void configure(Map<String, ?> configs, boolean isKey) { if (listClass != null || inner != null) { log.error("Could not configure ListDeserializer as some parameters were already set -- listClass: {}, inner: {}", listClass, inner); throw new ConfigException("List dese...
@Test public void testListValueDeserializerNoArgConstructorsShouldThrowConfigExceptionDueInnerSerdeClassNotFound() { props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_TYPE_CLASS, ArrayList.class); props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_INNER_CLASS, nonExistingClass); fin...
@Override public List<GrantedAuthority> getAuthorities(JsonObject introspectionResponse) { List<GrantedAuthority> auth = new ArrayList<>(getAuthorities()); if (introspectionResponse.has("scope") && introspectionResponse.get("scope").isJsonPrimitive()) { String scopeString = introspectionResponse.get("scope").g...
@Test public void testGetAuthoritiesJsonObject_withScopes() { introspectionResponse.addProperty("scope", "foo bar baz batman"); List<GrantedAuthority> expected = new ArrayList<>(); expected.add(new SimpleGrantedAuthority("ROLE_API")); expected.add(new SimpleGrantedAuthority("OAUTH_SCOPE_foo")); expected.add...
public static byte[] ecdh(XECPrivateKey privateKey, XECPublicKey publicKey) { try { var keyAgreement = KeyAgreement.getInstance("XDH"); keyAgreement.init(privateKey); keyAgreement.doPhase(publicKey, true); byte[] sharedSecret = keyAgreement.generateSecret(); ...
@Test void x25519_ecdh_fails_if_shared_secret_is_all_zeros_case_1() { var alice_priv = xecPrivFromHex("88227494038f2bb811d47805bcdf04a2ac585ada7f2f23389bfd4658f9ddd45e"); var bob_public = xecPubFromHex( "0000000000000000000000000000000000000000000000000000000000000000"); // This actually int...
public static <T> void invokeAll(List<Callable<T>> callables, long timeoutMs) throws TimeoutException, ExecutionException { ExecutorService service = Executors.newCachedThreadPool(); try { invokeAll(service, callables, timeoutMs); } finally { service.shutdownNow(); } }
@Test public void invokeAllHang() throws Exception { int numTasks = 5; List<Callable<Void>> tasks = new ArrayList<>(); for (int i = 0; i < numTasks; i++) { tasks.add(new Callable<Void>() { @Override public Void call() throws Exception { Thread.sleep(10 * Constants.SECOND_MS...
@Override protected Optional<ErrorResponse> filter(DiscFilterRequest req) { var now = clock.instant(); var bearerToken = requestBearerToken(req).orElse(null); if (bearerToken == null) { log.fine("Missing bearer token"); return Optional.of(new ErrorResponse(Response.St...
@Test void supports_handler_with_custom_request_spec() { // Spec that maps POST as action 'read' var spec = RequestHandlerSpec.builder() .withAclMapping(HttpMethodAclMapping.standard() .override(Method.POST, Action.READ).build()) ...
public static Field p(String fieldName) { return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName); }
@Test void contains_uri() { String q = Q.p("f1").containsUri("https://test.uri") .build(); assertEquals(q, "yql=select * from sources * where f1 contains uri(\"https://test.uri\")"); }
public static String getUUID() { UUID id = UUID.randomUUID(); ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(id.getMostSignificantBits()); bb.putLong(id.getLeastSignificantBits()); return Base64.encodeBase64URLSafeString(bb.array()); }
@Test public void testGetUUID() { String id1 = Util.getUUID(); String id2 = Util.getUUID(); System.out.println("uuid = " + id1); System.out.println("uuid = " + id2); Assert.assertNotEquals(id1, id2); }
@Deprecated public static MessageType convert(StructType struct, FieldProjectionFilter filter) { return convert(struct, filter, true, new Configuration()); }
@Test public void testConvertLogicalI32Type() { LogicalTypeAnnotation timeLogicalType = LogicalTypeAnnotation.timeType(true, TimeUnit.MILLIS); String fieldName = "timeI32Type"; Short fieldId = 0; ThriftType timeI32Type = new ThriftType.I32Type(); timeI32Type.setLogicalTypeAnnotation(timeLogicalTy...
@Override public TensorProto serialize() { TensorProto.Builder builder = TensorProto.newBuilder(); builder.setVersion(CURRENT_VERSION); builder.setClassName(DenseMatrix.class.getName()); DenseTensorProto.Builder dataBuilder = DenseTensorProto.newBuilder(); dataBuilder.addAl...
@Test public void serializationTest() { DenseMatrix a = generateA(); TensorProto proto = a.serialize(); Tensor deser = Tensor.deserialize(proto); assertEquals(a,deser); }
@Override public BytesInput getBytes() { // The Page Header should include: blockSizeInValues, numberOfMiniBlocks, totalValueCount if (deltaValuesToFlush != 0) { flushBlockBuffer(); } return BytesInput.concat( config.toBytesInput(), BytesInput.fromUnsignedVarInt(totalValueCount),...
@Test public void shouldConsumePageDataInInitialization() throws IOException { int[] data = new int[2 * blockSize + 3]; for (int i = 0; i < data.length; i++) { data[i] = i * 32; } writeData(data); reader = new DeltaBinaryPackingValuesReader(); BytesInput bytes = writer.getBytes(); b...
@Override protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName) throws Exception { Message in = exchange.getIn(); MetricsTimerAction action = endpoint.getAction(); MetricsTimerAction finalAction = in.getHeader(HEADER_TI...
@Test public void testProcessStop() throws Exception { when(endpoint.getAction()).thenReturn(MetricsTimerAction.stop); when(in.getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.stop, MetricsTimerAction.class)) .thenReturn(MetricsTimerAction.stop); when(exchange.getProperty(PR...
public Future<KafkaVersionChange> reconcile() { return getPods() .compose(this::detectToAndFromVersions) .compose(i -> prepareVersionChange()); }
@Test public void testUpgradeWithAllVersionAndMixedPods(VertxTestContext context) { VersionChangeCreator vcc = mockVersionChangeCreator( mockKafka(VERSIONS.defaultVersion().version(), VERSIONS.version(KafkaVersionTestUtils.PREVIOUS_KAFKA_VERSION).metadataVersion(), VERSIONS.defaultVersion()....
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if (resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersion.class) || resourceInfo.getResourceMethod().isAnnotationPresent(SupportedSearchVersions.class)) { checkVersion(...
@Test public void testFilterOnMethod() throws Exception { final Method resourceMethod = TestResourceWithMethodAnnotation.class.getMethod("methodWithAnnotation"); when(resourceInfo.getResourceMethod()).thenReturn(resourceMethod); when(versionProvider.get()).thenReturn(openSearchV1); ...
@Override public String render(String text) { if (StringUtils.isBlank(text)) { return ""; } if (regex.isEmpty() || link.isEmpty()) { Comment comment = new Comment(); comment.escapeAndAdd(text); return comment.render(); } try { ...
@Test public void shouldRenderUsingFixedUrlIfLinkDoesNotContainVariable() throws Exception { String link = "http://mingle05/projects/cce/cards/wall-E"; String regex = "(evo-\\d+)"; trackingTool = new DefaultCommentRenderer(link, regex); String result = trackingTool.render("evo-111: ...
@Override public ConnectorMetadata getMetadata() { Optional<IHiveMetastore> hiveMetastore = Optional.empty(); if (isHiveOrGlueCatalogType()) { MetastoreType metastoreType = MetastoreType.get(catalogType); HiveMetaClient metaClient = HiveMetaClient.createHiveMetaClient(this.hd...
@Test public void testGetMetadata() { Map<String, String> properties = new HashMap<>(); properties.put("kudu.master", "localhost:7051"); properties.put("kudu.catalog.type", "kudu"); KuduConnector connector = new KuduConnector(new ConnectorContext("kudu_catalog", "kudu", properties));...
public boolean cleanExpiredConsumeQueue(final String addr, long timeoutMillis) throws MQClientException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException { RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLEAN_EXPIR...
@Test public void assertCleanExpiredConsumeQueue() throws RemotingException, InterruptedException, MQClientException { mockInvokeSync(); assertTrue(mqClientAPI.cleanExpiredConsumeQueue(defaultBrokerAddr, defaultTimeout)); }
public void insertOrUpdateOutputData(OutputData outputData) { final String outputDataStr = validateAndToJson(outputData); withMetricLogError( () -> withRetryableUpdate(UPSERT_OUTPUT_DATA_QUERY, stmt -> stmt.setString(1, outputDataStr)), "insertOrUpdateOutputData", "Failed upd...
@Test public void testParamsSizeOverLimit() throws Exception { ObjectMapper mockMapper = mock(ObjectMapper.class); OutputDataDao testDao = new OutputDataDao(dataSource, mockMapper, config); when(mockMapper.writeValueAsString(any())) .thenReturn(new String(new char[Constants.JSONIFIED_PARAMS_STRING...
@Override public String getExtraOptionsHelpText() { return "http://docs.aws.amazon.com/redshift/latest/mgmt/configure-jdbc-connection.html"; }
@Test public void testGetExtraOptionsHelpText() throws Exception { assertEquals( "http://docs.aws.amazon.com/redshift/latest/mgmt/configure-jdbc-connection.html", dbMeta.getExtraOptionsHelpText() ); }
public static Fiat parseFiatInexact(final String currencyCode, final String str) { try { long val = new BigDecimal(str).movePointRight(SMALLEST_UNIT_EXPONENT).longValue(); return Fiat.valueOf(currencyCode, val); } catch (ArithmeticException e) { throw new IllegalArgum...
@Test(expected = IllegalArgumentException.class) public void testParseFiatInexactInvalidAmount() { Fiat.parseFiatInexact("USD", "33.xx"); }
@Override public void restRequest(RestRequest request, Callback<RestResponse> callback, String routeKey) { this.restRequest(request, new RequestContext(), callback, routeKey); }
@Test public void testRouteLookupClientFuture() throws ExecutionException, InterruptedException { RouteLookup routeLookup = new SimpleTestRouteLookup(); final D2Client d2Client = new D2ClientBuilder().setZkHosts("localhost:2121").build(); d2Client.start(new FutureCallback<>()); RouteLookupClient ro...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final ThreadPool pool = ThreadPoolFactory.get("list", concurrency); try { final String prefix = this.createPrefix(directory); if(log.isDebugEnabl...
@Test public void testDirectoyPlaceholderNoChildren() throws Exception { final Path bucket = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final Path direc...
@Override public KsMaterializedQueryResult<Row> get( final GenericKey key, final int partition, final Optional<Position> position ) { try { final ReadOnlyKeyValueStore<GenericKey, ValueAndTimestamp<GenericRow>> store = stateStore .store(QueryableStoreTypes.timestampedKeyValueSt...
@Test public void shouldThrowIfGettingStateStoreFails() { // Given: when(stateStore.store(any(), anyInt())).thenThrow(new MaterializationTimeOutException("Boom")); // When: final Exception e = assertThrows( MaterializationException.class, () -> table.get(A_KEY, PARTITION) ); ...
public static <T> ThrowingConsumer<StreamRecord<T>, Exception> getRecordProcessor( Input<T> input) { boolean canOmitSetKeyContext; if (input instanceof AbstractStreamOperator) { canOmitSetKeyContext = canOmitSetKeyContext((AbstractStreamOperator<?>) input, 0); } else { ...
@Test void testGetRecordProcessor() throws Exception { TestOperator input1 = new TestOperator(); TestOperator input2 = new TestKeyContextHandlerOperator(true); TestOperator input3 = new TestKeyContextHandlerOperator(false); RecordProcessorUtils.getRecordProcessor(input1).accept(new ...
@Override public long queryOffset(final String group, final String topic, final int queueId) { if (!MixAll.isLmq(group)) { return super.queryOffset(group, topic, queueId); } // topic@group String key = topic + TOPIC_GROUP_SEPARATOR + group; Long offset = lmqOffset...
@Test public void testQueryOffsetForLmqGroupWithoutExistingOffset() { // Act Map<Integer, Long> actualOffsets = offsetManager.queryOffset(LMQ_GROUP, "nonExistingTopic"); // Assert assertNotNull(actualOffsets); assertTrue("The map should be empty for non-existing offsets", ac...
public static DataChecksum newDataChecksum(Type type, int bytesPerChecksum ) { if ( bytesPerChecksum <= 0 ) { return null; } switch ( type ) { case NULL : return new DataChecksum(type, new ChecksumNull(), bytesPerChecksum ); case CRC32 : return new DataChecksum(type, newCrc32(...
@Test public void testBulkOps() throws Exception { for (DataChecksum.Type type : CHECKSUM_TYPES) { System.err.println( "---- beginning tests with checksum type " + type + "----"); DataChecksum checksum = DataChecksum.newDataChecksum( type, BYTES_PER_CHUNK); for (boolean useD...
@Nonnull public MappingResults applyToPrimaryResource(@Nonnull Mappings mappings) { mappings = enrich(mappings); WorkspaceResource resource = workspace.getPrimaryResource(); MappingResults results = new MappingResults(mappings, listeners.createBundledMappingApplicationListener()) .withAggregateManager(aggre...
@Test void applyClassWithAnnotation() { String annotationName = AnnotationImpl.class.getName().replace('.', '/'); String classWithAnnotationName = ClassWithAnnotation.class.getName().replace('.', '/'); // Create mappings for all classes but the target 'ClassWithAnnotation' Mappings mappings = mappingGenerator...
public long next() { final long duration; if (mDurations == null) { duration = mDuration; } else { duration = mDurations[mIndex]; if (mIndex < mDurations.length - 1) { mIndex++; } } mNextTime = now() + duration; ...
@Test public void testDelayOne() { final long millis = 5000; final Delay delay = new Delay(millis); for (int i = 0; i < 5; i++) { check(delay, millis); final long next = delay.next(); Assert.assertEquals(millis, next); } }
@Override public void setConf(Configuration conf) { this.conf = conf; uid = conf.getInt(UID, 0); user = conf.get(USER); if (null == user) { try { user = UserGroupInformation.getCurrentUser().getShortUserName(); } catch (IOException e) { user = "hadoop"; } } gi...
@Test public void testDefault() { String user; try { user = UserGroupInformation.getCurrentUser().getShortUserName(); } catch (IOException e) { user = "hadoop"; } Configuration conf = new Configuration(false); ugi.setConf(conf); Map<Integer, String> ids = ugi.ugiMap(); asse...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final ReadOnlyWindowStore<GenericKey, ValueAndTime...
@Test public void shouldFetchWithOnlyStartBounds() { // When: table.get(A_KEY, PARTITION, WINDOW_START_BOUNDS, Range.all()); // Then: verify(cacheBypassFetcher).fetch( eq(tableStore), any(), eq(WINDOW_START_BOUNDS.lowerEndpoint()), eq(WINDOW_START_BOUNDS.upperEndpoint(...
@Override public <T> T loadObject(String accountName, ObjectType objectType, String objectKey) throws IllegalArgumentException, NotFoundException { if (objectType.equals(ObjectType.CANARY_RESULT_ARCHIVE)) { var record = sqlCanaryArchiveRepo .findById(objectKey) .o...
@Test public void testLoadObjectWhenMetricSetPairs() throws IOException { var testAccountName = UUID.randomUUID().toString(); var testObjectType = ObjectType.METRIC_SET_PAIR_LIST; var testObjectKey = UUID.randomUUID().toString(); var testMetricSetPair = createTestMetricSetPair(); var testSqlMetr...
@Override public Stream<MappingField> resolveAndValidateFields( boolean isKey, List<MappingField> userFields, Map<String, String> options, InternalSerializationService serializationService ) { if (userFields.isEmpty()) { throw QueryException.er...
@Test @Parameters({ "true, __key", "false, this" }) public void test_resolveFields(boolean key, String prefix) { Stream<MappingField> fields = INSTANCE.resolveAndValidateFields( key, singletonList(field("field", QueryDataType.INT, prefix + ".fi...
@Nullable AuthTemplate getAuthFor(String registry) { Map.Entry<String, AuthTemplate> authEntry = findFirstInMapByKey(dockerConfigTemplate.getAuths(), getRegistryMatchersFor(registry)); return authEntry != null ? authEntry.getValue() : null; }
@Test public void testGetAuthFor_orderOfMatchPreference() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig_extra_matches.json").toURI()); DockerConfig dockerConfig = new DockerConfig(JsonTemplateMapper.readJsonFromFile(json, DockerCo...
public static void reset() { settings = null; }
@Test public void reset_sets_static_json_schema_validator_settings_to_null() { // Given JsonSchemaValidator.settings = new JsonSchemaValidatorSettings(); // When JsonSchemaValidator.reset(); // Then try { assertThat(JsonSchemaValidator.settings, nullValu...
public static Stream<String> splitAsStream(CharSequence text, String regex) { if (text == null || regex == null) { return Stream.empty(); } return Pattern.compile(regex).splitAsStream(text); }
@Test public void testSplitAsStream() { List<String> items = StringHelper.splitAsStream("a,b,c", ",").toList(); assertTrue(items.contains("a")); assertTrue(items.contains("b")); assertTrue(items.contains("c")); }
private void rewrapDataSource(String jndiName, DataSource dataSource) throws IllegalAccessException { final String dataSourceClassName = dataSource.getClass().getName(); LOG.debug("Datasource needs rewrap: " + jndiName + " of class " + dataSourceClassName); final String dataSourceRewrappedMessage = "Datasource...
@Test public void testRewrapDataSource() throws Exception { final org.apache.tomcat.dbcp.dbcp2.BasicDataSource tomcat2DataSource = new org.apache.tomcat.dbcp.dbcp2.BasicDataSource(); tomcat2DataSource.setUrl(H2_DATABASE_URL); rewrapDataSource(tomcat2DataSource); final org.apache.commons.dbcp2.BasicDataSource d...