focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
private synchronized RemotingCommand removeColdDataFlowCtrGroupConfig(ChannelHandlerContext ctx, RemotingCommand request) { final RemotingCommand response = RemotingCommand.createResponseCommand(null); LOGGER.info("removeColdDataFlowCtrGroupConfig called by {}", RemotingHelper.parseChannelRemote...
@Test public void testRemoveColdDataFlowCtrGroupConfig() throws RemotingCommandException { RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.REMOVE_COLD_DATA_FLOW_CTR_CONFIG, null); RemotingCommand response = adminBrokerProcessor.processRequest(handlerContext, request); ...
@Override @Nullable public Throwable error() { return status.getCause(); }
@Test void error_null() { assertThat(response.error()).isNull(); }
public static boolean isBean(Type type) { return isBean(TypeRef.of(type)); }
@Test public void isBean() { Assert.assertTrue(TypeUtils.isBean(BeanA.class)); Assert.assertTrue(TypeUtils.isBean(Bean.class)); Assert.assertFalse(TypeUtils.isBean(ArrayList.class)); }
@Deprecated public String withoutNamespace(String resource) { return NamespaceUtil.withoutNamespace(resource, this.getNamespace()); }
@Test public void testWithoutNamespace() { String actual = clientConfig.withoutNamespace(resource); assertEquals(resource, actual); Set<String> resources = clientConfig.withoutNamespace(Collections.singleton(resource)); assertTrue(resources.contains(resource)); }
public static boolean equalTo(Inspector a, Inspector b) { if (a.type() != b.type()) return false; switch (a.type()) { case NIX: return a.valid() == b.valid(); case BOOL: return a.asBool() == b.asBool(); case LONG: return a.asLong() == b.asLong(); case DOU...
@Test public void verifyArrayEquality() { Slime slimeLeft = new Slime(); Cursor left = slimeLeft.setArray(); left.addArray().addString("a"); left.addArray().addString("b"); Slime slimeRight = new Slime(); Cursor right = slimeRight.setArray(); right.addArray()...
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testHeaders() { buildFetcher(); MemoryRecordsBuilder builder = MemoryRecords.builder(ByteBuffer.allocate(1024), Compression.NONE, TimestampType.CREATE_TIME, 1L); builder.append(0L, "key".getBytes(), "value-1".getBytes()); Header[] headersArray = new Header[1]; ...
public static Build withPropertyValue(String propertyValue) { return new Builder(propertyValue); }
@Test void it_should_return_transport_as_default_value_when_property_is_empty() { //GIVEN String empty = ""; //WHEN ElasticsearchClientType clientType = ElasticsearchClientTypeBuilder.withPropertyValue(empty).build(); //THEN assertEquals(TRANSPORT, clientType); }
@Override public List<String> batchDeleteMetadata(String namespaceId, InstanceOperationInfo instanceOperationInfo, Map<String, String> metadata) throws NacosException { boolean isEphemeral = !UtilsAndCommons.PERSIST.equals(instanceOperationInfo.getConsistencyType()); String serviceName =...
@Test void testBatchDeleteMetadata() throws NacosException { Instance instance = new Instance(); instance.setServiceName("C"); instance.setIp("1.1.1.1"); instance.setPort(8848); ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setHosts(Collections.singletonLis...
public void abortIncompleteBatches() { // We need to keep aborting the incomplete batch until no thread is trying to append to // 1. Avoid losing batches. // 2. Free up memory in case appending threads are blocked on buffer full. // This is a tight loop but should be able to get through ...
@Test public void testAbortIncompleteBatches() throws Exception { int lingerMs = Integer.MAX_VALUE; int numRecords = 100; final AtomicInteger numExceptionReceivedInCallback = new AtomicInteger(0); final RecordAccumulator accum = createTestRecordAccumulator( 128 + Default...
public List<String> searchTags(@Nullable String textQuery, int page, int size) { int maxPageSize = 100; int maxPage = 20; checkArgument(size <= maxPageSize, "Page size must be lower than or equals to " + maxPageSize); checkArgument(page > 0 && page <= maxPage, "Page must be between 0 and " + maxPage); ...
@Test public void search_tags_with_no_tags() { List<String> result = underTest.searchTags("whatever", 1, 10); assertThat(result).isEmpty(); }
private void definePackageInternal(final String packageName, final Manifest manifest) { if (null != getPackage(packageName)) { return; } Attributes attributes = manifest.getMainAttributes(); String specTitle = attributes.getValue(Attributes.Name.SPECIFICATION_TITLE); ...
@Test public void testDefinePackageInternal() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException { Method definePackageInternal = ShenyuPluginLoader.class.getDeclaredMethod("definePackageInternal", String.class, Manifest.class); definePackageInternal.setAcce...
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { if(!new LocalFindFeature(session).find(file)) { throw new NotfoundException(file.getAbsolute()); ...
@Test public void testRenameCaseOnly() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCall...
public static String formatAddress(String host, Integer port) { return host.contains(":") ? "[" + host + "]:" + port // IPv6 : host + ":" + port; }
@Test public void testFormatAddress() { assertEquals("127.0.0.1:8000", formatAddress("127.0.0.1", 8000)); assertEquals("mydomain.com:8080", formatAddress("mydomain.com", 8080)); assertEquals("[::1]:1234", formatAddress("::1", 1234)); assertEquals("[2001:db8:85a3:8d3:1319:8a2e:370:734...
public static int binarySearch(Sortable data) { int value = data.size(); int lower = 0; int upper = data.size(); while (lower < upper) { int mid = (lower + upper) >> 1; if (data.isLess(mid, value)) { lower = mid + 1; } else { upper = mid; } } return lower;...
@Test public void testSearch() { int[] a = new int[] { 1, 2, 4, 4, 4, 5, 0 }; SimpleSortable sortable = new SimpleSortable(a, a.length - 1); // search 4 a[a.length - 1] = 4; assertThat(DataUtils.binarySearch(sortable), is(2)); // search 5 a[a.length - 1] = 5; assertThat(DataUtils.binar...
public static String serialize(AbstractHealthChecker healthChecker) { try { return MAPPER.writeValueAsString(healthChecker); } catch (JsonProcessingException e) { throw new NacosSerializationException(healthChecker.getClass(), e); } }
@Test void testSerializeFailure() { assertThrows(NacosSerializationException.class, () -> { SelfDependHealthChecker selfDependHealthChecker = new SelfDependHealthChecker(); System.out.println(HealthCheckerFactory.serialize(selfDependHealthChecker)); }); }
@SuppressWarnings("checkstyle:CyclomaticComplexity") @Override public void renameTable(TableIdentifier from, TableIdentifier to) { if (from.equals(to)) { return; } if (!tableExists(from)) { throw new NoSuchTableException("Table does not exist: %s", from); } if (!namespaceExists(to....
@Test public void testRenameTable() { TableIdentifier from = TableIdentifier.of("db", "tbl1"); TableIdentifier to = TableIdentifier.of("db", "tbl2-newtable"); catalog.createTable(from, SCHEMA, PartitionSpec.unpartitioned()); catalog.renameTable(from, to); assertThat(catalog.listTables(to.namespace...
public Optional<Details> sync( @NotNull StepInstance instance, @NotNull WorkflowSummary workflowSummary, @NotNull StepRuntimeSummary stepSummary) { try { switch (stepSummary.getDbOperation()) { case INSERT: case UPSERT: instanceDao.insertOrUpsertStepInstance( ...
@Test public void testPublishFailure() { when(publisher.publish(any())).thenReturn(Optional.of(Details.create("test error"))); StepRuntimeSummary stepRuntimeSummary = StepRuntimeSummary.builder() .stepId("test-summary") .stepAttemptId(2) .stepInstanceId(1) ...
@Override public GroupVersion groupVersion() { return PublicApiUtils.groupVersion(new Menu()); }
@Test void groupVersion() { GroupVersion groupVersion = endpoint.groupVersion(); assertThat(groupVersion.toString()).isEqualTo("api.halo.run/v1alpha1"); }
@Override public ResourceSet update(ResourceSet oldRs, ResourceSet newRs) { if (oldRs.getId() == null || newRs.getId() == null || !oldRs.getId().equals(newRs.getId())) { throw new IllegalArgumentException("Resource set IDs mismatched"); } if (!checkScopeConsistency(newRs)) { throw new IllegalArgume...
@Test(expected = IllegalArgumentException.class) public void testUpdate_mismatchedIds() { ResourceSet rs = new ResourceSet(); rs.setId(1L); ResourceSet rs2 = new ResourceSet(); rs2.setId(2L); resourceSetService.update(rs, rs2); }
@Override public Result reconcile(Request request) { client.fetch(Comment.class, request.name()) .ifPresent(comment -> { if (isDeleted(comment)) { if (removeFinalizers(comment.getMetadata(), Set.of(FINALIZER_NAME))) { cleanUpResources(c...
@Test void reconcileDelete() { Comment comment = new Comment(); comment.setMetadata(new Metadata()); comment.getMetadata().setName("test"); comment.getMetadata().setDeletionTimestamp(Instant.now()); Set<String> finalizers = new HashSet<>(); finalizers.add(CommentRecon...
@Override public List<DeptDO> getDeptList(Collection<Long> ids) { if (CollUtil.isEmpty(ids)) { return Collections.emptyList(); } return deptMapper.selectBatchIds(ids); }
@Test public void testGetDeptList_ids() { // mock 数据 DeptDO deptDO01 = randomPojo(DeptDO.class); deptMapper.insert(deptDO01); DeptDO deptDO02 = randomPojo(DeptDO.class); deptMapper.insert(deptDO02); // 准备参数 List<Long> ids = Arrays.asList(deptDO01.getId(), dept...
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { final boolean exists = Files.exists(session.toPath(file), LinkOption.NOFOLLOW_LINKS); if(exists) { if(Files.isSymbolicLink(session.toPath(file))) { return true...
@Test public void testFindCaseSensitive() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelC...
static URI determineClasspathResourceUri(Path baseDir, String basePackagePath, Path resource) { String subPackageName = determineSubpackagePath(baseDir, resource); String resourceName = resource.getFileName().toString(); String classpathResourcePath = of(basePackagePath, subPackageName, resource...
@Test void determineFullyQualifiedResourceNameFromRootPackage() { Path baseDir = Paths.get("path", "to"); String basePackageName = ""; Path resourceFile = Paths.get("path", "to", "com", "example", "app", "app.feature"); URI fqn = ClasspathSupport.determineClasspathResourceUri(baseDir...
@Override public ApiResult<TopicPartition, DeletedRecords> handleResponse( Node broker, Set<TopicPartition> keys, AbstractResponse abstractResponse ) { DeleteRecordsResponse response = (DeleteRecordsResponse) abstractResponse; Map<TopicPartition, DeletedRecords> completed...
@Test public void testMixedResponse() { Map<TopicPartition, Short> errorsByPartition = new HashMap<>(); TopicPartition errorPartition = t0p0; Errors error = Errors.UNKNOWN_SERVER_ERROR; errorsByPartition.put(errorPartition, error.code()); TopicPartition retriableErrorPartit...
public static <T> T[] replaceFirst(T[] src, T oldValue, T[] newValues) { int index = indexOf(src, oldValue); if (index == -1) { return src; } T[] dst = (T[]) Array.newInstance(src.getClass().getComponentType(), src.length - 1 + newValues.length); // copy the first p...
@Test public void replace_whenInMiddle() { Integer[] result = replaceFirst(new Integer[]{1, 6, 4}, 6, new Integer[]{2, 3}); System.out.println(Arrays.toString(result)); assertArrayEquals(new Integer[]{1, 2, 3, 4}, result); }
public synchronized <K> KeyQueryMetadata getKeyQueryMetadataForKey(final String storeName, final K key, final Serializer<K> keySerializer) { Objects.requireNonNull(keySer...
@Test public void shouldGetQueryMetadataForGlobalStoreWithKey() { final KeyQueryMetadata metadata = metadataState.getKeyQueryMetadataForKey(globalTable, "key", Serdes.String().serializer()); assertEquals(hostOne, metadata.activeHost()); assertTrue(metadata.standbyHosts().isEmpty()); }
@Override public Map<K, V> getAllWithTTLOnly(Set<K> keys) { return get(getAllWithTTLOnlyAsync(keys)); }
@Test public void testGetAllWithTTLOnly() throws InterruptedException { RMapCache<Integer, Integer> cache = redisson.getMapCache("testGetAllWithTTLOnly"); cache.put(1, 2, 3, TimeUnit.SECONDS); cache.put(3, 4, 1, TimeUnit.SECONDS); cache.put(5, 6, 1, TimeUnit.SECONDS); Map<In...
public static void checkTopic(String topic) throws MQClientException { if (UtilAll.isBlank(topic)) { throw new MQClientException("The specified topic is blank", null); } if (topic.length() > TOPIC_MAX_LENGTH) { throw new MQClientException( String.format("...
@Test public void testCheckTopic_BlankTopic() { String blankTopic = ""; try { Validators.checkTopic(blankTopic); failBecauseExceptionWasNotThrown(MQClientException.class); } catch (MQClientException e) { assertThat(e).hasMessageStartingWith("The specified ...
@SuppressWarnings("unchecked") @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { try { if (statement.getStatement() instanceof CreateAsSelect) { registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement); ...
@Test public void shouldThrowAuthorizationException() throws Exception { // Given: givenStatement("CREATE STREAM sink WITH(value_format='AVRO') AS SELECT * FROM SOURCE;"); when(schemaRegistryClient.register(anyString(), any(ParsedSchema.class))) .thenThrow(new RestClientException( "Use...
public IssueQuery create(SearchRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone()); Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules()); Collection<String> rule...
@Test public void dates_are_inclusive() { when(clock.getZone()).thenReturn(ZoneId.of("Europe/Paris")); SearchRequest request = new SearchRequest() .setCreatedAfter("2013-04-16") .setCreatedBefore("2013-04-17"); IssueQuery query = underTest.create(request); assertThat(query.createdAfter()...
@VisibleForTesting void persistQueue(final Account account, final Device device) throws MessagePersistenceException { final UUID accountUuid = account.getUuid(); final byte deviceId = device.getId(); final Timer.Sample sample = Timer.start(); messagesCache.lockQueueForPersistence(accountUuid, device...
@Test void testPersistQueueRetryLoop() { final String queueName = new String( MessagesCache.getMessageQueueKey(DESTINATION_ACCOUNT_UUID, DESTINATION_DEVICE_ID), StandardCharsets.UTF_8); final int messageCount = (MessagePersister.MESSAGE_BATCH_LIMIT * 3) + 7; final Instant now = Instant.now(); ...
public NumericIndicator max(Indicator<Num> other) { return NumericIndicator.of(BinaryOperation.max(this, other)); }
@Test public void max() { final NumericIndicator numericIndicator = NumericIndicator.of(cp1); final NumericIndicator staticOp = numericIndicator.max(5); assertNumEquals(5, staticOp.getValue(0)); assertNumEquals(9, staticOp.getValue(8)); final NumericIndicator dynamicOp = nu...
public Optional<Projection> createProjection(final ProjectionSegment projectionSegment) { if (projectionSegment instanceof ShorthandProjectionSegment) { return Optional.of(createProjection((ShorthandProjectionSegment) projectionSegment)); } if (projectionSegment instanceof ColumnProj...
@Test void assertCreateProjectionWhenProjectionSegmentInstanceOfParameterMarkerExpressionSegment() { ParameterMarkerExpressionSegment parameterMarkerExpressionSegment = new ParameterMarkerExpressionSegment(7, 7, 0); parameterMarkerExpressionSegment.setAlias(new AliasSegment(0, 0, new IdentifierValue...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testFetchAfterPartitionWithFetchedRecordsIsUnassigned() { buildFetcher(2); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 1); // Returns 3 records while `max.poll.records` is configured to 2 client.prepareResponse(matchesOffset(tidp0, 1), fullFetc...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testMapAddBeforeGet() throws Exception { StateTag<MapState<String, Integer>> addr = StateTags.map("map", StringUtf8Coder.of(), VarIntCoder.of()); MapState<String, Integer> mapState = underTest.state(NAMESPACE, addr); final String tag = "tag"; SettableFuture<Integer> future =...
public void updateServiceMetadata(Service service, ServiceMetadata serviceMetadata) { MetadataOperation<ServiceMetadata> operation = buildMetadataOperation(service); operation.setMetadata(serviceMetadata); WriteRequest operationLog = WriteRequest.newBuilder().setGroup(Constants.SERVICE_METADATA)...
@Test void testUpdateServiceMetadata() { assertThrows(NacosRuntimeException.class, () -> { ServiceMetadata serviceMetadata = new ServiceMetadata(); namingMetadataOperateService.updateServiceMetadata(service, serviceMetadata); Mockito.verify(service).getNamesp...
public static JsonElement parseReader(Reader reader) throws JsonIOException, JsonSyntaxException { try { JsonReader jsonReader = new JsonReader(reader); JsonElement element = parseReader(jsonReader); if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) { throw new Json...
@Test public void testParseReader() { StringReader reader = new StringReader("{a:10,b:'c'}"); JsonElement e = JsonParser.parseReader(reader); assertThat(e.isJsonObject()).isTrue(); assertThat(e.getAsJsonObject().get("a").getAsInt()).isEqualTo(10); assertThat(e.getAsJsonObject().get("b").getAsStrin...
public static Set<Integer> toSet(int[] replicas) { Set<Integer> result = new HashSet<>(); for (int replica : replicas) { result.add(replica); } return result; }
@Test public void testToSet() { assertEquals(Collections.emptySet(), Replicas.toSet(new int[] {})); assertEquals(new HashSet<>(Arrays.asList(3, 1, 5)), Replicas.toSet(new int[] {1, 3, 5})); assertEquals(new HashSet<>(Arrays.asList(1, 2, 10)), Replicas.toSet(new int[] ...
@Nullable public byte[] getValue() { return mValue; }
@Test public void setValue_SINT16() { final MutableData data = new MutableData(new byte[2]); data.setValue(-6192, Data.FORMAT_SINT16_LE, 0); assertArrayEquals(new byte[] { (byte) 0xD0, (byte) 0xE7 } , data.getValue()); }
@Override public Stream<HoodieInstant> getCandidateInstants(HoodieTableMetaClient metaClient, HoodieInstant currentInstant, Option<HoodieInstant> lastSuccessfulInstant) { HoodieActiveTimeline activeTimeline = metaClient.reloadActiveTimeline(); if (Clustering...
@Test public void testConcurrentWritesWithInterleavingSuccessfulCluster() throws Exception { createCommit(metaClient.createNewInstantTime(), metaClient); HoodieActiveTimeline timeline = metaClient.getActiveTimeline(); // consider commits before this are all successful Option<HoodieInstant> lastSuccess...
@Override public ConfigAdvanceInfo findConfigAdvanceInfo(final String dataId, final String group, final String tenant) { final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; List<String> configTagList = this.selectTagByConfig(dataId, group, tenant); Con...
@Test void testFindConfigAdvanceInfo() { String dataId = "dataId1324"; String group = "group23546"; String tenant = "tenant13245"; //mock select tags List<String> mockTags = Arrays.asList("tag1", "tag2", "tag3"); when(databaseOperate.queryMany(anyString(), eq...
public static String validateIndexNameIgnoreCase(@Nullable String indexName) { checkDbIdentifier(indexName, "Index name", INDEX_NAME_MAX_SIZE, true); return indexName; }
@Test public void accept_allowed_identifier_for_index_name_that_is_SQL_reserved_keyword_ignoring_case() { assertThatCode(() -> validateIndexNameIgnoreCase("value")) .doesNotThrowAnyException(); assertThatCode(() -> validateIndexNameIgnoreCase("VALUE")) .doesNotThrowAnyException(); }
public static String elasticsearchEvent(String indexName, String eventId) { checkArgument("indexName", indexName); checkArgument("eventId", eventId); return String.join(":", ES_EVENT, indexName, eventId); }
@Test public void elasticsearchEvent() { assertThat(EventOriginContext.elasticsearchEvent("gl-events_0", "01DF13GB094MT6390TYQB2Q73Q")) .isEqualTo("urn:graylog:event:es:gl-events_0:01DF13GB094MT6390TYQB2Q73Q"); assertThatCode(() -> EventOriginContext.elasticsearchEvent("", "01DF13GB...
public static boolean setIfEqualOrGreaterThan(AtomicLong oldValue, long newValue) { while (true) { long local = oldValue.get(); if (newValue < local) { return false; } if (oldValue.compareAndSet(local, newValue)) { return true; ...
@Test public void testSetIfEqualOrGreaterThan() { assertTrue(ConcurrencyUtil.setIfEqualOrGreaterThan(new AtomicLong(1), 1)); assertTrue(ConcurrencyUtil.setIfEqualOrGreaterThan(new AtomicLong(1), 2)); assertFalse(ConcurrencyUtil.setIfEqualOrGreaterThan(new AtomicLong(2), 1)); }
private void cleanupRemovedIndices() throws IOException { File tmpIdxFile = new File(_segmentDirectory, V1Constants.INDEX_FILE_NAME + ".tmp"); // Sort indices by column name and index type while copying, so that the // new index_map file is easy to inspect for troubleshooting. List<IndexEntry> ret...
@Test public void testCleanupRemovedIndices() throws IOException, ConfigurationException { try (SingleFileIndexDirectory sfd = new SingleFileIndexDirectory(TEMP_DIR, _segmentMetadata, ReadMode.mmap)) { PinotDataBuffer buf = sfd.newBuffer("col1", StandardIndexes.forward(), 1024); buf.putInt(0, 1)...
@Override public Set<OAuth2RefreshTokenEntity> getAllRefreshTokensForUser(String userName) { return tokenRepository.getRefreshTokensByUserName(userName); }
@Test public void getAllRefreshTokensForUser(){ when(tokenRepository.getRefreshTokensByUserName(userName)).thenReturn(newHashSet(refreshToken)); Set<OAuth2RefreshTokenEntity> tokens = service.getAllRefreshTokensForUser(userName); assertEquals(1, tokens.size()); assertTrue(tokens.contains(refreshToken)); }
@Secured(action = ActionTypes.READ) @GetMapping("/service") public Object serviceDetail(@RequestParam(defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId, String serviceName) throws NacosException { String serviceNameWithoutGroup = NamingUtils.getServiceName(serviceName); ...
@Test void testServiceDetail() throws Exception { Object expected = new Object(); when(catalogServiceV2.getServiceDetail(Constants.DEFAULT_NAMESPACE_ID, TEST_GROUP_NAME, TEST_SERVICE_NAME)).thenReturn(expected); Object actual = catalogController.serviceDetail(Constants.DEFAULT_NAMESPACE_ID, ...
public static KafkaUserModel fromCrd(KafkaUser kafkaUser, String secretPrefix, boolean aclsAdminApiSupported) { KafkaUserModel result = new KafkaUserModel(kafkaUser.getMetadata().getNamespace(), kafkaUser.getMetada...
@Test public void testFromCrdScramShaUserWithEmptyPasswordThrows() { KafkaUser emptyPassword = new KafkaUserBuilder(scramShaUser) .editSpec() .withNewKafkaUserScramSha512ClientAuthentication() .withNewPassword() .endPassw...
public Node parse() throws ScanException { return E(); }
@Test public void keywordGluedToLitteral() throws Exception { Parser<Object> p = new Parser("%x{}a"); Node t = p.parse(); SimpleKeywordNode witness = new SimpleKeywordNode("x"); witness.setOptions(new ArrayList<String>()); witness.next = new Node(Node.LITERAL, "a"); assertEquals(witness, t); ...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "RequestBody with ref") public void testRequestBodyWithRef() { Components components = new Components(); components.addRequestBodies("User", new RequestBody().description("Test RequestBody")); OpenAPI oas = new OpenAPI() .info(new Info().description("info"...
@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 shouldReturnValuesForOpenEndBounds_fetchAll() { // Given: final Range<Instant> end = Range.open( NOW, NOW.plusSeconds(10) ); final Range<Instant> startEquiv = Range.open( end.lowerEndpoint().minus(WINDOW_SIZE), end.upperEndpoint().minus(WINDOW_SIZE) ...
@Override public GenericRow transform(GenericRow record) { try { GenericRow originalRow = _fieldsToUnnest.isEmpty() ? null : record.copy(_fieldsToUnnest); flattenMap(record, new ArrayList<>(record.getFieldToValueMap().keySet())); for (String field : _fieldsToUnnest) { unnestCollection(re...
@Test public void testUnnestMultiLevelArray() { // { // "level1" : [ { // "level2" : { // "level3" : [ { // "level4" : "foo_bar" // }, { // "level4" : "foo_bar" // } ] // } // }, { // "level2" : { // ...
@Override public int compareVersions(String v1, String v2) { return Version.parse(v1).compareTo(Version.parse(v2)); }
@Test void compareSnapshotVersion() { assertTrue(versionManager.compareVersions("1.1.0", "1.0.0-SNAPSHOT") > 0); assertTrue(versionManager.compareVersions("1.1.0", "1.2.0-SNAPSHOT") < 0); assertTrue(versionManager.compareVersions("1.0.0-SNAPSHOT", "1.1.0-SNAPSHOT") < 0); assertEquals...
public Map<String, Object> getKsqlFunctionsConfigProps(final String functionName) { final Map<String, Object> udfProps = originalsWithPrefix( KSQL_FUNCTIONS_PROPERTY_PREFIX + functionName.toLowerCase(), false); final Map<String, Object> globals = originalsWithPrefix( KSQ_FUNCTIONS_GLOBAL_PROPER...
@Test public void shouldReturnUdfConfig() { // Given: final String functionName = "bob"; final String udfConfigName = KsqlConfig.KSQL_FUNCTIONS_PROPERTY_PREFIX + functionName + ".some-setting"; final KsqlConfig config = new KsqlConfig(ImmutableMap.of( udfConfigName, "should-be-visibl...
@Override public String toString() { return StringUtil.simpleClassName(this) + "(default: " + defaultValue + ", map: " + map + ')'; }
@Test public void testToString() { DomainNameMapping<String> mapping = new DomainNameMappingBuilder<String>("NotFound") .add("*.netty.io", "Netty") .add("downloads.netty.io", "Netty-Download") .build(); assertEquals( "ImmutableDomainNameMapping(defaul...
@Override public boolean validate(Path path, ResourceContext context) { // explicitly call a method not depending on LinkResourceService return validate(path); }
@Test public void testSatisfyWaypoints() { sut = new WaypointConstraint(DID1, DID2, DID3); assertThat(sut.validate(path, resourceContext), is(true)); }
@Override public List<T> select(List<T> context) { return context; }
@Test void testSelect() { NoneSelector<Instance> noneSelector = new NoneSelector<>(); List<Instance> providers = Collections.emptyList(); assertEquals(providers, noneSelector.select(providers)); }
@Override public void removeNetwork(String netId) { checkArgument(!Strings.isNullOrEmpty(netId), ERR_NULL_NETWORK_ID); synchronized (this) { if (isNetworkInUse(netId)) { final String error = String.format(MSG_NETWORK, netId, ERR_IN_USE); throw new IllegalS...
@Test(expected = IllegalArgumentException.class) public void testRemoveNetworkWithNull() { target.removeNetwork(null); }
static String getConfigValueAsString(ServiceConfiguration conf, String configProp) throws IllegalArgumentException { String value = getConfigValueAsStringImpl(conf, configProp); log.info("Configuration for [{}] is [{}]", configProp, value); return ...
@Test public void testGetConfigValueAsStringWorks() { Properties props = new Properties(); props.setProperty("prop1", "audience"); ServiceConfiguration config = new ServiceConfiguration(); config.setProperties(props); String actual = ConfigUtils.getConfigValueAsString(config,...
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { URL indexResource = getServletContext().getResource("/index.html"); String content = IOUtils.toString(indexResource, StandardCharsets.UTF_8); // read original content...
@Test void testZeppelinWebHtmlAddon() throws IOException, ServletException { ZeppelinConfiguration zConf = mock(ZeppelinConfiguration.class); when(zConf.getHtmlBodyAddon()).thenReturn(TEST_BODY_ADDON); when(zConf.getHtmlHeadAddon()).thenReturn(TEST_HEAD_ADDON); ServletConfig sc = mock(Servl...
@Override protected Component<? super Component<?, ?>, ?> doBuild(DeployState deployState, TreeConfigProducer<AnyConfigProducer> ancestor, Element spec) { var component = buildComponent(spec, deployState, ancestor); addChildren(deployState, ancestor, spec, component); return component; }
@Test void ensureCorrectModel() { Component<?, ?> handler = new DomComponentBuilder().doBuild(root.getDeployState(), root, parse( "<handler id='theId' class='theClass' bundle='theBundle' />")); BundleInstantiationSpecification instantiationSpecification = handler.model.bundleInstant...
public static HeaderTemplate create(String name, Iterable<String> values) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("name is required."); } if (values == null) { throw new IllegalArgumentException("values are required"); } return new HeaderTemplate(name...
@Test void it_should_throw_exception_when_value_is_null() { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> HeaderTemplate.create("test", null)); assertThat(exception.getMessage()).isEqualTo("values are required"); }
public static <T> T toBean(Object source, Class<T> clazz) { return toBean(source, clazz, null); }
@Test public void valueProviderToBeanTest() { // https://gitee.com/dromara/hutool/issues/I5B4R7 final CopyOptions copyOptions = CopyOptions.create(); final Map<String, String> filedMap = new HashMap<>(); filedMap.put("name", "sourceId"); copyOptions.setFieldMapping(filedMap); final TestPojo pojo = BeanUtil...
public static byte setBooleanToByte(byte modifiers, int i, boolean bool) { boolean old = getBooleanFromByte(modifiers, i); if (old && !bool) { // true-->false return (byte) (modifiers - (1 << i)); } else if (!old && bool) { // false-->true return (byte) (modifiers + (1 <<...
@Test public void setBooleanToByte() { byte b = 0x35; // 0011 0101 byte b1 = CodecUtils.setBooleanToByte(b, 0, true); Assert.assertEquals(b, b1); byte b2 = CodecUtils.setBooleanToByte(b, 1, false); Assert.assertEquals(b, b2); byte b3 = CodecUtils.setBooleanToByte(b, ...
@Override public NetworkClientDelegate.PollResult poll(long currentTimeMs) { if (!coordinatorRequestManager.coordinator().isPresent() || membershipManager.shouldSkipHeartbeat()) { membershipManager.onHeartbeatRequestSkipped(); return NetworkClientDelegate.PollResult.EMPTY...
@Test public void testPollTimerExpirationShouldNotMarkMemberStaleIfMemberAlreadyLeaving() { when(membershipManager.shouldSkipHeartbeat()).thenReturn(false); when(membershipManager.isLeavingGroup()).thenReturn(true); time.sleep(DEFAULT_MAX_POLL_INTERVAL_MS); NetworkClientDelegate.Pol...
@Override public Double getValue() { return getRatio().getValue(); }
@Test public void handlesInfiniteDenominators() throws Exception { final RatioGauge infinite = new RatioGauge() { @Override protected Ratio getRatio() { return Ratio.of(10, Double.POSITIVE_INFINITY); } }; assertThat(infinite.getValue()) ...
public String generateInvalidPayloadExceptionMessage(final byte[] hl7Bytes) { if (hl7Bytes == null) { return "HL7 payload is null"; } return generateInvalidPayloadExceptionMessage(hl7Bytes, hl7Bytes.length); }
@Test public void testGenerateInvalidPayloadExceptionMessageWithEmbeddedStartOfBlock() { byte[] basePayload = TEST_MESSAGE.getBytes(); ByteArrayOutputStream payloadStream = new ByteArrayOutputStream(basePayload.length + 1); int embeddedStartOfBlockIndex = basePayload.length / 2; pa...
@Override public PluginRuntime getPluginRuntime() { return new PluginRuntime(getId()) .addInfo("awaitTerminationMillis", awaitTerminationMillis + "ms"); }
@Test public void testGetRuntime() { Assert.assertNotNull(new ThreadPoolExecutorShutdownPlugin(1000L).getPluginRuntime()); }
public void executeInInteractiveMode() { executeInInteractiveMode(null); }
@Test void testHistoryFile() throws Exception { final MockExecutor mockExecutor = new MockExecutor(); InputStream inputStream = new ByteArrayInputStream("help;\nuse catalog cat;\n".getBytes()); Path historyFilePath = historyTempFile(); try (Terminal terminal = ...
public void add(final Portal portal) throws SQLException { boolean isNamedPortal = !portal.getName().isEmpty(); Preconditions.checkState(!isNamedPortal || !portals.containsKey(portal.getName()), "Named portal `%s` must be explicitly closed", portal.getName()); Portal previousPortal = portals.put...
@Test void assertAddDuplicateNamedPortal() throws SQLException { Portal portal = mock(Portal.class); when(portal.getName()).thenReturn("P_1"); portalContext.add(portal); assertThrows(IllegalStateException.class, () -> portalContext.add(portal)); }
public String getQuery() throws Exception { return getQuery(weatherConfiguration.getLocation()); }
@Test public void testCurrentLocationQuery2() throws Exception { WeatherConfiguration weatherConfiguration = new WeatherConfiguration(); weatherConfiguration.setMode(WeatherMode.XML); weatherConfiguration.setLocation("current"); weatherConfiguration.setPeriod("3"); weatherCon...
@Deprecated public static <T> T mapToBean(Map<?, ?> map, Class<T> beanClass, boolean isIgnoreError) { return fillBeanWithMap(map, ReflectUtil.newInstanceIfPossible(beanClass), isIgnoreError); }
@Test public void mapToBeanTest() { final HashMap<String, Object> map = MapUtil.newHashMap(); map.put("a_name", "Joe"); map.put("b_age", 12); // 别名,用于对应bean的字段名 final HashMap<String, String> mapping = MapUtil.newHashMap(); mapping.put("a_name", "name"); mapping.put("b_age", "age"); final Person perso...
@Deprecated @Override public void init(final ProcessorContext context, final StateStore root) { this.context = context instanceof InternalProcessorContext ? (InternalProcessorContext<?, ?>) context : null; taskId = context.taskId(); initStoreSerde(context); s...
@SuppressWarnings("deprecation") @Test public void shouldDelegateDeprecatedInit() { setUp(); final MeteredSessionStore<String, String> outer = new MeteredSessionStore<>( innerStore, STORE_TYPE, Serdes.String(), Serdes.String(), new Mock...
public boolean appliesTo(String pipelineName, String stageName) { boolean pipelineMatches = this.pipelineName.equals(pipelineName) || this.pipelineName.equals(GoConstants.ANY_PIPELINE); boolean stageMatches = this.stageName.equals(stageName) || this.stageName.equals(GoConstants.A...
@Test void anyStageShouldAlwaysApply() { NotificationFilter filter = new NotificationFilter("cruise2", GoConstants.ANY_STAGE, StageEvent.Breaks, false); assertThat(filter.appliesTo("cruise2", "dev")).isTrue(); }
@Override public Page<ConfigInfo> findConfigInfo4Page(final int pageNo, final int pageSize, final String dataId, final String group, final String tenant, final Map<String, Object> configAdvanceInfo) { String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; Pagination...
@Test void testFindConfigInfo4PageWithTags() { String dataId = "dataId4567222"; String group = "group3456789"; String tenant = "tenant4567890"; Map<String, Object> configAdvanceInfo = new HashMap<>(); configAdvanceInfo.put("config_tags", "tags1,tags3"); //moc...
public static void main(String[] args) { // populate the in-memory database initData(); // query the data using the service queryData(); }
@Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
protected S state() { return state; }
@Test public void testChannelInputShutdownEvent() { final AtomicReference<Error> error = new AtomicReference<Error>(); EmbeddedChannel channel = new EmbeddedChannel(new ReplayingDecoder<Integer>(0) { private boolean decoded; @Override protected void decode(Chann...
public SubsetItem getClientsSubset(String serviceName, int minClusterSubsetSize, int partitionId, Map<URI, Double> possibleUris, long version, SimpleLoadBalancerState state) { SubsettingStrategy<URI> subsettingStrategy = _subsettingStrategyFactory.get(serviceName, minClusterSubsetSiz...
@Test public void testDoNotSlowStart() { Mockito.when(_subsettingMetadataProvider.getSubsettingMetadata(_state)) .thenReturn(new DeterministicSubsettingMetadata(0, 5, 0)); Map<URI, Double> weightedUris = createUris(20); SubsettingState.SubsetItem subsetItem = _subsettingState.getClientsSubset(S...
@SuppressWarnings("MethodLength") public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header) { final MessageHeaderDecoder headerDecoder = decoders.header; headerDecoder.wrap(buffer, offset); final int schemaId = headerDecoder.schemaId(); ...
@Test void shouldHandleReplicationRequest2() { final ControlSessionDemuxer controlSessionDemuxer = new ControlSessionDemuxer( new ControlRequestDecoders(), mockImage, mockConductor, mockAuthorisationService); setupControlSession(controlSessionDemuxer, CONTROL_SESSION_ID); fi...
public static DataType getDataType(final List<Field<?>> fields, final String fieldName) { return fields.stream() .filter(fld -> Objects.equals(fieldName,fld.getName())) .map(Field::getDataType) .findFirst() .o...
@Test void getDataTypeFromDerivedFieldsAndDataDictionary() { final DataDictionary dataDictionary = new DataDictionary(); IntStream.range(0, 3).forEach(i -> { final DataField dataField = getRandomDataField(); dataDictionary.addDataFields(dataField); }); final L...
@Override public int compare(String version1, String version2) { if(ObjectUtil.equal(version1, version2)) { return 0; } if (version1 == null && version2 == null) { return 0; } else if (version1 == null) {// null或""视为最小版本,排在前 return -1; } else if (version2 == null) { return 1; } return Compar...
@Test public void startWithNoneNumberTest() { final int compare = VersionComparator.INSTANCE.compare("V1", "A1"); assertTrue(compare > 0); }
public long getNumConsumingSegmentsQueried() { return _brokerResponse.has(NUM_CONSUMING_SEGMENTS_QUERIED) ? _brokerResponse.get(NUM_CONSUMING_SEGMENTS_QUERIED) .asLong() : -1L; }
@Test public void testGetNumConsumingSegmentsQueried() { // Run the test final long result = _executionStatsUnderTest.getNumConsumingSegmentsQueried(); // Verify the results assertEquals(10L, result); }
@Override @SuppressWarnings({"rawtypes", "unchecked"}) public SimpleVersionedSerializer<CommitRecoverable> getCommitRecoverableSerializer() { return (SimpleVersionedSerializer) GSCommitRecoverableSerializer.INSTANCE; }
@Test public void testGetCommitRecoverableSerializer() { Object serializer = writer.getCommitRecoverableSerializer(); assertEquals(GSCommitRecoverableSerializer.class, serializer.getClass()); }
Optional<PriorityAndResource> getPriorityAndResource( final TaskExecutorProcessSpec taskExecutorProcessSpec) { tryAdaptAndAddTaskExecutorResourceSpecIfNotExist(taskExecutorProcessSpec); return Optional.ofNullable( taskExecutorProcessSpecToPriorityAndResource.get(taskExecutorP...
@Test void testExternalResourceFailExceedMax() { assumeThat(isExternalResourceSupported()).isTrue(); assertThatThrownBy( () -> getAdapterWithExternalResources( SUPPORTED_EXTERNAL_RESOURCE_NAME, ...
@Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { SQLite3DBParser p = new SQLite3DBParser(); p.parse(stream, handler, metadata, context); }
@Test public void testSpacesInBodyContentHandler() throws Exception { Metadata metadata = new Metadata(); metadata.set(TikaCoreProperties.RESOURCE_NAME_KEY, TEST_FILE_NAME); ContentHandler handler = new BodyContentHandler(-1); ParseContext ctx = new ParseContext(); try (Input...
public String validate(String password) { return validators.stream() .map(validator -> validator.validate(password)) .filter(Optional::isPresent).map(Optional::get) .reduce("", (partialString, element) -> (partialString.isEmpty() ? "" : partialString + ", ") + ele...
@Test public void testPolicyCombinedOutput() { String specialCharacterErrorMessage = "must contain at least one special character"; String upperCaseErrorMessage = "must contain at least one upper case"; String output = passwordValidator.validate("password123"); Assert.assertTrue(outp...
@Override public String originalArgument() { return value; }
@Test public void shouldReturnStringValueForCommandLine() { assertThat(argument.originalArgument(), is("test")); }
public String getStringHeader(Message in, String header, String defaultValue) { String headerValue = in.getHeader(header, String.class); return ObjectHelper.isNotEmpty(headerValue) ? headerValue : defaultValue; }
@Test public void testGetStringHeaderWithWhiteSpaces() { when(in.getHeader(HEADER_METRIC_NAME, String.class)).thenReturn(" "); assertThat(okProducer.getStringHeader(in, HEADER_METRIC_NAME, "value"), is("value")); inOrder.verify(in, times(1)).getHeader(HEADER_METRIC_NAME, String.class); ...
public E set(int index, E value) { if (index >= mSize || index + mSize < 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize); } return mElements.set(index < 0 ? index + mSize : index, value); }
@Test void testIllegalSetNegative() throws Exception { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { Stack<String> stack = new Stack<String>(); stack.set(-1, "illegal"); }); }
@Override public void execute() { PutItemResponse result = ddbClient.putItem(PutItemRequest.builder().tableName(determineTableName()) .item(determineItem()).expected(determineUpdateCondition()) .returnValues(determineReturnValues()).build()); addAttributesToResult(re...
@Test public void execute() { Map<String, AttributeValue> attributeMap = new HashMap<>(); AttributeValue attributeValue = AttributeValue.builder().s("test value").build(); attributeMap.put("name", attributeValue); exchange.getIn().setHeader(Ddb2Constants.ITEM, attributeMap); ...
@Udf(schema = "ARRAY<STRUCT<K STRING, V BIGINT>>") public List<Struct> entriesBigInt( @UdfParameter(description = "The map to create entries from") final Map<String, Long> map, @UdfParameter(description = "If true then the resulting entries are sorted by key") final boolean sorted ) { return e...
@Test public void shouldReturnNullListForNullMapBigInt() { assertNull(entriesUdf.entriesBigInt(null, false)); }
@Override public boolean deletePlugin(String pluginId) { if (currentPluginId.equals(pluginId)) { return original.deletePlugin(pluginId); } else { throw new IllegalAccessError(PLUGIN_PREFIX + currentPluginId + " tried to execute deletePlugin for foreign pluginId!"); } ...
@Test public void deletePlugin() { pluginManager.loadPlugins(); assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.deletePlugin(OTHER_PLUGIN_ID)); assertTrue(wrappedPluginManager.deletePlugin(THIS_PLUGIN_ID)); }
@SuppressWarnings("SameParameterValue") protected final String formatSqlMaybeWithParam(String sqlStr, Object... params) { if (StringUtils.isBlank(sqlStr)) { return null; } if (ArrayUtils.isNotEmpty(params)) { for (int i = 0; i < params.length; ++i) { S...
@Test void formatSqlMaybeWithParam() { QueryWrapper<Object> wrapper = new QueryWrapper<>(); String s = wrapper.formatSqlMaybeWithParam("c={0}", 1); assertThat(s).isEqualTo("c=#{ew.paramNameValuePairs.MPGENVAL1}"); s = wrapper.formatSqlMaybeWithParam("c={0,javaType=int}", 1); ...
@PUT @Path("/domain") @Consumes({ MediaType.APPLICATION_JSON /* , MediaType.APPLICATION_XML */}) @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8 /* , MediaType.APPLICATION_XML */}) public TimelinePutResponse putDomain( @Context HttpServletRequest req, @Context HttpServletRespo...
@Test void testPutDomain() throws Exception { TimelineDomain domain = new TimelineDomain(); domain.setId("test_domain_id"); WebResource r = resource(); // No owner, will be rejected ClientResponse response = r.path("ws").path("v1") .path("timeline").path("domain") .accept(MediaType...
@VisibleForTesting ExportResult<MusicContainerResource> exportPlaylists( TokensAndUrlAuthData authData, Optional<PaginationData> paginationData, UUID jobId) throws IOException, InvalidTokenException, PermissionDeniedException { Optional<String> paginationToken = Optional.empty(); String pageTokenP...
@Test public void exportPlaylistSubsequentSet() throws IOException, InvalidTokenException, PermissionDeniedException { setUpSinglePlaylist(GOOGLE_PLAYLIST_NAME_PREFIX + "p1_id"); when(playlistExportResponse.getNextPageToken()).thenReturn(null); StringPaginationToken inputPaginationToken = n...
public static Containerizer from( CommonCliOptions commonCliOptions, ConsoleLogger logger, CacheDirectories cacheDirectories) throws InvalidImageReferenceException, FileNotFoundException { Containerizer containerizer = create(commonCliOptions, logger); applyHandlers(containerizer, logger); appl...
@Test public void testFrom_dockerDaemonImage() throws InvalidImageReferenceException, FileNotFoundException { CommonCliOptions commonCliOptions = CommandLine.populateCommand( new CommonCliOptions(), "-t", "docker://gcr.io/test/test-image-ref"); ContainerizerTestProxy containerizer = ...
@Override public void close() throws UnavailableException { // JournalContext is closed before block deletion context so that file system master changes // are written before block master changes. If a failure occurs between deleting an inode and // remove its blocks, it's better to have an orphaned block...
@Test public void throwTwoRuntimeExceptions() throws Throwable { Exception bdcException = new IllegalStateException("block deletion context exception"); Exception jcException = new IllegalArgumentException("journal context exception"); doThrow(bdcException).when(mMockBDC).close(); doThrow(jcException)...
@Override public boolean tryLock() { return get(tryLockAsync()); }
@Test public void testReentrancy() throws InterruptedException { Lock lock = redisson.getLock("lock1"); Assertions.assertTrue(lock.tryLock()); Assertions.assertTrue(lock.tryLock()); lock.unlock(); // next row for test renew expiration tisk. //Thread.currentThread().s...
@Override public <R> List<R> queryMany(String sql, Object[] args, RowMapper<R> mapper) { return queryMany(jdbcTemplate, sql, args, mapper); }
@Test void testQueryMany5() { String sql = "SELECT data_id FROM config_info WHERE id >= ? AND id <= ?"; Object[] args = new Object[] {1, 2}; String dataId1 = "test1"; String dataId2 = "test2"; List<String> resultList = new ArrayList<>(); resultList.add(dataId1); ...
private static String approximateSimpleName(Class<?> clazz, boolean dropOuterClassNames) { checkArgument(!clazz.isAnonymousClass(), "Attempted to get simple name of anonymous class"); return approximateSimpleName(clazz.getName(), dropOuterClassNames); }
@Test public void testApproximateSimpleNameOverride() { NameOverride overriddenName = () -> "CUSTOM_NAME"; assertEquals("CUSTOM_NAME", NameUtils.approximateSimpleName(overriddenName)); }