focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public V remove(K key) { return cache.getAndRemove(key); }
@Test public void testRemove() { cache.put(23, "value-23"); assertTrue(cache.containsKey(23)); assertEquals("value-23", adapter.remove(23)); assertFalse(cache.containsKey(23)); }
@Override public void acknowledgeAllRecordsProcessed(RemoteInputChannel inputChannel) { sendToChannel(new AcknowledgeAllRecordsProcessedMessage(inputChannel)); }
@TestTemplate void testAcknowledgeAllRecordsProcessed() throws Exception { CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); EmbeddedChannel channel = new EmbeddedChannel(handler); PartitionRequestClient client = ...
private int refreshClusterMaxPriority(String subClusterId) throws IOException, YarnException { // Refresh cluster max priority ResourceManagerAdministrationProtocol adminProtocol = createAdminProtocol(); RefreshClusterMaxPriorityRequest request = recordFactory.newRecordInstance(RefreshClusterMaxPrio...
@Test public void testRefreshClusterMaxPriority() throws Exception { String[] args = { "-refreshClusterMaxPriority" }; assertEquals(0, rmAdminCLI.run(args)); verify(admin).refreshClusterMaxPriority( any(RefreshClusterMaxPriorityRequest.class)); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void editMessageLiveLocation() { BaseResponse response = bot.execute(new EditMessageLiveLocation(chatId, 10009, 21, 105) .replyMarkup(new InlineKeyboardMarkup())); if (!response.isOk()) { assertEquals(400, response.errorCode()); assertEquals("Bad ...
@Override public boolean isSearchable(final int column) { Preconditions.checkArgument(1 == column); return false; }
@Test void assertIsSearchable() throws SQLException { assertFalse(actualMetaData.isSearchable(1)); }
public static CreateSourceProperties from(final Map<String, Literal> literals) { try { return new CreateSourceProperties(literals, DurationParser::parse, false); } catch (final ConfigException e) { final String message = e.getMessage().replace( "configuration", "property" )...
@Test public void shouldThrowOnHoppingWindowWithOutSize() { // When: final Exception e = assertThrows( KsqlException.class, () -> CreateSourceProperties.from( ImmutableMap.<String, Literal>builder() .putAll(MINIMUM_VALID_PROPS) .put(WINDOW_TYPE_PROPE...
public List<String> searchTags(@Nullable String textQuery, int page, int size) { int maxPageSize = 100; int maxPage = 20; checkArgument(size <= maxPageSize, "Page size must be lower than or equals to " + maxPageSize); checkArgument(page > 0 && page <= maxPage, "Page must be between 0 and " + maxPage); ...
@Test public void search_tags_follows_paging() { index( newDoc().setTags(newArrayList("finance", "offshore", "java")), newDoc().setTags(newArrayList("official", "javascript")), newDoc().setTags(newArrayList("marketing", "official")), newDoc().setTags(newArrayList("marketing", "Madhoff")), ...
public Node parse() throws ScanException { if (tokenList == null || tokenList.isEmpty()) return null; return E(); }
@Test public void literalWithAccolade0() throws ScanException { Tokenizer tokenizer = new Tokenizer("{}"); Parser parser = new Parser(tokenizer.tokenize()); Node node = parser.parse(); Node witness = new Node(Node.Type.LITERAL, "{"); witness.next = new Node(Node.Type.LITERAL,...
@Override public long extractWatermark(IcebergSourceSplit split) { return split.task().files().stream() .map( scanTask -> { Preconditions.checkArgument( scanTask.file().lowerBounds() != null && scanTask.file().lowerBounds().get(eventTimeFie...
@TestTemplate public void testTimeUnit() throws IOException { assumeThat(columnName).isEqualTo("long_column"); ColumnStatsWatermarkExtractor extractor = new ColumnStatsWatermarkExtractor(SCHEMA, columnName, TimeUnit.MICROSECONDS); assertThat(extractor.extractWatermark(split(0))) .isEqualT...
@Override protected ExecuteContext doBefore(ExecuteContext context) throws Exception { LogUtils.printHttpRequestBeforePoint(context); final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class); Request request = (Request) context.getArguments()[0]; ...
@Test public void testFeignInvokeInterceptor() throws Exception { ExecuteContext context = ExecuteContext.forMemberMethod(new Object(), null, arguments, null, null); Request request = createRequest(HttpMethod.GET, url); arguments[0] = request; // No domain name is configured in the ...
@Override public <R> R eval(Mode mode, String luaScript, ReturnType returnType) { return eval(mode, luaScript, returnType, Collections.emptyList()); }
@Test public void testMulti() { RLexSortedSet idx2 = redisson.getLexSortedSet("ABCD17436"); Long l = Long.valueOf("1506524856000"); for (int i = 0; i < 100; i++) { String s = "DENY" + "\t" + "TESTREDISSON" + "\t" + Long.valueOf(l) + "\t" + "helloworld...
public void createTableLike(CreateTableLikeStmt stmt) throws DdlException { String catalogName = stmt.getCatalogName(); Optional<ConnectorMetadata> connectorMetadata = getOptionalMetadata(catalogName); if (connectorMetadata.isPresent()) { String dbName = stmt.getDbName(); ...
@Test public void testHiveCreateTableLike() throws Exception { class MockedHiveMetadataMgr extends MockedMetadataMgr { public MockedHiveMetadataMgr(LocalMetastore localMetastore, ConnectorMgr connectorMgr) { super(localMetastore, connectorMgr); } @Overri...
@Override public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility( TypeSerializerSnapshot<T> oldSerializerSnapshot) { if (!(oldSerializerSnapshot instanceof AvroSerializerSnapshot)) { return TypeSerializerSchemaCompatibility.incompatible(); } AvroSerial...
@Test void restorePastSnapshots() throws IOException { for (int pastVersion : PAST_VERSIONS) { AvroSerializer<GenericRecord> currentSerializer = new AvroSerializer<>(GenericRecord.class, Address.getClassSchema()); DataInputView in = new DataIn...
public Path parse(final String uri) throws HostParserException { final Host host = new HostParser(factory).get(uri); if(StringUtils.isBlank(host.getDefaultPath())) { return new Path(String.valueOf(Path.DELIMITER), EnumSet.of((Path.Type.directory))); } switch(new ContainerPath...
@Test public void testParseProfile() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new SwiftProtocol()))); final ProfilePlistReader reader = new ProfilePlistReader(factory); final Profile profile = reader.read( this.get...
public Optional<Object> getLiteralValue(final int index) { ExpressionSegment valueExpression = valueExpressions.get(index); if (valueExpression instanceof ParameterMarkerExpressionSegment) { return Optional.ofNullable(parameters.get(getParameterIndex((ParameterMarkerExpressionSegment) valueE...
@Test void assertGetLiteralValueWhenParameterIsNull() { Collection<ExpressionSegment> assignments = makeParameterMarkerExpressionSegment(); int parametersOffset = 0; InsertValueContext insertValueContext = new InsertValueContext(assignments, Collections.singletonList(null), parametersOffset)...
protected Stream<DTO> streamQueryWithSort(Bson query, Bson sort) { final DBCursor<DTO> cursor = db.find(query).sort(sort); return Streams.stream((Iterable<DTO>) cursor).onClose(cursor::close); }
@Test public void streamQueryWithSort() { dbService.save(newDto("hello1")); dbService.save(newDto("hello2")); dbService.save(newDto("hello3")); dbService.save(newDto("hello4")); dbService.save(newDto("hello5")); final DBQuery.Query query = DBQuery.in("title", "hello5...
@Override public void onPartitionsAssigned(final Collection<TopicPartition> partitions) { // NB: all task management is already handled by: // org.apache.kafka.streams.processor.internals.StreamsPartitionAssignor.onAssignment if (assignmentErrorCode.get() == AssignorError.INCOMPLETE_SOURCE_T...
@Test public void shouldThrowTaskAssignmentException() { assignmentErrorCode.set(AssignorError.ASSIGNMENT_ERROR.code()); final TaskAssignmentException exception = assertThrows( TaskAssignmentException.class, () -> streamsRebalanceListener.onPartitionsAssigned(Collections.emp...
@Override public boolean tryClaim(Long i) { checkArgument( lastAttemptedOffset == null || i > lastAttemptedOffset, "Trying to claim offset %s while last attempted was %s", i, lastAttemptedOffset); checkArgument( i >= range.getFrom(), "Trying to claim offset %s before st...
@Test public void testTryClaim() throws Exception { OffsetRange range = new OffsetRange(100, 200); OffsetRangeTracker tracker = new OffsetRangeTracker(range); assertEquals(range, tracker.currentRestriction()); assertTrue(tracker.tryClaim(100L)); assertTrue(tracker.tryClaim(150L)); assertTrue(t...
public static double conversion(String expression) { return (new Calculator()).calculate(expression); }
@Test public void issue2964Test() { // https://github.com/dromara/hutool/issues/2964 final double calcValue = Calculator.conversion("(11+2)12"); assertEquals(156D, calcValue, 0.001); }
@Nullable static ProxyProvider createFrom(Properties properties) { Objects.requireNonNull(properties, "properties"); if (properties.containsKey(HTTP_PROXY_HOST) || properties.containsKey(HTTPS_PROXY_HOST)) { return createHttpProxyFrom(properties); } if (properties.containsKey(SOCKS_PROXY_HOST)) { return...
@Test void proxyFromSystemProperties_errorWhenHttpsPortIsEmptyString() { Properties properties = new Properties(); properties.setProperty(ProxyProvider.HTTPS_PROXY_HOST, "host"); properties.setProperty(ProxyProvider.HTTPS_PROXY_PORT, ""); assertThatIllegalArgumentException() .isThrownBy(() -> ProxyProvide...
@Override public IntStream intStream() { return IntStream.range(0, size); }
@Test public void intStream() throws Exception { IntSet rs = new RangeSet(5); assertEquals(10, rs.intStream().sum()); }
@Override public BranchRegisterResponseProto convert2Proto(BranchRegisterResponse branchRegisterResponse) { final short typeCode = branchRegisterResponse.getTypeCode(); final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType( MessageTypeProto.forNum...
@Test public void convert2Proto() { BranchRegisterResponse branchRegisterResponse = new BranchRegisterResponse(); branchRegisterResponse.setTransactionExceptionCode(TransactionExceptionCode.GlobalTransactionNotActive); branchRegisterResponse.setResultCode(ResultCode.Failed); branchR...
@Override synchronized public void close() { if (stream != null) { IOUtils.cleanupWithLogger(LOG, stream); stream = null; } }
@Test(timeout=120000) public void testRandomInt() throws Exception { OsSecureRandom random = getOsSecureRandom(); int rand1 = random.nextInt(); int rand2 = random.nextInt(); while (rand1 == rand2) { rand2 = random.nextInt(); } random.close(); }
@Override public SymbolTable getSymbolTable(String symbolTableName) { try { SymbolTableMetadata metadata = _symbolTableNameHandler.extractMetadata(symbolTableName); String serverNodeUri = metadata.getServerNodeUri(); String tableName = metadata.getSymbolTableName(); boolean isRemote ...
@Test public void testGetRemoteSymbolTableFetchSuccess() throws IOException { RestResponseBuilder builder = new RestResponseBuilder(); builder.setStatus(200); SymbolTable symbolTable = new InMemorySymbolTable("https://OtherHost:100/service|Test--332004310", Collections.unmodifiableList(Arrays.as...
@SuppressWarnings("checkstyle:NestedIfDepth") @Nullable public PartitioningStrategy getPartitioningStrategy( String mapName, PartitioningStrategyConfig config, final List<PartitioningAttributeConfig> attributeConfigs ) { if (attributeConfigs != null && !attributeC...
@Test public void whenStrategyForMapAlreadyDefined_getPartitioningStrategy_returnsSameInstance() { PartitioningStrategyConfig cfg = new PartitioningStrategyConfig(); cfg.setPartitioningStrategyClass("com.hazelcast.partition.strategy.StringPartitioningStrategy"); // when we have already obtai...
@Override public GetNodesToAttributesResponse getNodesToAttributes( GetNodesToAttributesRequest request) throws YarnException, IOException { if (request == null || request.getHostNames() == null) { routerMetrics.incrGetNodesToAttributesFailedRetrieved(); String msg = "Missing getNodesToAttribute...
@Test public void testNodesToAttributes() throws Exception { LOG.info("Test FederationClientInterceptor : Get NodesToAttributes request."); // null request LambdaTestUtils.intercept(YarnException.class, "Missing getNodesToAttributes request or hostNames.", () -> interceptor.getNodesToAttr...
@Override public boolean equals( Object obj ) { if ( !( obj instanceof TransMeta ) ) { return false; } return compare( this, (TransMeta) obj ) == 0; }
@Test public void testEquals() { TransMeta transMeta = new TransMeta( "1", "2" ); assertNotEquals( "somethingelse", transMeta ); assertEquals( transMeta, new TransMeta( "1", "2" ) ); }
protected void commitTransaction(final Map<TopicPartition, OffsetAndMetadata> offsets, final ConsumerGroupMetadata consumerGroupMetadata) { if (!eosEnabled()) { throw new IllegalStateException(formatException("Exactly-once is not enabled")); } may...
@Test public void shouldThrowStreamsExceptionOnEosCommitTxError() { eosAlphaMockProducer.commitTransactionException = new KafkaException("KABOOM!"); final StreamsException thrown = assertThrows( StreamsException.class, () -> eosAlphaStreamsProducer.commitTransaction(offsetsA...
@Override public ParsedSchema fromConnectSchema(final Schema schema) { // Bug in ProtobufData means `fromConnectSchema` throws on the second invocation if using // default naming. return new ProtobufData(new ProtobufDataConfig(updatedConfigs)) .fromConnectSchema(injectSchemaFullName(schema)); }
@Test public void shouldApplyNullableAsWrapper() { // Given: givenNullableAsWrapper(); // When: final ParsedSchema schema = schemaTranslator.fromConnectSchema(CONNECT_SCHEMA_WITH_NULLABLE_PRIMITIVES); // Then: assertThat(schema.canonicalString(), is("syntax = \"proto3\";\n" + "\n" ...
@Override protected Object getTargetObject(boolean key) { Object targetObject; if (key) { // keyData is never null if (keyData.isPortable() || keyData.isJson() || keyData.isCompact()) { targetObject = keyData; } else { targetObject ...
@Test public void testGetTargetObject_givenValueIsData_whenKeyFlagIsFalse_thenReturnValueObject() { Data key = serializationService.toData("key"); Data value = serializationService.toData("value"); QueryableEntry entry = createEntry(key, value, newExtractor()); Object targetObject =...
@Override public SqlGatewayEndpoint createSqlGatewayEndpoint(Context context) { SqlGatewayEndpointFactoryUtils.EndpointFactoryHelper helper = SqlGatewayEndpointFactoryUtils.createEndpointFactoryHelper(this, context); ReadableConfig configuration = helper.getOptions(); validat...
@Test public void testCreateHiveServer2Endpoint() throws Exception { assertThat( SqlGatewayEndpointFactoryUtils.createSqlGatewayEndpoint( service, Configuration.fromMap(getDefaultConfig()))) .isEqualTo( Collectio...
@SuppressWarnings("unchecked") @Override public void sendMessage(final P message) { try { if (message == null) { delegate().sendMessage(null); return; } String jsonFormat = JsonFormat.printer().includingDefaultValueFields().preservingP...
@Test public void sentMsgTest() { testJsonForwardingServerCall.sendMessage(new TestResponse("test-response")); }
public void decode(ByteBuf buffer) { boolean last; int statusCode; while (true) { switch(state) { case READ_COMMON_HEADER: if (buffer.readableBytes() < SPDY_HEADER_SIZE) { return; } ...
@Test public void testLastSpdySynStreamFrame() throws Exception { short type = 1; byte flags = 0x01; // FLAG_FIN int length = 10; int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01; int associatedToStreamId = RANDOM.nextInt() & 0x7FFFFFFF; byte priority = (byte) (RAN...
@SafeVarargs static <K, V> Mono<Map<K, V>> toMonoWithExceptionFilter(Map<K, KafkaFuture<V>> values, Class<? extends KafkaException>... classes) { if (values.isEmpty()) { return Mono.just(Map.of()); } List<Mono<Tuple2<K, Optional<V>>>> monos ...
@Test void testToMonoWithExceptionFilter() { var failedFuture = new KafkaFutureImpl<String>(); failedFuture.completeExceptionally(new UnknownTopicOrPartitionException()); var okFuture = new KafkaFutureImpl<String>(); okFuture.complete("done"); var emptyFuture = new KafkaFutureImpl<String>(); ...
@Override public synchronized T getValue(int index) { BarSeries series = getBarSeries(); if (series == null) { // Series is null; the indicator doesn't need cache. // (e.g. simple computation of the value) // --> Calculating the value T result = calcul...
@Test public void getValueWithCacheLengthIncrease() { double[] data = new double[200]; Arrays.fill(data, 10); SMAIndicator sma = new SMAIndicator(new ClosePriceIndicator(new MockBarSeries(numFunction, data)), 100); assertNumEquals(10, sma.getValue(105)); }
public Optional<Column> findValueColumn(final ColumnName columnName) { return findColumnMatching(withNamespace(VALUE).and(withName(columnName))); }
@Test public void shouldGetColumnByName() { // When: final Optional<Column> result = SOME_SCHEMA.findValueColumn(F0); // Then: assertThat(result, is(Optional.of( Column.of(F0, STRING, Namespace.VALUE, 0)) )); }
@Override public SelType call(String methodName, SelType[] args) { if (args.length == 0 && "size".equals(methodName)) { return SelLong.of(val == null ? 0 : val.size()); } else if (args.length == 1 && "get".equals(methodName)) { if (!val.containsKey((SelString) args[0])) { return NULL; ...
@Test(expected = UnsupportedOperationException.class) public void testCallGetInvalidArgs() { orig.call("get", new SelType[] {}); }
@SuppressWarnings("unchecked") public static <K, V> Map<K, V> toMap(Object... pairs) { Map<K, V> ret = new HashMap<>(); if (pairs == null || pairs.length == 0) { return ret; } if (pairs.length % 2 != 0) { throw new IllegalArgumentException("Map pairs can not ...
@Test void testToMap2() { Assertions.assertThrows(IllegalArgumentException.class, () -> toMap("a", "b", "c")); }
public static MDS of(double[][] proximity) { return of(proximity, new Properties()); }
@Test public void testPositive() { System.out.println("MDS positive = true"); double[] eigs = {42274973.753, 31666186.428}; double[][] points = { {-2716.561820, -3549.216493}, { 1453.753109, -455.895291}, { -217.426476, 1073.442137}, { -1....
public CeActivityDto setEntityUuid(@Nullable String s) { validateUuid(s, "ENTITY_UUID"); this.entityUuid = s; return this; }
@Test void seEntityUuid_throws_IAE_if_value_is_41_chars() { String str_41_chars = STR_40_CHARS + "a"; assertThatThrownBy(() -> underTest.setEntityUuid(str_41_chars)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value is too long for column CE_ACTIVITY.ENTITY_UUID: " + str_41_chars);...
public DirectGraph getGraph() { checkState(finalized, "Can't get a graph before the Pipeline has been completely traversed"); return DirectGraph.create( producers, viewWriters, perElementConsumers, rootTransforms, stepNames); }
@Test public void getGraphWithoutVisitingThrows() { thrown.expect(IllegalStateException.class); thrown.expectMessage("completely traversed"); thrown.expectMessage("get a graph"); visitor.getGraph(); }
@Override public boolean wasNull() throws SQLException { return mergedResult.wasNull(); }
@Test void assertWasNull() throws SQLException { assertFalse(new MaskMergedResult(mock(MaskRule.class), mock(SelectStatementContext.class), mergedResult).wasNull()); }
@SuppressWarnings("unchecked") @Override public RegisterNodeManagerResponse registerNodeManager( RegisterNodeManagerRequest request) throws YarnException, IOException { NodeId nodeId = request.getNodeId(); String host = nodeId.getHost(); int cmPort = nodeId.getPort(); int httpPort = requ...
@Test public void testNodeRegistrationWithInvalidLabelsSyntax() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, ...
@Override public boolean getStatus(final Path file) throws BackgroundException { final Path bucket = containerService.getContainer(file); try { return session.getClient().getAccelerateConfig(bucket.isRoot() ? StringUtils.EMPTY : bucket.getName()).isEnabled(); } catch(S3Se...
@Test public void getStatus() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final S3TransferAccelerationService service = new S3TransferAccelerationService(session); service.getStatus(container); }
@PostMapping("/server/config") public ServerConfig createOrUpdatePortalDBConfig(@Valid @RequestBody ServerConfig serverConfig) { return serverConfigService.createOrUpdateConfig(serverConfig); }
@Test @Sql(scripts = "/controller/test-server-config.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) void createOrUpdatePortalDBConfig() { ServerConfig serverConfig = new ServerConfig(); serverConfig.set...
public static HttpRequest toHttpRequest(int streamId, Http2Headers http2Headers, boolean validateHttpHeaders) throws Http2Exception { // HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line. final CharSequence method = checkNotNul...
@Test public void connectNoPath() throws Exception { String authority = "netty.io:80"; Http2Headers headers = new DefaultHttp2Headers(); headers.authority(authority); headers.method(HttpMethod.CONNECT.asciiName()); HttpRequest request = HttpConversionUtil.toHttpRequest(0, hea...
public boolean isTimeField() { // since we don't really have an info if the field is a time or not, we use a hack that if the field name ends with `ms` and of type // int or long. Not pretty but is the only feasible workaround here. return isMillSecondsInTheFieldName(fieldDef.name) ...
@Test void testIfDiscoversDurationFieldCorrectly() { final ConfigDef.ConfigKey configKey = new ConfigDef.ConfigKey( "field.test_underscore.Ms", ConfigDef.Type.LONG, "100", null, ConfigDef.Importance.MEDIUM, "testing", "testGroup", 1, ConfigDef.Width.MEDIUM, "displayName", ...
@Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { Class<?> loadedClass = findLoadedClass(name); if (loadedClass != null) { return loadedClass; } if (isClosed) { throw new ClassNotFoun...
@Test public void shouldInterceptFilteredStaticMethodInvocations() throws Exception { setClassLoader( new SandboxClassLoader( configureBuilder() .addInterceptedMethod( new MethodRef(AClassToForget.class, "forgettableStaticMethod")) .build()))...
@Override public void apply(IntentOperationContext<FlowRuleIntent> context) { Optional<IntentData> toUninstall = context.toUninstall(); Optional<IntentData> toInstall = context.toInstall(); if (toInstall.isPresent() && toUninstall.isPresent()) { Intent intentToInstall = toInstal...
@Test public void testRuleModifyMissing() { List<Intent> intentsToInstall = createFlowRuleIntents(); List<Intent> intentsToUninstall = createFlowRuleIntentsWithSameMatch(); IntentData toInstall = new IntentData(createP2PIntent(), IntentState.INSTALLING, new W...
public Comparator<?> getValueComparator(int column) { return valueComparators[column]; }
@Test public void getDefaultComparatorForNullClass() { ObjectTableSorter sorter = new ObjectTableSorter(createTableModel("null", null)); assertThat(sorter.getValueComparator(0), is(nullValue())); }
public static void trim(String[] strs) { if (null == strs) { return; } String str; for (int i = 0; i < strs.length; i++) { str = strs[i]; if (null != str) { strs[i] = trim(str); } } }
@Test public void trimTabTest() { final String str = "\taaa"; assertEquals("aaa", StrUtil.trim(str)); }
private Collection<Integer> transform(Transformation<?> transform) { if (alreadyTransformed.containsKey(transform)) { return alreadyTransformed.get(transform); } LOG.debug("Transforming " + transform); if (transform.getMaxParallelism() <= 0) { // if the max par...
@Test void testOutputTypeConfigurationWithOneInputTransformation() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<Integer> source = env.fromData(1, 10); OutputTypeConfigurableOperationWithOneInput outputTypeConfigurableOperation = ...
public static Serializable decode(final ByteBuf byteBuf) { int valueType = byteBuf.readUnsignedByte() & 0xff; StringBuilder result = new StringBuilder(); decodeValue(valueType, 1, byteBuf, result); return result.toString(); }
@Test void assertDecodeSmallJsonObjectWithString() { List<JsonEntry> jsonEntries = new LinkedList<>(); String value1 = ""; String value2 = Strings.repeat("1", (int) (Math.pow(2D, 7D) - 1D)); String value3 = Strings.repeat("1", (int) (Math.pow(2D, 7D) - 1D + 1D)); String value...
public static Builder in(Table table) { return new Builder(table); }
@TestTemplate public void testInPartitions() { table .newAppend() .appendFile(FILE_A) // bucket 0 .appendFile(FILE_B) // bucket 1 .appendFile(FILE_C) // bucket 2 .appendFile(FILE_D) // bucket 3 .commit(); Iterable<DataFile> files = FindFiles.in(table) ...
public static void initMatchKeys(RouterConfiguration configuration) { MATCH_KEYS.clear(); if (!RouterConfiguration.isInValid(configuration, RouterConstant.FLOW_MATCH_KIND)) { Map<String, List<Rule>> routeRules = configuration.getRouteRule().get(RouterConstant.FLOW_MATCH_KIND); if...
@Test public void testInitMatchKeys() { RouterConfiguration configuration = new RouterConfiguration(); RuleUtils.initMatchKeys(configuration); Assert.assertTrue(RuleUtils.getMatchKeys().isEmpty()); Map<String, List<EntireRule>> map = new HashMap<>(); EntireRule entireRule = n...
@Udf public Map<String, String> records(@UdfParameter final String jsonObj) { if (jsonObj == null) { return null; } final JsonNode node = UdfJsonMapper.parseJson(jsonObj); if (node.isMissingNode() || !node.isObject()) { return null; } final Map<String, String> ret = new HashMap<>...
@Test(expected = KsqlFunctionException.class) public void shouldThrowForInvalidJson() { udf.records("abc"); }
@Override public String pluginNamed() { return PluginEnum.REWRITE.getName(); }
@Test public void testPluginNamed() { Assertions.assertEquals(rewritePluginDataHandler.pluginNamed(), "rewrite"); }
@Override public double p(int k) { if (k < Math.max(0, m + n - N) || k > Math.min(m, n)) { return 0.0; } else { return Math.exp(logp(k)); } }
@Test public void testP() { System.out.println("p"); HyperGeometricDistribution instance = new HyperGeometricDistribution(100, 30, 70); instance.rand(); assertEquals(0.0, instance.p(-1), 1E-6); assertEquals(3.404564e-26, instance.p(0), 1E-30); assertEquals(7.149584e-2...
public static BigInteger decodeQuantity(String value) { if (isLongValue(value)) { return BigInteger.valueOf(Long.parseLong(value)); } if (!isValidHexQuantity(value)) { throw new MessageDecodingException("Value must be in format 0x[0-9a-fA-F]+"); } try { ...
@Test public void testQuantityDecode() { assertEquals(Numeric.decodeQuantity("0x0"), (BigInteger.valueOf(0L))); assertEquals(Numeric.decodeQuantity("0x400"), (BigInteger.valueOf(1024L))); assertEquals(Numeric.decodeQuantity("0x41"), (BigInteger.valueOf(65L))); assertEquals( ...
@Override public boolean retryRequest( HttpRequest request, IOException exception, int execCount, HttpContext context) { if (execCount > maxRetries) { // Do not retry if over max retries return false; } if (nonRetriableExceptions.contains(exception.getClass())) { return false; ...
@Test public void noRetryOnConnectTimeout() { HttpGet request = new HttpGet("/"); assertThat(retryStrategy.retryRequest(request, new SocketTimeoutException(), 1, null)) .isFalse(); }
public static ResourceHints fromOptions(PipelineOptions options) { ResourceHintsOptions resourceHintsOptions = options.as(ResourceHintsOptions.class); ResourceHints result = create(); List<String> hints = resourceHintsOptions.getResourceHints(); Splitter splitter = Splitter.on('=').limit(2); for (St...
@Test public void testFromOptions() { ResourceHintsOptions options = PipelineOptionsFactory.fromArgs( "--resourceHints=minRam=1KB", "--resourceHints=beam:resources:bar=foo") .as(ResourceHintsOptions.class); assertEquals( ResourceHints.fromOptions(options), R...
@Override public boolean mayHaveMergesPending(String bucketSpace, int contentNodeIndex) { if (!stats.hasUpdatesFromAllDistributors()) { return true; } ContentNodeStats nodeStats = stats.getStats().getNodeStats(contentNodeIndex); if (nodeStats != null) { Conten...
@Test void unknown_bucket_space_has_no_merges_pending() { Fixture f = Fixture.fromBucketsPending(1); assertFalse(f.mayHaveMergesPending("global", 1)); }
@Override public boolean assign(final Map<ProcessId, ClientState> clients, final Set<TaskId> allTaskIds, final Set<TaskId> statefulTaskIds, final AssignmentConfigs configs) { final int numStandbyReplicas = configs.numStandbyReplic...
@Test public void shouldDistributeStandbyTasksWhenActiveTasksAreLocatedOnSameCluster() { final Map<ProcessId, ClientState> clientStates = mkMap( mkEntry(PID_1, createClientStateWithCapacity(PID_1, 2, mkMap(mkEntry(ZONE_TAG, ZONE_1), mkEntry(CLUSTER_TAG, CLUSTER_1)), TASK_0_0, TASK_1_0)), ...
public FEELFnResult<Boolean> invoke(@ParameterName("string") String string, @ParameterName("match") String match) { if ( string == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null")); } if ( match == null ) { return...
@Test void invokeParamsNull() { FunctionTestUtil.assertResultError(containsFunction.invoke((String) null, null), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(containsFunction.invoke(null, "test"), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(contains...
public static String processPattern(String pattern, TbMsg tbMsg) { try { String result = processPattern(pattern, tbMsg.getMetaData()); JsonNode json = JacksonUtil.toJsonNode(tbMsg.getData()); if (json.isObject()) { Matcher matcher = DATA_PATTERN.matcher(result...
@Test public void testSameKeysReplacement() { String pattern = "ABC ${key} $[key]"; TbMsgMetaData md = new TbMsgMetaData(); md.putValue("key", "metadata_value"); ObjectNode node = JacksonUtil.newObjectNode(); node.put("key", "data_value"); TbMsg msg = TbMsg.newMsg(T...
public byte[] readBytes() { byte[] bytes = slice.getBytes(); offset = slice.length(); return bytes; }
@Test public void testReadBytes() { int numElements = 100; Slice slice = Slices.allocate(2 * numElements); byte[] expected = new byte[2 * numElements]; int offset = 0; for (int i = 0; i < numElements; i++) { String str = "" + i; slice.setBytes(off...
@Override public TransformResultMetadata getResultMetadata() { return _resultMetadata; }
@Test public void testArrayIndexOfAllInt() { ExpressionContext expression = RequestContextUtils.getExpression( String.format("array_indexes_of_int(%s, 0)", INT_MONO_INCREASING_MV_1)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); assertTrue(transfo...
@Override public RedisClusterNode clusterGetNodeForKey(byte[] key) { int slot = executorService.getConnectionManager().calcSlot(key); return clusterGetNodeForSlot(slot); }
@Test public void testClusterGetNodeForKey() { RedisClusterNode node = connection.clusterGetNodeForKey("123".getBytes()); assertThat(node).isNotNull(); }
@Override public boolean next() throws SQLException { return proxyBackendHandler.next(); }
@Test void assertNext() throws SQLException { when(proxyBackendHandler.next()).thenReturn(true, false); assertTrue(queryExecutor.next()); assertFalse(queryExecutor.next()); }
static boolean objectIsAcyclic(Object object) { if (object == null) { return true; } Class<?> klass = object.getClass(); if (isPrimitiveClass(klass)) { return true; } else if (isComplexClass(klass)) { DataComplex complex = (DataComplex) object; try { ...
@Test public void testNoCyclesOnAddAndPut() { assertTrue(Data.objectIsAcyclic(true)); assertTrue(Data.objectIsAcyclic(1)); assertTrue(Data.objectIsAcyclic(1L)); assertTrue(Data.objectIsAcyclic(1.0f)); assertTrue(Data.objectIsAcyclic(1.0)); assertTrue(Data.objectIsAcyclic("string")); asse...
public List<X509Certificate> operatorCertificates() { return operatorCertificates; }
@Test public void testOperatorCertificates() throws IOException { Slime slime = SlimeUtils.jsonToSlime(json); Cursor cursor = slime.get(); Cursor array = cursor.setArray(PrepareParams.OPERATOR_CERTIFICATES); X509Certificate certificate = X509CertificateUtils.createSelfSigned("cn=myse...
public static String asString(Duration duration) { long numDays = duration.toDays(); long numHours = duration.toHours() % 24; long numMinutes = duration.toMinutes() % 60; long numSeconds = duration.getSeconds() % 60; String output = String.format("%d:%02d:%02d", numHours, numMi...
@Test public void testDurationFormatting_2() { //2 days, 13 hours, 22 minutes, and 15 seconds int SECONDS_PER_DAY = 24 * 60 * 60; long numSeconds = 2 * SECONDS_PER_DAY + 13 * 3600 + 22 * 60 + 15; Duration dur = Duration.ofSeconds(numSeconds); assertEquals( "2 d...
static Object parseCell(String cell, Schema.Field field) { Schema.FieldType fieldType = field.getType(); try { switch (fieldType.getTypeName()) { case STRING: return cell; case INT16: return Short.parseShort(cell); case INT32: return Integer.parseInt(c...
@Test public void givenValidShortCell_parses() { Short shortNum = Short.parseShort("36"); DefaultMapEntry cellToExpectedValue = new DefaultMapEntry("36", shortNum); Schema schema = Schema.builder() .addInt32Field("an_integer") .addInt64Field("a_long") .addInt16F...
@Override public T deserialize(final String topic, final byte[] bytes) { return tryDeserialize(topic, bytes).get(); }
@Test public void shouldThrowIfDelegateThrows() { // Given: when(delegate.deserialize(any(), any())).thenThrow(ERROR); // When: final RuntimeException e = assertThrows( RuntimeException.class, () -> deserializer.deserialize("t", SOME_BYTES) ); // Then: assertThat(e, is(ER...
public CompletableFuture<Account> confirmReservedUsernameHash(final Account account, final byte[] reservedUsernameHash, @Nullable final byte[] encryptedUsername) { if (account.getUsernameHash().map(currentUsernameHash -> Arrays.equals(currentUsernameHash, reservedUsernameHash)).orElse(false)) { // the client ...
@Test void testConfirmReservedRetry() throws UsernameHashNotAvailableException, UsernameReservationNotFoundException { final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]...
@Override public List<String> findRolesLikeRoleName(String role) { String sql = "SELECT role FROM roles WHERE role LIKE ?"; List<String> users = this.jt.queryForList(sql, new String[] {String.format("%%%s%%", role)}, String.class); return users; }
@Test void testFindRolesLikeRoleName() { List<String> role = externalRolePersistService.findRolesLikeRoleName("role"); assertEquals(0, role.size()); }
void configure(Tomcat tomcat, Props props) { tomcat.setSilent(true); tomcat.getService().addLifecycleListener(new LifecycleLogger(LoggerFactory.getLogger(TomcatAccessLog.class))); configureLogbackAccess(tomcat, props); }
@Test public void enable_access_logs_by_Default() throws Exception { Tomcat tomcat = mock(Tomcat.class, Mockito.RETURNS_DEEP_STUBS); Props props = new Props(new Properties()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); underTest.configure(tomcat, props); verify(tomcat.getH...
public static String toJavaCode( final String argName, final Class<?> argType, final String lambdaBody ) { return toJavaCode(ImmutableList.of(new Pair<>(argName, argType)), lambdaBody); }
@Test public void shouldGenerateBiFunction() { // Given: final Pair<String, Class<?>> argName1 = new Pair<>("fred", Long.class); final Pair<String, Class<?>> argName2 = new Pair<>("bob", Long.class); final List<Pair<String, Class<?>>> argList = ImmutableList.of(argName1, argName2); // When: ...
@Override public URL select(List<URL> urls, String serviceId, String tag, String requestKey) { String key = tag == null ? serviceId : serviceId + "|" + tag; // search for a URL in the same ip first List<URL> localUrls = searchLocalUrls(urls, ip); if(localUrls.size() > 0) { ...
@Test public void testSelectFirstThenRoundRobin() throws Exception{ List<URL> urls = new ArrayList<>(); urls.add(new URLImpl("http", "127.0.0.10", 8081, "v1", new HashMap<String, String>())); urls.add(new URLImpl("http", "127.0.0.10", 8082, "v1", new HashMap<String, String>())); urls...
public Object resolve(final Expression expression) { return new Visitor().process(expression, null); }
@Test public void shouldThrowIfCannotCoerce() { // Given: final SqlType type = SqlTypes.array(SqlTypes.INTEGER); final Expression exp = new IntegerLiteral(1); // When: final KsqlException e = assertThrows( KsqlException.class, () -> new GenericExpressionResolver(type, FIELD_NAME, ...
@Override public String[] listFiles(URI fileUri, boolean recursive) throws IOException { ImmutableList.Builder<String> builder = ImmutableList.builder(); visitFiles(fileUri, recursive, s3Object -> { // TODO: Looks like S3PinotFS filters out directories, inconsistent with the other implementations....
@Test public void testListFilesInFolderNonRecursive() throws Exception { String folder = "list-files"; String[] originalFiles = new String[]{"a-list-2.txt", "b-list-2.txt", "c-list-2.txt"}; for (String fileName : originalFiles) { createEmptyFile(folder, fileName); } // Files in sub fo...
@Override // NameNode public void stop() { stop(true); }
@Test public void startBackupNodeWithIncorrectAuthentication() throws IOException { Configuration c = new HdfsConfiguration(); StartupOption startupOpt = StartupOption.CHECKPOINT; String dirs = getBackupNodeDir(startupOpt, 1); c.set(DFSConfigKeys.FS_DEFAULT_NAME_KEY, "hdfs://127.0.0.1:" + Se...
public static int[] computePhysicalIndicesOrTimeAttributeMarkers( TableSource<?> tableSource, List<TableColumn> logicalColumns, boolean streamMarkers, Function<String, String> nameRemapping) { Optional<String> proctimeAttribute = getProctimeAttribute(tableSource);...
@Test void testMappingWithBatchTimeAttributes() { TestTableSource tableSource = new TestTableSource( DataTypes.BIGINT(), Collections.singletonList("rowtime"), "proctime"); int[] indices = TypeMappingUtils.computePhysicalIndicesOrTimeAttributeMa...
public boolean isFinished() { return job.isFinished(); }
@Test public void testInsertOverwrite() throws Exception { String sql = "insert overwrite t1 select * from t2"; InsertStmt insertStmt = (InsertStmt) UtFrameUtils.parseStmtWithNewParser(sql, connectContext); StmtExecutor executor = new StmtExecutor(connectContext, insertStmt); Databas...
CompletableFuture<Void> beginExecute( @Nonnull List<? extends Tasklet> tasklets, @Nonnull CompletableFuture<Void> cancellationFuture, @Nonnull ClassLoader jobClassLoader ) { final ExecutionTracker executionTracker = new ExecutionTracker(tasklets.size(), cancellationFuture...
@Test public void when_nonBlockingTaskletIsCancelled_then_completesEarly() { // Given final List<MockTasklet> tasklets = Stream.generate(() -> new MockTasklet().callsBeforeDone(Integer.MAX_VALUE)) .limit(100).collect(toList()); // When Completab...
@Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); }
@Test void isWarnEnabled() { jobRunrDashboardLogger.isWarnEnabled(); verify(slfLogger).isWarnEnabled(); }
public RegistryBuilder file(String file) { this.file = file; return getThis(); }
@Test void file() { RegistryBuilder builder = new RegistryBuilder(); builder.file("file"); Assertions.assertEquals("file", builder.build().getFile()); }
@Override @SuppressWarnings("unchecked") public <T> T getProxy(Class<T> interfaceClass, Invoker proxyInvoker) { StringBuilder debug = null; if (LOGGER.isDebugEnabled()) { debug = new StringBuilder(); } try { Class clazz = null; if (!disableCach...
@Test public void getProxy() throws Exception { JavassistProxy proxy = new JavassistProxy(); AbstractTestClass testClass = null; try { testClass = proxy.getProxy(AbstractTestClass.class, new TestInvoker()); } catch (Exception e) { LOGGER.info(e.getMessage()); ...
public static List<Transformation<?>> optimize(List<Transformation<?>> transformations) { final Map<Transformation<?>, Set<Transformation<?>>> outputMap = buildOutputMap(transformations); final LinkedHashSet<Transformation<?>> chainedTransformations = new LinkedHashSet<>(); fina...
@Test void testChainingTwoInputOperators() { ExternalPythonKeyedCoProcessOperator<?> keyedCoProcessOperator1 = createCoKeyedProcessOperator( "f1", new RowTypeInfo(Types.INT(), Types.STRING()), new RowTypeInfo(Types.INT()...
public static void retry(String action, RunnableThrowsIOException f, RetryPolicy policy) throws IOException { IOException e = null; while (policy.attempt()) { try { f.run(); return; } catch (IOException ioe) { e = ioe; LOG.debug("Failed to {} (attempt {}): {}", ...
@Test public void success() throws IOException { AtomicInteger count = new AtomicInteger(0); RetryUtils.retry("success test", () -> { count.incrementAndGet(); if (count.get() == 5) { return; } throw new IOException("Fail"); }, new CountingRetry(10)); assertEquals(5, cou...
public static ObjectMapper of() { if (MAPPER == null) { MAPPER = JacksonMapper.ofJson(false).copy(); final SimpleModule module = new SimpleModule(); module.addSerializer(Instant.class, new JsonSerializer<>() { @Override public void serialize(I...
@Test void zoneDateTime() throws JsonProcessingException { String serialize = JdbcMapper.of().writeValueAsString(MultipleConditionWindow.builder() .start(ZonedDateTime.parse("2013-09-08T16:19:12.000000+02:00")) .build() ); assertThat(serialize, containsString("2013-...
public String getHostname() { return hostNameSupplier.getHostName(); }
@Test void testGetHostname1() { try { InetAddress address = mock(InetAddress.class); when(address.getCanonicalHostName()).thenReturn("worker10"); when(address.getHostName()).thenReturn("worker10"); when(address.getHostAddress()).thenReturn("127.0.0.1"); ...
public void setInitialAttributes(File file, FileAttribute<?>... attrs) { // default values should already be sanitized by their providers for (int i = 0; i < defaultValues.size(); i++) { FileAttribute<?> attribute = defaultValues.get(i); int separatorIndex = attribute.name().indexOf(':'); Str...
@Test public void testSetAttribute_onCreate_failsForAttributeThatIsNotSettableOnCreate() { File file = createFile(); try { service.setInitialAttributes(file, new BasicFileAttribute<>("test:foo", "world")); fail(); } catch (UnsupportedOperationException expected) { // it turns out that UO...
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = ...
@Test(expected=AclException.class) public void testMergeAclDefaultEntriesInputTooLarge() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(DEFAULT, USER, ALL)) .add(aclEntry(DEFAULT, GROUP, READ)) .add(aclEntry(DEFAULT, OTHER, NONE)) .build...
@Override public Output run(RunContext runContext) throws Exception { String renderedNamespace = runContext.render(this.namespace); FlowService flowService = ((DefaultRunContext) runContext).getApplicationContext().getBean(FlowService.class); flowService.checkAllowedNamespace(runContext.ten...
@Test void shouldGetGivenExistingKey() throws Exception { // Given String namespaceId = "io.kestra." + IdUtils.create(); RunContext runContext = this.runContextFactory.of(Map.of( "flow", Map.of("namespace", namespaceId), "inputs", Map.of( "key", TEST_K...
@Transactional @Cacheable(CACHE_DATABASE_SEARCH) @CacheEvict(value = CACHE_AVERAGE_REVIEW_RATING, allEntries = true) public SearchHits<ExtensionSearch> search(ISearchService.Options options) { // grab all extensions var matchingExtensions = repositories.findAllActiveExtensions(); //...
@Test public void testCategory() { var ext1 = mockExtension("yaml", 3.0, 100, 0, "redhat", List.of("Snippets", "Programming Languages")); var ext2 = mockExtension("java", 4.0, 100, 0, "redhat", List.of("Snippets", "Programming Languages")); var ext3 = mockExtension("openshift", 4.0, 100, 0, ...
@SuppressWarnings("unchecked") public <IN, OUT> AvroDatumConverter<IN, OUT> create(Class<IN> inputClass) { boolean isMapOnly = ((JobConf) getConf()).getNumReduceTasks() == 0; if (AvroKey.class.isAssignableFrom(inputClass)) { Schema schema; if (isMapOnly) { schema = AvroJob.getMapOutputKeyS...
@Test void convertAvroValue() throws IOException { AvroJob.setOutputValueSchema(mJob, Schema.create(Schema.Type.INT)); AvroValue<Integer> avroValue = new AvroValue<>(42); @SuppressWarnings("unchecked") AvroDatumConverter<AvroValue<Integer>, Integer> converter = mFactory .create((Class<AvroVal...
public static MutableInodeDirectory create(long id, long parentId, String name, CreateDirectoryContext context) { return new MutableInodeDirectory(id) .setParentId(parentId) .setName(name) .setTtl(context.getTtl()) .setTtlAction(context.getTtlAction()) .setOwner(context...
@Test public void equalsTest() throws Exception { MutableInodeDirectory inode1 = MutableInodeDirectory.create(1, 0, "test1", CreateDirectoryContext.defaults()); MutableInodeDirectory inode2 = MutableInodeDirectory.create(1, 0, "test2", CreateDirectoryContext.defaults()); MutableInodeDirect...
protected void notifyModelsChanged() { if (diffHelper == null) { throw new IllegalStateException("You must enable diffing before notifying models changed"); } diffHelper.notifyModelChanges(); }
@Test public void testThrowIfChangeModelIdAfterDiff() { TestModel testModel = new TestModel(); testModel.id(100); testAdapter.models.add(testModel); testAdapter.notifyModelsChanged(); thrown.expect(IllegalEpoxyUsage.class); thrown.expectMessage("Cannot change a model's id after it has been a...
@Override public CommitWorkStream commitWorkStream() { return windmillStreamFactory.createCommitWorkStream( dispatcherClient.getWindmillServiceStub(), throttleTimers.commitWorkThrottleTimer()); }
@Test public void testStreamingCommitManyThreads() throws Exception { ConcurrentHashMap<Long, WorkItemCommitRequest> commitRequests = new ConcurrentHashMap<>(); serviceRegistry.addService( new CloudWindmillServiceV1Alpha1ImplBase() { @Override public StreamObserver<StreamingCommitW...