focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Response noContent() { stream.setStatus(204); return this; }
@Test public void test_noContent() throws Exception { underTest.noContent(); verify(response).setStatus(204); verify(response, never()).getOutputStream(); }
public static <E> List<E> executePaginatedRequest(String request, OAuth20Service scribe, OAuth2AccessToken accessToken, Function<String, List<E>> function) { List<E> result = new ArrayList<>(); readPage(result, scribe, accessToken, addPerPageQueryParameter(request, DEFAULT_PAGE_SIZE), function); return resu...
@Test public void fail_to_executed_paginated_request() { mockWebServer.enqueue(new MockResponse() .setHeader("Link", "<" + serverUrl + "/test?per_page=100&page=2>; rel=\"next\", <" + serverUrl + "/test?per_page=100&page=2>; rel=\"last\"") .setBody("A")); mockWebServer.enqueue(new MockResponse().se...
@Override public void assign(Collection<TopicPartition> partitions) { acquireAndEnsureOpen(); try { if (partitions == null) { throw new IllegalArgumentException("Topic partitions collection to assign to cannot be null"); } if (partitions.isEmpty()...
@Test public void testAssignOnNullTopicPartition() { consumer = newConsumer(); assertThrows(IllegalArgumentException.class, () -> consumer.assign(null)); }
@Override public NullsOrderType getDefaultNullsOrderType() { return NullsOrderType.FIRST; }
@Test void assertGetDefaultNullsOrderType() { assertThat(dialectDatabaseMetaData.getDefaultNullsOrderType(), is(NullsOrderType.FIRST)); }
public static Enabled enabled(XmlPullParser parser) throws XmlPullParserException, IOException { ParserUtils.assertAtStartTag(parser); boolean resume = ParserUtils.getBooleanAttribute(parser, "resume", false); String id = parser.getAttributeValue("", "id"); String location = parser.getAt...
@Test public void testParseEnabled() throws Exception { String stanzaID = "zid615d9"; boolean resume = true; String location = "test"; int max = 42; String enabledStanza = XMLBuilder.create("enabled") .a("xmlns", "urn:xmpp:sm:3") .a("id", "zid...
@SuppressWarnings("UnstableApiUsage") @Override public Stream<ColumnName> resolveSelectStar( final Optional<SourceName> sourceName ) { final Stream<ColumnName> names = Stream.of(left, right) .flatMap(JoinNode::getPreJoinProjectDataSources) .filter(s -> !sourceName.isPresent() || sourceNa...
@Test public void shouldResolveUnaliasedSelectStarWithMultipleJoins() { // Given: final JoinNode inner = new JoinNode(new PlanNodeId("foo"), LEFT, joinKey, true, right, right2, empty(), "KAFKA"); final JoinNode joinNode = new JoinNode(nodeId, LEFT, joinKey, ...
@Override public Long createLevel(MemberLevelCreateReqVO createReqVO) { // 校验配置是否有效 validateConfigValid(null, createReqVO.getName(), createReqVO.getLevel(), createReqVO.getExperience()); // 插入 MemberLevelDO level = MemberLevelConvert.INSTANCE.convert(createReqVO); memberLeve...
@Test public void testCreateLevel_success() { // 准备参数 MemberLevelCreateReqVO reqVO = randomPojo(MemberLevelCreateReqVO.class, o -> { o.setDiscountPercent(randomInt()); o.setIcon(randomURL()); o.setBackgroundUrl(randomURL()); o.setStatus(randomCommonSta...
public static Logger empty() { return EMPTY_LOGGER; }
@Test public void loggersReturnsEmptyInstance() { Logger logger = Loggers.empty(); assertThat(logger, instanceOf(EmptyLogger.class)); }
@Override public void commitSync() { commitSync(Duration.ofMillis(defaultApiTimeoutMs)); }
@Test public void testInterceptorCommitSync() { Properties props = requiredConsumerConfigAndGroupId("test-id"); props.setProperty(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, MockConsumerInterceptor.class.getName()); props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); ...
public static boolean hasLeadership(KubernetesConfigMap configMap, String lockIdentity) { final String leader = configMap.getAnnotations().get(LEADER_ANNOTATION_KEY); return leader != null && leader.contains(lockIdentity); }
@Test void testAnnotationMatched() { leaderConfigMap .getAnnotations() .put(LEADER_ANNOTATION_KEY, "other information " + lockIdentity); assertThat(KubernetesLeaderElector.hasLeadership(leaderConfigMap, lockIdentity)).isTrue(); }
@Override public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { return copy(source, segmentService.list(source), target, status, callback, listener); }
@Test public void testCopyManifestDifferentBucket() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final Path originFolder = new Path(container, UUID.randomUUID().toString(),...
@VisibleForTesting Map<String, String> generateApplicationMasterEnv( final YarnApplicationFileUploader fileUploader, final String classPathStr, final String localFlinkJarStr, final String appIdStr) throws IOException { final Map<String, String> env...
@Test public void testGenerateApplicationMasterEnv(@TempDir File flinkHomeDir) throws IOException { final String fakeLocalFlinkJar = "./lib/flink_dist.jar"; final String fakeClassPath = fakeLocalFlinkJar + ":./usrlib/user.jar"; final ApplicationId appId = ApplicationId.newInstance(0, 0); ...
public static String replaceFirst(String source, String search, String replace) { int start = source.indexOf(search); int len = search.length(); if (start == -1) { return source; } if (start == 0) { return replace + source.substring(len); } ...
@Test public void testReplace3() { assertEquals("abcxyz", JOrphanUtils.replaceFirst("abcdef", "def", "xyz")); }
public Properties getProperties() { return properties; }
@Test public void testHibernateProperties() { assertNull(Configuration.INSTANCE.getProperties().getProperty("hibernate.types.nothing")); assertEquals("def", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.abc")); }
public static String from(Path path) { return from(path.toString()); }
@Test void testHtmlContentType() { assertThat(ContentType.from(Path.of("index.html"))).isEqualTo(TEXT_HTML); }
public static Date getNextExecutionDate(Period period) { // calcule de la date de prochaine exécution (le dimanche à minuit) final Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILL...
@Test public void testGetNextExecutionDate() { assertNotNull("getNextExecutionDate", MailReport.getNextExecutionDate(Period.JOUR)); assertNotNull("getNextExecutionDate", MailReport.getNextExecutionDate(Period.SEMAINE)); assertNotNull("getNextExecutionDate", MailReport.getNextExecutionDate(Period.MOIS)); }
public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors( ReconnaissanceReport reconnaissanceReport) { return tsunamiPlugins.entrySet().stream() .filter(entry -> isVulnDetector(entry.getKey())) .map(entry -> matchAllVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanc...
@Test public void getVulnDetectors_whenRemoteDetectorServiceNameFilterHasMatchingService_returnsMatchedService() { NetworkService httpService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80)) .setTransportProtocol(TransportPro...
@Override public ResultSet getFunctions(final String catalog, final String schemaPattern, final String functionNamePattern) { return null; }
@Test void assertGetFunctions() { assertNull(metaData.getFunctions("", "", "")); }
@Override public void reportErrorAndInvalidate(String bundleSymbolicName, List<String> messages) { try { pluginRegistry.markPluginInvalid(bundleSymbolicName, messages); } catch (Exception e) { LOGGER.warn("[Plugin Health Service] Plugin with id '{}' tried to report health wit...
@Test void shouldMarkPluginAsInvalidWhenServiceReportsAnError() { String bundleSymbolicName = "plugin-id"; String message = "plugin is broken beyond repair"; List<String> reasons = List.of(message); doNothing().when(pluginRegistry).markPluginInvalid(bundleSymbolicName, reasons); ...
static Map<String, ValueExtractor> instantiateExtractors(List<AttributeConfig> attributeConfigs, ClassLoader classLoader) { Map<String, ValueExtractor> extractors = createHashMap(attributeConfigs.size()); for (AttributeConfig config : attribut...
@Test public void instantiate_extractors_accessException() { // GIVEN AttributeConfig string = new AttributeConfig("iq", "com.hazelcast.query.impl.getters.ExtractorHelperTest$AccessExceptionExtractor"); // WHEN assertThatThrownBy(() -> instantiateExtractors(singleton...
@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 testMoveFile() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback()...
public static ManagedTransform write(String sink) { return new AutoValue_Managed_ManagedTransform.Builder() .setIdentifier( Preconditions.checkNotNull( WRITE_TRANSFORMS.get(sink.toLowerCase()), "An unsupported sink was specified: '%s'. Please specify one of the fo...
@Test public void testManagedTestProviderWithConfigMap() { Managed.ManagedTransform writeOp = Managed.write(Managed.ICEBERG) .toBuilder() .setIdentifier(TestSchemaTransformProvider.IDENTIFIER) .build() .withSupportedIdentifiers(Arrays.asList(TestSchemaTransf...
public List<String> generate(String tableName, String columnName, boolean isAutoGenerated) throws SQLException { return generate(tableName, singleton(columnName), isAutoGenerated); }
@Test public void generate_for_ms_sql() throws SQLException { when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT)); when(db.getDialect()).thenReturn(MS_SQL); List<String> sqls = underTest.generate(TABLE_NAME, PK_COLUMN, true); assertThat(sqls).containsExactly("...
@Override public DataSource get() { if (highAvailableDataSource == null) { return null; } Map<String, DataSource> dataSourceMap = highAvailableDataSource.getAvailableDataSourceMap(); if (dataSourceMap == null || dataSourceMap.isEmpty()) { return null; ...
@Test public void testEmptyMap() { dataSourceMap.clear(); NamedDataSourceSelector selector = new NamedDataSourceSelector(null); assertNull(selector.get()); selector = new NamedDataSourceSelector(dataSource); assertNull(selector.get()); }
public final void tag(I input, ScopedSpan span) { if (input == null) throw new NullPointerException("input == null"); if (span == null) throw new NullPointerException("span == null"); if (span.isNoop()) return; tag(span, input, span.context()); }
@Test void tag_span_empty() { when(parseValue.apply(input, context)).thenReturn(""); tag.tag(input, span); verify(span).context(); verify(span).isNoop(); verify(parseValue).apply(input, context); verifyNoMoreInteractions(parseValue); // doesn't parse twice verify(span).tag("key", ""); ...
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) { final Fetch<K, V> fetch = Fetch.empty(); final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>(); int recordsRemaining = fetchConfig.maxPollRecords; try { while (recordsRemaining > 0) { ...
@Test public void testFetchWithReadReplica() { buildDependencies(); assignAndSeek(topicAPartition0); // Set the preferred read replica and just to be safe, verify it was set. int preferredReadReplicaId = 67; subscriptions.updatePreferredReadReplica(topicAPartition0, preferre...
@Override public long getQueueSize() { return asyncExecutionMonitoring.getQueueSize(); }
@Test public void getQueueSize_delegates_to_AsyncExecutionMonitoring() { when(asyncExecutionMonitoring.getQueueSize()).thenReturn(12); assertThat(underTest.getQueueSize()).isEqualTo(12); verify(asyncExecutionMonitoring).getQueueSize(); }
@VisibleForTesting static int checkJar(Path file) throws Exception { final URI uri = file.toUri(); int numSevereIssues = 0; try (final FileSystem fileSystem = FileSystems.newFileSystem( new URI("jar:file", uri.getHost(), uri.getPath(), uri.getFragment...
@Test void testRejectedOnNoticeFileInRoot(@TempDir Path tempDir) throws Exception { assertThat( JarFileChecker.checkJar( createJar( tempDir, Entry.fileEntry(VALID_NOTICE_CO...
@Override public String execute(CommandContext commandContext, String[] args) { if (args.length > 0) { return "Unsupported parameter " + Arrays.toString(args) + " for pwd."; } String service = commandContext.getRemote().attr(ChangeTelnet.SERVICE_KEY).get(); ...
@Test void testMessageError() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null); String result = pwdTelnet.execute(mockCommandContext, new String[] {"test"}); assertEquals("Unsupported parameter [test] for pwd.", result); }
public static Iterable<OGCGeometry> flattenCollection(OGCGeometry geometry) { if (geometry == null) { return ImmutableList.of(); } if (!(geometry instanceof OGCConcreteGeometryCollection)) { return ImmutableList.of(geometry); } if (((OGCConcreteGeometr...
@Test public void testFlattenCollection() { assertFlattenLeavesUnchanged(OGCGeometry.fromText("POINT EMPTY")); assertFlattenLeavesUnchanged(OGCGeometry.fromText("POINT (1 2)")); assertFlattenLeavesUnchanged(OGCGeometry.fromText("MULTIPOINT EMPTY")); assertFlattenLeavesUnchanged(O...
@GET @Path("{path:.*}") @Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8}) public Response get(@PathParam("path") String path, @Context UriInfo uriInfo, @QueryParam(OperationParam.NAME) O...
@Test @TestDir @TestJetty @TestHdfs public void testHdfsAccess() throws Exception { createHttpFSServer(false, false); long oldOpsListStatus = metricsGetter.get("LISTSTATUS").call(); String user = HadoopUsersConfTestHelper.getHadoopUsers()[0]; URL url = new URL(TestJettyHelper.getJettyURL...
@Override @CacheEvict(value = RedisKeyConstants.MAIL_ACCOUNT, key = "#id") public void deleteMailAccount(Long id) { // 校验是否存在账号 validateMailAccountExists(id); // 校验是否存在关联模版 if (mailTemplateService.getMailTemplateCountByAccountId(id) > 0) { throw exception(MAIL_ACCOUNT...
@Test public void testDeleteMailAccount_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> mailAccountService.deleteMailAccount(id), MAIL_ACCOUNT_NOT_EXISTS); }
@Override public Num calculate(BarSeries series, Position position) { return position.hasLoss() ? series.one() : series.zero(); }
@Test public void calculateWithOneLongPosition() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); Position position = new Position(Trade.buyAt(1, series), Trade.sellAt(3, series)); assertNumEquals(1, getCriterion().calculate(series, position)); }
public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); }
@Test public void retryOnResultFailAfterMaxAttemptsUsingMaybe() throws InterruptedException { RetryConfig config = RetryConfig.<String>custom() .retryOnResult("retry"::equals) .waitDuration(Duration.ofMillis(50)) .maxAttempts(3).build(); Retry retry = Retry.of("te...
@Override public NotifyMessageDO getNotifyMessage(Long id) { return notifyMessageMapper.selectById(id); }
@Test public void testGetNotifyMessage() { // mock 数据 NotifyMessageDO dbNotifyMessage = randomPojo(NotifyMessageDO.class, o -> o.setTemplateParams(randomTemplateParams())); notifyMessageMapper.insert(dbNotifyMessage); // 准备参数 Long id = dbNotifyMessage.getId();...
public static ImmutableList<SbeField> generateFields(Ir ir, IrOptions irOptions) { ImmutableList.Builder<SbeField> fields = ImmutableList.builder(); TokenIterator iterator = getIteratorForMessage(ir, irOptions); while (iterator.hasNext()) { Token token = iterator.next(); switch (token.signal())...
@Test public void testGenerateFieldsWithInvalidMessageName() throws Exception { Ir ir = getIr(OnlyPrimitives.RESOURCE_PATH); IrOptions options = IrOptions.builder().setMessageName(UUID.randomUUID().toString()).build(); assertThrows( IllegalArgumentException.class, () -> IrFieldGenerator.generateF...
@Override public Mono<String> resolve(Subscription.Subscriber subscriber) { var identity = UserIdentity.of(subscriber.getName()); if (identity.isAnonymous()) { return Mono.fromSupplier(() -> getEmail(subscriber)); } return client.fetch(User.class, subscriber.getName()) ...
@Test void testResolve() { var subscriber = new Subscription.Subscriber(); subscriber.setName(AnonymousUserConst.PRINCIPAL + "#test@example.com"); subscriberEmailResolver.resolve(subscriber) .as(StepVerifier::create) .expectNext("test@example.com") .verify...
public List<R> scanForResourcesInPackage(String packageName, Predicate<String> packageFilter) { requireValidPackageName(packageName); requireNonNull(packageFilter, "packageFilter must not be null"); BiFunction<Path, Path, Resource> createResource = createPackageResource(packageName); Lis...
@Test void scanForResourcesInSubPackage() { String basePackageName = "io.cucumber.core.resource"; List<URI> resources = resourceScanner.scanForResourcesInPackage(basePackageName, aPackage -> true); assertThat(resources, containsInAnyOrder( URI.create("classpath:io/cucumber/core/r...
public @CheckForNull URL toExternalURL() throws IOException { return null; }
@Test public void testExternalUrl() throws Exception { VirtualFile root = new VirtualFileMinimalImplementation(); assertThat(root.toExternalURL(), nullValue()); }
@Override public FastAppend appendFile(DataFile file) { Preconditions.checkNotNull(file, "Invalid data file: null"); if (newFilePaths.add(file.path())) { this.hasNewFiles = true; newFiles.add(file); summaryBuilder.addedFile(spec, file); } return this; }
@TestTemplate public void appendNullFile() { assertThatThrownBy(() -> table.newFastAppend().appendFile(null).commit()) .isInstanceOf(NullPointerException.class) .hasMessage("Invalid data file: null"); }
@Override public PipelineDef parse(Path pipelineDefPath, Configuration globalPipelineConfig) throws Exception { return parse(mapper.readTree(pipelineDefPath.toFile()), globalPipelineConfig); }
@Test void testEvaluateDefaultLocalTimeZone() throws Exception { URL resource = Resources.getResource("definitions/pipeline-definition-minimized.yaml"); YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser(); PipelineDef pipelineDef = parser.parse(Paths.get(resource.toURI()...
@Override public Optional<IndexSet> get(final String indexSetId) { return this.indexSetsCache.get() .stream() .filter(indexSet -> Objects.equals(indexSet.id(), indexSetId)) .map(indexSetConfig -> (IndexSet) mongoIndexSetFactory.create(indexSetConfig)) ...
@Test public void indexSetsCacheShouldBeInvalidatedForIndexSetDeletion() { final IndexSetConfig indexSetConfig = mock(IndexSetConfig.class); final List<IndexSetConfig> indexSetConfigs = Collections.singletonList(indexSetConfig); when(indexSetService.findAll()).thenReturn(indexSetConfigs); ...
@Override public final String toString() { StringJoiner result = new StringJoiner(", ", "(", ")"); for (int i = 0; i < values.size(); i++) { result.add(getValue(i)); } return result.toString(); }
@Test void assertSysdateToString() { List<ExpressionSegment> expressionSegments = new ArrayList<>(1); expressionSegments.add(new ColumnSegment(0, 6, new IdentifierValue("SYSDATE"))); InsertValue insertValue = new InsertValue(expressionSegments); String actualToString = insertValue.to...
@Override public Optional<SelectionContext<VariableMap>> match(SelectionCriteria criteria) { Map<String, String> variables = new HashMap<>(); if (userRegex.isPresent()) { Matcher userMatcher = userRegex.get().matcher(criteria.getUser()); if (!userMatcher.matches()) { ...
@Test public void testSchema() { ResourceGroupId resourceGroupId = new ResourceGroupId(new ResourceGroupId("global"), "schema1"); StaticSelector selector = new StaticSelector( Optional.empty(), Optional.empty(), Optional.of(ImmutableList.of()), ...
public static boolean isKeepAlive(HttpMessage message) { return !message.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true) && (message.protocolVersion().isKeepAliveDefault() || message.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderVa...
@Test public void testKeepAliveIfConnectionHeaderMultipleValues() { HttpMessage http11Message = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http:localhost/http_1_1"); http11Message.headers().set( HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE + ", ...
@VisibleForTesting void globalUpdates(String args, SchedConfUpdateInfo updateInfo) { if (args == null) { return; } HashMap<String, String> globalUpdates = new HashMap<>(); for (String globalUpdate : args.split(SPLIT_BY_SLASH_COMMA)) { globalUpdate = globalUpdate.replace("\\", ""); pu...
@Test(timeout = 10000) public void testGlobalUpdate() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); cli.globalUpdates("schedKey1=schedVal1,schedKey2=schedVal2", schedUpdateInfo); Map<String, String> paramValues = new HashMap<>(); paramValues.put("schedKey1", "schedVal1"); ...
@Override public Map<String, String> context() { return context; }
@Test public void contextShouldContainEnvAndPropertiesAndHostAndPort() throws Exception { String hostname = "xx.xx.xx"; int port = 20; AgentBootstrapperArgs bootstrapperArgs = new AgentBootstrapperArgs().setServerUrl(new URL("https://" + hostname + ":" + port + "/go")).setRootCertFile(null)....
public static <T> Collector<T, ?, List<T>> toUnmodifiableList() { return Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList); }
@Test public void convertToUnmodifiableProducesFaithfulCopy() { List<Integer> list = Arrays.asList(1, 2, 3); List<Integer> unmodifiable = list.stream().collect(StreamUtils.toUnmodifiableList()); assertEquals(list, unmodifiable); }
@Description("transforms the string to normalized form") @ScalarFunction @LiteralParameters({"x", "y"}) @SqlType(StandardTypes.VARCHAR) public static Slice normalize(@SqlType("varchar(x)") Slice slice, @SqlType("varchar(y)") Slice form) { Normalizer.Form targetForm; try { ...
@Test public void testNormalize() { assertFunction("normalize('sch\u00f6n', NFD)", VARCHAR, "scho\u0308n"); assertFunction("normalize('sch\u00f6n')", VARCHAR, "sch\u00f6n"); assertFunction("normalize('sch\u00f6n', NFC)", VARCHAR, "sch\u00f6n"); assertFunction("normalize('sch\u00f...
@Override public Class<GetDataTypes> getRequestType() { return GetDataTypes.class; }
@Test public void testGetRequestType() { AuthServiceProviderRegistry registry = mock(AuthServiceProviderRegistry.class); DataTypesAction dataTypesAction = new DataTypesAction(registry, new Monitor() { }); Class<GetDataTypes> actual = dataTypesAction.getRequestType(); assertNotEquals(actual, null)...
@Override public Processor<KIn, VIn, KOut, VOut> get() { return new KStreamMapProcessor(); }
@Test public void testMap() { final StreamsBuilder builder = new StreamsBuilder(); final String topicName = "topic"; final int[] expectedKeys = new int[] {0, 1, 2, 3}; final MockApiProcessorSupplier<String, Integer, Void, Void> supplier = new MockApiProcessorSupplier<>(); fi...
public void setCodec(final Codec codec) { this.codec = checkNotNull(codec, "codec can not be null"); }
@Test void testCompression() throws Exception { // given final Path outputPath = new Path(File.createTempFile("avro-output-file", "avro").getAbsolutePath()); final AvroOutputFormat<User> outputFormat = new AvroOutputFormat<>(outputPath, User.class); outputFormat.setWr...
public static ParseResult parse(String text) { Map<String, String> localProperties = new HashMap<>(); String intpText = ""; String scriptText = null; Matcher matcher = REPL_PATTERN.matcher(text); if (matcher.find()) { String headingSpace = matcher.group(1); intpText = matcher.group(2); ...
@Test void testParagraphTextQuotedPropertyValue1() { ParagraphTextParser.ParseResult parseResult = ParagraphTextParser.parse( "%spark.pyspark(pool=\"value with = inside\")"); assertEquals("spark.pyspark", parseResult.getIntpText()); assertEquals(1, parseResult.getLocalProperties().size()); ...
@Override public Map<RedisClusterNode, Collection<RedisClusterNode>> clusterGetMasterReplicaMap() { Iterable<RedisClusterNode> res = clusterGetNodes(); Set<RedisClusterNode> masters = new HashSet<RedisClusterNode>(); for (Iterator<RedisClusterNode> iterator = res.iterator(); iterato...
@Test public void testClusterGetMasterSlaveMap() { Map<RedisClusterNode, Collection<RedisClusterNode>> map = connection.clusterGetMasterReplicaMap(); assertThat(map).hasSize(3); for (Collection<RedisClusterNode> slaves : map.values()) { assertThat(slaves).hasSize(1); } ...
public void validateConvertedConfig(String outputDir) throws Exception { QueueMetrics.clearQueueMetrics(); Path configPath = new Path(outputDir, "capacity-scheduler.xml"); CapacitySchedulerConfiguration csConfig = new CapacitySchedulerConfiguration( new Configuration(false), false...
@Test public void testValidationPassed() throws Exception { validator.validateConvertedConfig(CONFIG_DIR_PASSES); // expected: no exception }
@Operation(summary = "updateResourceContent", description = "UPDATE_RESOURCE_NOTES") @Parameters({ @Parameter(name = "content", description = "CONTENT", required = true, schema = @Schema(implementation = String.class)), @Parameter(name = "fullName", description = "FULL_NAME", required = true...
@Test public void testUpdateResourceContent() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.TENANT_NOT_EXIST.getCode()); Mockito.when(resourcesService.updateResourceContent(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any...
public MemcacheProtocolConfig getMemcacheProtocolConfig() { return memcacheProtocolConfig; }
@Test public void testMemcacheProtocolConfig_isNotNullByDefault() { assertNotNull(networkConfig.getMemcacheProtocolConfig()); }
public void setParentArtifactId(String parentArtifactId) { this.parentArtifactId = parentArtifactId; }
@Test public void testSetParentArtifactId() { String parentArtifactId = "something"; Model instance = new Model(); instance.setParentArtifactId(parentArtifactId); assertNotNull(instance.getParentArtifactId()); }
public String getName() { return name; }
@Test public void getName() { assertEquals(file.getName(), ss.getName()); }
public List<AnalyzedInstruction> getAnalyzedInstructions() { return analyzedInstructions.getValues(); }
@Test public void testInstanceOfNarrowingNez_art() throws IOException { MethodImplementationBuilder builder = new MethodImplementationBuilder(2); builder.addInstruction(new BuilderInstruction22c(Opcode.INSTANCE_OF, 0, 1, new ImmutableTypeReference("Lmain;"))); builder.addIns...
public boolean setRuleDescriptionContextKey(DefaultIssue issue, @Nullable String previousContextKey) { String currentContextKey = issue.getRuleDescriptionContextKey().orElse(null); issue.setRuleDescriptionContextKey(previousContextKey); if (!Objects.equals(currentContextKey, previousContextKey)) { iss...
@Test void setRuleDescriptionContextKey_dontSetContextKeyIfBothValuesAreNull() { issue.setRuleDescriptionContextKey(null); boolean updated = underTest.setRuleDescriptionContextKey(issue, null); assertThat(updated).isFalse(); assertThat(issue.getRuleDescriptionContextKey()).isEmpty(); }
protected RemotingCommand request(ChannelHandlerContext ctx, RemotingCommand request, ProxyContext context, long timeoutMillis) throws Exception { String brokerName; if (request.getCode() == RequestCode.SEND_MESSAGE_V2) { if (request.getExtFields().get(BROKER_NAME_FIELD_FOR_SEND_MESS...
@Test public void testRequestProxyException() throws Exception { ArgumentCaptor<RemotingCommand> captor = ArgumentCaptor.forClass(RemotingCommand.class); String brokerName = "broker"; String remark = "exception"; CompletableFuture<RemotingCommand> future = new CompletableFuture<>(); ...
public SelectorDO getSelector() { return (SelectorDO) getSource(); }
@Test void getSelector() { SelectorDO selector = selectorCreatedEvent.getSelector(); assertEquals(selectorDO, selector); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("sds.listing.chunksize")); }
@Test public void testList() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume...
@Override public RLock writeLock() { return new RedissonWriteLock(commandExecutor, getName()); }
@Test public void testWriteLock() throws InterruptedException { final RReadWriteLock lock = redisson.getReadWriteLock("lock"); final RLock writeLock = lock.writeLock(); writeLock.lock(); Assertions.assertTrue(lock.writeLock().tryLock()); Thread t = new Thread() { ...
@Override public TimeSeriesEntry<V, L> pollFirstEntry() { return get(pollFirstEntryAsync()); }
@Test public void testPollFirstEntry() { RTimeSeries<String, String> t = redisson.getTimeSeries("test"); t.add(1, "10", "100"); t.add(2, "20"); t.add(3, "30"); TimeSeriesEntry<String, String> e = t.pollFirstEntry(); assertThat(e).isEqualTo(new TimeSeriesEntry<>(1, "1...
@Override public void triggerOnIndexCreation() { try (DbSession dbSession = dbClient.openSession(false)) { // remove already existing indexing task, if any removeExistingIndexationTasks(dbSession); dbClient.branchDao().updateAllNeedIssueSync(dbSession); List<BranchDto> branchInNeedOfIss...
@Test public void remove_existing_indexation_task() { String reportTaskUuid = persistReportTasks(); CeQueueDto task = new CeQueueDto(); task.setUuid("uuid_2"); task.setTaskType(BRANCH_ISSUE_SYNC); dbClient.ceQueueDao().insert(dbTester.getSession(), task); CeActivityDto activityDto = new CeAct...
@ExecuteOn(TaskExecutors.IO) @Post(uri = "/{executionId}/eval/{taskRunId}", consumes = MediaType.TEXT_PLAIN) @Operation(tags = {"Executions"}, summary = "Evaluate a variable expression for this taskrun") public EvalResult eval( @Parameter(description = "The execution id") @PathVariable String execut...
@Test void eval() throws TimeoutException { Execution execution = runnerUtils.runOne(null, "io.kestra.tests", "each-sequential-nested"); ExecutionController.EvalResult result = this.eval(execution, "my simple string", 0); assertThat(result.getResult(), is("my simple string")); resu...
public ConcurrentNavigableMap<String, Object> toTreeMap(final String json) { return GSON_MAP.fromJson(json, new TypeToken<ConcurrentSkipListMap<String, Object>>() { }.getType()); }
@Test public void testToTreeMap() { Map<String, Object> map = ImmutableMap.of("id", 123L, "name", "test", "double", 1.0D, "boolean", true, "data", generateTestObject()); String json = "{\"name\":\"test\",\"id\":123,\"double\":1.0,\"boolean\":true,\"data\":" + EXPECTE...
public void putValue(String fieldName, @Nullable Object value) { _fieldToValueMap.put(fieldName, value); }
@Test public void testIntValuesEqual() { GenericRow first = new GenericRow(); first.putValue("one", 1); GenericRow second = new GenericRow(); second.putValue("one", 1); Assert.assertEquals(first, second); }
public static <T> CompletionStage<T> recover(CompletionStage<T> completionStage, Function<Throwable, T> exceptionHandler){ return completionStage.exceptionally(exceptionHandler); }
@Test public void shouldThrowRuntimeException() { RuntimeException exception = new RuntimeException("blub"); CompletableFuture<String> future = new CompletableFuture<>(); future.completeExceptionally(exception); assertThatThrownBy(() -> recover(future, TimeoutException.class, (e) -...
public List<Protocol> find() { return this.find(Protocol::isEnabled); }
@Test public void testGetProtocols() { final TestProtocol defaultProtocol = new TestProtocol(Scheme.ftp); final TestProtocol providerProtocol = new TestProtocol(Scheme.ftp) { @Override public String getProvider() { return "c"; } }; ...
@Bean public PluginDataHandler rewritePluginDataHandler() { return new RewritePluginDataHandler(); }
@Test public void testRewritePluginDataHandler() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RewritePluginConfiguration.class)) .withBean(RewritePluginConfigurationTest.class) .withPropertyValues("debug=true") .run(context -> { ...
private ExitStatus run() { try { init(); return new Processor().processNamespace().getExitStatus(); } catch (IllegalArgumentException e) { System.out.println(e + ". Exiting ..."); return ExitStatus.ILLEGAL_ARGUMENTS; } catch (IOException e) { System.out.println(e + ". Exiting...
@Test(timeout = 300000) public void testWithFederateClusterWithinSameNode() throws Exception { final Configuration conf = new HdfsConfiguration(); initConf(conf); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(4).storageTypes( new StorageType[] {StorageType.DI...
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (msg instanceof Http2DataFrame) { Http2DataFrame dataFrame = (Http2DataFrame) msg; encoder().writeData(ctx, dataFrame.stream().id(), dataFrame.content(), dataFrame.padd...
@Test public void unknownFrameTypeShouldThrowAndBeReleased() throws Exception { class UnknownHttp2Frame extends AbstractReferenceCounted implements Http2Frame { @Override public String name() { return "UNKNOWN"; } @Override protect...
@Override public Flux<String> getServices() { return Flux.defer(() -> Flux.fromIterable(getRegisterCenterService().getServices())) .onErrorResume(ex -> { LOGGER.error("Can not acquire services list", ex); return Flux.empty(); }).subscri...
@Test public void getServices() { final Flux<String> services = client.getServices(); final List<String> block = services.collectList().block(); Assert.assertNotNull(block); Assert.assertEquals(block.size(), SERVICES.size()); for (int i = 0; i < block.size(); i++) { ...
public static boolean isUnrecoverableError(Throwable cause) { Optional<Throwable> unrecoverableError = ThrowableClassifier.findThrowableOfThrowableType( cause, ThrowableType.NonRecoverableError); return unrecoverableError.isPresent(); }
@Test void testUnrecoverableErrorCheck() { // normal error assertThat(ExecutionFailureHandler.isUnrecoverableError(new Exception())).isFalse(); // direct unrecoverable error assertThat( ExecutionFailureHandler.isUnrecoverableError( ...
public static String truncateContent(String content) { if (content == null) { return ""; } else if (content.length() <= SHOW_CONTENT_SIZE) { return content; } else { return content.substring(0, SHOW_CONTENT_SIZE) + "..."; } }
@Test void testTruncateContent() { String content = "aa"; String actual = ContentUtils.truncateContent(content); assertEquals(content, actual); }
@Override public int getCanaryDistributionPolicy() { switch (_clusterInfoItem.getClusterPropertiesItem().getDistribution()) { case STABLE: return 0; case CANARY: return 1; default: return -1; } }
@Test(dataProvider = "getCanaryDistributionPoliciesTestData") public void testGetCanaryDistributionPolicy(CanaryDistributionProvider.Distribution distribution, int expectedValue) { ClusterInfoJmx clusterInfoJmx = new ClusterInfoJmx( new ClusterInfoItem(_mockedSimpleBalancerState, new ClusterProperties("...
@Override public boolean areEqual(Object one, Object another) { if (one == another) { return true; } if (one == null || another == null) { return false; } if (one instanceof String && another instanceof String) { return one.equals(another);...
@Test public void testAbstractClassImplementationsAreEqual() { JsonTypeDescriptor descriptor = new JsonTypeDescriptor(); FormImpl firstEntity = new FormImpl("value1"); FormImpl secondEntity = new FormImpl("value2"); assertTrue(descriptor.areEqual(firstEntity, secondEntity)); }
@Override public ProcessingResult process(ReplicationTask task) { try { EurekaHttpResponse<?> httpResponse = task.execute(); int statusCode = httpResponse.getStatusCode(); Object entity = httpResponse.getEntity(); if (logger.isDebugEnabled()) { ...
@Test public void testBatchableTaskListExecution() throws Exception { TestableInstanceReplicationTask task = aReplicationTask().build(); replicationClient.withBatchReply(200); replicationClient.withNetworkStatusCode(200); ProcessingResult status = replicationTaskProcessor.process(Co...
public static TerminateQuery query(final Optional<NodeLocation> location, final QueryId queryId) { return new TerminateQuery(location, Optional.of(queryId)); }
@SuppressWarnings("UnstableApiUsage") @Test public void shouldImplementHashCodeAndEqualsProperty() { new EqualsTester() .addEqualityGroup( // Note: At the moment location does not take part in equality testing TerminateQuery.query(Optional.of(SOME_LOCATION), SOME_QUERY_ID), ...
public static <T> ByFields<T> byFieldNames(String... fieldNames) { return ByFields.of(FieldAccessDescriptor.withFieldNames(fieldNames)); }
@Test @Category(NeedsRunner.class) public void testGroupByNestedKey() throws NoSuchSchemaException { PCollection<Row> grouped = pipeline .apply( Create.of( Outer.of(Basic.of("key1", 1L, "value1")), Outer.of(Basic.of("key1", 1L, "value2"...
@Operation(summary = "Receive app to app SAML AuthnRequest") @PostMapping(value = {"/frontchannel/saml/v4/entrance/request_authentication", "/frontchannel/saml/v4/idp/request_authentication"}, produces = "application/json", consumes = "application/x-www-form-urlencoded", params = "Type") @ResponseBody publi...
@Test public void requestAuthenticationEntranceApp() throws AdException, SamlSessionException, DienstencatalogusException, SharedServiceClientException, SamlValidationException, MessageDecodingException, ComponentInitializationException { Map<String, Object> authenticationParameters = new HashMap<>(); ...
public XAConnection xaConnection(XAConnection xaConnection) { return TracingXAConnection.create(xaConnection, this); }
@Test void xaConnection_wrapsInput() { assertThat(jmsTracing.xaConnection(mock(XAConnection.class))) .isInstanceOf(TracingXAConnection.class); }
public void scheduleUpdateIfAbsent(String serviceName, String groupName, String clusters) { if (!asyncQuerySubscribeService) { return; } String serviceKey = ServiceInfo.getKey(NamingUtils.getGroupedName(serviceName, groupName), clusters); if (futureMap.get(serviceKey) != null...
@Test void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientPro...
@Override public SchemaResult getKeySchema( final Optional<String> topicName, final Optional<Integer> schemaId, final FormatInfo expectedFormat, final SerdeFeatures serdeFeatures ) { return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, true); }
@Test public void shouldReturnSchemaFromGetKeySchemaIfFound() { // When: final SchemaResult result = supplier.getKeySchema(Optional.of(TOPIC_NAME), Optional.empty(), expectedFormat, SerdeFeatures.of(SerdeFeature.UNWRAP_SINGLES)); // Then: assertThat(result.schemaAndId, is(not(Optional.empty()...
@Override public boolean tryLock() { return get(tryLockAsync()); }
@Test public void testRedisFailed() { GenericContainer<?> redis = createRedis(); redis.start(); Config config = createConfig(redis); RedissonClient redisson = Redisson.create(config); Assertions.assertThrows(RedisException.class, () -> { RLock lock = redisson.g...
public RouteContext route(final ConnectionContext connectionContext, final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database) { SQLRouteExecutor executor = isNeedAllSchemas(queryContext.getSqlStatementContext().getSqlStatement()) ? new AllSQLRouteExecutor() ...
@Test void assertRouteFailure() { ConnectionContext connectionContext = mock(ConnectionContext.class); when(connectionContext.getCurrentDatabaseName()).thenReturn(Optional.of("logic_schema")); ShardingSphereMetaData metaData = mock(ShardingSphereMetaData.class); RuleMetaData ruleMeta...
@Override public Date getStartedAt() { return new Date(state.getStartedAt()); }
@Test public void test_startup_information() { long time = 123_456_789L; when(state.getStartedAt()).thenReturn(time); assertThat(underTest.getStartedAt().getTime()).isEqualTo(time); }
@Override public Comparable convert(Comparable value) { if (!(value instanceof CompositeValue)) { throw new IllegalArgumentException("Cannot convert [" + value + "] to composite"); } CompositeValue compositeValue = (CompositeValue) value; Comparable[] components = compos...
@Test public void testSpecialValuesArePreserved() { assertEquals(value(NULL), converter(INTEGER_CONVERTER).convert(value(NULL))); assertEquals(value(NEGATIVE_INFINITY), converter(INTEGER_CONVERTER).convert(value(NEGATIVE_INFINITY))); assertEquals(value(POSITIVE_INFINITY), converter(INTEGER_C...
public boolean isSecure() { if(getScheme().equalsIgnoreCase(HTTPS_PREFIX)) { return true; } return false; }
@Test void testIsSecure() { { URI uri = URI.create("http://example.yahoo.com/test"); HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1); DiscFilterRequest request = new DiscFilterRequest(httpReq); assertFalse(request.is...
@Override synchronized void setPartitionTime(final TopicPartition partition, final long partitionTime) { wrapped.setPartitionTime(partition, partitionTime); }
@Test public void testSetPartitionTime() { final TopicPartition partition = new TopicPartition("topic", 0); final long partitionTime = 12345678L; synchronizedPartitionGroup.setPartitionTime(partition, partitionTime); verify(wrapped, times(1)).setPartitionTime(partition, partitionTi...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertDate() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("date").dataType("date").build(); Column column = MySqlTypeConverter.DEFAULT_INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName()...
@Override public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) { Preconditions.checkNotNull(path, "Unable to create UnderFileSystem instance:" + " URI path should not be null"); if (checkOBSCredentials(conf)) { try { return OBSUnderFileSystem.createInstance(new ...
@Test public void createInstanceWithPath() { UnderFileSystem ufs = mFactory.create(mObsPath, mConf); Assert.assertNotNull(ufs); Assert.assertTrue(ufs instanceof OBSUnderFileSystem); }
public void lock(long lockedByPipelineId) { this.lockedByPipelineId = lockedByPipelineId; locked = true; }
@Test void shouldNotBeEqualToAnotherPipelineStateIfAllAttributesDoNotMatch() { PipelineState pipelineState1 = new PipelineState("p", new StageIdentifier("p", 1, "1", 1L, "s", "1")); PipelineState pipelineState2 = new PipelineState("p", new StageIdentifier("p", 1, "1", 1L, "s", "1")); pipelin...
public static ImmutableList<String> splitToLowercaseTerms(String identifierName) { if (ONLY_UNDERSCORES.matcher(identifierName).matches()) { // Degenerate case of names which contain only underscore return ImmutableList.of(identifierName); } return TERM_SPLITTER .splitToStream(identifier...
@Test public void splitToLowercaseTerms_separatesTerms_withLowerCamelCase() { String identifierName = "camelCaseTerm"; ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName); assertThat(terms).containsExactly("camel", "case", "term"); }
public final void isNotSameInstanceAs(@Nullable Object unexpected) { if (actual == unexpected) { /* * We use actualCustomStringRepresentation() because it might be overridden to be better than * actual.toString()/unexpected.toString(). */ failWithoutActual( fact("expected ...
@Test public void isNotSameInstanceAsWithDifferentTypesAndSameToString() { Object a = "true"; Object b = true; assertThat(a).isNotSameInstanceAs(b); }
public TopicList getTopicListFromNameServer(final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException { RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_TOPIC_LIST_FROM_NAMESERVER, null); RemotingCommand response = this.remoting...
@Test public void assertGetTopicListFromNameServer() throws RemotingException, InterruptedException, MQClientException { mockInvokeSync(); TopicList responseBody = new TopicList(); responseBody.setBrokerAddr(defaultBrokerAddr); responseBody.getTopicList().add(defaultTopic); s...
@Override public boolean acquireLock(List<RowLock> rowLock) { return false; }
@Test public void testAcquireLock() { LocalDBLocker locker = new LocalDBLocker(); List<RowLock> rowLocks = new ArrayList<>(); boolean result = locker.acquireLock(rowLocks); // Assert the result of the acquireLock method Assertions.assertFalse(result); }