focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override protected void write(final MySQLPacketPayload payload) { payload.writeInt1(protocolVersion); payload.writeStringNul(serverVersion); payload.writeInt4(connectionId); payload.writeStringNul(new String(authPluginData.getAuthenticationPluginDataPart1())); payload.writeI...
@Test void assertWrite() { MySQLAuthenticationPluginData authPluginData = new MySQLAuthenticationPluginData(part1, part2); new MySQLHandshakePacket(1000, false, authPluginData).write(payload); verify(payload).writeInt1(MySQLConstants.PROTOCOL_VERSION); verify(payload).writeStringNul(...
public String getString(HazelcastProperty property) { String value = properties.getProperty(property.getName()); if (value != null) { return value; } value = property.getSystemProperty(); if (value != null) { return value; } HazelcastProp...
@Test public void getString_whenDeprecatedNameUsed() { Properties props = new Properties(); props.setProperty("oldname", "10"); HazelcastProperties properties = new HazelcastProperties(props); HazelcastProperty property = new HazelcastProperty("newname") .setDeprecat...
@Override public boolean askForNotificationPostPermission(@NonNull Activity activity) { return PermissionRequestHelper.check( activity, PermissionRequestHelper.NOTIFICATION_PERMISSION_REQUEST_CODE); }
@Test @Config(sdk = Build.VERSION_CODES.TIRAMISU) public void testReturnsTrueIfAlreadyHasPermission() { var appShadow = Shadows.shadowOf(RuntimeEnvironment.getApplication()); appShadow.grantPermissions(Manifest.permission.POST_NOTIFICATIONS); try (var scenario = ActivityScenario.launch(TestFragmentActiv...
public static int getDigit(final int index, final byte value) { if (value < 0x30 || value > 0x39) { throw new AsciiNumberFormatException("'" + ((char)value) + "' is not a valid digit @ " + index); } return value - 0x30; }
@Test void shouldThrowExceptionWhenDecodingCharNonNumericValue() { assertThrows(AsciiNumberFormatException.class, () -> AsciiEncoding.getDigit(0, 'a')); }
@Operation(summary = "queryDataSourceListPaging", description = "QUERY_DATA_SOURCE_LIST_PAGING_NOTES") @Parameters({ @Parameter(name = "searchVal", description = "SEARCH_VAL", schema = @Schema(implementation = String.class)), @Parameter(name = "pageNo", description = "PAGE_NO", required = tr...
@Test public void testQueryDataSourceListPaging() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("searchVal", "mysql"); paramsMap.add("pageNo", "1"); paramsMap.add("pageSize", "1"); MvcResult mvcResult = mockMvc.perform...
@UdafFactory(description = "Compute sample standard deviation of column with type Integer.", aggregateSchema = "STRUCT<SUM integer, COUNT bigint, M2 double>") public static TableUdaf<Integer, Struct, Double> stdDevInt() { return getStdDevImplementation( 0, STRUCT_INT, (agg, newValue)...
@Test public void shouldMergeInts() { final TableUdaf<Integer, Struct, Double> udaf = stdDevInt(); Struct left = udaf.initialize(); final Integer[] leftValues = new Integer[] {5, 8, 10}; for (final Integer thisValue : leftValues) { left = udaf.aggregate(thisValue, left); } Struct right...
@Override public Set<ConstraintCheckResult> checkConstraints(Collection<Constraint> requestedConstraints) { final ImmutableSet.Builder<ConstraintCheckResult> fulfilledConstraints = ImmutableSet.builder(); for (Constraint constraint : requestedConstraints) { if (constraint instanceof Plug...
@Test public void checkConstraintsFails() { final TestPluginMetaData pluginMetaData = new TestPluginMetaData(); final PluginVersionConstraintChecker constraintChecker = new PluginVersionConstraintChecker(Collections.singleton(pluginMetaData)); final GraylogVersionConstraint graylogVersionCo...
public List<MavenArtifact> searchSha1(String sha1) throws IOException, TooManyRequestsException { if (null == sha1 || !sha1.matches("^[0-9A-Fa-f]{40}$")) { throw new IllegalArgumentException("Invalid SHA1 format"); } if (cache != null) { final List<MavenArtifact> cached =...
@Test(expected = IllegalArgumentException.class) public void testNullSha1() throws Exception { searcher.searchSha1(null); }
@Override public void collect(long elapsedTime, StatementContext ctx) { final Timer timer = getTimer(ctx); timer.update(elapsedTime, TimeUnit.NANOSECONDS); }
@Test public void updatesTimerForSqlObjects() throws Exception { final StatementNameStrategy strategy = new SmartNameStrategy(); final InstrumentedTimingCollector collector = new InstrumentedTimingCollector(registry, ...
@Override public Collection<String> getActualTableNames() { return actualTableNames; }
@Test void assertGetActualTableMapper() { assertThat(new LinkedList<>(ruleAttribute.getActualTableNames()), is(Collections.singletonList("foo_tbl_0"))); }
@Override public void dropDb(String dbName, boolean isForceDrop) throws MetaNotFoundException { if (listTableNames(dbName).size() != 0) { throw new StarRocksConnectorException("Database %s not empty", dbName); } hmsOps.dropDb(dbName, isForceDrop); }
@Test public void dropDbTest() { ExceptionChecker.expectThrowsWithMsg(StarRocksConnectorException.class, "Database d1 not empty", () -> hiveMetadata.dropDb("d1", true)); ExceptionChecker.expectThrowsWithMsg(MetaNotFoundException.class, "Failed to acce...
public static void releaseLock(FileLock lock) throws IOException { String lockPath = LOCK_MAP.remove(lock); if (lockPath == null) { throw new LockException("Cannot release unobtained lock"); } lock.release(); lock.channel().close(); boolean removed = LOCK_HELD...
@Test public void LockReleaseLock() throws IOException { FileLockFactory.releaseLock(lock); }
public MyNewIssuesNotification newMyNewIssuesNotification(Map<String, UserDto> assigneesByUuid) { verifyAssigneesByUuid(assigneesByUuid); return new MyNewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid)); }
@Test public void newMyNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_returns_name_of_project_in_TreeRootHolder() { treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).setUuid("rootUuid").setName("root").build()); MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotificat...
@Override public void close() throws IOException { this.inStream.close(); }
@Test void testClose() throws Exception { final AtomicBoolean closeCalled = new AtomicBoolean(false); InputStream mockedInputStream = new InputStream() { @Override public int read() { return 0; } ...
@Deprecated public static int findCounterIdByRecording(final CountersReader countersReader, final long recordingId) { return findCounterIdByRecording(countersReader, recordingId, Aeron.NULL_VALUE); }
@Test void shouldFindByRecordingIdAndArchiveId() { final long recordingId = 42; final long archiveId = 19; final int sourceIdentityLength = 10; final CountersReader countersReader = mock(CountersReader.class); when(countersReader.maxCounterId()).thenReturn(5); whe...
@Udf(description = "Converts a string representation of a date in the given format" + " into the number of days since 1970-01-01 00:00:00 UTC/GMT.") public int stringToDate( @UdfParameter( description = "The string representation of a date.") final String formattedDate, @UdfParameter( ...
@Test public void shouldThrowOnNullDateFormat() { final Exception e = assertThrows( KsqlFunctionException.class, () -> udf.stringToDate("2021-12-01", null) ); // Then: assertThat(e.getMessage(), containsString("Failed to parse date '2021-12-01' with formatter 'null'")); }
@Override public Image call() throws LayerPropertyNotFoundException { try (ProgressEventDispatcher ignored = progressEventDispatcherFactory.create("building image format", 1); TimerEventDispatcher ignored2 = new TimerEventDispatcher(buildContext.getEventHandlers(), DESCRIPTION)) { ...
@Test public void test_inheritedUser() { Mockito.when(mockContainerConfiguration.getUser()).thenReturn(null); Image image = new BuildImageStep( mockBuildContext, mockProgressEventDispatcherFactory, baseImage, baseImageLayers, ...
static ArgumentParser argParser() { ArgumentParser parser = ArgumentParsers .newArgumentParser("producer-performance") .defaultHelp(true) .description("This tool is used to verify the producer performance. To enable transactions, " + "you c...
@Test public void testEnableTransactionByTransactionId() throws IOException, ArgumentParserException { File producerConfigFile = createTempFile("transactional.id=foobar"); ArgumentParser parser = ProducerPerformance.argParser(); String[] args = new String[]{ "--topic", "Hello-Kaf...
@SuppressWarnings("unchecked") @Override public Result execute(Query query, Target target) { Query adjustedQuery = adjustQuery(query); switch (target.mode()) { case ALL_NODES: adjustedQuery = Query.of(adjustedQuery).partitionIdSet(getAllPartitionIds()).build(); ...
@Test public void runQueryOnAllPartitions() { Predicate<Object, Object> predicate = Predicates.equal("this", value); Query query = Query.of().mapName(map.getName()).predicate(predicate).iterationType(KEY).build(); QueryResult result = queryEngine.execute(query, Target.ALL_NODES); a...
@Override public FinishApplicationMasterResponse finishApplicationMaster( FinishApplicationMasterRequest request) throws YarnException, IOException { try { return this.rmClient.finishApplicationMaster(request); } catch (ApplicationMasterNotRegisteredException e) { LOG.warn("Out of sync...
@Test public void testConcurrentReregister() throws YarnException, IOException { // Set RM restart and failover flag this.mockAMS.setFailoverFlag(); this.mockAMS.setThrowAlreadyRegister(); relayer.finishApplicationMaster(null); }
@ScalarFunction(value = "noisy_empty_approx_set_sfm", deterministic = false) @Description("an SfmSketch object representing an empty set") @SqlType(SfmSketchType.NAME) public static Slice emptyApproxSet(@SqlType(StandardTypes.DOUBLE) double epsilon, @SqlType(StandardTypes.BIGINT) long numberOfBu...
@Test public void testEmptyApproxSet() { // with no privacy (epsilon = infinity), an empty approx set should return 0 cardinality assertFunction("cardinality(noisy_empty_approx_set_sfm(infinity()))", BIGINT, 0L); assertFunction("cardinality(noisy_empty_approx_set_sfm(infinity(), 4096))",...
private ScalarOperator reduceDatetimeToDateCast(BinaryPredicateOperator operator) { ScalarOperator castChild = operator.getChild(0).getChild(0); ConstantOperator child2 = (ConstantOperator) operator.getChild(1); if (child2.isNull()) { return operator; } LocalDateTime...
@Test public void testReduceDatetimeToDateCast() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); ReduceCastRule reduceCastRule = new ReduceCastRule(); { CastOperator castOperator = new CastOperator(Type.DATE, new ColumnRefO...
public ConsumerStatsManager getConsumerStatsManager() { return this.defaultMQPushConsumerImpl.getConsumerStatsManager(); }
@Test public void testGetConsumerStatsManager() { ConsumerStatsManager actual = popService.getConsumerStatsManager(); assertNotNull(actual); assertEquals(consumerStatsManager, actual); }
static void start(Keys key, String value, StringBuilder b) { b.append(key.name()).append(AuditConstants.KEY_VAL_SEPARATOR).append(value); }
@Test public void testRouterAuditLoggerWithIP() throws Exception { Configuration conf = new Configuration(); RPC.setProtocolEngine(conf, TestRpcBase.TestRpcService.class, ProtobufRpcEngine2.class); // Create server side implementation MyTestRouterRPCServer serverImpl = new MyTestRouterRPCServer(); ...
@VisibleForTesting static String formatBonusPercentage(float bonus) { final int bonusValue = Math.round(10_000 * bonus); final float bonusPercent = bonusValue / 100f; final int bonusPercentInt = (int) bonusPercent; if (bonusPercent == bonusPercentInt) { return String.valueOf(bonusPercentInt); } else...
@Test public void testFormatBonusPercentage() { assertEquals("33.33", formatBonusPercentage(0.33333333f)); assertEquals("50", formatBonusPercentage(0.5f)); assertEquals("102.5", formatBonusPercentage(1.025f)); assertEquals("105", formatBonusPercentage(1.05f)); assertEquals("110", formatBonusPercentage(1.1f)...
@JsonProperty public boolean isReportOnStop() { return reportOnStop; }
@Test void reportOnStopCanBeTrue() throws Exception { config = factory.build(new ResourceConfigurationSourceProvider(), "yaml/metrics-report-on-stop.yml"); assertThat(config.isReportOnStop()).isTrue(); }
@Override public String execute(CommandContext commandContext, String[] args) { StringBuilder buf = new StringBuilder(); String port = null; boolean detail = false; if (args.length > 0) { for (String part : args) { if ("-l".equals(part)) { ...
@Test void testNoPort() throws RemotingException { String result = port.execute(mockCommandContext, new String[] {"-l", "20880"}); assertEquals("No such port 20880", result); }
protected boolean isWrapperClass(Class<?> clazz) { Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0] == type) { return true; ...
@Test void isWrapperClass() { assertFalse(getExtensionLoader(Demo.class).isWrapperClass(DemoImpl.class)); assertTrue(getExtensionLoader(Demo.class).isWrapperClass(DemoWrapper.class)); assertTrue(getExtensionLoader(Demo.class).isWrapperClass(DemoWrapper2.class)); }
public void cleanupBeforeRelaunch(Container container) throws IOException, InterruptedException { if (container.getLocalizedResources() != null) { Map<Path, Path> symLinks = resolveSymLinks( container.getLocalizedResources(), container.getUser()); for (Map.Entry<Path, Path> symLink : s...
@Test public void testCleanupBeforeLaunch() throws Exception { Container container = mock(Container.class); java.nio.file.Path linkName = Paths.get("target/linkName"); java.nio.file.Path target = Paths.get("target"); //deletes the link if it already exists because of previous test failures FileUti...
public List<ZAddressRange<Integer>> zOrderSearchCurveIntegers(List<ZValueRange> ranges) { List<ZAddressRange<Long>> addressRanges = zOrderSearchCurve(ranges); List<ZAddressRange<Integer>> integerAddressRanges = new ArrayList<>(); for (ZAddressRange<Long> addressRange : addressRanges) { ...
@Test public void testZOrderSearchCurveMultipleRanges() { List<Integer> bitPositions = ImmutableList.of(3); ZOrder zOrder = new ZOrder(bitPositions); List<ZValueRange> ranges = ImmutableList.of(new ZValueRange(ImmutableList.of(Optional.empty(), Optional.of(6)), ImmutableList.of(Optional...
@SneakyThrows @Override public Integer call() throws Exception { super.call(); PicocliRunner.call(App.class, "flow", "namespace", "--help"); return 0; }
@Test void runWithNoParam() { ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); try (ApplicationContext ctx = ApplicationContext.builder().deduceEnvironment(false).start()) { String[] args = {}; Integer call = PicocliRunner...
public Predicate convert(ScalarOperator operator) { if (operator == null) { return null; } return operator.accept(this, null); }
@Test public void testGreaterEq() { ConstantOperator value = ConstantOperator.createInt(5); ScalarOperator op = new BinaryPredicateOperator(BinaryType.GE, F0, value); Predicate result = CONVERTER.convert(op); Assert.assertTrue(result instanceof LeafPredicate); LeafPredicate l...
@Override public Result search(Query query, Execution execution) { Result mergedResults = execution.search(query); var targets = getTargets(query.getModel().getSources(), query.properties()); warnIfUnresolvedSearchChains(extractErrors(targets), mergedResults.hits()); var prunedTarg...
@Test void require_that_hits_are_not_automatically_filled() { Result result = federationToSingleAddHitSearcher().search(); assertNotFilled(firstHitInFirstGroup(result)); }
public abstract long getFirstDataPageOffset();
@Test public void testConversionSmall() { long small = 1; ColumnChunkMetaData md = newMD(small); assertTrue(md instanceof IntColumnChunkMetaData); assertEquals(small, md.getFirstDataPageOffset()); }
@Override public boolean onActivity() { return false; }
@Test public void testOnActivity() { assertFalse(strategy.onActivity(), "onActivity() should always return false."); }
@Override public String[] getReferencedObjectDescriptions() { return new String[] { BaseMessages.getString( PKG, "BaseStreamStepMeta.ReferencedObject.SubTrans.Description" ) }; }
@Test public void testReferencedObjectHasDescription() { BaseStreamStepMeta meta = new StuffStreamMeta(); assertEquals( 1, meta.getReferencedObjectDescriptions().length ); assertTrue( meta.getReferencedObjectDescriptions()[ 0 ] != null ); testRoundTrip( meta ); }
@Override public Map<String, Optional<HivePartitionDataInfo>> getPartitionDataInfos() { Map<String, Optional<HivePartitionDataInfo>> partitionDataInfos = Maps.newHashMap(); List<String> partitionNameToFetch = partitionNames; if (partitionLimit >= 0 && partitionLimit < partitionNames.size()) ...
@Test public void testGetPartitionDataInfos(@Mocked MetadataMgr metadataMgr) { List<PartitionInfo> partitionInfoList = createRemotePartitions(4); new Expectations() { { GlobalStateMgr.getCurrentState().getMetadataMgr(); result = metadataMgr; ...
@Override public Map<String, List<String>> getDockerCommandWithArguments() { return super.getDockerCommandWithArguments(); }
@Test public void testSetClientConfigDir() { dockerRunCommand.setClientConfigDir(CLIENT_CONFIG_PATH); assertEquals(CLIENT_CONFIG_PATH, StringUtils.join(",", dockerRunCommand.getDockerCommandWithArguments().get("docker-config"))); }
public static List<InetSocketAddress> getMasterRpcAddresses(AlluxioConfiguration conf) { // First check whether rpc addresses are explicitly configured. if (conf.isSet(PropertyKey.MASTER_RPC_ADDRESSES)) { return parseInetSocketAddresses(conf.getList(PropertyKey.MASTER_RPC_ADDRESSES)); } // Fall b...
@Test public void getMasterRpcAddressesFallback() { AlluxioConfiguration conf = createConf(ImmutableMap.of( PropertyKey.MASTER_EMBEDDED_JOURNAL_ADDRESSES, "host1:99,host2:100", PropertyKey.MASTER_RPC_PORT, 50)); assertEquals( Arrays.asList(InetSocketAddress.createUnreso...
@Override public Map<String, Object> batchInsertOrUpdate(List<ConfigAllInfo> configInfoList, String srcUser, String srcIp, Map<String, Object> configAdvanceInfo, SameConfigPolicy policy) throws NacosException { int succCount = 0; int skipCount = 0; List<Map<String, String>> failD...
@Test void testBatchInsertOrUpdateSkip() throws NacosException { List<ConfigAllInfo> configInfoList = new ArrayList<>(); //insert direct configInfoList.add(createMockConfigAllInfo(0)); //exist config and overwrite configInfoList.add(createMockConfigAllInfo(1)); //inse...
@Override public List<ProductCategoryDO> getCategoryList(ProductCategoryListReqVO listReqVO) { return productCategoryMapper.selectList(listReqVO); }
@Test public void testGetCategoryList() { // mock 数据 ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class, o -> { // 等会查询到 o.setName("奥特曼"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setParentId(PARENT_ID_NULL); }); productCa...
public static <T> TreeSet<Point<T>> subset(TimeWindow subsetWindow, NavigableSet<Point<T>> points) { checkNotNull(subsetWindow); checkNotNull(points); //if the input collection is empty the output collection will be empty to if (points.isEmpty()) { return newTreeSet(); ...
@Test public void subset_reflectsEndTime() { Track<NopHit> t1 = createTrackFromFile(getResourceFile("Track1.txt")); //this is the time of 21st point in the track Instant endTime = parseNopTime("07/08/2017", "14:10:45.534"); TimeWindow extractionWindow = TimeWindow.of(EPOCH, endTim...
@Override public MenuButton deserializeResponse(String answer) throws TelegramApiRequestException { return deserializeResponse(answer, MenuButton.class); }
@Test public void testGetChatMenuButtonDeserializeValidResponse() { String responseText = "{\"ok\":true,\"result\":{\"type\": \"default\"}}"; GetChatMenuButton getChatMenuButton = GetChatMenuButton .builder() .chatId("12345") .build(); try { ...
@Override public Page<RoleInfo> getRoles(int pageNo, int pageSize) { AuthPaginationHelper<RoleInfo> helper = createPaginationHelper(); String sqlCountRows = "SELECT count(*) FROM (SELECT DISTINCT role FROM roles) roles WHERE "; String sqlFetchRows = "SELECT role,userna...
@Test void testGetRoles() { Page<RoleInfo> roles = embeddedRolePersistService.getRoles(1, 10); assertNotNull(roles); }
public String resolve(String ensName) { if (Strings.isBlank(ensName) || (ensName.trim().length() == 1 && ensName.contains("."))) { return null; } try { if (isValidEnsName(ensName, addressLength)) { OffchainResolverContract resolver = obtainOffchainResolve...
@Test public void testResolve() throws Exception { configureSyncing(false); configureLatestBlock(System.currentTimeMillis() / 1000); // block timestamp is in seconds NetVersion netVersion = new NetVersion(); netVersion.setResult(Long.toString(ChainIdLong.MAINNET)); String r...
public static Sensor droppedRecordsSensor(final String threadId, final String taskId, final StreamsMetricsImpl streamsMetrics) { return invocationRateAndTotalSensor( threadId, taskId, ...
@Test public void shouldGetDroppedRecordsSensor() { final String operation = "dropped-records"; final String totalDescription = "The total number of dropped records"; final String rateDescription = "The average number of dropped records per second"; when(streamsMetrics.taskLevelSenso...
public synchronized long run(JobConfig jobConfig) throws JobDoesNotExistException, ResourceExhaustedException { long jobId = getNewJobId(); run(jobConfig, jobId); return jobId; }
@Test public void flowControl() throws Exception { try (MockedStatic<PlanCoordinator> mockStaticPlanCoordinator = mockPlanCoordinator()) { TestPlanConfig jobConfig = new TestPlanConfig("/test"); for (long i = 0; i < TEST_JOB_MASTER_JOB_CAPACITY; i++) { mJobMaster.run(jobConfig); } ...
@Override public void publishLong(MetricDescriptor descriptor, long value) { publishNumber(descriptor, value, LONG); }
@Test public void when_double_rendering_values_are_reported() { MetricDescriptor descriptor1 = newDescriptor() .withMetric("c") .withTag("tag1", "a") .withTag("tag2", "b"); jmxPublisher.publishLong(descriptor1, 1L); MetricDescriptor descriptor...
@Override public HttpServletRequest readRequest(HttpApiV2ProxyRequest request, SecurityContext securityContext, Context lambdaContext, ContainerConfig config) throws InvalidRequestEventException { if (request.getRequestContext() == null || request.getRequestContext().getHttp().getMethod() == null || request...
@Test void baseRequest_read_populatesSuccessfully() { HttpApiV2ProxyRequest req = new AwsProxyRequestBuilder("/hello", "GET") .referer("localhost") .userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36") ...
public final void moveToEnd(E element) { if (element.prev() == INVALID_INDEX || element.next() == INVALID_INDEX) { throw new RuntimeException("Element " + element + " is not in the collection."); } Element prevElement = indexToElement(head, elements, element.prev()); Element ...
@Test public void testMoveToEnd() { ImplicitLinkedHashCollection<TestElement> coll = new ImplicitLinkedHashCollection<>(); TestElement e1 = new TestElement(1, 1); TestElement e2 = new TestElement(2, 2); TestElement e3 = new TestElement(3, 3); assertTrue(coll.add(e1)); ...
protected GelfMessage toGELFMessage(final Message message) { final DateTime timestamp; final Object fieldTimeStamp = message.getField(Message.FIELD_TIMESTAMP); if (fieldTimeStamp instanceof DateTime) { timestamp = (DateTime) fieldTimeStamp; } else { timestamp = To...
@Test public void testToGELFMessageWithInvalidNumericLevel() throws Exception { final GelfTransport transport = mock(GelfTransport.class); final GelfOutput gelfOutput = new GelfOutput(transport); final DateTime now = DateTime.now(DateTimeZone.UTC); final Message message = messageFact...
public void processVerstrekkingAanAfnemer(VerstrekkingAanAfnemer verstrekkingAanAfnemer){ if (logger.isDebugEnabled()) logger.debug("Processing verstrekkingAanAfnemer: {}", marshallElement(verstrekkingAanAfnemer)); Afnemersbericht afnemersbericht = afnemersberichtRepository.findByOnzeRefere...
@Test public void testProcessAf11(){ String testANummer = "SSSSSSSSSS"; Af11 testAf11 = TestDglMessagesUtil.createTestAf11(testANummer); VerstrekkingInhoudType inhoudType = new VerstrekkingInhoudType(); inhoudType.setAf11(testAf11); GeversioneerdType type = new GeversioneerdT...
@Override public boolean accept(RequestedField field) { return Message.FIELD_GL2_SOURCE_NODE.equals(field.name()) && acceptsDecorator(field.decorator()); }
@Test void accept() { Assertions.assertThat(decorator.accept(RequestedField.parse(Message.FIELD_GL2_SOURCE_NODE))).isTrue(); Assertions.assertThat(decorator.accept(RequestedField.parse(Message.FIELD_STREAMS))).isFalse(); }
@Override public int hashCode() { return Objects.hash(change, changedIssues); }
@Test public void hashcode_is_based_on_change_and_issues() { AnalysisChange analysisChange = new AnalysisChange(new Random().nextLong()); ChangedIssue changedIssue = IssuesChangesNotificationBuilderTesting.newChangedIssue("doo", IssuesChangesNotificationBuilderTesting.newProject("prj"), newRandomNotAHot...
public void addPet(Pet body) throws RestClientException { addPetWithHttpInfo(body); }
@Test public void addPetTest() { Pet body = null; api.addPet(body); // TODO: test validations }
@Override public <R extends MessageResponse<?>> void chatStream(Prompt<R> prompt, StreamResponseListener<R> listener, ChatOptions options) { LlmClient llmClient = new SseClient(); Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers....
@Test public void testChatOllama() { OpenAiLlmConfig config = new OpenAiLlmConfig(); config.setEndpoint("http://localhost:11434"); config.setModel("llama3"); // config.setDebug(true); Llm llm = new OpenAiLlm(config); llm.chatStream("who are you", new StreamResponseLis...
@Override public void verify(X509Certificate certificate, Date date) { logger.debug("Verifying {} issued by {}", certificate.getSubjectX500Principal(), certificate.getIssuerX500Principal()); // Create trustAnchors final Set<TrustAnchor> trustAnchors = getTrusted().stream().map( ...
@Test public void shouldThrowExceptionIfCertificateIsExpired() { thrown.expect(VerificationException.class); thrown.expectMessage("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"); ...
@Override public void accept(Point newPoint) { //ensure this method is never called by multiple threads at the same time. parallelismDetector.run( () -> doAccept(newPoint) ); }
@Test public void testTrackClosure_atTimeLimit() { TestConsumer consumer = new TestConsumer(); Duration TIME_LIMIT = Duration.ofSeconds(5); TrackMaker maker = new TrackMaker(TIME_LIMIT, consumer); assertTrue( consumer.numCallsToAccept == 0, "The consumer h...
public void remove(String key) { if (key == null) { return; } Map<String, String> oldMap = copyOnThreadLocal.get(); if (oldMap == null) return; Integer lastOp = getAndSetLastOperation(WRITE_OPERATION); if (wasLastOpReadOrNull(lastOp)) { Map<String, String> newMap = duplicateAndInse...
@Test public void removeForNullKeyTest() { mdcAdapter.remove(null); }
public static void main(String[] args) throws Exception { Path tikaConfigPath = Paths.get(args[0]); PipesIterator pipesIterator = PipesIterator.build(tikaConfigPath); long start = System.currentTimeMillis(); try (AsyncProcessor processor = new AsyncProcessor(tikaConfigPath, pipesIterator...
@Test public void testCrash() throws Exception { Path config = getPath("/configs/tika-config-broken.xml"); assertThrows(TikaConfigException.class, () -> TikaAsyncCLI.main(new String[]{config.toAbsolutePath().toString()})); }
@Override public CompletableFuture<ConsumeMessageDirectlyResult> consumeMessageDirectly(String address, ConsumeMessageDirectlyResultRequestHeader requestHeader, long timeoutMillis) { CompletableFuture<ConsumeMessageDirectlyResult> future = new CompletableFuture<>(); RemotingCommand request =...
@Test public void assertConsumeMessageDirectlyWithError() { setResponseError(); ConsumeMessageDirectlyResultRequestHeader requestHeader = mock(ConsumeMessageDirectlyResultRequestHeader.class); CompletableFuture<ConsumeMessageDirectlyResult> actual = mqClientAdminImpl.consumeMessageDirectly(d...
@Override public Collection<LocalDataQueryResultRow> getRows(final ShowReadwriteSplittingRulesStatement sqlStatement, final ContextManager contextManager) { Collection<LocalDataQueryResultRow> result = new LinkedList<>(); Map<String, Map<String, String>> exportableDataSourceMap = getExportableDataSo...
@Test void assertGetRowDataWithSpecifiedRuleName() throws SQLException { engine = setUp(new ShowReadwriteSplittingRulesStatement("readwrite_ds", null), createRuleConfiguration()); engine.executeQuery(); Collection<LocalDataQueryResultRow> actual = engine.getRows(); assertThat(actual....
@Override public RetryStrategy getNextRetryStrategy() { int nextRemainingRetries = remainingRetries - 1; Preconditions.checkState( nextRemainingRetries >= 0, "The number of remaining retries must not be negative"); long nextRetryDelayMillis = Math.min(currentR...
@Test void testRetryFailure() { assertThatThrownBy( () -> new IncrementalDelayRetryStrategy( 0, Duration.ofMillis(20L), ...
@Override public Optional<KsqlConstants.PersistentQueryType> getPersistentQueryType() { if (!queryPlan.isPresent()) { return Optional.empty(); } // CREATE_AS and CREATE_SOURCE commands contain a DDL command and a Query plan. if (ddlCommand.isPresent()) { if (ddlCommand.get() instanceof Cr...
@Test public void shouldReturnCreateSourcePersistentQueryTypeOnCreateSourceTable() { // Given: final CreateTableCommand ddlCommand = Mockito.mock(CreateTableCommand.class); when(ddlCommand.getIsSource()).thenReturn(true); final KsqlPlanV1 plan = new KsqlPlanV1( "stmt", Optional.of(ddlC...
public LeaderAndIsr newLeader(int leader) { return newLeaderAndIsrWithBrokerEpoch(leader, isrWithBrokerEpoch); }
@Test public void testNewLeader() { LeaderAndIsr leaderAndIsr = new LeaderAndIsr(2, Arrays.asList(1, 2, 3)); assertEquals(2, leaderAndIsr.leader()); assertEquals(Arrays.asList(1, 2, 3), leaderAndIsr.isr()); LeaderAndIsr newLeaderAndIsr = leaderAndIsr.newLeader(3); assertEq...
static Collection<String> getMandatoryJvmOptions(int javaMajorVersion){ return Arrays.stream(MANDATORY_JVM_OPTIONS) .map(option -> jvmOptionFromLine(javaMajorVersion, option)) .flatMap(Optional::stream) .collect(Collectors.toUnmodifiableList()); }
@Test public void testMandatoryJvmOptionApplicableJvmPresent() throws IOException{ assertTrue("Contains add-exports value for Java 17", JvmOptionsParser.getMandatoryJvmOptions(17).contains("--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED")); }
@Override public boolean putIfAbsent(K key, V value) { begin(); V oldValue = transactionalMap.putIfAbsent(key, value); commit(); return oldValue == null; }
@Test public void testPutIfAbsent() { map.put(42, "oldValue"); assertTrue(adapter.putIfAbsent(23, "newValue")); assertFalse(adapter.putIfAbsent(42, "newValue")); assertEquals("newValue", map.get(23)); assertEquals("oldValue", map.get(42)); }
@Override public void inc() { inc(1L); }
@Test public void testCounterSanity() { long expected = 1000L; for (int i = 0; i < expected; i++) { counter.inc(); } assertSanity(expected); }
@Override public SeriesSpec apply(final Metric metric) { metricValidator.validate(metric); return switch (metric.functionName()) { case Average.NAME -> Average.builder().field(metric.fieldName()).build(); case Cardinality.NAME -> Cardinality.builder().field(metric.fieldName(...
@Test void constructsProperSeriesSpec() { final Metric metric = new Metric("avg", "took_ms"); final SeriesSpec result = toTest.apply(metric); assertThat(result) .isNotNull() .isInstanceOf(Average.class) .satisfies(a -> assertEquals("took_ms", (...
@Override public ResponseHeader execute() throws SQLException { check(sqlStatement, connectionSession.getConnectionContext().getGrantee()); if (isDropCurrentDatabase(sqlStatement.getDatabaseName())) { checkSupportedDropCurrentDatabase(connectionSession); connectionSession.set...
@Test void assertExecuteDropNotExistDatabaseWithIfExists() { when(sqlStatement.getDatabaseName()).thenReturn("test_not_exist_db"); when(sqlStatement.isIfExists()).thenReturn(true); assertDoesNotThrow(() -> handler.execute()); }
@Override public synchronized Throwable fillInStackTrace() { // do nothing return null; }
@Test void testFillInStackTrace() { SkipCallbackWrapperException skipCallbackWrapperException = new SkipCallbackWrapperException(new Throwable("error")); assertNull(skipCallbackWrapperException.fillInStackTrace()); }
@OnlyForTest protected static ThreadPoolExecutor getExecutor(String groupId) { return GROUP_THREAD_POOLS.getOrDefault(groupId, GlobalThreadPoolHolder.INSTANCE); }
@Test public void testGlobalExecutor() { ThreadPoolExecutor executor1 = ThreadPoolsFactory.getExecutor(GROUP_ID_001); ThreadPoolExecutor executor2 = ThreadPoolsFactory.getExecutor(GROUP_ID_002); Assert.assertEquals(executor1, executor2); }
private void bfs(int v, int[] cc, int id) { cc[v] = id; Queue<Integer> queue = new LinkedList<>(); queue.offer(v); int n = graph.length; while (!queue.isEmpty()) { int t = queue.poll(); for (int i = 0; i < n; i++) { if (graph[t][i] != 0.0 &...
@Test public void testBfs() { System.out.println("bfs sort"); int[] ts = {0, 8, 1, 2, 7, 3, 6, 5, 4, 9, 10, 11, 12}; Graph graph = new AdjacencyMatrix(13, true); graph.addEdge(8, 7); graph.addEdge(7, 6); graph.addEdge(0, 1); graph.addEdge(0, 2); graph...
public void setAbandon(boolean abandon) { this.abandon = abandon; }
@Test void testSetAbandon() { assertFalse(connection.isAbandon()); connection.setAbandon(true); assertTrue(connection.isAbandon()); }
@Override public HttpResponseOutputStream<Node> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final DelayedHttpEntityCallable<Node> command = new DelayedHttpEntityCallable<Node>(file) { @Override public Node call(f...
@Test public void testOverwrite() throws Exception { final DeepboxIdProvider nodeid = new DeepboxIdProvider(session); final Path documents = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Documents/", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new Path(documents...
static Collection<String> getMandatoryJvmOptions(int javaMajorVersion){ return Arrays.stream(MANDATORY_JVM_OPTIONS) .map(option -> jvmOptionFromLine(javaMajorVersion, option)) .flatMap(Optional::stream) .collect(Collectors.toUnmodifiableList()); }
@Test public void testAlwaysMandatoryJvmPresent() { assertTrue("Contains regexp interruptible for Java 11", JvmOptionsParser.getMandatoryJvmOptions(11).contains("-Djruby.regexp.interruptible=true")); assertTrue("Contains regexp interruptible for Java 17", JvmOptionsPa...
public Exchange createExchange(Message message, Session session) { Exchange exchange = createExchange(getExchangePattern()); exchange.setIn(new SjmsMessage(exchange, message, session, getBinding())); return exchange; }
@Test public void testInOutExchangePattern() { try { Endpoint sjms = context.getEndpoint("sjms:queue:test.SjmsEndpointTest?exchangePattern=" + ExchangePattern.InOut); assertNotNull(sjms); assertEquals(ExchangePattern.InOut, sjms.createExchange().getPattern()); } c...
@Override public int countWords(Note note) { return countChars(note); }
@Test public void getWords() { Note note = getNote(1L, "这是中文测试", "這是中文測試\n これは日本語のテストです"); assertEquals(24, new IdeogramsWordCounter().countWords(note)); note.setTitle("这"); assertEquals(19, new IdeogramsWordCounter().countWords(note)); }
public BucketId getBucketIdForType(ClientParameters.SelectionType type, String id) throws BucketStatsException { switch (type) { case DOCUMENT: return bucketIdFactory.getBucketId(new DocumentId(id)); case BUCKET: // The internal parser of BucketID is used ...
@Test void testGetBucketId() throws BucketStatsException { BucketStatsRetriever retriever = createRetriever(); assertEquals("BucketId(0x80000000000004d2)", retriever.getBucketIdForType(ClientParameters.SelectionType.USER, "1234").toString()); assertEquals("BucketId(0x8000000...
public void tick() { // The main loop does two primary things: 1) drive the group membership protocol, responding to rebalance events // as they occur, and 2) handle external requests targeted at the leader. All the "real" work of the herder is // performed in this thread, which keeps synchroniz...
@Test public void testTaskConfigAdded() { // Task config always requires rebalance when(member.memberId()).thenReturn("member"); when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V0); when(herder.connectorType(anyMap())).thenReturn(ConnectorType.SOURCE); // j...
public static AppsInfo mergeAppsInfo(ArrayList<AppInfo> appsInfo, boolean returnPartialResult) { AppsInfo allApps = new AppsInfo(); Map<String, AppInfo> federationAM = new HashMap<>(); Map<String, AppInfo> federationUAMSum = new HashMap<>(); for (AppInfo a : appsInfo) { // Check if this App...
@Test public void testMergeAppsRunning() { AppsInfo apps = new AppsInfo(); String amHost = "http://i_am_the_AM2:1234"; AppInfo am = new AppInfo(); am.setAppId(APPID2.toString()); am.setAMHostHttpAddress(amHost); am.setState(YarnApplicationState.RUNNING); int value = 1000; setAppInfo...
@Override public void addVisualizedAutoTrackActivities(List<Class<?>> activitiesList) { }
@Test public void addVisualizedAutoTrackActivities() { List<Class<?>> activities = new ArrayList<>(); activities.add(EmptyActivity.class); activities.add(ListActivity.class); mSensorsAPI.addVisualizedAutoTrackActivities(activities); Assert.assertFalse(mSensorsAPI.isHeatMapAct...
@Override public void delete(final String key) { try ( Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(repositorySQL.getDeleteSQL())) { preparedStatement.setString(1, key + "%"); pre...
@Test void assertDeleteFailure() throws SQLException { String key = "key"; when(mockJdbcConnection.prepareStatement(repositorySQL.getDeleteSQL())).thenReturn(mockPreparedStatementForPersist); repository.delete(key); verify(mockPreparedStatement, times(0)).executeUpdate(); }
abstract void execute(Admin admin, Namespace ns, PrintStream out) throws Exception;
@Test public void testFindHangingLookupTopicPartitionsForTopic() throws Exception { String topic = "foo"; String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "find-hanging", "--topic", topic }; Node node0...
public String text() { return text; }
@Test public void textInfo() { badge = NodeBadge.text(Status.INFO, TXT); checkFields(badge, Status.INFO, false, TXT, null); }
public static LocalDate toLocalDate(int value) { final int day = value % 100; value /= 100; final int month = value % 100; value /= 100; final int year = value < 1000 ? value + 2000: value; return LocalDate.of(year, month, day); }
@Test public void shouldConvertIntWithFourDigitYearToLocalDate() { final LocalDate ld = LocalDate.of(2013, 8, 30); assertEquals(ld, DateUtils.toLocalDate(20130830)); }
public static String validSchemaName(String identifier) { return validIdentifier(identifier); }
@Test public void testValidSchemaName() { assertEquals("foo", validSchemaName("foo")); assertEquals("\"select\"", validSchemaName("select")); }
public User userDTOToUser(AdminUserDTO userDTO) { if (userDTO == null) { return null; } else { User user = new User(); user.setId(userDTO.getId()); user.setLogin(userDTO.getLogin()); user.setFirstName(userDTO.getFirstName()); user.s...
@Test void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities() { Set<String> authoritiesAsString = new HashSet<>(); authoritiesAsString.add("ADMIN"); userDto.setAuthorities(authoritiesAsString); User user = userMapper.userDTOToUser(userDto); assertThat(us...
@Override public boolean isValid() { // Validate type/devices type(); devices(); return super.isValid() && hasOnlyFields(ALLOWED, NAME, LATITUDE, LONGITUDE, UI_TYPE, RACK_ADDRESS, OWNER, TYPE, DEVICES, LOC_IN_PEERS); }
@Test(expected = InvalidFieldException.class) public void sampleInvalidConfig() { ObjectNode node = new TmpJson() .props(NAME, TYPE, "foo") .arrays(DEVICES) .node(); cfg = new BasicRegionConfig(); cfg.init(regionId(R1), BASIC, node, mapper, del...
public static SpringBeanUtils getInstance() { return INSTANCE; }
@Test public void testGetInstance() { final SpringBeanUtils result = SpringBeanUtils.getInstance(); assertNotNull(result); }
@Override public final void isEqualTo(@Nullable Object other) { if (Objects.equal(actual, other)) { return; } // Fail but with a more descriptive message: if (actual == null || !(other instanceof Map)) { super.isEqualTo(other); return; } containsEntriesInAnyOrder((Map<?, ?...
@Test public void isEqualToActualNullOtherMap() { expectFailureWhenTestingThat(null).isEqualTo(ImmutableMap.of()); }
@Deprecated @Restricted(DoNotUse.class) public static String resolve(ConfigurationContext context, String toInterpolate) { return context.getSecretSourceResolver().resolve(toInterpolate); }
@Test public void resolve_JsonWithNewlineInValue() { String input = "{ \"a\": \"hello\\nworld\", \"b\": 2 }"; environment.set("FOO", input); String output = resolve("${json:a:${FOO}}"); assertThat(output, equalTo("hello\nworld")); }
public static String toParams(Map<String, ?> paramMap) { return toParams(paramMap, CharsetUtil.CHARSET_UTF_8); }
@Test public void toParamsTest() { final String paramsStr = "uuuu=0&a=b&c=3Ddsssss555555"; final Map<String, List<String>> map = HttpUtil.decodeParams(paramsStr, CharsetUtil.UTF_8); final String encodedParams = HttpUtil.toParams(map); assertEquals(paramsStr, encodedParams); }
@Override public Set<Pair<Integer, StructLike>> keySet() { PartitionSet keySet = PartitionSet.create(specs); for (Entry<Integer, Map<StructLike, V>> specIdAndPartitionMap : partitionMaps.entrySet()) { int specId = specIdAndPartitionMap.getKey(); Map<StructLike, V> partitionMap = specIdAndPartitio...
@Test public void testKeySet() { PartitionMap<String> map = PartitionMap.create(SPECS); map.put(BY_DATA_SPEC.specId(), Row.of("aaa"), "v1"); map.put(BY_DATA_SPEC.specId(), CustomRow.of("ccc"), "v2"); assertThat(map.get(BY_DATA_SPEC.specId(), CustomRow.of("aaa"))).isEqualTo("v1"); assertThat(map.ge...
public static String unQuote(String string) { return string == null ? null : string.replaceAll("^\"|\"$", ""); }
@Test public void shouldUnQuote() throws Exception { assertThat(unQuote("\"Hello World\""), is("Hello World")); assertThat(unQuote(null), is(nullValue())); assertThat(unQuote("\"Hello World\" to everyone\""), is("Hello World\" to everyone")); }
public AccessPrivilege getAccessPrivilege(InetAddress addr) { return getAccessPrivilege(addr.getHostAddress(), addr.getCanonicalHostName()); }
@Test public void testMultiMatchers() throws Exception { long shortExpirationPeriod = 1 * 1000 * 1000 * 1000; // 1s NfsExports matcher = new NfsExports(CacheSize, shortExpirationPeriod, "192.168.0.[0-9]+;[a-z]+.b.com rw"); Assert.assertEquals(AccessPrivilege.READ_ONLY, matcher.getAccessPr...
static final String generateForFunction(RuleBuilderStep step, FunctionDescriptor<?> function) { return generateForFunction(step, function, 1); }
@Test public void generateFunctionWithNoParamGeneration() { RuleBuilderStep step = RuleBuilderStep.builder().function("function1").build(); final FunctionDescriptor<Boolean> descriptor = FunctionUtil.testFunction( "function1", ImmutableList.of( string("require...
public KsqlTarget target(final URI server) { return target(server, Collections.emptyMap()); }
@Test public void shouldRequestStatus() { // Given: CommandStatus commandStatus = new CommandStatus(Status.SUCCESS, "msg"); server.setResponseObject(commandStatus); // When: KsqlTarget target = ksqlClient.target(serverUri); RestResponse<CommandStatus> response = target.getStatus("foo"); ...
@Nullable public static String getDisplayNameFromCertificate(@Nonnull X509Certificate certificate, boolean withLocation) throws CertificateParsingException { X500Name name = new X500Name(certificate.getSubjectX500Principal().getName()); String commonName = null, org = null, location = null, country ...
@Test public void testDisplayName() throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate clientCert = (X509Certificate) cf.generateCertificate(getClass().getResourceAsStream( "startssl-client.crt")); assertEquals("Andreas Schild...
public static String toJson(Message message) { StringWriter json = new StringWriter(); try (JsonWriter jsonWriter = JsonWriter.of(json)) { write(message, jsonWriter); } return json.toString(); }
@Test public void do_not_write_null_wrapper_of_map() { TestNullableMap msg = TestNullableMap.newBuilder() .setLabel("world") .build(); assertThat(toJson(msg)).isEqualTo("{\"label\":\"world\"}"); }