focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static long calculate(PhysicalRel rel, ExpressionEvalContext evalContext) { GcdCalculatorVisitor visitor = new GcdCalculatorVisitor(evalContext); visitor.go(rel); if (visitor.gcd == 0) { // there's no window aggr in the rel, return the value for joins, which is already capped...
@Test public void when_twoConsecutiveSlidingWindowsAgg_then_returnGcdOfWindowsSize() { HazelcastTable table = streamGeneratorTable("s1", 100); HazelcastTable table2 = partitionedTable("map", asList(field(KEY, INT), field(VALUE, INT)), 1); List<QueryDataType> parameterTypes = asList(INT, INT)...
@Override public int hashCode() { int result = super.hashCode(); result = 31 * result + getKey().hashCode(); result = 31 * result + getValue().hashCode(); long cost = getCost(); long creationTime = getCreationTime(); long expirationTime = getExpirationTime(); ...
@Test public void test_hashCode() { EntryView entryView = createLazyEvictableEntryView(); assertEquals(entryView.hashCode(), view.hashCode()); }
@SuppressWarnings("deprecation") public static <K> KStreamHolder<K> build( final KStreamHolder<K> left, final KStreamHolder<K> right, final StreamStreamJoin<K> join, final RuntimeBuildContext buildContext, final StreamJoinedFactory streamJoinedFactory) { final QueryContext queryConte...
@Test public void shouldDoInnerJoin() { // Given: givenInnerJoin(L_KEY); // When: final KStreamHolder<Struct> result = join.build(planBuilder, planInfo); // Then: verify(leftKStream).join( same(rightKStream), eq(new KsqlValueJoiner(LEFT_SCHEMA.value().size(), RIGHT_SCHEMA.val...
public static Map<String, MavenArtifact> getWebappDependencies() throws IOException { // list dependencies in WEB-INF/lib // and read names, urls, licences in META-INF/maven/.../pom.xml from jar files when available final Map<String, MavenArtifact> webappDependencies = getWebappDependenciesFromWebInfLib(); // ...
@Test public void testGetWebappDependencies() throws IOException { final ServletContext context = createNiceMock(ServletContext.class); final String javamelodyDir = "/META-INF/maven/net.bull.javamelody/"; final String webapp = javamelodyDir + "javamelody-test-webapp/"; expect(context.getResourcePaths("/META-IN...
@Override public boolean syncData(DistroData data, String targetServer) { if (isNoExistTarget(targetServer)) { return true; } DistroDataRequest request = new DistroDataRequest(data, data.getType()); Member member = memberManager.find(targetServer); if (checkTarget...
@Test void testSyncDataForMemberDisconnect() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); member.setState(NodeState.UP); assertFalse(transportAgent.syncData(new DistroDat...
@Override public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception { // ask for a mandatory type conversion to avoid a possible NPE beforehand as we do copy from the InputStream final InputStream is = exchange.getContext().getTypeConverter().mandat...
@Test public void testMarshalTextToZipBestSpeed() throws Exception { context.addRoutes(new RouteBuilder() { public void configure() { from("direct:start") .marshal().zipDeflater(Deflater.BEST_SPEED) .process(new ZippedMessageProcess...
public Map<String, Long> getClusterTerm(String clusterName) { return clusterTerm.computeIfAbsent(clusterName, k -> new ConcurrentHashMap<>()); }
@Test public void testGetClusterTerm() { Assertions.assertDoesNotThrow(() -> metadata.getClusterTerm("cluster")); }
public static ParsedCommand parse( // CHECKSTYLE_RULES.ON: CyclomaticComplexity final String sql, final Map<String, String> variables) { validateSupportedStatementType(sql); final String substituted; try { substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),...
@Test public void shouldThrowOnMissingSemicolon() { // When: final MigrationException e = assertThrows(MigrationException.class, () -> parse("create stream foo as select * from no_semicolon_after_this")); // Then: assertThat(e.getMessage(), containsString("Unmatched command at end of file; mi...
public static <T> Read<T> read() { return new AutoValue_CassandraIO_Read.Builder<T>().build(); }
@Test public void testReadWithUnfilteredQuery() throws Exception { String query = String.format( "select person_id, writetime(person_name) from %s.%s", CASSANDRA_KEYSPACE, CASSANDRA_TABLE); PCollection<Scientist> output = pipeline.apply( CassandraIO.<Scient...
@Override public boolean supportsGroupBy() { return false; }
@Test void assertSupportsGroupBy() { assertFalse(metaData.supportsGroupBy()); }
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testGetName() { FalsePositiveAnalyzer instance = new FalsePositiveAnalyzer(); String expResult = "False Positive Analyzer"; String result = instance.getName(); assertEquals(expResult, result); }
@Override public Split.Output run(RunContext runContext) throws Exception { URI from = new URI(runContext.render(this.from)); return Split.Output.builder() .uris(StorageService.split(runContext, this, from)) .build(); }
@Test void rows() throws Exception { RunContext runContext = runContextFactory.of(); URI put = storageUpload(1000); Split result = Split.builder() .from(put.toString()) .rows(10) .build(); Split.Output run = result.run(runContext); asser...
public void setType( String type ) { this.type = type; }
@Test public void setType() { JobScheduleParam jobScheduleParam = mock( JobScheduleParam.class ); doCallRealMethod().when( jobScheduleParam ).setType( any() ); String type = "hitachi"; jobScheduleParam.setType( type ); Assert.assertEquals( type, ReflectionTestUtils.getField( jobScheduleParam, "typ...
public static Map<String, String> getClientMd5Map(String configKeysString) { Map<String, String> md5Map = new HashMap<>(5); if (null == configKeysString || "".equals(configKeysString)) { return md5Map; } int start = 0; List<String> tmpList = new Arra...
@Test void testGetClientMd5Map() { String configKeysString = "test0" + MD5Util.WORD_SEPARATOR_CHAR + "test1" + MD5Util.WORD_SEPARATOR_CHAR + "test2" + MD5Util.LINE_SEPARATOR_CHAR; Map<String, String> actualValueMap = MD5Util.getClientMd5Map(configKeysString); ...
public ConcurrentLongHashMap<CompletableFuture<Producer>> getProducers() { return producers; }
@Test(timeOut = 30000) public void testBrokerClosedProducerClientRecreatesProducerThenSendCommand() throws Exception { resetChannel(); setChannelConnected(); setConnectionVersion(ProtocolVersion.v5.getValue()); serverCnx.cancelKeepAliveTask(); String producerName = "my-produ...
@Override public void process(SynthesizedAnnotation synthesizedAnnotation, AnnotationSynthesizer synthesizer) { final Map<String, AnnotationAttribute> attributeMap = synthesizedAnnotation.getAttributes(); // 记录别名与属性的关系 final ForestMap<String, AnnotationAttribute> attributeAliasMappings = new LinkedForestMap<>(f...
@Test public void processTest() { AliasAnnotationPostProcessor processor = new AliasAnnotationPostProcessor(); Map<Class<?>, SynthesizedAnnotation> annotationMap = new HashMap<>(); SynthesizedAggregateAnnotation synthesizedAnnotationAggregator = new TestSynthesizedAggregateAnnotation(annotationMap); Annotatio...
public static String[] parseKey(String groupKey) { StringBuilder sb = new StringBuilder(); String dataId = null; String group = null; String tenant = null; for (int i = 0; i < groupKey.length(); ++i) { char c = groupKey.charAt(i); if ('+' == c) { ...
@Test void testParseInvalidGroupKey() { String key = "11111+222+333333+444"; try { GroupKey.parseKey(key); fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } key = "11111+"; try { ...
public SchemaMapping fromArrow(Schema arrowSchema) { List<Field> fields = arrowSchema.getFields(); List<TypeMapping> parquetFields = fromArrow(fields); MessageType parquetType = addToBuilder(parquetFields, Types.buildMessage()).named("root"); return new SchemaMapping(arrowSchema, parquetType, pa...
@Test public void testArrowTimeMillisecondToParquet() { MessageType expected = converter .fromArrow(new Schema(asList(field("a", new ArrowType.Time(TimeUnit.MILLISECOND, 32))))) .getParquetSchema(); Assert.assertEquals( expected, Types.buildMessage() .addField(Types...
@Override public boolean add(final Long value) { return add(value.longValue()); }
@Test public void setsWithTheDifferentValuesAreNotEqual() { final LongHashSet other = new LongHashSet(100, -1); set.add(1); set.add(1001); other.add(2); other.add(1001); assertNotEquals(set, other); }
public static String partitionsToLogString(Collection<TopicIdPartition> partitions, Boolean traceEnabled) { if (traceEnabled) { return String.format("( %s )", String.join(", ", partitions.toString())); } return String.format("%s partition(s)", partitions.size()); }
@Test public void testPartitionsToLogString() { Uuid uuid1 = Uuid.randomUuid(); Uuid uuid2 = Uuid.randomUuid(); List<TopicIdPartition> partitions = Arrays.asList( new TopicIdPartition(uuid1, 0, "foo"), new TopicIdPartition(uuid2, 1, "bar")); String response =...
@VisibleForTesting void validateOldPassword(Long id, String oldPassword) { AdminUserDO user = userMapper.selectById(id); if (user == null) { throw exception(USER_NOT_EXISTS); } if (!isPasswordMatch(oldPassword, user.getPassword())) { throw exception(USER_PASSW...
@Test public void testValidateOldPassword_notExists() { assertServiceException(() -> userService.validateOldPassword(randomLongId(), randomString()), USER_NOT_EXISTS); }
@Override public String generate(TokenType tokenType) { String rawToken = generateRawToken(); return buildIdentifiablePartOfToken(tokenType) + rawToken; }
@Test public void token_does_not_contain_colon() { assertThat(underTest.generate(TokenType.USER_TOKEN)).doesNotContain(":"); }
@Override public Set<String> getRoleNames(User user) { final Set<String> roleIds = user.getRoleIds(); if (roleIds.isEmpty()) { return Collections.emptySet(); } Map<String, Role> idMap; try { idMap = roleService.loadAllIdMap(); } catch (NotFou...
@Test public void testGetRoleNames() throws Exception { final UserImplFactory factory = new UserImplFactory(new Configuration(), permissions); final UserImpl user = factory.create(new HashMap<>()); final Role role = createRole("Foo"); final ImmutableMap<String, Role> map = Immutable...
static Map<String, Double> getGroupedCategoricalPredictorMap(final List<CategoricalPredictor> categoricalPredictors) { final Map<String, Double> toReturn = new LinkedHashMap<>(); for (CategoricalPredictor categoricalPredictor : categoricalPredictors) { toReturn.put(categoricalPredictor.getVa...
@Test void getGroupedCategoricalPredictorMap() { final List<CategoricalPredictor> categoricalPredictors = new ArrayList<>(); for (int i = 0; i < 3; i++) { String predictorName = "predictorName-" + i; double coefficient = 1.23 * i; categoricalPredictors.add(PMMLMod...
public static ParameterMetric getParamMetric(ResourceWrapper resourceWrapper) { if (resourceWrapper == null || resourceWrapper.getName() == null) { return null; } return metricsMap.get(resourceWrapper.getName()); }
@Test public void testGetNullParamMetric() { assertNull(ParameterMetricStorage.getParamMetric(null)); }
public synchronized boolean hasOutOfBandData() { return hasLeadingOutOfBandData() || hasTrailingOutOfBandData(); }
@Test public void testhasOutOfBandData() throws Exception { assertFalse(instance.hasOutOfBandData(), "Unexpected initial value"); instance.write(buildTestBytes(true, true, true)); assertFalse(instance.hasOutOfBandData()); instance.write("BLAH".getBytes()); assertTrue(instan...
public static URL appendTrailingSlash(URL originalURL) { try { return originalURL.getPath().endsWith("/") ? originalURL : new URL(originalURL.getProtocol(), originalURL.getHost(), originalURL.getPort(), ...
@Test void appendTrailingSlashDoesntASlashWhenOneIsAlreadyPresent() { final URL url = getClass().getResource("/META-INF/"); assertThat(url.toExternalForm()) .endsWith("/"); assertThat(ResourceURL.appendTrailingSlash(url).toExternalForm()) .doesNotMatch(".*//$...
public InternalRowCollector getInternalRowCollector( Handover<InternalRow> handover, Object checkpointLock, Map<String, String> envOptionsInfo) { if (isMultiTable) { return new InternalMultiRowCollector( handover, checkpointLock, rowSerializati...
@Test public void testMultiReaderConverter() throws IOException { initSchema(); initData(); MultiTableManager multiTableManager = new MultiTableManager( new CatalogTable[] {catalogTable1, catalogTable2, catalogTable3}); InternalMultiRowCollecto...
public static String getHttpMethod(Exchange exchange, Endpoint endpoint) { // 1. Use method provided in header. Object method = exchange.getIn().getHeader(Exchange.HTTP_METHOD); if (method instanceof String) { return (String) method; } else if (method instanceof Enum) { ...
@Test public void testGetMethodFromMethodHeaderEnum() { Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(exchange.getIn()).thenReturn(message); Mockito.when(message.getHeader(Exchange.HTTP_METHOD)).thenReturn(HttpMethods.G...
public List<String> keyNames() { return keyNames; }
@Test void oneFunction_keyNames() { assertThat(oneFunction.keyNames()).containsExactly("one"); }
public RuntimeOptionsBuilder parse(Map<String, String> properties) { return parse(properties::get); }
@Test void should_parse_features_and_preserve_existing_tag_filters() { RuntimeOptions existing = RuntimeOptions.defaultOptions(); existing.setTagExpressions(Collections.singletonList(TagExpressionParser.parse("@example"))); properties.put(Constants.FEATURES_PROPERTY_NAME, "classpath:com/exam...
@Override public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException { try (InputStream input = provider.open(requireNonNull(path))) { final JsonNode node = mapper.readTree(createParser(input)); if (node == null) { th...
@Test void throwsAnExceptionOnEmptyFiles() { assertThatExceptionOfType(ConfigurationParsingException.class) .isThrownBy(() -> factory.build(configurationSourceProvider, emptyFile)) .withMessageContaining(" * Configuration at " + emptyFile + " must not be empty"); }
@VisibleForTesting Path getJarArtifact() throws IOException { Optional<String> classifier = Optional.empty(); Path buildDirectory = Paths.get(project.getBuild().getDirectory()); Path outputDirectory = buildDirectory; // Read <classifier> and <outputDirectory> from maven-jar-plugin. Plugin jarPlug...
@Test public void testGetJarArtifact_classifier() throws IOException { when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); when(mockMavenProject.getPlugin("org.apache.maven.plugins:maven-jar-plugin")) .thenReturn(...
public static InMemorySorter create(Options options) { return new InMemorySorter(options); }
@Test public void testEmptyKeyValueElement() throws Exception { SorterTestUtils.testEmptyKeyValueElement(InMemorySorter.create(new InMemorySorter.Options())); }
@Override public NSImage folderIcon(final Integer size) { NSImage folder = this.iconNamed("NSFolder", size); if(null == folder) { return this.iconNamed("NSFolder", size); } return folder; }
@Test public void testFolderIcon32() { final NSImage icon = new NSImageIconCache().folderIcon(32); assertNotNull(icon); assertTrue(icon.isValid()); assertFalse(icon.isTemplate()); assertEquals(32, icon.size().width.intValue()); assertEquals(32, icon.size().height.intV...
protected static void checkMandatoryProperties(Map<String, String> props, String[] mandatoryProps) { StringBuilder missing = new StringBuilder(); for (String mandatoryProperty : mandatoryProps) { if (!props.containsKey(mandatoryProperty)) { if (missing.length() > 0) { missing.append(", "...
@Test public void shouldFailIfMandatoryPropertiesAreNotPresentButWithProjectKey() { Map<String, String> props = new HashMap<>(); props.put("foo1", "bla"); props.put("sonar.projectKey", "my-project"); assertThatThrownBy(() -> ProjectReactorBuilder.checkMandatoryProperties(props, new String[] {"foo1", ...
@SuppressWarnings("unchecked") public static String encode(Type parameter) { if (parameter instanceof NumericType) { return encodeNumeric(((NumericType) parameter)); } else if (parameter instanceof Address) { return encodeAddress((Address) parameter); } else if (param...
@Test public void testPrimitiveDouble() { assertThrows( UnsupportedOperationException.class, () -> encode(new org.web3j.abi.datatypes.primitive.Double(0))); }
@Override public HostToKeyMapper<Integer> getAllPartitionsMultipleHosts(URI serviceUri, int numHostPerPartition) throws ServiceUnavailableException { return getHostToKeyMapper(serviceUri, null, numHostPerPartition, null); }
@Test(dataProvider = "ringFactories") public void testAllPartitionMultipleHosts(RingFactory<URI> ringFactory) throws URISyntaxException, ServiceUnavailableException { URI serviceURI = new URI("d2://articles"); ConsistentHashKeyMapper mapper = getConsistentHashKeyMapper(ringFactory); HostToKeyMapp...
public static <FROM, TO> MappedCondition<FROM, TO> mappedCondition(Function<FROM, TO> mapping, Condition<TO> condition, String mappingDescription, Object... args) { requireNonNull(mappingDescription, "The given mappingDescription should not be nul...
@Test void mappedCondition_with_description_and_null_mapping_function_should_throw_NPE() { thenNullPointerException().isThrownBy(() -> mappedCondition(null, isBarString, "::toString")) .withMessage("The given mapping function should not be null"); }
public boolean isFound() { return found; }
@Test public void testCalcInstructionsRoundaboutBegin() { Weighting weighting = new SpeedWeighting(mixedCarSpeedEnc); Path p = new Dijkstra(roundaboutGraph.g, weighting, TraversalMode.NODE_BASED) .calcPath(2, 8); assertTrue(p.isFound()); InstructionList wayList = Inst...
public static List<PropertyDefinition> all() { List<PropertyDefinition> defs = new ArrayList<>(); defs.addAll(IssueExclusionProperties.all()); defs.addAll(ExclusionProperties.all()); defs.addAll(SecurityProperties.all()); defs.addAll(DebtProperties.all()); defs.addAll(PurgeProperties.all()); ...
@Test public void all_includes_scanner_properties() { List<PropertyDefinition> defs = CorePropertyDefinitions.all(); assertThat(defs.stream() .filter(def -> def.key().equals(ScannerProperties.BRANCH_NAME)) .findFirst()).isPresent(); }
long parkTime(long n) { final long proposedShift = n - parkThreshold; final long allowedShift = min(maxShift, proposedShift); return proposedShift > maxShift ? maxParkPeriodNs : proposedShift < maxShift ? minParkPeriodNs << allowedShift : min(minParkPeriodNs << al...
@Test public void when_maxShiftedGreaterThanMaxParkTime_thenParkMax() { final BackoffIdleStrategy strat = new BackoffIdleStrategy(0, 0, 3, 4); assertEquals(3, strat.parkTime(0)); assertEquals(4, strat.parkTime(1)); assertEquals(4, strat.parkTime(2)); }
public void simulateTypedWord(CharSequence typedWord) { final var typedCodes = new int[1]; mTypedWord.insert(mCursorPosition, typedWord); int index = 0; while (index < typedWord.length()) { final int codePoint = Character.codePointAt(typedWord, index); typedCodes[0] = codePoint; final...
@Test public void testSimulateTypedWord() { final var underTest = new WordComposer(); underTest.simulateTypedWord("hello"); Assert.assertEquals("hello", underTest.getTypedWord()); Assert.assertEquals(5, underTest.charCount()); Assert.assertEquals(5, underTest.codePointCount()); Assert.assertE...
@Transactional(readOnly = true) public ArticleResponse readArticle(Long id) { Article article = articleRepository.getById(id); return ArticleResponse.from(article); }
@DisplayName("아티클 조회 성공") @Test void readArticle() { // given articleRepository.save(ARTICLE); // when & then assertThatCode(() -> articleService.readArticle(ARTICLE.getId())) .doesNotThrowAnyException(); }
void shutdown(@Observes ShutdownEvent event) { if (jobRunrBuildTimeConfiguration.backgroundJobServer().enabled()) { backgroundJobServerInstance.get().stop(); } if (jobRunrBuildTimeConfiguration.dashboard().enabled()) { dashboardWebServerInstance.get().stop(); } ...
@Test void jobRunrStarterStopsBackgroundJobServerIfConfigured() { when(backgroundJobServerConfiguration.enabled()).thenReturn(true); jobRunrStarter.shutdown(new ShutdownEvent()); verify(backgroundJobServer).stop(); }
public void setResultMessages(List<AbstractResultMessage> resultMessages) { this.resultMessages = resultMessages; }
@Test void setResultMessages() { BatchResultMessage batchResultMessage = new BatchResultMessage(); List<AbstractResultMessage> resultMessages = Arrays.asList(new RegisterTMResponse(), new RegisterRMResponse(false)); batchResultMessage.setResultMessages(resultMessages); Assertions.a...
@Override public Num calculate(BarSeries series, Position position) { if (position.isClosed()) { Num loss = excludeCosts ? position.getGrossProfit() : position.getProfit(); return loss.isNegative() ? loss : series.zero(); } return series.zero(); }
@Test public void calculateOnlyWithLossPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(1, series), Trade.buyAt(2, series), Trade.sellAt(5, series));...
@VisibleForTesting static Map<String, FileSystem> verifySchemesAreUnique( PipelineOptions options, Set<FileSystemRegistrar> registrars) { Multimap<String, FileSystem> fileSystemsBySchemes = TreeMultimap.create(Ordering.<String>natural(), Ordering.arbitrary()); for (FileSystemRegistrar registrar...
@Test public void testVerifySchemesAreUnique() throws Exception { thrown.expect(RuntimeException.class); thrown.expectMessage("Scheme: [file] has conflicting filesystems"); FileSystems.verifySchemesAreUnique( PipelineOptionsFactory.create(), Sets.newHashSet(new LocalFileSystemRegistrar(), ...
@Override public List<Intent> compile(PointToPointIntent intent, List<Intent> installable) { log.trace("compiling {} {}", intent, installable); ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint(); ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint(); ...
@Test public void testSuggestedPath() { String[] suggestedPathHops = {S1, S3, S4, S5, S6, S8}; List<Link> suggestedPath = NetTestTools.createPath(suggestedPathHops).links(); PointToPointIntent intent = makeIntentSuggestedPath(new ConnectPoint(DID_1, PORT_1), ...
@CheckForNull public Charset detect(byte[] buf) { // Try UTF-8 first since we are very confident in it if it's a yes. // Fail if we see nulls to not have FPs if the text is ASCII encoded in UTF-16. Result utf8Result = validator.isUTF8(buf, true); if (utf8Result.valid() == Validation.YES) { retur...
@Test public void tryUTF8First() { when(validation.isUTF8(any(byte[].class), anyBoolean())).thenReturn(Result.newValid(StandardCharsets.UTF_8)); assertThat(charsets.detect(new byte[1])).isEqualTo(StandardCharsets.UTF_8); }
void parseFistline(Modification modification, String line, ConsoleResult result) throws P4OutputParseException { Pattern pattern = Pattern.compile(FIRST_LINE_PATTERN); Matcher matcher = pattern.matcher(line); if (matcher.find()) { modification.setRevision(matcher.group(1)); ...
@Test void shouldThrowExceptionIfP4ReturnDifferentDateFormatWhenCannotParseFistLineOfP4Describe() { String output = "Change 2 on 08/08/19 by cceuser@connect4 'some modification message'"; Modification modification = new Modification(); try { parser.parseFistline(modification, out...
@Override protected int poll() throws Exception { // must reset for each poll shutdownRunningTask = null; pendingExchanges = 0; List<software.amazon.awssdk.services.sqs.model.Message> messages = pollingTask.call(); // okay we have some response from aws so lets mark the cons...
@Test void shouldIgnoreEmptyAttributeNames() throws Exception { // given configuration.setAttributeNames(""); configuration.setMessageAttributeNames(""); configuration.setSortAttributeName(""); try (var tested = createConsumer(9)) { // when var polled...
@Override public OAuth2AccessTokenDO grantAuthorizationCodeForAccessToken(String clientId, String code, String redirectUri, String state) { OAuth2CodeDO codeDO = oauth2CodeService.consumeAuthorizationCode(code); Assert.notNull(codeD...
@Test public void testGrantAuthorizationCodeForAccessToken() { // 准备参数 String clientId = randomString(); String code = randomString(); List<String> scopes = Lists.newArrayList("read", "write"); String redirectUri = randomString(); String state = randomString(); ...
@Override public N getSchedulerNode(NodeId nodeId) { return nodeTracker.getNode(nodeId); }
@Test(timeout = 30000l) public void testContainerReleaseWithAllocationTags() throws Exception { // Currently only can be tested against capacity scheduler. if (getSchedulerType().equals(SchedulerType.CAPACITY)) { final String testTag1 = "some-tag"; final String testTag2 = "some-other-tag"; Y...
@Override public Map<String, Long> call() throws Exception { Map<String, Long> result = new LinkedHashMap<>(); for (DownloadableItem item : items) { InputStreamWrapper stream = connectionProvider.getInputStreamForItem(jobId, item); long size = stream.getBytes(); if (size <= 0) { size...
@Test public void testExceptionIsThrown() throws Exception { when(connectionProvider.getInputStreamForItem(any(), any())) .thenThrow(new IOException("oh no!")); assertThrows(IOException.class, () -> { new CallableSizeCalculator(jobId, connectionProvider, Collections.singleton(createIte...
public static ValueLabel formatClippedBitRate(long bytes) { return new ValueLabel(bytes * 8, BITS_UNIT).perSec().clipG(100.0); }
@Test public void formatClippedBitsKilo() { vl = TopoUtils.formatClippedBitRate(2_004); assertEquals(AM_WL, "15.66 Kbps", vl.toString()); assertFalse(AM_CL, vl.clipped()); }
public static SortDir sortDir(String s) { return !DESC.equals(s) ? SortDir.ASC : SortDir.DESC; }
@Test public void sortDirDesc() { assertEquals("desc sort dir", SortDir.DESC, TableModel.sortDir("desc")); }
static String headerLine(CSVFormat csvFormat) { return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader()); }
@Test public void givenNoIgnoreEmptyLines_isNoop() { CSVFormat csvFormat = csvFormat().withIgnoreEmptyLines(false); PCollection<String> input = pipeline.apply(Create.of(headerLine(csvFormat), "a,1,1.1", "", "b,2,2.2", "", "c,3,3.3")); CsvIOStringToCsvRecord underTest = new CsvIOStringToCsvRecord(...
private AlarmId(DeviceId id, String uniqueIdentifier) { super(id.toString() + ":" + uniqueIdentifier); checkNotNull(id, "device id must not be null"); checkNotNull(uniqueIdentifier, "unique identifier must not be null"); checkArgument(!uniqueIdentifier.isEmpty(), "unique identifier must ...
@Test public void valueOf() { final AlarmId id = AlarmId.alarmId(DEVICE_ID, UNIQUE_ID_1); assertEquals("incorrect valueOf", id, ID_A); }
static Result coerceUserList( final Collection<Expression> expressions, final ExpressionTypeManager typeManager ) { return coerceUserList(expressions, typeManager, Collections.emptyMap()); }
@Test public void shouldCoerceLambdaVariables() { // Given: final ImmutableList<Expression> expressions = ImmutableList.of( BIGINT_EXPRESSION, new LambdaVariable("X"), INT_EXPRESSION ); // When: final Result result = CoercionUtil.coerceUserList( expressions, ...
public GetWorkBudget totalCurrentActiveGetWorkBudget() { return computationCache.asMap().values().stream() .map(ComputationState::getActiveWorkBudget) .reduce(GetWorkBudget.noBudget(), GetWorkBudget::apply); }
@Test public void testTotalCurrentActiveGetWorkBudget() { String computationId = "computationId"; String computationId2 = "computationId2"; MapTask mapTask = new MapTask().setStageName("stageName").setSystemName("systemName"); Map<String, String> userTransformToStateFamilyName = ImmutableMap.o...
public static String getRelativePath(Path basePath, Path fullPath) { return basePath.toUri().relativize(fullPath.toUri()).getPath(); }
@Test public void testRelativizeSelf() { assertEquals("", getRelativePath(BASE, BASE)); }
public static GraphQLRequestParams toGraphQLRequestParams(byte[] postData, final String contentEncoding) throws JsonProcessingException, UnsupportedEncodingException { final String encoding = StringUtils.isNotEmpty(contentEncoding) ? contentEncoding : EncoderCache.URL_ARGUMENT_ENCODI...
@Test void testToGraphQLRequestParamsWithHttpArguments() throws Exception { Arguments args = new Arguments(); args.addArgument(new HTTPArgument("query", "query { droid { id }}", "=", false)); GraphQLRequestParams params = GraphQLRequestParamUtils.toGraphQLRequestParams(args, null); a...
public static Optional<TableMetaData> load(final DataSource dataSource, final String tableNamePattern, final DatabaseType databaseType) throws SQLException { DialectDatabaseMetaData dialectDatabaseMetaData = new DatabaseTypeRegistry(databaseType).getDialectDatabaseMetaData(); try (MetaDataLoaderConnecti...
@Test void assertLoadWithNotExistedTable() throws SQLException { Map<String, SchemaMetaData> actual = MetaDataLoader.load(Collections.singleton(new MetaDataLoaderMaterial(Collections.singleton(NOT_EXISTED_TABLE), dataSource, databaseType, "sharding_db"))); assertFalse(actual.isEmpty()); asse...
@Override public <A extends ThreadPoolPlugin> Optional<A> getPlugin(String pluginId) { return Optional.empty(); }
@Test public void testGetPlugin() { Assert.assertSame(Optional.empty(), manager.getPlugin("")); }
public static Optional<OP_TYPE> getOpTypeFromFields(final List<Field<?>> fields, final String fieldName) { return fields == null ? Optional.empty() : fields.stream() .filter(dataField -> Objects.equals(fieldName,data...
@Test void getOpTypeFromFields() { Optional<OP_TYPE> opType = org.kie.pmml.compiler.api.utils.ModelUtils.getOpTypeFromFields(null, "vsd"); assertThat(opType).isNotNull(); assertThat(opType.isPresent()).isFalse(); final DataDictionary dataDictionary = new DataDictionary(); fin...
@Override public boolean generatedKeyAlwaysReturned() { return false; }
@Test void assertGeneratedKeyAlwaysReturned() { assertFalse(metaData.generatedKeyAlwaysReturned()); }
public Set<String> getLogicTableNames() { return tableMappers.stream().map(RouteMapper::getLogicName).collect(Collectors.toCollection(() -> new HashSet<>(tableMappers.size(), 1L))); }
@Test void assertGetLogicTableNames() { Set<String> actual = routeUnit.getLogicTableNames(); assertThat(actual.size(), is(1)); assertTrue(actual.contains(LOGIC_TABLE)); }
public static <T> Promise<T> error(final Throwable error) { return new ResolvedError<T>(error); }
@Test public void testError() { final Exception error = new Exception(); final Promise<?> promise = Promises.error(error); assertTrue(promise.isDone()); assertTrue(promise.isFailed()); assertEquals(error, promise.getError()); }
public static <T> T jsonToObject(final String json, final Class<T> valueTypeRef) { try { return MAPPER.readValue(json, valueTypeRef); } catch (IOException e) { LOG.warn("write to Object error: " + json, e); return null; } }
@Test public void testJsonToObject() { TestObject testObject = JsonUtils.jsonToObject(EXPECTED_JSON, TestObject.class); assertNotNull(testObject); assertEquals(testObject.getName(), "test object"); }
public String toAngular() { StringBuilder builder = new StringBuilder(); builder.append("%angular "); String outputText = template; for (int i = 0; i < values.size(); ++i) { outputText = outputText.replace("{" + i + "}", "{{value_" + i + "}}"); } builder.append(outputText); return buil...
@Test void testAngular() { List<Object> list = Arrays.asList("2020-01-01", 10); String template = "Total count:{1} for {0}"; InterpreterContext context = InterpreterContext.builder().build(); SingleRowInterpreterResult singleRowInterpreterResult = new SingleRowInterpreterResult(list, template, context...
public List<ModuleEntry> listFullModules() { // keep the order for used modules List<ModuleEntry> moduleEntries = usedModules.stream() .map(name -> new ModuleEntry(name, true)) .collect(Collectors.toList()); loadedModules.keySet().s...
@Test void testListFullModules() { ModuleMock x = new ModuleMock("x"); ModuleMock y = new ModuleMock("y"); ModuleMock z = new ModuleMock("z"); manager.loadModule("y", y); manager.loadModule("x", x); manager.loadModule("z", z); manager.useModules("z", "y"); ...
public static <T extends OrderedSPI<?>> Map<Class<?>, T> getServicesByClass(final Class<T> serviceInterface, final Collection<Class<?>> types) { Collection<T> services = getServices(serviceInterface); Map<Class<?>, T> result = new LinkedHashMap<>(services.size(), 1F); for (T each : services) { ...
@SuppressWarnings("rawtypes") @Test void assertGetServicesByClass() { Map<Class<?>, OrderedSPIFixture> actual = OrderedSPILoader.getServicesByClass(OrderedSPIFixture.class, Collections.singleton(OrderedInterfaceFixtureImpl.class)); assertThat(actual.size(), is(1)); assertThat(actual.get(...
@Config("resource-groups.config-file") public FileResourceGroupConfig setConfigFile(String configFile) { this.configFile = configFile; return this; }
@Test public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("resource-groups.config-file", "/test.json") .build(); FileResourceGroupConfig expected = new FileResourceGroupConfig() ...
public static byte[] readNullTerminatedBytes(byte[] data, int index) { ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int i = index; i < data.length; i++) { byte item = data[i]; if (item == MSC.NULL_TERMINATED_STRING_DELIMITER) { break; ...
@Test public void testReadNullTerminatedBytes() { Assert.assertArrayEquals(new byte[] {}, ByteHelper.readNullTerminatedBytes(new byte[] {0}, 0)); Assert.assertArrayEquals(new byte[] {8}, ByteHelper.readNullTerminatedBytes(new byte[] {8}, 0)); }
public synchronized void setLevel(Level newLevel) { if (level == newLevel) { // nothing to do; return; } if (newLevel == null && isRootLogger()) { throw new IllegalArgumentException("The level of the root logger cannot be set to null"); } leve...
@Test public void testEnabled_Debug() throws Exception { root.setLevel(Level.DEBUG); checkLevelThreshold(loggerTest, Level.DEBUG); }
@Override public boolean rename(Path src, Path dst) throws IOException { FTPClient client = connect(); try { boolean success = rename(client, src, dst); return success; } finally { disconnect(client); } }
@Test public void testRenameFileWithFullQualifiedPath() throws Exception { BaseUser user = server.addUser("test", "password", new WritePermission()); Configuration configuration = new Configuration(); configuration.set("fs.defaultFS", "ftp:///"); configuration.set("fs.ftp.host", "localhost"); conf...
public static String safeAvroToJsonString(GenericRecord record) { try { return avroToJsonString(record, false); } catch (Exception e) { return record.toString(); } }
@Test void testSafeAvroToJsonStringMissingRequiredField() { Schema schema = new Schema.Parser().parse(EXAMPLE_SCHEMA); GenericRecord record = new GenericData.Record(schema); record.put("non_pii_col", "val1"); record.put("pii_col", "val2"); record.put("timestamp", 3.5); String jsonString = Hood...
public List<String> getConsumerIdListByGroup( final String addr, final String consumerGroup, final long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, MQBrokerException, InterruptedException { GetConsumerListByGroupRequestH...
@Test public void testGetConsumerIdListByGroup() throws Exception { doAnswer((Answer<RemotingCommand>) mock -> { RemotingCommand request = mock.getArgument(1); final RemotingCommand response = RemotingCommand.createResponseCommand(GetConsumerListByGroupResponseHe...
public OutputStream scaleThroughput(double v) { return new OutputStream(id, rate.scaleBy(v), areKeysSkewed); }
@Test public void scaleThroughput() { OutputStream orig = new OutputStream("ID", new NormalDistStats(100.0, 1.0, 99.0, 101.0), false); OutputStream scaled = orig.scaleThroughput(2.0); assertEquals(orig.id, scaled.id); assertEquals(orig.areKeysSkewed, scaled.areKeysSkewed); as...
@Override protected Optional<ErrorResponse> filter(DiscFilterRequest req) { var now = clock.instant(); var bearerToken = requestBearerToken(req).orElse(null); if (bearerToken == null) { log.fine("Missing bearer token"); return Optional.of(new ErrorResponse(Response.St...
@Test void fails_on_handler_with_custom_request_spec_with_invalid_action() { var spec = RequestHandlerSpec.builder() .withAclMapping(HttpMethodAclMapping.standard() .override(Method.GET, Action.custom("custom")).build()) .build(); ...
@Override public DataSource getNamedDataSource( String datasourceName ) throws DataSourceNamingException { ClassLoader original = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); return DatabaseUtil.getDataSourceFrom...
@Test public void testCl() throws NamingException { DataSource dataSource = mock( DataSource.class ); when( context.lookup( testName ) ).thenReturn( dataSource ); DatabaseUtil util = new DatabaseUtil(); ClassLoader orig = Thread.currentThread().getContextClassLoader(); ClassLoader cl = mock( Class...
@Override public Iterable<DiscoveryNode> discoverNodes() { try { Collection<AzureAddress> azureAddresses = azureClient.getAddresses(); logAzureAddresses(azureAddresses); List<DiscoveryNode> result = new ArrayList<>(); for (AzureAddress azureAddress : azureAddr...
@Test public void discoverNodesException() { // given given(azureClient.getAddresses()).willThrow(new RuntimeException("Error while checking Azure instances")); // when Iterable<DiscoveryNode> nodes = azureDiscoveryStrategy.discoverNodes(); // then assertFalse(nodes...
@Override public InetSocketAddress getLocalAddress() { return channel.getLocalAddress(); }
@Test void getLocalAddressTest() { Assertions.assertNull(header.getLocalAddress()); }
@Override public void deleteDictData(Long id) { // 校验是否存在 validateDictDataExists(id); // 删除字典数据 dictDataMapper.deleteById(id); }
@Test public void testDeleteDictData_success() { // mock 数据 DictDataDO dbDictData = randomDictDataDO(); dictDataMapper.insert(dbDictData);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbDictData.getId(); // 调用 dictDataService.deleteDictData(id); // 校验数据不存在了 ...
public static Object convert(Type type, String value) { if (null == value) { return value; } if ("".equals(value)) { if (type.equals(String.class)) { return value; } if (type.equals(int.class) || type.equals(double.class) || ...
@Test public void testConvert() { Object o1 = ReflectKit.convert(String.class, "hello"); Assert.assertEquals("hello", o1); Object o2 = ReflectKit.convert(BigDecimal.class, "20.1"); Assert.assertEquals(new BigDecimal("20.1"), o2); Object o3 = ReflectKit.convert(Float.class, ...
public boolean isDeletionInProgress(String workflowId) { return withRetryableQuery( EXIST_IN_PROGRESS_DELETION_QUERY, stmt -> stmt.setString(1, workflowId), ResultSet::next); }
@Test public void testIsDeletionInProgress() throws Exception { WorkflowDefinition wfd = loadWorkflow(TEST_WORKFLOW_ID1); workflowDao.addWorkflowDefinition(wfd, wfd.getPropertiesSnapshot().extractProperties()); assertFalse(deletionDao.isDeletionInProgress(TEST_WORKFLOW_ID1)); workflowDao.deleteWorkflo...
public CompletableFuture<Void> commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets) { if (offsets.isEmpty()) { log.debug("Skipping commit of empty offsets"); return CompletableFuture.completedFuture(null); } OffsetCommitRequestState commitRequest = createOffs...
@Test public void testPollEnsureManualCommitSent() { CommitRequestManager commitRequestManager = create(false, 0); assertPoll(0, commitRequestManager); Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>(); offsets.put(new TopicPartition("t1", 0), new OffsetAndMetadata(0)...
@Override public void execute(GraphModel graphModel) { isCanceled = false; UndirectedGraph undirectedGraph = graphModel.getUndirectedGraphVisible(); Column weaklyConnectedColumn = initializeWeaklyConnectedColumn(graphModel); Column stronglyConnectedColumn = null; if (isDire...
@Test public void testColumnReplace() { GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1); graphModel.getNodeTable().addColumn(ConnectedComponents.WEAKLY, String.class); ConnectedComponents cc = new ConnectedComponents(); cc.execute(graphModel); }
static Serde<List<?>> createSerde(final PersistenceSchema schema) { final List<SimpleColumn> columns = schema.columns(); if (columns.isEmpty()) { // No columns: return new KsqlVoidSerde<>(); } if (columns.size() != 1) { throw new KsqlException("The '" + FormatFactory.KAFKA.name() ...
@Test public void shouldThrowIfDecimal() { // Given: final PersistenceSchema schema = schemaWithFieldOfType(SqlTypes.decimal(1, 1)); // When: final Exception e = assertThrows( KsqlException.class, () -> KafkaSerdeFactory.createSerde(schema) ); // Then: assertThat(e.getMes...
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); for (final Thread.State state : Thread.State.values()) { gauges.put(name(state.toString().toLowerCase(), "count"), (Gauge<Object>) () -> getThreadCount(state)); ...
@Test public void hasASetOfGauges() { assertThat(gauges.getMetrics().keySet()) .containsOnly("terminated.count", "new.count", "count", "timed_waiting.count", "deadlocks", "blocked.count", "waiting.cou...
static boolean canDelay(@Nonnull final Packet stanza) { if (stanza instanceof IQ) { return false; } if (stanza instanceof Presence) { final Presence presence = (Presence) stanza; if (presence.getType() == null || presence.getType() == Presence.Type.unavai...
@Test public void testJinglePropose() throws Exception { // Setup test fixture. final Packet input = parse("<message type=\"chat\" id=\"jm-propose-LE3clSJQobTiFcrAoSD52\" to=\"user@example.com\">\n" + " <propose xmlns=\"urn:xmpp:jingle-message:0\" id=\"LE3clSJQobTiFcrAoNLR2A\">\n" ...
@VisibleForTesting boolean isLeader(Collection<MemberDescription> members, Collection<TopicPartition> partitions) { // there should only be one task assigned partition 0 of the first topic, // so elect that one the leader TopicPartition firstTopicPartition = members.stream() .flatMap(m...
@Test public void testIsLeader() { CommitterImpl committer = new CommitterImpl(); MemberAssignment assignment1 = new MemberAssignment( ImmutableSet.of(new TopicPartition("topic1", 0), new TopicPartition("topic2", 1))); MemberDescription member1 = new MemberDescription(null, Op...
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void nestedContexts() { String inputExpression = "{ a value : 10," + " an applicant : { " + " first name : \"Edson\", " + " last + name : \"Tirelli\", " + " full name : first name + last + name, " ...
public static <T> T copyWithGson(Object orig, Class<T> c) { // Backup the current MetaContext before assigning a new one. MetaContext oldContext = MetaContext.get(); MetaContext metaContext = new MetaContext(); metaContext.setStarRocksMetaVersion(FeConstants.STARROCKS_META_VERSION); ...
@Test public void testCopyWithJson() { GsonSerializationTest.OrigClassA classA = new GsonSerializationTest.OrigClassA(1); GsonSerializationTest.OrigClassA copied = DeepCopy.copyWithGson(classA, GsonSerializationTest.OrigClassA.class); Assert.assertTrue(copied != null); Assert.assertE...
@Override public Page<RoleInfo> getRolesByUserNameAndRoleName(String username, String role, int pageNo, int pageSize) { AuthPaginationHelper<RoleInfo> helper = createPaginationHelper(); String sqlCountRows = "SELECT count(*) FROM roles "; String sqlFetchRows = "SELECT ...
@Test void testGetRolesByUserName() { Page<RoleInfo> userName = externalRolePersistService.getRolesByUserNameAndRoleName("userName", "roleName", 1, 10); assertNotNull(userName); }
public static PostgreSQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find PostgreSQL type '%s' in column type when process binary protocol value", binaryColumnType); return ...
@Test void assertGetDateBinaryProtocolValue() { PostgreSQLBinaryProtocolValue binaryProtocolValue = PostgreSQLBinaryProtocolValueFactory.getBinaryProtocolValue(PostgreSQLColumnType.DATE); assertThat(binaryProtocolValue, instanceOf(PostgreSQLDateBinaryProtocolValue.class)); }
public static Document loadXMLFrom( String xml ) throws SAXException, IOException { return loadXMLFrom( new ByteArrayInputStream( xml.getBytes() ) ); }
@Test( timeout = 2000 ) public void whenLoadingMaliciousXmlFromInputStreamParsingEndsWithNoErrorAndNullValueIsReturned() throws Exception { assertNull( PDIImportUtil.loadXMLFrom( MALICIOUS_XML ) ); }
static PartitionSpec createPartitionSpec( org.apache.iceberg.Schema schema, List<String> partitionBy) { if (partitionBy.isEmpty()) { return PartitionSpec.unpartitioned(); } PartitionSpec.Builder specBuilder = PartitionSpec.builderFor(schema); partitionBy.forEach( partitionField -> {...
@Test public void testCreatePartitionSpecUnpartitioned() { PartitionSpec spec = SchemaUtils.createPartitionSpec(SCHEMA_FOR_SPEC, ImmutableList.of()); assertThat(spec.isPartitioned()).isFalse(); }
public boolean hasValues() { return hasValues; }
@Test public void testEmptyCells() { builder = new LhsBuilder(9, 1, "Person"); assertThat(builder.hasValues()).isFalse(); }