focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
private boolean updateTenantUsage(CounterMode counterMode, String tenant, boolean ignoreQuotaLimit) { final Timestamp now = TimeUtils.getCurrentTime(); TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setTenant(tenant); tenantCapacity.setQuota(PropertyUtil.getDefaultT...
@Test void testUpdateTenantUsage() { when(tenantCapacityPersistService.incrementUsageWithDefaultQuotaLimit(any())).thenReturn(true); when(tenantCapacityPersistService.decrementUsage(any())).thenReturn(true); service.updateTenantUsage(CounterMode.INCREMENT, "testTenant"); Moc...
public static String getTagValue( Node n, KettleAttributeInterface code ) { return getTagValue( n, code.getXmlCode() ); }
@Test public void getTagValueEmptyTagYieldsNullValue() { System.setProperty( Const.KETTLE_XML_EMPTY_TAG_YIELDS_EMPTY_VALUE, "N" ); assertNull( XMLHandler.getTagValue( getNode(), "text" ) ); }
@Override public void connect() throws IllegalStateException, IOException { if (isConnected()) { throw new IllegalStateException("Already connected"); } InetSocketAddress address = this.address; // the previous dns retry logic did not work, as address.getAddress would alw...
@Test public void connectsToGraphiteWithHostAndPort() throws Exception { try (Graphite graphite = new Graphite(host, port, socketFactory)) { graphite.connect(); } verify(socketFactory).createSocket(address.getAddress(), port); }
public static void populateMethodDeclarations(final ClassOrInterfaceDeclaration toPopulate, final Collection<MethodDeclaration> methodDeclarations) { methodDeclarations.forEach(toPopulate::addMember); }
@Test void populateMethodDeclarations() { final List<MethodDeclaration> toAdd = IntStream.range(0, 5) .boxed() .map(index -> getMethodDeclaration("METHOD_" + index)) .collect(Collectors.toList()); final ClassOrInterfaceDeclaration toPopulate = new Clas...
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n, @ParameterName( "scale" ) BigDecimal scale) { if ( n == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "n", "cannot be null")); } if ( scale == null ) { return FEEL...
@Test void invokeOutRangeScale() { FunctionTestUtil.assertResultError(decimalFunction.invoke(BigDecimal.valueOf(1.5), BigDecimal.valueOf(6177)), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(decimalFunction.invoke(BigDecimal.valueOf(1.5)...
@Override public void removeSecurityGroup(String sgId) { checkArgument(!Strings.isNullOrEmpty(sgId), ERR_NULL_SG_ID); osSecurityGroupStore.removeSecurityGroup(sgId); log.info(String.format(MSG_SG, sgId, MSG_REMOVED)); }
@Test(expected = IllegalArgumentException.class) public void testRemoveSecurityGroupWithNull() { target.removeSecurityGroup(null); }
public void mergeWith(RuntimeMetric metric) { if (metric == null) { return; } checkState(unit == metric.getUnit(), "The metric to be merged must have the same unit type as the current one."); sum.addAndGet(metric.getSum()); count.addAndGet(metric.getCount()); ...
@Test public void testMergeWith() { RuntimeMetric metric1 = new RuntimeMetric(TEST_METRIC_NAME, NONE, 5, 2, 4, 1); RuntimeMetric metric2 = new RuntimeMetric(TEST_METRIC_NAME, NONE, 20, 2, 11, 9); metric1.mergeWith(metric2); assertRuntimeMetricEquals(metric1, new RuntimeMetric(TES...
public static Set<X509Certificate> filterValid( X509Certificate... certificates ) { final Set<X509Certificate> results = new HashSet<>(); if (certificates != null) { for ( X509Certificate certificate : certificates ) { if ( certificate == null ) ...
@Test public void testFilterValidWithTwoDistinctValidCerts() throws Exception { // Setup fixture. final X509Certificate validA = KeystoreTestUtils.generateValidCertificate().getCertificate(); final X509Certificate validB = KeystoreTestUtils.generateValidCertificate().getCertificate(); ...
public static Class<?> getLiteral(String className, String literal) { LiteralAnalyzer analyzer = ANALYZERS.get( className ); Class result = null; if ( analyzer != null ) { analyzer.validate( literal ); result = analyzer.getLiteral(); } return result; }
@Test public void testFloatWithLongLiteral() { assertThat( getLiteral( float.class.getCanonicalName(), "156L" ) ).isNotNull(); assertThat( getLiteral( float.class.getCanonicalName(), "156l" ) ).isNotNull(); }
private CoordinatorResult<ShareGroupHeartbeatResponseData, CoordinatorRecord> shareGroupHeartbeat( String groupId, String memberId, int memberEpoch, String rackId, String clientId, String clientHost, List<String> subscribedTopicNames ) throws ApiException { ...
@Test public void testShareGroupUnknownGroupId() { String groupId = "fooup"; String memberId = Uuid.randomUuid().toString(); MockPartitionAssignor assignor = new MockPartitionAssignor("share"); GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() ...
public static int[] sort(int[] array) { int[] order = new int[array.length]; for (int i = 0; i < order.length; i++) { order[i] = i; } sort(array, order); return order; }
@Test public void testSortFloat() { System.out.println("sort float"); float[] data1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int[] order1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; assertArrayEquals(order1, QuickSort.sort(data1)); float[] data2 = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; int[]...
@Modified public void modified(ComponentContext context) { readComponentConfiguration(context); if (requestInterceptsEnabled) { requestIntercepts(); } else { withdrawIntercepts(); } }
@Test public void removeHostByDeviceOffline() { provider.modified(CTX_FOR_REMOVE); testProcessor.process(new TestArpPacketContext(DEV1)); testProcessor.process(new TestArpPacketContext(DEV4)); Device device = new DefaultDevice(ProviderId.NONE, deviceId(DEV1), SWITCH, ...
@Override public Map<String, String[]> getParameterMap() { return stringMap; }
@Test void testGetParameterMapEmpty() { Map<String, String[]> parameterMap = reuseUploadFileHttpServletRequest.getParameterMap(); assertEquals(0, parameterMap.size()); }
private RemotingCommand getAllTopicConfig(ChannelHandlerContext ctx, RemotingCommand request) { final RemotingCommand response = RemotingCommand.createResponseCommand(GetAllTopicConfigResponseHeader.class); // final GetAllTopicConfigResponseHeader responseHeader = // (GetAllTopicConfigResponseHe...
@Test public void testGetAllTopicConfig() throws Exception { GetAllTopicConfigResponseHeader getAllTopicConfigResponseHeader = new GetAllTopicConfigResponseHeader(); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_TOPIC_CONFIG, getAllTopicConfigResponseHeader); ...
@SuppressWarnings("unchecked") public static void validateResponse(HttpURLConnection conn, int expectedStatus) throws IOException { if (conn.getResponseCode() != expectedStatus) { Exception toThrow; InputStream es = null; try { es = conn.getErrorStream(); Map json = JsonSer...
@Test public void testValidateResponseJsonErrorKnownException() throws Exception { Map<String, Object> json = new HashMap<String, Object>(); json.put(HttpExceptionUtils.ERROR_EXCEPTION_JSON, IllegalStateException.class.getSimpleName()); json.put(HttpExceptionUtils.ERROR_CLASSNAME_JSON, IllegalStateExcepti...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof EntryView that)) { return false; } return getKey().equals(that.getKey()) && getValue().equals(that.getValue()) && getVersio...
@Test public void test_equals_whenSameReference() { assertTrue(view.equals(view)); }
public static Object deserialize(String json) throws ParseException { // 去掉注释 return new JSONSerializer(json).nextValue(); }
@Test public void testDeserializeWithComment() { String s = "{" + "\"a\": null, // 111\n" + " \"b\":1, /*2 // asdsad / das */\n" + " \"c\":1, /*2 // asdsad \n \r / das */\n" + " \"d\":9999999999" + "}"; LOGGER.info...
synchronized SyncableFileSystemView getSecondaryView() { if (secondaryView == null) { secondaryView = secondaryViewSupplier.get(); } return secondaryView; }
@Test public void testGetSecondaryView() { when(secondaryViewSupplier.get()).thenReturn(secondary); assertEquals(secondary, fsView.getSecondaryView()); }
@Override public boolean wasNull() throws SQLException { return queryResult.wasNull(); }
@Test void assertWasNull() throws SQLException { TransparentMergedResult actual = new TransparentMergedResult(mock(QueryResult.class)); assertFalse(actual.wasNull()); }
public void start() { if (timeLimit > 0 && this.flushFuture == null) { this.flushFuture = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("DataBufferOutboundFlusher-thread") ...
@Test public void testConfiguredTimeLimit() throws Exception { List<Elements> values = new ArrayList<>(); PipelineOptions options = PipelineOptionsFactory.create(); options .as(ExperimentalOptions.class) .setExperiments(Arrays.asList("data_buffer_time_limit_ms=1")); final CountDownLatc...
public CommandReturn runWithOutput() throws IOException { Process process = null; BufferedReader inReader = null; try { process = new ProcessBuilder(mCommand).redirectErrorStream(true).start(); inReader = new BufferedReader(new InputStreamReader(process.getInputStream())); /...
@Test public void execCommandTolerateFailureFailed() throws Exception { // create temp file File testDir = AlluxioTestDirectory.createTemporaryDirectory("command"); // do sth wrong String[] testCommandFail = new String[]{"ls", String.format("%saaaa", testDir.getAbsolutePath())}; Comma...
public void removeMetricsForCertificates(Predicate<CertificateMetricKey> shouldDelete) { final List<CertificateMetricKey> removedKeys = new ArrayList<>(); certificateExpirationMap.keySet().stream() .map(CertificateMetricKey.class::cast) .filter(shouldDelete) ...
@Test @DisplayName("Should not remove certificate metrics for cluster CA type") void shouldNotRemoveCertificateMetricsForClusterCaType() { Predicate<CertificateMetricKey> predicate = key -> matchCaTypes(key.getCaType(), CertificateMetricKey.Type.CLIENT_CA); metricsHolder.removeMetricsForCertific...
@Override public <T> T unwrap(Class<T> clazz) { if (!clazz.isInstance(this)) { throw new IllegalArgumentException("Class " + clazz + " is unknown to this implementation"); } @SuppressWarnings("unchecked") T castedEntry = (T) this; return castedEntry; }
@Test public void unwrap_fail() { assertThrows(IllegalArgumentException.class, () -> event.unwrap(Map.Entry.class)); }
@CanIgnoreReturnValue public final Ordered containsAtLeastEntriesIn(Multimap<?, ?> expectedMultimap) { checkNotNull(expectedMultimap, "expectedMultimap"); checkNotNull(actual); ListMultimap<?, ?> missing = difference(expectedMultimap, actual); // TODO(kak): Possible enhancement: Include "[1 copy]" if...
@Test public void containsAtLeastInOrderFailureValuesOnly() { ImmutableMultimap<Integer, String> actual = ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four"); ImmutableMultimap<Integer, String> expected = ImmutableMultimap.of(3, "six", 3, "one", 4, "five", 4, "four"); ...
@Override public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) { HealthCheckInstancePublishInfo instance = (HealthCheckInstancePublishInfo) task.getClient() .getInstancePublishInfo(service); if (null == instance) { return; } ...
@Test void testProcess() { httpHealthCheckProcessor.process(healthCheckTaskV2, service, clusterMetadata); verify(healthCheckTaskV2).getClient(); verify(healthCheckInstancePublishInfo).tryStartCheck(); }
public Materialization create( final StreamsMaterialization delegate, final MaterializationInfo info, final QueryId queryId, final QueryContext.Stacker contextStacker ) { final TransformVisitor transformVisitor = new TransformVisitor(queryId, contextStacker); final List<Transform> tran...
@Test public void shouldUseCorrectLoggerForSelectMapper() { // When: factory.create(materialization, info, queryId, new Stacker().push("project")); // Then: verify(mapperInfo).getMapper(loggerCaptor.capture()); assertThat( loggerCaptor.getValue().apply(new Stacker().getQueryContext()), ...
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testMergeMapSourceNoOverlap() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'tomergemap1': {'type': 'MAP', 'source': 'SYSTEM', 'value': {'tomerge1': {'source':'SYSTEM', 'type': 'STRING','value': 'hello'}}}}"); Map<String, Pa...
@Override public void unsubscribe(String serviceName, EventListener listener) throws NacosException { unsubscribe(serviceName, new ArrayList<>(), listener); }
@Test void testUnSubscribe1() throws NacosException { //given String serviceName = "service1"; EventListener listener = event -> { }; when(changeNotifier.isSubscribed(Constants.DEFAULT_GROUP, serviceName)).thenReturn(false); //when client.unsubscribe(...
@Override @Nullable public char[] readCharArray(@Nonnull String fieldName) throws IOException { return readIncompatibleField(fieldName, CHAR_ARRAY, super::readCharArray); }
@Test(expected = IncompatibleClassChangeError.class) public void testReadCharArray_IncompatibleClass() throws Exception { reader.readCharArray("byte"); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("List containers for %s", session)); } try { final AttributedList<Path> containers = n...
@Test public void testListLimitRegion() throws Exception { final AttributedList<Path> list = new SwiftContainerListService(session, new SwiftLocationFeature.SwiftRegion("IAD") ).list(new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory)), new DisabledListProgress...
public V getValue() { access(); return getValueInternal(); }
@Test public void testGetValue() { assertEquals(0, replicatedRecord.getHits()); assertEquals("value", replicatedRecord.getValue()); assertEquals(1, replicatedRecord.getHits()); }
@Override public CustomPage<Product> getProducts(ProductPagingRequest productPagingRequest) { final Page<ProductEntity> productEntityPage = productRepository.findAll(productPagingRequest.toPageable()); if (productEntityPage.getContent().isEmpty()) { throw new ProductNotFoundException("...
@Test void givenProductPagingRequest_WhenProductPageList_ThenReturnCustomPageProductList() { // Given ProductPagingRequest pagingRequest = ProductPagingRequest.builder() .pagination( CustomPaging.builder() .pageSize(1) ...
@Override public DirectoryTimestamp getDirectoryTimestamp() { return DirectoryTimestamp.implicit; }
@Test public void testFeatures() { assertEquals(Protocol.Case.sensitive, new FTPTLSProtocol().getCaseSensitivity()); assertEquals(Protocol.DirectoryTimestamp.implicit, new FTPTLSProtocol().getDirectoryTimestamp()); }
public KafkaConfiguration getConfiguration() { return configuration; }
@Test public void testBrokersOnComponent() { KafkaComponent kafka = context.getComponent("kafka", KafkaComponent.class); kafka.getConfiguration().setBrokers("broker1:12345,broker2:12566"); String uri = "kafka:mytopic?partitioner=com.class.Party"; KafkaEndpoint endpoint = context.ge...
public void writeHeapHistogram(HeapHistogram heapHistogram) throws IOException { try { document.open(); addParagraph( getFormattedString("heap_histo_du", I18N.createDateAndTimeFormat().format(heapHistogram.getTime())), "memory.png"); new PdfHeapHistogramReport(heapHistogram, document).toPdf(...
@Test public void testWriteHeapHistogram() throws IOException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); try (InputStream input = getClass().getResourceAsStream("/heaphisto.txt")) { final PdfOtherReport pdfOtherReport = new PdfOtherReport(TEST_APP, output); final HeapHistogram heapHi...
public static List<URL> parseConfigurators(String rawConfig) { // compatible url JsonArray, such as [ "override://xxx", "override://xxx" ] List<URL> compatibleUrls = parseJsonArray(rawConfig); if (CollectionUtils.isNotEmpty(compatibleUrls)) { return compatibleUrls; } ...
@Test void parseConfiguratorsServiceNoAppTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Asser...
public static TableElements of(final TableElement... elements) { return new TableElements(ImmutableList.copyOf(elements)); }
@SuppressWarnings("UnstableApiUsage") @Test public void shouldImplementHashCodeAndEqualsProperty() { final List<TableElement> someElements = ImmutableList.of( tableElement("bob", INT_TYPE) ); new EqualsTester() .addEqualityGroup(TableElements.of(someElements), TableElements.of(someEleme...
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchIcmpv6TypeTest() { Criterion criterion = Criteria.matchIcmpv6Type((byte) 250); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
public AgeRecogniser() { try { secondaryParser = new Tika(new TikaConfig()); available = true; } catch (Exception e) { available = false; LOG.error("Unable to initialize secondary parser", e); } }
@Test public void testAgeRecogniser() throws Exception { //test config is added to resources directory try (InputStream is = getResourceAsStream(CONFIG_FILE); InputStream bis = new ByteArrayInputStream( TEST_TEXT.getBytes(StandardCharsets.UTF_8))) { ...
public static OutputStreamAndPath createEntropyAware( FileSystem fs, Path path, WriteMode writeMode) throws IOException { final Path processedPath = addEntropy(fs, path); // create the stream on the original file system to let the safety net // take its effect final FSDataO...
@Test void testCreateEntropyAwarePlainFs() throws Exception { File folder = TempDirUtils.newFolder(tempFolder); Path path = new Path(Path.fromLocalFile(folder), "_entropy_/file"); OutputStreamAndPath out = EntropyInjector.createEntropyAware( LocalFile...
@Override public void setConfigAttributes(Object attributes) { if (attributes != null) { this.clear(); ((List<Map<String, String>>)attributes).forEach(attributeMap -> this.add(new EnvironmentAgentConfig(attributeMap.get("uuid")))); } }
@Test void shouldNotSetAgentConfigAttributesWhenItIsNull(){ envAgentsConfig.setConfigAttributes(null); assertThat(envAgentsConfig.size(), is(0)); }
public static Calendar parseXmlDate(String xsDate) throws ParseException { try { final DatatypeFactory df = DatatypeFactory.newInstance(); final XMLGregorianCalendar dateTime = df.newXMLGregorianCalendar(xsDate); return dateTime.toGregorianCalendar(); } catch (Datatyp...
@Test public void testParseXmlDate() throws ParseException { String xsDate = "2019-01-02Z"; Calendar result = DateUtil.parseXmlDate(xsDate); assertEquals(2019, result.get(Calendar.YEAR)); //month is zero based. assertEquals(0, result.get(Calendar.MONTH)); assertEquals...
public Optional<Node> localCorpusDispatchTarget() { if (localCorpusDispatchTarget == null) return Optional.empty(); // Only use direct dispatch if the local group has sufficient coverage Group localSearchGroup = groups.get(localCorpusDispatchTarget.group()); if ( ! localSearchGroup.hasS...
@Test void requireThatZeroDocsAreFine() { try (State test = new State("cluster.1", 2, "a", "b")) { test.waitOneFullPingRound(); assertTrue(test.vipStatus.isInRotation()); assertTrue(test.searchCluster.localCorpusDispatchTarget().isEmpty()); test.numDocsPerNo...
@SuppressWarnings("unchecked") void sort(String[] filenames) { Arrays.sort(filenames, new Comparator<String>() { @Override public int compare(String f1, String f2) { int result = 0; for (FilenameParser p : parsers) { Comparable c2 = p.parseFilename(f2); Comparable ...
@Test public void sortsDescendingByDateAndInteger() { final String[] FILENAMES = new String[] { "/var/logs/my-app/2018-10-31/9.log", "/var/logs/my-app/2019-01-01/1.log", "/var/logs/my-app/1999-03-17/3.log", "/var/logs/my-app/2019-01-01/11.log", "/var/logs/my-app/2019-01-01/2.log", ...
@Override protected double maintain() { // Reboot candidates: Nodes in long-term states, where we know we can safely orchestrate a reboot List<Node> nodesToReboot = nodeRepository().nodes().list(Node.State.active, Node.State.ready).stream() .filter(node -> node.type().isHost()) ...
@Test public void testRebootScheduling() { Duration rebootInterval = Duration.ofDays(30); InMemoryFlagSource flagSource = new InMemoryFlagSource(); ProvisioningTester tester = createTester(rebootInterval, flagSource); makeReadyHosts(15, tester); NodeRepository nodeRepository...
public void addOtherTesseractConfig(String key, String value) { if (key == null) { throw new IllegalArgumentException("key must not be null"); } if (value == null) { throw new IllegalArgumentException("value must not be null"); } Matcher m = ALLOWABLE_OTH...
@Test public void testGoodOtherParameters() { TesseractOCRConfig config = new TesseractOCRConfig(); config.addOtherTesseractConfig("good", "good"); }
@Override public void setConf(Configuration conf) { if (conf != null) { conf = addSecurityConfiguration(conf); } super.setConf(conf); }
@Test public void testFencingConfigPerNameNode() throws Exception { Mockito.doReturn(STANDBY_READY_RESULT).when(mockProtocol).getServiceStatus(); final String nsSpecificKey = DFSConfigKeys.DFS_HA_FENCE_METHODS_KEY + "." + NSID; final String nnSpecificKey = nsSpecificKey + ".nn1"; HdfsConfigurati...
@Override public MailLogDO getMailLog(Long id) { return mailLogMapper.selectById(id); }
@Test public void testGetMailLog() { // mock 数据 MailLogDO dbMailLog = randomPojo(MailLogDO.class, o -> o.setTemplateParams(randomTemplateParams())); mailLogMapper.insert(dbMailLog); // 准备参数 Long id = dbMailLog.getId(); // 调用 MailLogDO mailLog = mailLogService...
void onAddRcvDestination(final long registrationId, final String destinationChannel, final long correlationId) { if (destinationChannel.startsWith(IPC_CHANNEL)) { onAddRcvIpcDestination(registrationId, destinationChannel, correlationId); } else if (destinationChannel.star...
@Test void shouldThrowExceptionWhenRcvDestinationHasResponseCorrelationIdSet() { final Exception exception = assertThrowsExactly(InvalidChannelException.class, () -> driverConductor.onAddRcvDestination( 42, "aeron:udp?endpoint=localhost:8080|response-correlation-id=1234", 1) ...
public void clear() { this.setRemoteAddress(null).setLocalAddress(null).setFuture(null).setProviderSide(null) .setProviderInfo(null); this.attachments = new ConcurrentHashMap<String, Object>(); this.stopWatch.reset(); }
@Test public void testClear() { RpcInternalContext context = RpcInternalContext.getContext(); context.setRemoteAddress("127.0.0.1", 1234); context.setLocalAddress("127.0.0.1", 2345); context.setFuture(new ResponseFuture<String>() { @Override public boolean can...
public long getAndInc() { return value++; }
@Test public void testGetAndInc() { MutableLong mutableLong = MutableLong.valueOf(13); assertEquals(13L, mutableLong.getAndInc()); assertEquals(14L, mutableLong.value); }
@Override public ScannerReport.Component readComponent(int componentRef) { ensureInitialized(); return delegate.readComponent(componentRef); }
@Test public void verify_readComponent_returns_Component() { writer.writeComponent(COMPONENT); assertThat(underTest.readComponent(COMPONENT_REF)).isEqualTo(COMPONENT); }
@Override public RowExpression optimize(RowExpression rowExpression, Level level, ConnectorSession session) { if (level.ordinal() <= OPTIMIZED.ordinal()) { return toRowExpression(rowExpression.getSourceLocation(), new RowExpressionInterpreter(rowExpression, metadata.getFunctionAndTypeManager...
@Test public void testCastWithJsonParseOptimization() { FunctionHandle jsonParseFunctionHandle = functionAndTypeManager.lookupFunction("json_parse", fromTypes(VARCHAR)); // constant FunctionHandle jsonCastFunctionHandle = functionAndTypeManager.lookupCast(CAST, JSON, functionAndTypeMana...
public EmbeddedCacheManager getNativeCacheManager() { return this.nativeCacheManager; }
@Test public final void getNativeCacheShouldReturnTheEmbeddedCacheManagerSuppliedAtConstructionTime() { withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) { @Override public void call() { final SpringEmbeddedCacheManager objectUnderTest = new S...
public void setString(@NotNull final String key, @NotNull final String value) { props.setProperty(key, value); LOGGER.debug("Setting: {}='{}'", key, getPrintableValue(key, value)); }
@Test public void testSetString() { String key = "newProperty"; String value = "someValue"; getSettings().setString(key, value); String expResults = getSettings().getString(key); Assert.assertEquals(expResults, value); }
public static LocalDate parseDate(CharSequence text) { return parseDate(text, (DateTimeFormatter) null); }
@Test public void parseDateTest() { LocalDate localDate = LocalDateTimeUtil.parseDate("2020-01-23"); assertEquals("2020-01-23", localDate.toString()); localDate = LocalDateTimeUtil.parseDate("2020-01-23T12:23:56", DateTimeFormatter.ISO_DATE_TIME); assertNotNull(localDate); assertEquals("2020-01-23", localDa...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void unbanChatMember() { BaseResponse response = bot.execute(new UnbanChatMember(channelName, chatId)); assertFalse(response.isOk()); assertEquals(400, response.errorCode()); assertEquals("Bad Request: can't remove chat owner", response.description()); // return...
static void dissectControlResponse(final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { int encodedLength = dissectLogHeader(CONTEXT, CMD_OUT_RESPONSE, buffer, offset, builder); HEADER_DECODER.wrap(buffer, offset + encodedLength); encodedLength += MessageHeader...
@Test void controlResponse() { internalEncodeLogHeader(buffer, 0, 100, 100, () -> 1_250_000_000); final ControlResponseEncoder responseEncoder = new ControlResponseEncoder(); responseEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder) .controlSessionId(13) ...
@ScalarFunction public static double[] decodeGeoHash(String geohash) { return decode(geohash); }
@Test(dataProvider = "decodeHashTestCases") public void testDecodeHash(String geohash, double[] expectedCoords) { double[] decodedCoords = GeohashFunctions.decodeGeoHash(geohash); assertEquals(decodedCoords.length, 2); assertEquals(decodedCoords[0], expectedCoords[0], 0.001); assertEquals(decodedCoord...
@Override public CompletableFuture<String> triggerSavepoint( @Nullable String targetDirectory, boolean cancelJob, SavepointFormatType formatType) { return state.tryCall( StateWithExecutionGraph.class, stateWithExecutionGraph -> { ...
@Test void testTriggerSavepointFailsInIllegalState() throws Exception { final AdaptiveScheduler scheduler = new AdaptiveSchedulerBuilder( createJobGraph(), mainThreadExecutor, EXECUTOR_RESOURCE.ge...
@UdafFactory(description = "Compute average of column with type Integer.", aggregateSchema = "STRUCT<SUM integer, COUNT bigint>") public static TableUdaf<Integer, Struct, Double> averageInt() { return getAverageImplementation( 0, STRUCT_INT, (sum, newValue) -> sum.getInt32(SUM) + ne...
@Test public void shouldAverageEmpty() { final TableUdaf<Integer, Struct, Double> udaf = AverageUdaf.averageInt(); final Struct agg = udaf.initialize(); final double avg = udaf.map(agg); assertThat(0.0, equalTo(avg)); }
@Operation(summary = "delUserById", description = "DELETE_USER_BY_ID_NOTES") @Parameters({ @Parameter(name = "id", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")) }) @PostMapping(value = "/delete") @ResponseStatus(HttpStatus.OK) @A...
@Test public void testDelUserById() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("id", "32"); MvcResult mvcResult = mockMvc.perform(post("/users/delete") .header(SESSION_ID, sessionId) .params(paramsM...
@VisibleForTesting static Optional<String> getChildValue(@Nullable Xpp3Dom dom, String... childNodePath) { if (dom == null) { return Optional.empty(); } Xpp3Dom node = dom; for (String child : childNodePath) { node = node.getChild(child); if (node == null) { return Optional....
@Test public void testGetChildValue_noChild() { Xpp3Dom root = newXpp3Dom("root", "value"); assertThat(MavenProjectProperties.getChildValue(root, "foo")).isEmpty(); assertThat(MavenProjectProperties.getChildValue(root, "foo", "bar")).isEmpty(); }
@Override public Integer getJavaVersion() { return jarJavaVersion; }
@Test public void testGetJavaVersion() { SpringBootPackagedProcessor springBootPackagedProcessor = new SpringBootPackagedProcessor(Paths.get("ignore"), 8); assertThat(springBootPackagedProcessor.getJavaVersion()).isEqualTo(8); }
protected static SimpleDateFormat getLog4j2Appender() { Optional<Appender> log4j2xmlAppender = configuration.getAppenders().values().stream() .filter( a -> a.getName().equalsIgnoreCase( log4J2Appender ) ).findFirst(); if ( log4j2xmlAppender.isPresent() ) { ArrayList<String> matchesArray = ne...
@Test public void testGetLog4j2UsingAppender2() { // This will throw an Illegal pattern character 'n' Exception parsing to Java SimpleDateFormat() and set Default // Pattern value "yyyy/MM/dd HH:mm:ss" KettleLogLayout.log4J2Appender = "pdi-execution-appender-test-2"; Assert.assertNotSame( "HH:mm:ss,nn...
synchronized void ensureTokenInitialized() throws IOException { // we haven't inited yet, or we used to have a token but it expired if (!hasInitedToken || (action != null && !action.isValid())) { //since we don't already have a token, go get one Token<?> token = fs.getDelegationToken(null); //...
@Test public void testCachedInitialization() throws IOException, URISyntaxException { Configuration conf = new Configuration(); DummyFs fs = spy(new DummyFs()); Token<TokenIdentifier> token = new Token<TokenIdentifier>(new byte[0], new byte[0], DummyFs.TOKEN_KIND, new Text("127.0.0.1:1234")); ...
public Pair<Long, Jwts> refresh(String refreshToken) { JwtClaims claims = refreshTokenProvider.getJwtClaimsFromToken(refreshToken); Long userId = JwtClaimsParserUtil.getClaimsValue(claims, RefreshTokenClaimKeys.USER_ID.getValue(), Long::parseLong); String role = JwtClaimsParserUtil.getClaimsVal...
@Test @DisplayName("사용자 아이디에 해당하는 리프레시 토큰이 존재할 시, 리프레시 토큰 갱신에 성공한다.") public void RefreshTokenRefreshSuccess() { // given RefreshToken refreshToken = RefreshToken.builder() .userId(1L) .token("refreshToken") .ttl(1000L) .build(); ...
@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 testListKeyDeserializerNoArgConstructorsShouldThrowConfigExceptionDueListClassNotFound() { props.put(CommonClientConfigs.DEFAULT_LIST_KEY_SERDE_TYPE_CLASS, nonExistingClass); props.put(CommonClientConfigs.DEFAULT_LIST_KEY_SERDE_INNER_CLASS, Serdes.StringSerde.class); final ...
@POST @Timed @ApiOperation(value = "Resolve dependencies of entities and return their configuration") @RequiresPermissions(RestPermissions.CATALOG_RESOLVE) @NoAuditEvent("this is not changing any data") public CatalogResolveResponse resolveEntities( @ApiParam(name = "JSON body", required...
@Test public void resolveEntities() { final EntityDescriptor entityDescriptor = EntityDescriptor.builder() .id(ModelId.of("1234567890")) .type(ModelType.of("test", "1")) .build(); final MutableGraph<EntityDescriptor> entityDescriptors = GraphBuilder.di...
@Nonnull public static Number shiftRightU(@Nonnull Number value, @Nonnull Number shift) { // Check for widest types first, go down the type list to narrower types until reaching int. if (value instanceof Long) { return value.longValue() >>> shift.longValue(); } else { return value.intValue() >>> shift.intV...
@Test void testShiftRightU() { assertEquals(16 >> 1, NumberUtil.shiftRightU(16, 1)); assertEquals(16L >> 1, NumberUtil.shiftRightU(16L, 1)); }
public RuntimeOptionsBuilder parse(String... args) { return parse(Arrays.asList(args)); }
@Test void scans_class_path_root_for_glue_by_default() { RuntimeOptions options = parser .parse() .addDefaultGlueIfAbsent() .build(); assertThat(options.getGlue(), is(singletonList(rootPackageUri()))); }
@Override @SuppressWarnings("unchecked") @SuppressFBWarnings("SERVLET_QUERY_STRING") public void include(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { if (lambdaContainerHandler == null) { throw new IllegalStateExceptio...
@Test void include_appendsNewHeader_cannotAppendNewHeaders() throws InvalidRequestEventException, IOException { final String firstPart = "first"; final String secondPart = "second"; final String headerKey = "X-Custom-Header"; AwsProxyRequest proxyRequest = new AwsProxyRequestBuilder(...
public long getLong(HazelcastProperty property) { return Long.parseLong(getString(property)); }
@Test public void getLong() { long lockMaxLeaseTimeSeconds = defaultProperties.getLong(ClusterProperty.LOCK_MAX_LEASE_TIME_SECONDS); assertEquals(Long.MAX_VALUE, lockMaxLeaseTimeSeconds); }
public static AvroGenericCoder of(Schema schema) { return AvroGenericCoder.of(schema); }
@Test @Category(NeedsRunner.class) public void testDefaultCoder() throws Exception { // Use MyRecord as input and output types without explicitly specifying // a coder (this uses the default coders, which may not be AvroCoder). PCollection<String> output = pipeline .apply(Create.of(n...
public static LocalDateTime parse(String dateTime, DateTimeFormatter dateTimeFormatter) { TemporalAccessor parsedTimestamp = dateTimeFormatter.parse(dateTime); LocalTime localTime = parsedTimestamp.query(TemporalQueries.localTime()); LocalDate localDate = parsedTimestamp.query(TemporalQueries.lo...
@Test public void testParseDateString() { final String datetime = "2023-12-22 00:00:00"; LocalDateTime parse = DateTimeUtils.parse(datetime, Formatter.YYYY_MM_DD_HH_MM_SS); Assertions.assertEquals(0, parse.getMinute()); Assertions.assertEquals(0, parse.getHour()); Assertions....
public static KeyStore loadKeyStore(final String name, final char[] password) { InputStream stream = null; try { stream = Config.getInstance().getInputStreamFromFile(name); if (stream == null) { String message = "Unable to load keystore '" + name + "', please prov...
@Test public void testLoadPKCS12KeyStore() { KeyStore keyStore = TlsUtil.loadKeyStore("serverpkcs12.keystore", PASSWORD); Assert.assertNotNull(keyStore); }
public List<R> scanForClasspathResource(String resourceName, Predicate<String> packageFilter) { requireNonNull(resourceName, "resourceName must not be null"); requireNonNull(packageFilter, "packageFilter must not be null"); List<URI> urisForResource = getUrisForResource(getClassLoader(), resourc...
@Test void scanForClasspathResourceWithSpaces() { String resourceName = "io/cucumber/core/resource/test/spaces in name resource.txt"; List<URI> resources = resourceScanner.scanForClasspathResource(resourceName, aPackage -> true); assertThat(resources, contains(URI.create("classpa...
static VertexWithInputConfig join( DAG dag, String mapName, String tableName, JetJoinInfo joinInfo, KvRowProjector.Supplier rightRowProjectorSupplier ) { int leftEquiJoinPrimitiveKeyIndex = leftEquiJoinPrimitiveKeyIndex(joinInfo, rightRowProjectorS...
@Test @Parameters(method = "joinTypes") public void test_joinByPredicate(JoinRelType joinType) { // given given(rightRowProjectorSupplier.paths()).willReturn(new QueryPath[]{QueryPath.create("path")}); given(dag.newUniqueVertex(contains("Predicate"), isA(ProcessorMetaSupplier.class))).wi...
static boolean isValidComparison( final SqlType left, final ComparisonExpression.Type operator, final SqlType right ) { if (left == null || right == null) { throw nullSchemaException(left, operator, right); } return HANDLERS.stream() .filter(h -> h.handles.test(left.baseType())) ...
@SuppressWarnings("ConstantConditions") @Test public void shouldNotCompareLeftNullSchema() { // When: final Exception e = assertThrows( KsqlException.class, () -> ComparisonUtil.isValidComparison(null, ComparisonExpression.Type.EQUAL, SqlTypes.STRING) ); // Then: assertThat(e.ge...
@Override public String getName() { return "AppVeyor"; }
@Test public void getName() { assertThat(underTest.getName()).isEqualTo("AppVeyor"); }
public final void isAtLeast(int other) { isAtLeast((double) other); }
@Test public void isAtLeast_int() { expectFailureWhenTestingThat(2.0).isAtLeast(3); assertThat(2.0).isAtLeast(2); assertThat(2.0).isAtLeast(1); }
public Statistics getTableStatistics( OptimizerContext session, Table table, List<ColumnRefOperator> columns, List<PartitionKey> partitionKeys) { Statistics.Builder builder = Statistics.builder(); HiveMetaStoreTable hmsTbl = (HiveMetaStoreTable) table; ...
@Test public void testGetTableStatistics() throws AnalysisException { HiveTable hiveTable = (HiveTable) hmsOps.getTable("db1", "table1"); ColumnRefOperator partColumnRefOperator = new ColumnRefOperator(0, Type.INT, "col1", true); ColumnRefOperator dataColumnRefOperator = new ColumnRefOperato...
public static String config() { return "v1/config"; }
@Test public void testConfigPath() { // prefix does not affect the config route because config is merged into catalog properties assertThat(ResourcePaths.config()).isEqualTo("v1/config"); }
@Override public void preflight(final Path source, final Path target) throws BackgroundException { if(!CteraTouchFeature.validate(target.getName())) { throw new InvalidFilenameException(MessageFormat.format(LocaleFactory.localizedString("Cannot rename {0}", "Error"), source.getName())).withFile(...
@Test public void testPreflightDirectoryAccessDeniedTargetNoCreatedirectoriesPermissionCustomProps() throws Exception { final Path source = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); source.setAttributes(so...
public static <T> List<T> notNullElements(List<T> list, String name) { notNull(list, name); for (int i = 0; i < list.size(); i++) { notNull(list.get(i), MessageFormat.format("list [{0}] element [{1}]", name, i)); } return list; }
@Test public void notNullElementsNotNull() { Check.notNullElements(new ArrayList<String>(), "name"); Check.notNullElements(Arrays.asList("a"), "name"); }
public boolean validate(final Protocol protocol, final LoginOptions options) { return protocol.validate(this, options); }
@Test public void testLoginAnonymous1() { Credentials credentials = new Credentials(PreferencesFactory.get().getProperty("connection.login.anon.name"), PreferencesFactory.get().getProperty("connection.login.anon.pass")); assertTrue(credentials.validate(new TestProtocol(Scheme.ftp), n...
public static int readIntBE(byte[] buffer, int offset) { return ((buffer[offset] & 0xFF) << 24) | ((buffer[offset + 1] & 0xFF) << 16) | ((buffer[offset + 2] & 0xFF) << 8) | (buffer[offset + 3] & 0xFF); }
@Test public void testReadInt() { int[] values = { 0, 1, -1, Byte.MAX_VALUE, Short.MAX_VALUE, 2 * Short.MAX_VALUE, Integer.MAX_VALUE / 2, Integer.MIN_VALUE / 2, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE }; ByteBuffer buffer = ByteBuffer.allocate(4 * valu...
@Override public <K, T> UncommittedBundle<T> createKeyedBundle( StructuralKey<K> key, PCollection<T> output) { return new CloningBundle<>(underlying.createKeyedBundle(key, output)); }
@Test public void keyedBundleDecodeFailsAddFails() { PCollection<Record> pc = p.apply(Create.empty(new RecordNoDecodeCoder())); UncommittedBundle<Record> bundle = factory.createKeyedBundle(StructuralKey.of("foo", StringUtf8Coder.of()), pc); thrown.expect(UserCodeException.class); thrown.expec...
public static boolean isCompositeType(LogicalType logicalType) { if (logicalType instanceof DistinctType) { return isCompositeType(((DistinctType) logicalType).getSourceType()); } LogicalTypeRoot typeRoot = logicalType.getTypeRoot(); return typeRoot == STRUCTURED_TYPE || typ...
@Test void testIsCompositeTypeStructuredType() { StructuredType logicalType = StructuredType.newBuilder(ObjectIdentifier.of("catalog", "database", "type")) .attributes( Arrays.asList( new Structur...
@Override public String getDataXML( Object object ) throws IOException { StringBuilder xml = new StringBuilder(); String string; if ( object != null ) { try { switch ( storageType ) { case STORAGE_TYPE_NORMAL: // Handle Content -- only when not NULL // ...
@Test public void testGetDataXML() throws IOException { BigDecimal bigDecimal = BigDecimal.ONE; ValueMetaBase valueDoubleMetaBase = new ValueMetaBase( String.valueOf( bigDecimal ), ValueMetaInterface.TYPE_BIGNUMBER ); assertEquals( "<value-data>" + Encode.forXml( String.valueOf( bigDecimal ) )...
public static Application fromServicesXml(String xml, Networking networking) { Path applicationDir = StandaloneContainerRunner.createApplicationPackage(xml); return new Application(applicationDir, networking, true); }
@Test void minimal_application_can_be_constructed() { try (Application application = Application.fromServicesXml("<container version=\"1.0\"/>", Networking.disable)) { } }
@Override public Publisher<Exchange> to(String uri, Object data) { String streamName = requestedUriToStream.computeIfAbsent(uri, camelUri -> { try { String uuid = context.getUuidGenerator().generateUuid(); context.addRoutes(new RouteBuilder() { ...
@Test public void testToFunctionWithExchange() throws Exception { context.start(); Set<String> values = Collections.synchronizedSet(new TreeSet<>()); CountDownLatch latch = new CountDownLatch(3); Function<Object, Publisher<Exchange>> fun = crs.to("bean:hello"); Flux.just(1,...
public static List<String> orderFields(List<String> fields, List<SortSpec> sorts) { if (!needsReorderingFields(fields, sorts)) { return fields; } final List<String> sortFields = sorts.stream() .filter(ValuesBucketOrdering::isGroupingSort) .map(SortSpe...
@Test void pivotUsedForSortIsPulledToTop() { final List<SortSpec> pivotSorts = List.of(PivotSort.create("baz", SortSpec.Direction.Descending)); final List<String> orderedBuckets = ValuesBucketOrdering.orderFields(List.of("foo", "bar", "baz"), pivotSorts); assertThat(orderedBuckets).contain...
@SuppressWarnings("unused") // Required for automatic type inference public static <K> Builder0<K> forClass(final Class<K> type) { return new Builder0<>(); }
@Test public void shouldWorkWithSuppliers1() { // Given: handlerMap1 = HandlerMaps.forClass(BaseType.class).withArgType(String.class) .put(LeafTypeA.class, () -> handler1_1) .build(); // When: handlerMap1.get(LeafTypeA.class).handle("A", LEAF_A); // Then: verify(handler1_1).h...
public static HazelcastInstance newHazelcastInstance(Config config) { if (config == null) { config = Config.load(); } return newHazelcastInstance( config, config.getInstanceName(), new DefaultNodeContext() ); }
@Test(expected = IllegalStateException.class) public void test_NewInstance_terminateInstance_afterNodeStart() throws Exception { NodeContext context = new TestNodeContext() { @Override public NodeExtension createNodeExtension(final Node node) { NodeExtension nodeExten...
@Override public String named() { return PluginEnum.WEB_SOCKET.getName(); }
@Test public void namedTest() { assertEquals(PluginEnum.WEB_SOCKET.getName(), webSocketPlugin.named()); }
public FEELFnResult<BigDecimal> invoke(@ParameterName("list") List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "the list cannot be null")); } if (list.isEmpty()) { return FEELFnResult.ofResult(null); // DMN ...
@Test void invokeListParamContainsUnsupportedType() { FunctionTestUtil.assertResultError(sumFunction.invoke(Arrays.asList(10, "test", 2)), InvalidParametersEvent.class); }
@Override public T getValue() { return transform(base.getValue()); }
@Test public void returnsATransformedValue() throws Exception { assertThat(gauge2.getValue()) .isEqualTo(3); }
@Override public Integer addAndGetRank(double score, V object) { return get(addAndGetRankAsync(score, object)); }
@Test public void testAddAndGetRank() { RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple"); Integer res = set.addAndGetRank(0.3, 1); assertThat(res).isEqualTo(0); Integer res2 = set.addAndGetRank(0.4, 2); assertThat(res2).isEqualTo(1); Integer res3 ...
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check ...
@Test public void testDisplayDataIncludesExplicitlySetDefaults() { HasDefaults options = PipelineOptionsFactory.as(HasDefaults.class); String defaultValue = options.getFoo(); options.setFoo(defaultValue); DisplayData data = DisplayData.from(options); assertThat(data, hasDisplayItem("foo", default...