focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static RedirectionAction buildFormPostContentAction(final WebContext context, final String content) { // is this an automatic form post generated by OpenSAML? if (content != null && content.contains("onload=\"document.forms[0].submit()\"")) { val url = StringEscapeUtils.unescapeHtml4(...
@Test public void testFormPostContentAction() { val action = HttpActionHelper.buildFormPostContentAction(MockWebContext.create(), VALUE); assertTrue(action instanceof OkAction); assertFalse(action instanceof AutomaticFormPostAction); assertEquals(VALUE, ((OkAction) action).getContent...
@Override public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException { if (1 == queryResults.size() && !isNeedAggregateRewri...
@Test void assertBuildGroupByMemoryMergedResultWithMySQLLimit() throws SQLException { final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "MySQL")); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_ST...
public static JibContainerBuilder toJibContainerBuilder( Path projectRoot, Path buildFilePath, Build buildCommandOptions, CommonCliOptions commonCliOptions, ConsoleLogger logger) throws InvalidImageReferenceException, IOException { BuildFileSpec buildFile = toBuildFileSpe...
@Test public void testToBuildFileSpec_withTemplating() throws URISyntaxException, InvalidImageReferenceException, IOException { Path buildfile = Paths.get(Resources.getResource("buildfiles/projects/templating/valid.yaml").toURI()); Mockito.when(buildCli.getTemplateParameters()) .thenRet...
static BayeuxClient createClient(final SalesforceComponent component, final SalesforceSession session) throws SalesforceException { // use default Jetty client from SalesforceComponent, it's shared by all consumers final SalesforceHttpClient httpClient = component.getConfig().getHttpClient()...
@Test public void shouldNotLoginWhenAccessTokenIsNullAndLazyLoginIsTrue() throws SalesforceException { final SalesforceHttpClient httpClient = mock(SalesforceHttpClient.class); httpClient.setTimeout(0L); final SalesforceEndpointConfig endpointConfig = new SalesforceEndpointConfig(); ...
@Subscribe public void handleUserDeletedEvent(UserDeletedEvent event) { final Set<GRN> grantees; try (final Stream<GrantDTO> grantStream = grantService.streamAll()) { grantees = grantStream .map(GrantDTO::grantee) .filter(grantee -> grantee.grnType...
@Test void userRemoved() { when(userService.streamAll()).thenReturn(Stream.of(userA)); when(grantService.streamAll()).thenReturn(Stream.of(grantUserA, grantUserB, grantTeam)); cleanupListener.handleUserDeletedEvent(mock(UserDeletedEvent.class)); verify(grantService).deleteForGrante...
@PostMapping("/verify") @Operation(summary = "Verify email address by user entering verificationcode") public DEmailVerifyResult verifyEmail(@RequestBody DEmailVerifyRequest deprecatedRequest) { validateVerificationCode(deprecatedRequest); AppSession appSession = validate(deprecatedRequest); ...
@Test public void validEmailVerify() { DEmailVerifyRequest request = new DEmailVerifyRequest(); request.setAppSessionId("id"); request.setVerificationCode("code"); EmailVerifyResult result = new EmailVerifyResult(); result.setStatus(Status.OK); result.setError("error...
public static Set<Set<LogicalVertex>> computePipelinedRegions( final Iterable<? extends LogicalVertex> topologicallySortedVertices) { final Map<LogicalVertex, Set<LogicalVertex>> vertexToRegion = PipelinedRegionComputeUtil.buildRawRegions( topologicallySorted...
@Test void testIsolatedVertices() { JobVertex v1 = new JobVertex("v1"); JobVertex v2 = new JobVertex("v2"); JobVertex v3 = new JobVertex("v3"); Set<Set<LogicalVertex>> regions = computePipelinedRegions(v1, v2, v3); checkRegionSize(regions, 3, 1, 1, 1); }
public Set<Cookie> decode(String header) { Set<Cookie> cookies = new TreeSet<Cookie>(); decode(cookies, header); return cookies; }
@Test public void testRejectCookieValueWithSemicolon() { Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode("name=\"foo;bar\";"); assertTrue(cookies.isEmpty()); }
public Set<ContentPackInstallation> loadAll() { try (final DBCursor<ContentPackInstallation> installations = dbCollection.find()) { return ImmutableSet.copyOf((Iterator<ContentPackInstallation>) installations); } }
@Test @MongoDBFixtures("ContentPackInstallationPersistenceServiceTest.json") public void loadAll() { final Set<ContentPackInstallation> contentPacks = persistenceService.loadAll(); assertThat(contentPacks).hasSize(4); }
public static BadRequestException namespaceNotExists() { return new BadRequestException("namespace not exist."); }
@Test public void testNamespaceNotExists() { BadRequestException namespaceNotExists = BadRequestException.namespaceNotExists(); assertEquals("namespace not exist.", namespaceNotExists.getMessage()); BadRequestException namespaceNotExists2 = BadRequestException.namespaceNotExists(appId, clusterName, names...
DateRange getRange(String dateRangeString) throws ParseException { if (dateRangeString == null || dateRangeString.isEmpty()) return null; String[] dateArr = dateRangeString.split("-"); if (dateArr.length > 2 || dateArr.length < 1) return null; // throw new Illega...
@Test public void testParseReverseDateRangeWithoutYear() throws ParseException { DateRange dateRange = dateRangeParser.getRange("Aug 14-Aug 10"); assertTrue(dateRange.isInRange(getCalendar(2014, Calendar.JANUARY, 9))); assertTrue(dateRange.isInRange(getCalendar(2014, Calendar.AUGUST, 9))); ...
@Override public <T> T get(String key, Class<T> type) { ClusterConfig config = findClusterConfig(key); if (config == null) { LOG.debug("Couldn't find cluster config of type {}", key); return null; } T result = extractPayload(config.payload(), type); ...
@Test public void getReturnsExistingConfig() throws Exception { DBObject dbObject = new BasicDBObjectBuilder() .add("type", CustomConfig.class.getCanonicalName()) .add("payload", Collections.singletonMap("text", "TEST")) .add("last_updated", TIME.toString()) ...
public ProcessingNodesState calculateProcessingState(TimeRange timeRange) { final DateTime updateThresholdTimestamp = clock.nowUTC().minus(updateThreshold.toMilliseconds()); try (DBCursor<ProcessingStatusDto> statusCursor = db.find(activeNodes(updateThresholdTimestamp))) { if (!statusCursor...
@Test @MongoDBFixtures("processing-status-all-nodes-up-to-date.json") public void processingStateAllNodesUpToDate() { when(clock.nowUTC()).thenReturn(DateTime.parse("2019-01-01T04:00:00.000Z")); when(updateThreshold.toMilliseconds()).thenReturn(Duration.hours(1).toMilliseconds()); TimeRa...
@Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> properties) throws Exception { AS400ConnectionPool connectionPool; if (properties.containsKey(CONNECTION_POOL)) { LOG.trace("AS400ConnectionPool instance specified in the URI - will look it up."...
@Test public void testCreateDatqSecuredEndpoint() throws Exception { Endpoint endpoint = component .createEndpoint( "jt400://user:password@host/qsys.lib/library.lib/queue.dtaq?connectionPool=#mockPool&secured=true"); assertNotNull(endpoint); assertTrue...
@Override public long getAndAdd(K key, long delta) { return complete(asyncCounterMap.getAndAdd(key, delta)); }
@Test public void testGetAndAdd() { atomicCounterMap.put(KEY1, VALUE1); Long beforeIncrement = atomicCounterMap.getAndAdd(KEY1, DELTA1); assertThat(beforeIncrement, is(VALUE1)); Long afterIncrement = atomicCounterMap.get(KEY1); assertThat(afterIncrement, is(VALUE1 + DELTA1));...
@Override public Map getAll(Set keys) { return null; }
@Test public void testGetAll() throws Exception { assertNull(NULL_QUERY_CACHE.getAll(null)); }
public void toPdf() throws IOException { try { document.open(); // il serait possible d'ouvrir la boîte de dialogue Imprimer de Adobe Reader // if (writer instanceof PdfWriter) { // ((PdfWriter) writer).addJavaScript("this.print(true);", false); // } pdfCoreReport.toPdf(); ...
@Test public void testToPdf() throws Exception { final Counter sqlCounter = new Counter("sql", "db.png"); // counterName doit être http, sql ou ejb pour que les libellés de graph soient trouvés dans les traductions final Counter counter = new Counter("http", "db.png", sqlCounter); final Counter errorCounter = ...
@Override public void checkClientTrusted( X509Certificate[] chain, String authType ) throws CertificateException { // Find and use the end entity as the selector for verification. final X509Certificate endEntityCert = CertificateUtils.identifyEndEntityCertificate( Arrays.asList( chain ) ); ...
@Test public void testInvalidChainExpiredTrustAnchor() throws Exception { // Setup fixture. // Execute system under test. assertThrows(CertificateException.class, () -> systemUnderTest.checkClientTrusted( expiredRootChain, "RSA" ) ); }
public static GetAllResourceTypeInfoResponse mergeResourceTypes( Collection<GetAllResourceTypeInfoResponse> responses) { GetAllResourceTypeInfoResponse resourceTypeInfoResponse = Records.newRecord(GetAllResourceTypeInfoResponse.class); Set<ResourceTypeInfo> resourceTypeInfoSet = new HashSet<>(); ...
@Test public void testMergeResourceTypes() { ResourceTypeInfo resourceTypeInfo1 = ResourceTypeInfo.newInstance("vcores"); ResourceTypeInfo resourceTypeInfo2 = ResourceTypeInfo.newInstance("gpu"); ResourceTypeInfo resourceTypeInfo3 = ResourceTypeInfo.newInstance("memory-mb"); List<ResourceTypeInfo> r...
public static boolean isBearerToken(final String authorizationHeader) { return StringUtils.hasText(authorizationHeader) && authorizationHeader.startsWith(TOKEN_PREFIX); }
@Test void testIsBearerToken_WithValidBearerToken() { // Given String authorizationHeader = "Bearer sampleAccessToken"; // When boolean result = Token.isBearerToken(authorizationHeader); // Then assertTrue(result); }
public static MetadataUpdate fromJson(String json) { return JsonUtil.parse(json, MetadataUpdateParser::fromJson); }
@Test public void testSetLocationFromJson() { String action = MetadataUpdateParser.SET_LOCATION; String location = "s3://bucket/warehouse/tbl_location"; String json = String.format("{\"action\":\"%s\",\"location\":\"%s\"}", action, location); MetadataUpdate expected = new MetadataUpdate.SetLocation(lo...
@Override public CompletableFuture<Acknowledge> submitFailedJob( JobID jobId, String jobName, Throwable exception) { final ArchivedExecutionGraph archivedExecutionGraph = ArchivedExecutionGraph.createSparseArchivedExecutionGraph( jobId, ...
@Test public void testRetrieveJobResultAfterSubmissionOfFailedJob() throws Exception { dispatcher = createAndStartDispatcher( heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(jobId)); final...
public static long freeSwapSpace() { return readLongAttribute("FreeSwapSpaceSize", -1L); }
@Test public void testFreeSwapSpace() { assertTrue(freeSwapSpace() >= -1); }
public Result waitForCondition(Config config, Supplier<Boolean>... conditionCheck) { return finishOrTimeout( config, conditionCheck, () -> jobIsDoneOrFinishing(config.project(), config.region(), config.jobId())); }
@Test public void testWaitForCondition() throws IOException { AtomicInteger callCount = new AtomicInteger(); int totalCalls = 3; Supplier<Boolean> checker = () -> callCount.incrementAndGet() >= totalCalls; when(client.getJobStatus(any(), any(), any())) .thenReturn(JobState.RUNNING) .th...
@Override public PageResult<MailLogDO> getMailLogPage(MailLogPageReqVO pageVO) { return mailLogMapper.selectPage(pageVO); }
@Test public void testGetMailLogPage() { // mock 数据 MailLogDO dbMailLog = randomPojo(MailLogDO.class, o -> { // 等会查询到 o.setUserId(1L); o.setUserType(UserTypeEnum.ADMIN.getValue()); o.setToMail("768@qq.com"); o.setAccountId(10L); o.setTemplateId(10...
@Override public String updateUserAvatar(Long id, InputStream avatarFile) { validateUserExists(id); // 存储文件 String avatar = fileApi.createFile(IoUtil.readBytes(avatarFile)); // 更新路径 AdminUserDO sysUserDO = new AdminUserDO(); sysUserDO.setId(id); sysUserDO.setA...
@Test public void testUpdateUserAvatar_success() throws Exception { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(); userMapper.insert(dbUser); // 准备参数 Long userId = dbUser.getId(); byte[] avatarFileBytes = randomBytes(10); ByteArrayInputStream avatarFile ...
public static ADLSLocationParts parseLocation(String location) { URI locationUri = URI.create(location); String[] authorityParts = locationUri.getAuthority().split("@"); if (authorityParts.length > 1) { return new ADLSLocationParts( locationUri.getScheme(), authorityParts[0], ...
@Test public void testContainerInAuthority() { String location = format( "abfs://%s@%s.dfs.core.windows.net/path/to/files", TEST_CONTAINER, TEST_STORAGE_ACCOUNT); ADLSLocationUtils.ADLSLocationParts parts = ADLSLocationUtils.parseLocation(location); assertThat(parts.conta...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldFindTwoSameArgs() { // Given: givenFunctions( function(EXPECTED, -1, STRING, STRING) ); // When: final KsqlScalarFunction fun = udfIndex .getFunction(ImmutableList.of(SqlArgument.of(SqlTypes.STRING), SqlArgument.of(SqlTypes.STRING))); // Then: asse...
public static String[] fastParseUri(String uri) { return doParseUri(uri, true); }
@Test public void testFastParse() { String[] out1 = CamelURIParser.fastParseUri("file:relative"); assertEquals("file", out1[0]); assertEquals("relative", out1[1]); assertNull(out1[2]); String[] out2 = CamelURIParser.fastParseUri("file://relative"); assertEquals(Camel...
public static String formatExpression(final Expression expression) { return formatExpression(expression, FormatOptions.of(s -> false)); }
@Test public void shouldFormatFunctionCountStar() { final FunctionCall functionCall = new FunctionCall(FunctionName.of("COUNT"), Collections.emptyList()); assertThat(ExpressionFormatter.formatExpression(functionCall), equalTo("COUNT(*)")); }
@Override public Statement getStatement() { checkState(); return statement; }
@Test void assertGetStatement() { assertThat(actualResultSet.getStatement(), is(statement)); }
public NamedClusterEmbedManager getNamedClusterEmbedManager( ) { return namedClusterEmbedManager; }
@Test public void testGetNamedClusterEmbedManager() { assertNull( meta.getNamedClusterEmbedManager() ); NamedClusterEmbedManager mockNamedClusterEmbedManager = mock( NamedClusterEmbedManager.class ); meta.namedClusterEmbedManager = mockNamedClusterEmbedManager; assertEquals( mockNamedClusterEmbedManag...
@ProtoFactory public static MediaType fromString(String tree) { if (tree == null || tree.isEmpty()) throw CONTAINER.missingMediaType(); Matcher matcher = TREE_PATTERN.matcher(tree); return parseSingleMediaType(tree, matcher, false); }
@Test(expected = EncodingException.class) public void testParsingMultipleSubType() { MediaType.fromString("application/json/on"); }
@Override public MaintenanceDomain decode(ObjectNode json, CodecContext context) { if (json == null || !json.isObject()) { return null; } JsonNode mdNode = json.get(MD); String mdName = nullIsIllegal(mdNode.get(MD_NAME), "mdName is required").asText(); String md...
@Test public void testDecodeMd4() throws IOException { String mdString = "{\"md\": { \"mdName\": \"\"," + "\"mdNameType\": \"NONE\"}}"; InputStream input = new ByteArrayInputStream( mdString.getBytes(StandardCharsets.UTF_8)); JsonNode cfg = mapper.readTree...
public static MapNameAndKeyPair parseMemcacheKey(String key) { key = URLDecoder.decode(key, StandardCharsets.UTF_8); String mapName = DEFAULT_MAP_NAME; int index = key.indexOf(':'); if (index != -1) { mapName = MAP_NAME_PREFIX + key.substring(0, index); key = key....
@Test public void withDefaultMap() { MapNameAndKeyPair mapNameKeyPair = MemcacheUtils.parseMemcacheKey("key"); assertEquals("hz_memcache_default", mapNameKeyPair.getMapName()); assertEquals("key", mapNameKeyPair.getKey()); }
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testReturnAbortedTransactionsInUncommittedMode() { buildFetcher(OffsetResetStrategy.EARLIEST, new ByteArrayDeserializer(), new ByteArrayDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_UNCOMMITTED); ByteBuffer buffer = ByteBuffer.allocate(1024); int cu...
@Override public void registerStore(final StateStore store, final StateRestoreCallback stateRestoreCallback, final CommitCallback commitCallback) { final String storeName = store.name(); // TODO (KAFKA-12887): we should not trigger user's ...
@Test public void shouldThrowOnFailureToWritePositionCheckpointFile() throws IOException { final ProcessorStateManager stateMgr = getStateManager(Task.TaskType.ACTIVE); final CommitCallback persistentCheckpoint = mock(CommitCallback.class); final IOException ioException = new IOException("as...
@Override public List<String> getServerList() { return serverList.isEmpty() ? serversFromEndpoint : serverList; }
@Test void testConstructWithEndpointWithEndpointPathAndName() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, "aaa"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CLUSTER_NAME, "bbb"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "...
@Override public void setMetadata(final Path file, final TransferStatus status) throws BackgroundException { try { final String fileid = this.fileid.getFileId(file); final File body = new File(); body.setProperties(status.getMetadata()); final File properties ...
@Test public void setMetadata() throws Exception { final Path home = DriveHomeFinderService.MYDRIVE_FOLDER; final Path test = new Path(home, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); final DriveFileIdProvider fileid = new DriveFileIdProvider(session); new DriveTouchF...
@Override public boolean next() throws SQLException { if (skipAll) { return false; } if (!paginationContext.getActualRowCount().isPresent()) { return getMergedResult().next(); } return rowNumber++ <= paginationContext.getActualRowCount().get() && getMe...
@Test void assertNextWithoutOffsetWithRowCount() throws SQLException { final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "SQLServer")); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); ...
@Override public Config build() { return build(new Config()); }
@Override @Test public void testQueryCacheFullConfig() { String yaml = """ hazelcast: map: test: query-caches: cache-name: entry-listeners: - class-na...
public static CommitReport fromJson(String json) { return JsonUtil.parse(json, CommitReportParser::fromJson); }
@Test public void missingFields() { assertThatThrownBy(() -> CommitReportParser.fromJson("{}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing string: table-name"); assertThatThrownBy(() -> CommitReportParser.fromJson("{\"table-name\":\"roundTripTableName\"}")...
public static void main(String[] args) { LOGGER.info("The alchemist begins his work."); var coin1 = CoinFactory.getCoin(CoinType.COPPER); var coin2 = CoinFactory.getCoin(CoinType.GOLD); LOGGER.info(coin1.getDescription()); LOGGER.info(coin2.getDescription()); }
@Test void shouldExecuteWithoutExceptions() { assertDoesNotThrow(() -> App.main(new String[]{})); }
static Map<String, String> resolveVariables(String expression, String str) { if (expression == null || str == null) return Collections.emptyMap(); Map<String, String> resolvedVariables = new HashMap<>(); StringBuilder variableBuilder = new StringBuilder(); State state = State.TEXT; int j ...
@Test public void testMalformedExpression2() { Map<String, String> res = resolveVariables("{counter }id}-", "whatever"); assertEquals(0, res.size()); }
@Override public void doGet( final HttpServletRequest req, final HttpServletResponse resp) throws IOException { // By default requests are persistent. We don't want long-lived connections // on server side. resp.addHeader("Connection", "close"); if (!isActive()) { // Report not SC_...
@Test public void testFailsOnInactive() throws IOException { servlet = new IsActiveServlet() { @Override protected boolean isActive() { return false; } }; doGet(); verify(resp, atLeastOnce()).sendError( eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), eq(IsActi...
public static String getUnresolvedSchemaName(final Schema schema) { if (!isUnresolvedSchema(schema)) { throw new IllegalArgumentException("Not a unresolved schema: " + schema); } return schema.getProp(UR_SCHEMA_ATTR); }
@Test(expected = IllegalArgumentException.class) public void testIsUnresolvedSchemaError3() { // Namespace not "org.apache.avro.compiler". Schema s = SchemaBuilder.record("UnresolvedSchema").prop("org.apache.avro.idl.unresolved.name", "x").fields() .endRecord(); SchemaResolver.getUnresolvedSchemaN...
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor( DoFn<InputT, OutputT> fn) { return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn); }
@Test public void testFinishBundleException() throws Exception { DoFnInvoker.ArgumentProvider<Integer, Integer> mockArguments = mock(DoFnInvoker.ArgumentProvider.class); when(mockArguments.finishBundleContext(any(DoFn.class))).thenReturn(null); DoFnInvoker<Integer, Integer> invoker = DoFnI...
@Override public void handleTenantMenu(TenantMenuHandler handler) { // 如果禁用,则不执行逻辑 if (isTenantDisable()) { return; } // 获得租户,然后获得菜单 TenantDO tenant = getTenant(TenantContextHolder.getRequiredTenantId()); Set<Long> menuIds; if (isSystemTenant(tenan...
@Test // 系统租户的情况 public void testHandleTenantMenu_system() { // 准备参数 TenantMenuHandler handler = mock(TenantMenuHandler.class); // mock 未禁用 when(tenantProperties.getEnable()).thenReturn(true); // mock 租户 TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setPackage...
public static <T> T[] toArray(Class<T> c, List<T> list) { @SuppressWarnings("unchecked") T[] ta= (T[])Array.newInstance(c, list.size()); for (int i= 0; i<list.size(); i++) ta[i]= list.get(i); return ta; }
@Test public void testWithEmptyList() { try { List<String> list = new ArrayList<String>(); String[] arr = GenericsUtil.toArray(list); fail("Empty array should throw exception"); System.out.println(arr); //use arr so that compiler will not complain }catch (IndexOutOfBoundsException ex)...
public int getHTTPFileArgCount() { return getHTTPFileArgsCollection().size(); }
@Test public void testConstructors() throws Exception { HTTPFileArgs files = new HTTPFileArgs(); assertEquals(0, files.getHTTPFileArgCount()); }
public static boolean isFloatingNumber(String text) { final int startPos = findStartPosition(text); if (startPos < 0) { return false; } boolean dots = false; for (int i = startPos; i < text.length(); i++) { char ch = text.charAt(i); if (!Chara...
@Test @DisplayName("Tests that isFloatingNumber returns true for empty, space or null") void isFloatingNumberEmpty() { assertFalse(ObjectHelper.isFloatingNumber("")); assertFalse(ObjectHelper.isFloatingNumber(" ")); assertFalse(ObjectHelper.isFloatingNumber(null)); }
@Override public boolean skip(final ServerWebExchange exchange) { return skipExcept(exchange, RpcTypeEnum.GRPC); }
@Test public void testSkip() { final boolean result = grpcPlugin.skip(getServerWebExchange()); assertFalse(result); }
@Override protected WritableByteChannel create(HadoopResourceId resourceId, CreateOptions createOptions) throws IOException { return Channels.newChannel( resourceId.toPath().getFileSystem(configuration).create(resourceId.toPath())); }
@Test public void testCreateAndReadFileWithShift() throws Exception { byte[] bytes = "testData".getBytes(StandardCharsets.UTF_8); create("testFile", bytes); int bytesToSkip = 3; byte[] expected = Arrays.copyOfRange(bytes, bytesToSkip, bytes.length); byte[] actual = read("testFile", bytesToSkip); ...
@Override public void setMonochrome(boolean monochrome) { formats = monochrome ? monochrome() : ansi(); }
@Test void should_print_tags() { Feature feature = TestFeatureParser.parse("path/test.feature", "" + "@feature_tag\n" + "Feature: feature name\n" + " @scenario_tag\n" + " Scenario: scenario name\n" + " Then first step\n" + ...
@Override public String get(String name) { checkKey(name); String value = null; String[] keyParts = splitKey(name); String ns = registry.getNamespaceURI(keyParts[0]); if (ns != null) { try { XMPProperty prop = xmpData.getProperty(ns, keyParts[1])...
@Test public void get_notExistingProp_null() throws TikaException { assertNull(xmpMeta.get(TikaCoreProperties.FORMAT)); }
public void shutdown() { shutdown(0); }
@Test public void testShutdown() { defaultMQPushConsumerImpl.setServiceState(ServiceState.RUNNING); defaultMQPushConsumerImpl.shutdown(); assertEquals(ServiceState.SHUTDOWN_ALREADY, defaultMQPushConsumerImpl.getServiceState()); }
public synchronized void addService(URL url) { // fixme, pass in application mode context during initialization of MetadataInfo. if (this.loader == null) { this.loader = url.getOrDefaultApplicationModel().getExtensionLoader(MetadataParamsFilter.class); } List<MetadataParamsFi...
@Test void testJdkSerialize() throws IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); MetadataI...
public String doLayout(ILoggingEvent event) { StringBuilder buf = new StringBuilder(); startNewTableIfLimitReached(buf); boolean odd = true; if (((counter++) & 1) == 0) { odd = false; } String level = event.getLevel().toString().toLowerCase(); buf.a...
@Test public void testDoLayout() throws Exception { ILoggingEvent le = createLoggingEvent(); String result = layout.getFileHeader(); result += layout.getPresentationHeader(); result += layout.doLayout(le); result += layout.getPresentationFooter(); result += layout.ge...
@Override public Timestamp getTimestamp(final int columnIndex) throws SQLException { return (Timestamp) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, Timestamp.class), Timestamp.class); }
@Test void assertGetTimestampWithColumnIndex() throws SQLException { when(mergeResultSet.getValue(1, Timestamp.class)).thenReturn(new Timestamp(0L)); assertThat(shardingSphereResultSet.getTimestamp(1), is(new Timestamp(0L))); }
static Map<String, Class<? extends PipelineRunner<?>>> getRegisteredRunners() { return CACHE.get().supportedPipelineRunners; }
@Test public void testAutomaticRegistrationOfRunners() { assertEquals( REGISTERED_RUNNER, PipelineOptionsFactory.getRegisteredRunners() .get(REGISTERED_RUNNER.getSimpleName().toLowerCase())); }
@Override public void onEvent(ApplicationEvent event) { // only onRequest is used }
@Test void onEvent_toleratesBadCustomizer() { setEventType(RequestEvent.Type.FINISHED); setBaseUri("/"); when(request.getProperty(SpanCustomizer.class.getName())).thenReturn("eyeballs"); listener.onEvent(requestEvent); verifyNoMoreInteractions(parser); }
@Bean public PluginDataHandler contextPathPluginDataHandler() { return new ContextPathPluginDataHandler(); }
@Test public void testContextPathPluginDataHandler() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ContextPathPluginConfiguration.class)) .withBean(ContextPathPluginConfigurationTest.class) .withPropertyValues("debug=true") .run(con...
public ClosableIterator<ActiveAction> getActiveActionsIterator() { return loadInstants(null); }
@Test void testReadLegacyArchivedTimeline() throws Exception { String tableName = "testTable"; String tablePath = tempFile.getAbsolutePath() + StoragePath.SEPARATOR + tableName; HoodieTableMetaClient metaClient = HoodieTestUtils.init( HoodieTestUtils.getDefaultStorageConf(), tablePath, HoodieTable...
@Override public void releaseFreeSlotsOnTaskManager(ResourceID taskManagerId, Exception cause) { assertHasBeenStarted(); if (isTaskManagerRegistered(taskManagerId)) { Collection<AllocationID> freeSlots = declarativeSlotPool.getFreeSlotTracker().getFreeSlotsInformatio...
@Test void testReleaseFreeSlotsOnTaskManager() throws Exception { try (DeclarativeSlotPoolService slotPoolService = createDeclarativeSlotPoolService()) { final LocalTaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation(); slotPoolService.registerTaskManager(taskManag...
public int deleteUnusedWorker() { int cnt = 0; try { WarehouseManager warehouseManager = GlobalStateMgr.getCurrentState().getWarehouseMgr(); Warehouse warehouse = warehouseManager.getBackgroundWarehouse(); long workerGroupId = warehouseManager.selectWorkerGroupByWareh...
@Test public void testDeleteUnusedWorker() throws Exception { new MockUp<SystemInfoService>() { @Mock public List<Backend> getBackends() { List<Backend> backends = new ArrayList<>(); Backend be1 = new Backend(10001, "host1", 1001); be1....
@Udf(description = "Adds a duration to a time") public Time timeAdd( @UdfParameter(description = "A unit of time, for example SECOND or HOUR") final TimeUnit unit, @UdfParameter(description = "An integer number of intervals to add") final Integer interval, @UdfParameter(description = "A TIME value."...
@Test public void handleNullTime() { assertNull(udf.timeAdd(TimeUnit.MILLISECONDS, -300, null)); }
@Override public boolean put(File localFile, JobID jobId, BlobKey blobKey) throws IOException { createBasePathIfNeeded(); String toBlobPath = BlobUtils.getStorageLocationPath(basePath, jobId, blobKey); try (FSDataOutputStream os = fileSystem.create(new Path(toBlobPath), FileS...
@Test void testSuccessfulPut() throws IOException { final Path temporaryFile = createTemporaryFileWithContent("put"); final JobID jobId = new JobID(); final BlobKey blobKey = createPermanentBlobKeyFromFile(temporaryFile); // Blob store operations are creating the base directory on-t...
public static <T> PTransform<PCollection<T>, PCollection<T>> exceptAll( PCollection<T> rightCollection) { checkNotNull(rightCollection, "rightCollection argument is null"); return new SetImpl<>(rightCollection, exceptAll()); }
@Test @Category(NeedsRunner.class) public void testExceptAll() { PAssert.that(first.apply("strings", Sets.exceptAll(second))) .containsInAnyOrder("a", "g", "g", "h", "h"); PCollection<Row> results = firstRows.apply("rows", Sets.exceptAll(secondRows)); PAssert.that(results).containsInAnyOrder(...
static void validateCsvFormat(CSVFormat format) { String[] header = checkArgumentNotNull(format.getHeader(), "Illegal %s: header is required", CSVFormat.class); checkArgument(header.length > 0, "Illegal %s: header cannot be empty", CSVFormat.class); checkArgument( !format.getAllowMissingCo...
@Test public void givenCSVFormatThatSkipsHeaderRecord_throwsException() { CSVFormat format = csvFormatWithHeader().withSkipHeaderRecord(true); String gotMessage = assertThrows( IllegalArgumentException.class, () -> CsvIOParseHelpers.validateCsvFormat(format)) .getMessage();...
public static int indexOfName( String[] databaseNames, String name ) { if ( databaseNames == null || name == null ) { return -1; } for ( int i = 0; i < databaseNames.length; i++ ) { String databaseName = databaseNames[ i ]; if ( name.equalsIgnoreCase( databaseName ) ) { return i; ...
@Test public void indexOfName_NonExactMatch() { assertEquals( 1, DatabaseMeta.indexOfName( new String[] { "a", "b", "c" }, "B" ) ); }
public void clear() { cacheMap.clear(); }
@Test public void testClear() { LruCache<String, SimpleValue> cache = new LruCache<String, SimpleValue>(2); String key1 = DEFAULT_KEY + 1; String key2 = DEFAULT_KEY + 2; SimpleValue value = new SimpleValue(true, true); cache.put(key1, value); cache.put(key2, value); assertEquals(value, ca...
@Nullable public Float getFloatValue(@FloatFormat final int formatType, @IntRange(from = 0) final int offset) { if ((offset + getTypeLen(formatType)) > size()) return null; switch (formatType) { case FORMAT_SFLOAT -> { if (mValue[offset + 1] == 0x07 && mValue[offset] == (byte) 0xFE) return F...
@Test public void setValue_FLOAT_negativeInfinity() { final MutableData data = new MutableData(new byte[4]); data.setValue(Float.NEGATIVE_INFINITY, Data.FORMAT_FLOAT, 0); final float value = data.getFloatValue(Data.FORMAT_FLOAT, 0); assertEquals(Float.NEGATIVE_INFINITY, value, 0.00); }
@Override public void asyncUpdateCursorInfo(String ledgerName, String cursorName, ManagedCursorInfo info, Stat stat, MetaStoreCallback<Void> callback) { if (log.isDebugEnabled()) { log.debug("[{}] [{}] Updating cursor info ledgerId={} mark-delete={}:{} lastActive={}", ...
@Test(timeOut = 20000) void updatingCursorNode() throws Exception { MetaStore store = new MetaStoreImpl(metadataStore, executor); metadataStore.put("/managed-ledgers/my_test", "".getBytes(), Optional.empty()).join(); final CompletableFuture<Void> promise = new CompletableFuture<>(); ...
public static String toJson(MetadataUpdate metadataUpdate) { return toJson(metadataUpdate, false); }
@Test public void testSetSnapshotRefTagToJsonDefault() { long snapshotId = 1L; SnapshotRefType type = SnapshotRefType.TAG; String refName = "hank"; Integer minSnapshotsToKeep = null; Long maxSnapshotAgeMs = null; Long maxRefAgeMs = null; String expected = "{\"action\":\"set-snapsho...
@Override public void set(K key, V value) { begin(); transactionalMap.set(key, value); commit(); }
@Test public void testSet() { adapter.set(23, "test"); assertEquals("test", map.get(23)); }
public int capacity() { return capacity; }
@Test void shouldCalculateCapacityForBuffer() { assertThat(broadcastTransmitter.capacity(), is(CAPACITY)); }
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR if (splittee == null || splitChar == null) { return new String[0]; } final String EMPTY_ELEMENT = ""; int spot; final int splitLength = splitChar.length(); final Stri...
@Test public void testSplitStringStringNullWithSingleDelimiter() { assertThat(JOrphanUtils.split("a,bc,,", ",", null), CoreMatchers.equalTo(new String[]{"a", "bc"})); }
public void clean(final Date now) { List<String> files = this.findFiles(); List<String> expiredFiles = this.filterFiles(files, this.createExpiredFileFilter(now)); for (String f : expiredFiles) { this.delete(new File(f)); } if (this.totalSizeCap != CoreConstants.UNBOUNDED_TOTAL_SIZE_CAP && thi...
@Test public void removesParentDirWhenEmpty() throws IOException { File[] emptyDirs = new File[] { tmpDir.newFolder("empty_2018", "08"), tmpDir.newFolder("empty_2018", "12"), tmpDir.newFolder("empty_2019", "01"), }; for (File d : emptyDirs) { d.deleteOnExit(); } remover = ...
public static Set<String> computeStepIdsInRuntimeDag( @NotNull WorkflowInstance instance, @NotNull Set<String> knownStepIds) { if (instance.isFreshRun() || instance.getRunConfig() == null || instance.getRunConfig().getPolicy() != RunPolicy.RESTART_FROM_SPECIFIC) { return instance.getRunt...
@Test public void testComputeStepIdsInRuntimeDagForStepRestartAnotherPath() { WorkflowInstance instance = new WorkflowInstance(); instance.setRunConfig(new RunConfig()); instance.getRunConfig().setPolicy(RunPolicy.RESTART_FROM_SPECIFIC); instance .getRunConfig() .setRestartConfig( ...
@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 hasAGaugeForEachThreadState() { assertThat(((Gauge<?>) gauges.getMetrics().get("new.count")).getValue()) .isEqualTo(1); assertThat(((Gauge<?>) gauges.getMetrics().get("runnable.count")).getValue()) .isEqualTo(1); assertThat(((Gauge<?>) gauges.getMe...
@SuppressWarnings({"rawtypes", "unchecked"}) @Override public Object getValue(final int columnIndex, final Class<?> type) throws SQLException { Optional<ColumnProjection> columnProjection = selectStatementContext.getProjectionsContext().findColumnProjection(columnIndex); if (!columnProjection.is...
@Test void assertGetValueWithoutColumnProjection() throws SQLException { when(mergedResult.getValue(1, String.class)).thenReturn("VALUE"); MaskRule maskRule = mock(MaskRule.class); assertThat(new MaskMergedResult(maskRule, mockSelectStatementContextWithoutColumnProjection(), mergedResult).ge...
@Override public void update(Collection<Route> routes) { log.debug("Received update {}", routes); routeStore.updateRoutes(routes); }
@Test public void testAsyncRouteAdd() { Route route = new Route(Route.Source.STATIC, V4_PREFIX1, V4_NEXT_HOP1); // 2nd route for the same nexthop Route route2 = new Route(Route.Source.STATIC, V4_PREFIX2, V4_NEXT_HOP2); // 3rd route with no valid nexthop Route route3 = new Rou...
public static String toString(Throwable e) { StackTraceElement[] traces = e.getStackTrace(); StringBuilder sb = new StringBuilder(1024); sb.append(e.toString()).append("\n"); if (traces != null) { for (StackTraceElement trace : traces) { sb.append("\tat ").app...
@Test public void testToString() throws Exception { SofaRpcException exception = new SofaRpcException(RpcErrorType.SERVER_BUSY, "111"); String string = ExceptionUtils.toString(exception); Assert.assertNotNull(string); Pattern pattern = Pattern.compile("at"); Matcher matcher =...
static StringBuilder escapeChar(char c, StringBuilder sb) { sb.append('%'); if (c < 16) { sb.append('0'); } sb.append(Integer.toHexString(c).toUpperCase()); return sb; }
@Test void testEscapeChar() { for (char c = 0; c <= 128; c++) { String expected = "%" + String.format("%1$02X", (int) c); String actual = PartitionPathUtils.escapeChar(c, new StringBuilder()).toString(); assertThat(actual).isEqualTo(expected); } }
public static boolean isS3FileSystem(HdfsContext context, HdfsEnvironment hdfsEnvironment, Path path) { try { return getRawFileSystem(hdfsEnvironment.getFileSystem(context, path)) instanceof PrestoS3FileSystem; } catch (IOException e) { throw new PrestoException(HIVE_...
@Test public void testIsS3FileSystem() { HdfsEnvironment hdfsEnvironment = createTestHdfsEnvironment(new HiveClientConfig(), new MetastoreClientConfig()); assertTrue(isS3FileSystem(CONTEXT, hdfsEnvironment, new Path("s3://test-bucket/test-folder"))); assertFalse(isS3FileSystem(CONTEXT, h...
@Override public <VR> KTable<K, VR> transformValues(final ValueTransformerWithKeySupplier<? super K, ? super V, ? extends VR> transformerSupplier, final String... stateStoreNames) { return doTransformValues(transformerSupplier, null, NamedInternal.empty(), state...
@Test public void shouldThrowNullPointerOnTransformValuesWithKeyWhenTransformerSupplierIsNull() { assertThrows(NullPointerException.class, () -> table.transformValues(null)); }
@Nullable protected V get(K key) { if (key == null) return null; Object[] state = state(); int i = indexOfExistingKey(state, key); return i != -1 ? (V) state[i + 1] : null; }
@Test void get_null_if_not_set() { assertThat(extra.get("1")).isNull(); }
public static Object project(Schema source, Object record, Schema target) throws SchemaProjectorException { checkMaybeCompatible(source, target); if (source.isOptional() && !target.isOptional()) { if (target.defaultValue() != null) { if (record != null) { ...
@Test public void testStructAddField() { Schema source = SchemaBuilder.struct() .field("field", Schema.INT32_SCHEMA) .build(); Struct sourceStruct = new Struct(source); sourceStruct.put("field", 1); Schema target = SchemaBuilder.struct() ...
public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) { return index(keyFunction, Function.identity()); }
@Test public void index_returns_ListMultimap() { ListMultimap<Integer, MyObj> multimap = LIST.stream().collect(index(MyObj::getId)); assertThat(multimap.size()).isEqualTo(3); Map<Integer, Collection<MyObj>> map = multimap.asMap(); assertThat(map.get(1)).containsOnly(MY_OBJ_1_A); assertThat(map.ge...
@Udf(description = "Returns the inverse (arc) tangent of an INT value") public Double atan( @UdfParameter( value = "value", description = "The value to get the inverse tangent of." ) final Integer value ) { return atan(value == null ? null : value.doubleVa...
@Test public void shouldHandleZero() { assertThat(udf.atan(0.0), closeTo(0.0, 0.000000000000001)); assertThat(udf.atan(0), closeTo(0.0, 0.000000000000001)); assertThat(udf.atan(0L), closeTo(0.0, 0.000000000000001)); }
@Override public List<PartitionGroupMetadata> computePartitionGroupMetadata(String clientId, StreamConfig streamConfig, List<PartitionGroupConsumptionStatus> partitionGroupConsumptionStatuses, int timeoutMillis) throws IOException, TimeoutException { List<PartitionGroupMetadata> newPartitionGroupMeta...
@Test public void getPartitionsGroupInfoChildShardsest() throws Exception { List<PartitionGroupConsumptionStatus> currentPartitionGroupMeta = new ArrayList<>(); Map<String, String> shardToSequenceMap = new HashMap<>(); shardToSequenceMap.put("1", "1"); KinesisPartitionGroupOffset kinesisPartiti...
public void add(Boolean bool) { elements.add(bool == null ? JsonNull.INSTANCE : new JsonPrimitive(bool)); }
@Test public void testIntegerPrimitiveAddition() { JsonArray jsonArray = new JsonArray(); int x = 1; jsonArray.add(x); x = 2; jsonArray.add(x); x = -3; jsonArray.add(x); jsonArray.add((Integer) null); x = 4; jsonArray.add(x); x = 0; jsonArray.add(x); assertTh...
@Override @SuppressWarnings("rawtypes") public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String,...
@Test public void reportsCounterValues() throws Exception { final Counter counter = mock(Counter.class); when(counter.getCount()).thenReturn(100L); reporter.report(map(), map("test.counter", counter), map(), map(), map()); ...
@Override public BackgroundException map(final AmazonClientException e) { final StringBuilder buffer = new StringBuilder(); if(e instanceof AmazonServiceException) { final AmazonServiceException failure = (AmazonServiceException) e; this.append(buffer, failure.getErrorMessage...
@Test public void testAccessFailure() { final AmazonServiceException f = new AmazonServiceException("message", null); f.setStatusCode(403); f.setErrorCode("AccessDenied"); assertTrue(new AmazonServiceExceptionMappingService().map(f) instanceof AccessDeniedException); f.setErr...
public NettyPoolKey setTransactionRole(TransactionRole transactionRole) { this.transactionRole = transactionRole; return this; }
@Test public void setTransactionRole() { nettyPoolKey.setTransactionRole(TM_ROLE); Assertions.assertEquals(nettyPoolKey.getTransactionRole(), TM_ROLE); }
public Optional<UserDto> authenticate(HttpRequest request) { return extractCredentialsFromHeader(request) .flatMap(credentials -> Optional.ofNullable(authenticate(credentials, request))); }
@Test public void authenticate_from_basic_http_header() { when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn("Basic " + CREDENTIALS_IN_BASE64); Credentials credentials = new Credentials(A_LOGIN, A_PASSWORD); when(credentialsAuthentication.authenticate(credentials, request, BASIC)).thenReturn(USER); ...
public <T> void resolve(T resolvable) { ParamResolver resolver = this; if (ParamScope.class.isAssignableFrom(resolvable.getClass())) { ParamScope newScope = (ParamScope) resolvable; resolver = newScope.applyOver(resolver); } resolveStringLeaves(resolvable, resolve...
@Test public void shouldAddResolutionErrorOnViewIfP4MaterialViewHasAnError() { P4MaterialViewConfig p4MaterialViewConfig = new P4MaterialViewConfig("#"); new ParamResolver(new ParamSubstitutionHandlerFactory(params(param("foo", "pavan"), param("bar", "jj"))), fieldCache).resolve(p4MaterialViewConfi...
public static Object transform(Object root, DataIterator it, Transform<Object,Object> transform) { DataElement element; // don't transform in place because iterator behavior with replacements (which behave like a remove and an add) while iterating is undefined ArrayList<ToTransform> transformList = new A...
@Test public void testTransformByPredicateAtPath() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.pathMatchesPattern("foo", Wildcard.ANY_ONE, "id")) .transform(plusTenTransfor...
@Override public Processor<K, Change<V>, KO, SubscriptionWrapper<K>> get() { return new UnbindChangeProcessor(); }
@Test public void leftJoinShouldPropagateChangeFromNullFKToNullFKValue() { final MockInternalNewProcessorContext<String, SubscriptionWrapper<String>> context = new MockInternalNewProcessorContext<>(); leftJoinProcessor.init(context); context.setRecordMetadata("topic", 0, 0); final L...
@Override View removeView(String name) { return (View) storage().remove(name); }
@Test public void when_removeAbsentValue_then_returnsNull() { assertThat(storage.removeView("non-existing")).isNull(); }