focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void release() { if (fileChannel != null) { try { fileChannel.close(); } catch (IOException e) { ExceptionUtils.rethrow(e, "Failed to close file channel."); } } IOUtils.deleteFileQuietly(dataFilePath); }
@Test void testRelease() { assertThat(testFilePath.toFile().exists()).isTrue(); partitionFileReader.release(); assertThat(testFilePath.toFile().exists()).isFalse(); }
public final Logger getLogger(final Class<?> clazz) { return getLogger(clazz.getName()); }
@Test public void testStatusWithUnconfiguredContext() { Logger logger = lc.getLogger(LoggerContextTest.class); for (int i = 0; i < 3; i++) { logger.debug("test"); } logger = lc.getLogger("x.y.z"); for (int i = 0; i < 3; i++) { logger.debug("test"); } StatusManager sm = lc.g...
public EvictionConfig getEvictionConfig() { return evictionConfig; }
@Test(expected = IllegalArgumentException.class) public void testSetMaxSizeCannotBeNegative() { new MapConfig().getEvictionConfig().setSize(-1); }
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) { return invoke(n, BigDecimal.ZERO); }
@Test void invokeRoundingEven() { FunctionTestUtil.assertResult(roundDownFunction.invoke(BigDecimal.valueOf(10.25)), BigDecimal.valueOf(10)); FunctionTestUtil.assertResult(roundDownFunction.invoke(BigDecimal.valueOf(10.25), BigDecimal.ONE), BigDecimal.valueOf(10...
public static <T, IdT> Deduplicate.WithRepresentativeValues<T, IdT> withRepresentativeValueFn( SerializableFunction<T, IdT> representativeValueFn) { return new Deduplicate.WithRepresentativeValues<T, IdT>( DEFAULT_TIME_DOMAIN, DEFAULT_DURATION, representativeValueFn, null, null); }
@Test @Category({NeedsRunner.class, UsesTestStreamWithProcessingTime.class}) public void testTriggeredRepresentativeValuesWithType() { Instant base = new Instant(0); TestStream<KV<Long, String>> values = TestStream.create(KvCoder.of(VarLongCoder.of(), StringUtf8Coder.of())) .advanceWater...
public Predicate<InMemoryFilterable> parse(final List<String> filterExpressions, final List<EntityAttribute> attributes) { if (filterExpressions == null || filterExpressions.isEmpty()) { return Predicates.alwaysTrue(); } final Map<String...
@Test void throwsExceptionOnWrongFilterFormat() { final List<EntityAttribute> attributes = List.of( EntityAttribute.builder().id("good").title("Good").filterable(true).build(), EntityAttribute.builder().id("another").title("Hidden and dangerous").filterable(true).build() ...
public void acceptRow(final List<?> key, final GenericRow value) { try { if (passedLimit()) { return; } final KeyValue<List<?>, GenericRow> row = keyValue(key, value); final KeyValueMetadata<List<?>, GenericRow> keyValueMetadata = new KeyValueMetadata<>(row); while (!closed) ...
@Test public void shouldCallLimitHandlerAsLimitReached() { // When: IntStream.range(0, SOME_LIMIT) .forEach(idx -> queue.acceptRow(KEY_ONE, VAL_ONE)); // Then: verify(limitHandler).limitReached(); }
@Bean public SofaServiceEventListener sofaServiceEventListener(final ShenyuClientConfig clientConfig, final ShenyuClientRegisterRepository shenyuClientRegisterRepository) { return new SofaServiceEventListener(clientConfig.getClient().get(RpcTypeEnum.SOFA.getName()), shenyuClientRegisterRepository); }
@Test public void testSofaServiceEventListener() { MockedStatic<RegisterUtils> registerUtilsMockedStatic = mockStatic(RegisterUtils.class); registerUtilsMockedStatic.when(() -> RegisterUtils.doLogin(any(), any(), any())).thenReturn(Optional.ofNullable("token")); applicationContextRunner.run(...
public double calculateMinPercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) { if (LOG.isTraceEnabled()) { LOG.trace("Calculating min percentage used by. Used Mem: {} Total Mem: {}" + " Used Normalized Resources: {} Total Normalized Resources:...
@Test public void testCalculateMinThrowsIfTotalIsMissingMemory() { NormalizedResources resources = new NormalizedResources(normalize(Collections.singletonMap(Constants.COMMON_CPU_RESOURCE_NAME, 2))); NormalizedResources usedResources = new NormalizedResources(normalize(Collections.singletonMap(Const...
public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec> specs) { return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(schema, specs)); }
@Test public void testGroupingKeyTypeWithSpecEvolutionInV1Tables() { TestTables.TestTable table = TestTables.create(tableDir, "test", SCHEMA, BY_DATA_SPEC, V1_FORMAT_VERSION); table.updateSpec().addField(Expressions.bucket("category", 8)).commit(); assertThat(table.specs()).hasSize(2); Stru...
@Override protected String transform(ILoggingEvent event, String in) { AnsiElement element = ELEMENTS.get(getFirstOption()); List<Marker> markers = event.getMarkerList(); if ((markers != null && !markers.isEmpty() && markers.get(0).contains(CRLF_SAFE_MARKER)) || isLoggerSafe(event)) { ...
@Test void transformShouldReturnInputStringWhenMarkersNotContainCRLFSafeMarker() { ILoggingEvent event = mock(ILoggingEvent.class); Marker marker = MarkerFactory.getMarker("CRLF_NOT_SAFE"); List<Marker> markers = Collections.singletonList(marker); when(event.getMarkerList()).thenRetu...
@Override public ServiceStateTransition.Response mayTransitionServiceTo(final ServiceInstance instance, final Service.ServiceState newState, final String reason) { return trans...
@Test void shouldReturnEmptyForTransitionWorkerStateGivenInvalidWorker() { // Given ServiceInstance instance = Fixtures.RunningServiceInstance; // When ServiceStateTransition.Response result = repository .mayTransitionServiceTo(instance, Service.ServiceState.TERMINATING)...
void addGetModelsMethod(StringBuilder sb) { sb.append( " @Override\n" + " public java.util.List<Model> getModels() {\n" + " return java.util.Arrays.asList(" ); String collected = modelsByKBase.values().stream().flatMap( List::...
@Test public void addGetModelsMethodEmptyModelsByKBaseTest() { ModelSourceClass modelSourceClass = new ModelSourceClass(RELEASE_ID, new HashMap<>(), new HashMap<>()); StringBuilder sb = new StringBuilder(); modelSourceClass.addGetModelsMethod(sb); String retrieved = sb.toString(); ...
static void process(int maxMessages, MessageFormatter formatter, ConsumerWrapper consumer, PrintStream output, boolean skipMessageOnError) { while (messageCount < maxMessages || maxMessages == -1) { ConsumerRecord<byte[], byte[]> msg; try { msg = consumer.receive(); ...
@Test public void shouldLimitReadsToMaxMessageLimit() { ConsoleConsumer.ConsumerWrapper consumer = mock(ConsoleConsumer.ConsumerWrapper.class); MessageFormatter formatter = mock(MessageFormatter.class); ConsumerRecord<byte[], byte[]> record = new ConsumerRecord<>("foo", 1, 1, new byte[0], ne...
public static String serialize(AWSCredentialsProvider awsCredentialsProvider) { ObjectMapper om = new ObjectMapper(); om.registerModule(new AwsModule()); try { return om.writeValueAsString(awsCredentialsProvider); } catch (JsonProcessingException e) { throw new IllegalArgumentException("AwsC...
@Test(expected = IllegalArgumentException.class) public void testFailOnAWSCredentialsProviderSerialization() { AWSCredentialsProvider credentialsProvider = new UnknownAwsCredentialsProvider(); serialize(credentialsProvider); }
@Override public void getConfig(FederationConfig.Builder builder) { for (Target target : resolvedTargets.values()) builder.target(target.getTargetConfig()); targetSelector.ifPresent(selector -> builder.targetSelector(selector.getGlobalComponentId().stringValue())); }
@Test void manually_specified_targets_overrides_inherited_targets() throws Exception { FederationFixture f = new FederationFixture(); f.registerProviderWithSources(createProvider(ComponentId.fromString("provider1"))); FederationSearcher federation = newFederationSearcher(true, ...
public static int read(final AtomicBuffer buffer, final EntryConsumer entryConsumer) { final int capacity = buffer.capacity(); int recordsRead = 0; int offset = 0; while (offset < capacity) { final long observationCount = buffer.getLongVolatile(offset + OBSERVAT...
@Test void shouldReadTwoEntries() { final long initialBytesLostOne = 32; final int timestampMsOne = 7; final int sessionIdOne = 3; final int streamIdOne = 1; final String channelOne = "aeron:udp://stuffOne"; final String sourceOne = "127.0.0.1:8888"; fina...
@Override public boolean tableExists(String dbName, String tblName) { return hmsOps.tableExists(dbName, tblName); }
@Test public void testTableExists() { boolean exists = hiveMetadata.tableExists("db1", "tbl1"); Assert.assertTrue(exists); }
@Override protected Release findActiveOne(long id, ApolloNotificationMessages clientMessages) { Tracer.logEvent(TRACER_EVENT_CACHE_GET_ID, String.valueOf(id)); return configIdCache.getUnchecked(id).orElse(null); }
@Test public void testFindActiveOneWithMultipleIdMultipleTimes() throws Exception { long someId = 1; long anotherId = 2; Release anotherRelease = mock(Release.class); when(releaseService.findActiveOne(someId)).thenReturn(someRelease); when(releaseService.findActiveOne(anotherId)).thenReturn(anoth...
public static float toFloat(final String str) { return toFloat(str, 0.0f); }
@Test void testToFloatString() { assertEquals(NumberUtils.toFloat("-1.2345"), -1.2345f, 0); assertEquals(1.2345f, NumberUtils.toFloat("1.2345"), 0); assertEquals(0.0f, NumberUtils.toFloat("abc"), 0); assertEquals(NumberUtils.toFloat("-001.2345"), -1.2345f, 0); assert...
@Override public void reset() { set(INIT); }
@Test public void testReset() { SnapshotRegistry registry = new SnapshotRegistry(new LogContext()); TimelineInteger value = new TimelineInteger(registry); registry.getOrCreateSnapshot(2); value.set(1); registry.getOrCreateSnapshot(3); value.set(2); registry.r...
protected boolean evaluation(Object inputValue) { switch (operator) { case EQUAL: return value.equals(inputValue); case NOT_EQUAL: return !value.equals(inputValue); case LESS_THAN: if (inputValue instanceof Number && value insta...
@Test void evaluationStringIsMissing() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { Object value = "43"; KiePMMLSimplePredicate kiePMMLSimplePredicate = getKiePMMLSimplePredicate(OPERATOR.IS_MISSING, value); kiePMMLSimplePredicate.evaluat...
@Override public int hashCode() { return executionId.hashCode() + executionState.ordinal(); }
@Test public void testEqualsHashCode() { try { final ExecutionAttemptID executionId = createExecutionAttemptId(); final ExecutionState state = ExecutionState.RUNNING; final Throwable error = new RuntimeException("some test error message"); TaskExecutionState ...
@Override public void removeDataConnection(String name) { dataConnections.computeIfPresent(name, (k, v) -> { if (CONFIG == v.source) { throw new HazelcastException("Data connection '" + name + "' is configured via Config " + "and can't be removed"); ...
@Test public void remove_non_existing_data_connection_should_be_no_op() { dataConnectionService.removeDataConnection("does-not-exist"); }
@Override public int remainingCapacity() { return capacity() - size(); }
@Test public void testRemainingCapacity() { assertEquals(CAPACITY, queue.remainingCapacity()); queue.offer(1); assertEquals(CAPACITY - 1, queue.remainingCapacity()); }
@Override public String[] split(String text) { if (splitContraction) { text = WONT_CONTRACTION.matcher(text).replaceAll("$1ill not"); text = SHANT_CONTRACTION.matcher(text).replaceAll("$1ll not"); text = AINT_CONTRACTION.matcher(text).replaceAll("$1m not"); f...
@Test public void testTokenize() { System.out.println("tokenize"); String text = "Good muffins cost $3.88\nin New York. Please buy " + "me\ntwo of them.\n\nYou cannot eat them. I gonna eat them. " + "Thanks. Of course, I won't. "; String[] expResult = {"Good...
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void testSlotSharingResourceConfiguration() { final String slotSharingGroup1 = "slot-a"; final String slotSharingGroup2 = "slot-b"; final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResour...
@Override public boolean rename(Path src, Path dst) throws IOException { return fs.rename(src, dst); }
@Test public void testRenameOptions() throws Exception { FileSystem mockFs = mock(FileSystem.class); FileSystem fs = new FilterFileSystem(mockFs); Path src = new Path("/src"); Path dst = new Path("/dest"); Rename opt = Rename.TO_TRASH; fs.rename(src, dst, opt); verify(mockFs).rename(eq(src...
public Node parse() throws ScanException { if (tokenList == null || tokenList.isEmpty()) return null; return E(); }
@Test public void nested() throws ScanException { Tokenizer tokenizer = new Tokenizer("a${b${c}}d"); Parser parser = new Parser(tokenizer.tokenize()); Node node = parser.parse(); Node witness = new Node(Node.Type.LITERAL, "a"); Node bLiteralNode = new Node(Node.Type.LITERAL, ...
public WebServiceField getFieldOutFromWsName( String wsName, boolean ignoreWsNsPrefix ) { WebServiceField param = null; if ( Utils.isEmpty( wsName ) ) { return param; } // if we are ignoring the name space prefix if ( ignoreWsNsPrefix ) { // we split the wsName and set it to the last ...
@Test public void testGetFieldOut() throws Exception { DatabaseMeta dbMeta = mock( DatabaseMeta.class ); IMetaStore metastore = mock( IMetaStore.class ); WebServiceMeta webServiceMeta = new WebServiceMeta( getTestNode(), Collections.singletonList( dbMeta ), metastore ); assertNull( webServiceMeta.getF...
public static StatementExecutorResponse execute( final ConfiguredStatement<ListProperties> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final KsqlConfigResolver resolver = new KsqlConfigResolver()...
@Test public void shouldListPropertiesWithOverrides() { // When: final PropertiesList properties = (PropertiesList) CustomExecutors.LIST_PROPERTIES.execute( engine.configure("LIST PROPERTIES;") .withConfigOverrides(ImmutableMap.of("ksql.streams.auto.offset.reset", "latest")), mock(...
@Override public void debug(String msg) { logger.debug(msg); }
@Test public void testDebugWithException() { Logger mockLogger = mock(Logger.class); when(mockLogger.getName()).thenReturn("foo"); InternalLogger logger = new Slf4JLogger(mockLogger); logger.debug("a", e); verify(mockLogger).getName(); verify(mockLogger).debug("a",...
private ContentType getContentType(Exchange exchange) throws ParseException { String contentTypeStr = ExchangeHelper.getContentType(exchange); if (contentTypeStr == null) { contentTypeStr = DEFAULT_CONTENT_TYPE; } ContentType contentType = new ContentType(contentTypeStr); ...
@Test public void attachmentReadOnce() throws IOException { String attContentType = "text/plain"; String attText = "Attachment Text"; InputStream attInputStream = new ByteArrayInputStream(attText.getBytes()); String attFileName = "Attachment File Name"; in.setBody("Body text"...
List<GcpAddress> instances(String project, String zone, Label label, String accessToken) { String response = RestClient .create(urlFor(project, zone, label)) .withHeader("Authorization", String.format("OAuth %s", accessToken)) .get() .getBody(); ...
@Test public void instances() { // given stubFor(get(urlEqualTo( String.format("/compute/v1/projects/%s/zones/%s/instances?filter=labels.%s+eq+%s", PROJECT, ZONE, LABEL_KEY, LABEL_VALUE))) .withHeader("Authorization", equalTo(String.format("OAu...
@Override public synchronized void editSchedule() { updateConfigIfNeeded(); long startTs = clock.getTime(); CSQueue root = scheduler.getRootQueue(); Resource clusterResources = Resources.clone(scheduler.getClusterResource()); containerBasedPreemptOrKill(root, clusterResources); if (LOG.isDe...
@Test public void testExpireKill() { final long killTime = 10000L; int[][] qData = new int[][]{ // / A B C { 100, 40, 40, 20 }, // abs { 100, 100, 100, 100 }, // maxCap { 100, 0, 60, 40 }, // used { 10, 10, 0, 0 }, // pending { 0, 0, 0, 0 }, // reserved...
public void waitUntilFinished() { while ( !isFinished() && !job.isStopped() ) { try { Thread.sleep( 0, 1 ); } catch ( InterruptedException e ) { // Ignore errors } } }
@Test public void testWaitUntilFinished() throws Exception { when( mockJob.isStopped() ).thenReturn( true ); when( mockJob.getParentJob() ).thenReturn( parentJob ); when( parentJob.isStopped() ).thenReturn( false ); when( mockJob.execute( Mockito.anyInt(), Mockito.any( Result.class ) ) ).thenReturn( m...
public long getId() { return id; }
@Test public void getMethodTest() { Assert.assertEquals(indexId, index.getId()); }
@Override public BeamSqlTable buildBeamSqlTable(Table table) { return new MongoDbTable(table); }
@Test public void testBuildBeamSqlTable_withUsernameAndPassword() { Table table = fakeTable("TEST", "mongodb://username:pasword@localhost:27017/database/collection"); BeamSqlTable sqlTable = provider.buildBeamSqlTable(table); assertNotNull(sqlTable); assertTrue(sqlTable instanceof MongoDbTabl...
@Override public List<Long> getTenantIdList() { List<TenantDO> tenants = tenantMapper.selectList(); return CollectionUtils.convertList(tenants, TenantDO::getId); }
@Test public void testGetTenantIdList() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L)); tenantMapper.insert(tenant); // 调用,并断言业务异常 List<Long> result = tenantService.getTenantIdList(); assertEquals(Collections.singletonList(1L), result); ...
@Nonnull public static List<JetSqlRow> evaluate( @Nullable Expression<Boolean> predicate, @Nullable List<Expression<?>> projection, @Nonnull Stream<JetSqlRow> rows, @Nonnull ExpressionEvalContext context ) { return rows .map(row -> evaluate...
@Test public void test_evaluateWithProjection() { List<Object[]> rows = asList(new Object[]{0, "a"}, new Object[]{1, "b"}, new Object[]{2, "c"}); MultiplyFunction<?> projection = MultiplyFunction.create(ColumnExpression.create(0, INT), ConstantExpression.create(2, INT), INT); ...
String getJwtFromBearerAuthorization(HttpServletRequest req) { String authorizationHeader = req.getHeader(HttpHeader.AUTHORIZATION.asString()); if (authorizationHeader == null || !authorizationHeader.startsWith(BEARER)) { return null; } else { return authorizationHeader.substring(BEARER.length()...
@Test public void testParseTokenFromAuthHeader() { JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN); HttpServletRequest request = mock(HttpServletRequest.class); expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(JwtAuthenticator.BEARER + " " + EXPECTE...
public static void checkParamV2(String tag) throws NacosApiException { if (StringUtils.isNotBlank(tag)) { if (!isValid(tag.trim())) { throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.PARAMETER_VALIDATE_ERROR, "invalid tag : " + tag); ...
@Test void testCheckParamV2() { //tag invalid String tag = "test!"; try { ParamUtils.checkParam(tag); fail(); } catch (IllegalArgumentException e) { System.out.println(e.toString()); } //tag over length tag = "testt...
public static Driver load(String className) throws DriverLoadException { final ClassLoader loader = DriverLoader.class.getClassLoader(); return load(className, loader); }
@Test public void testLoad_String() throws SQLException { String className = "org.h2.Driver"; Driver d = null; try { d = DriverLoader.load(className); } catch (DriverLoadException ex) { fail(ex.getMessage()); } finally { if (d != null) { ...
@Override public void download(String src, File destFile) { get(src, FileUtil.getAbsolutePath(destFile)); }
@Test @Disabled public void downloadTest() { sshjSftp.recursiveDownloadFolder("/home/test/temp", new File("C:\\Users\\akwangl\\Downloads\\temp")); }
public List<String> getRoles() { ArrayList<String> sortedRoles = new ArrayList<>(roles); Collections.sort(sortedRoles); return sortedRoles; }
@Test public void shouldReturnSortedRoles() { UserModel foo = new UserModel(new User("foo", new ArrayList<>(), "foo@bar.com", false), List.of("bbb", "aaa", "BBB"), true); assertThat(foo.getRoles(), is(List.of("BBB", "aaa", "bbb"))); }
@Override public byte[] deserialize(Asn1ObjectInputStream in) { return in.readAll(); }
@Test public void shouldDeserialize() { assertArrayEquals(new byte[] { 0x31 }, deserialize( new ByteArrayConverter(), byte[].class, new byte[] { 0x31 } )); }
public static String buildStoreNamePrefix(Scheme scheme) { // rule of key: /registry/[group]/plural-name/extension-name StringBuilder builder = new StringBuilder("/registry/"); if (StringUtils.hasText(scheme.groupVersionKind().group())) { builder.append(scheme.groupVersionKind().grou...
@Test void buildStoreNamePrefix() { var prefix = ExtensionStoreUtil.buildStoreNamePrefix(scheme); assertEquals("/registry/fake.halo.run/fakes", prefix); prefix = ExtensionStoreUtil.buildStoreNamePrefix(grouplessScheme); assertEquals("/registry/fakes", prefix); }
<T extends PipelineOptions> T as(Class<T> iface) { checkNotNull(iface); checkArgument(iface.isInterface(), "Not an interface: %s", iface); T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface); if (existingOption == null) { synchronized (this) { // double check ...
@Test public void testDisplayDataNullValuesConvertedToEmptyString() throws Exception { FooOptions options = PipelineOptionsFactory.as(FooOptions.class); options.setFoo(null); DisplayData data = DisplayData.from(options); assertThat(data, hasDisplayItem("foo", "")); FooOptions deserializedOptions...
public List<String> extensionNames() { return stream().map(PluginInfo::getExtensionName).collect(toList()); }
@Test public void shouldGetExtensionNamesOfAllExtensionsContainedWithin() { CombinedPluginInfo pluginInfo = new CombinedPluginInfo(List.of( new PluggableTaskPluginInfo(null, null, null), new NotificationPluginInfo(null, null))); assertThat(pluginInfo.extensionNames()...
@Override public int compareTo(RestartRequest o) { int result = connectorName.compareTo(o.connectorName); return result == 0 ? impactRank() - o.impactRank() : result; }
@Test public void compareImpact() { RestartRequest onlyFailedConnector = new RestartRequest(CONNECTOR_NAME, true, false); RestartRequest failedConnectorAndTasks = new RestartRequest(CONNECTOR_NAME, true, true); RestartRequest onlyConnector = new RestartRequest(CONNECTOR_NAME, false, false); ...
public UniVocityFixedDataFormat setFieldLengths(int[] fieldLengths) { this.fieldLengths = fieldLengths; return this; }
@Test public void shouldConfigureHeadersDisabled() { UniVocityFixedDataFormat dataFormat = new UniVocityFixedDataFormat() .setFieldLengths(new int[] { 1, 2, 3 }) .setHeadersDisabled(true); assertTrue(dataFormat.isHeadersDisabled()); assertNull(dataFormat.crea...
static InetSocketAddress parse( final String value, final String uriParamName, final boolean isReResolution, final NameResolver nameResolver) { if (Strings.isEmpty(value)) { throw new NullPointerException("input string must not be null or empty"); } final String ...
@Test void shouldRejectOnInvalidIpV6() { assertThrows(IllegalArgumentException.class, () -> SocketAddressParser.parse( "[FG07::789:1:0:0:3]:111", ENDPOINT_PARAM_NAME, false, DEFAULT_RESOLVER)); }
public Result checkout(String pluginId, final SCMPropertyConfiguration scmConfiguration, final String destinationFolder, final SCMRevision revision) { return pluginRequestHelper.submitRequest(pluginId, SCMExtension.REQUEST_CHECKOUT, new DefaultPluginInteractionCallback<>() { @Override pu...
@Test public void shouldTalkToPluginToCheckout() throws Exception { String destination = "destination"; SCMRevision revision = new SCMRevision(); when(jsonMessageHandler.requestMessageForCheckout(scmPropertyConfiguration, destination, revision)).thenReturn(requestBody); Result deseri...
@Override public byte[] serialize(final String topic, final List<?> data) { if (data == null) { return null; } try { final StringWriter stringWriter = new StringWriter(); final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat); csvPrinter.printRecord(() -> new FieldI...
@Test public void shouldSerializeRowWithNull() { // Given: final List<?> values = Arrays.asList(1511897796092L, 1L, "item_1", null, null, null, null, null, null); // When: final byte[] bytes = serializer.serialize("t1", values); // Then: final String delimitedString = new String(bytes, Stand...
@Override @MethodNotAvailable public CompletionStage<V> getAsync(K key) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testGetAsync() { adapter.getAsync(42); }
@Override public List<String> pop(String queueName, int count, int timeout) { List<String> tasks = new ArrayList<>(count); if (!queues.containsKey(queueName)) { queues.put(queueName, new ConcurrentLinkedDeque<>()); } for (int i = 0; i < count; ++i) { String entry = queues.get(queueName).po...
@Test public void testPop() { String queueName = "test-queue"; String id = "abcd-1234-defg-5678"; assertEquals(Collections.emptyList(), queueDao.pop(queueName, 2, 100)); queueDao.pushIfNotExists(queueName, id, 123); assertEquals(Collections.singletonList(id), queueDao.pop(queueName, 2, 100)); ...
@Override public void append(LogEvent event) { all.mark(); switch (event.getLevel().getStandardLevel()) { case TRACE: trace.mark(); break; case DEBUG: debug.mark(); break; case INFO: i...
@Test public void metersDebugEvents() { when(event.getLevel()).thenReturn(Level.DEBUG); appender.append(event); assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) .isEqualTo(1); assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()) ...
boolean touches(Bubble b) { //distance between them is greater than sum of radii (both sides of equation squared) return (this.coordinateX - b.coordinateX) * (this.coordinateX - b.coordinateX) + (this.coordinateY - b.coordinateY) * (this.coordinateY - b.coordinateY) <= (this.radius + b.radius) *...
@Test void touchesTest() { var b1 = new Bubble(0, 0, 1, 2); var b2 = new Bubble(1, 1, 2, 1); var b3 = new Bubble(10, 10, 3, 1); //b1 touches b2 but not b3 assertTrue(b1.touches(b2)); assertFalse(b1.touches(b3)); }
@Override public String named() { return PluginEnum.RATE_LIMITER.getName(); }
@Test public void namedTest() { assertEquals(PluginEnum.RATE_LIMITER.getName(), rateLimiterPlugin.named()); }
public abstract VoiceInstructionValue getConfigForDistance( double distance, String turnDescription, String thenVoiceInstruction);
@Test public void fixedDistanceInitialVICMetricTest() { FixedDistanceVoiceInstructionConfig configMetric = new FixedDistanceVoiceInstructionConfig(IN_HIGHER_DISTANCE_PLURAL.metric, trMap, locale, 2000, 2); compareVoiceInstructionValues( 2000, "In 2 ki...
@Override public YamlSQLParserRuleConfiguration swapToYamlConfiguration(final SQLParserRuleConfiguration data) { YamlSQLParserRuleConfiguration result = new YamlSQLParserRuleConfiguration(); result.setParseTreeCache(cacheOptionSwapper.swapToYamlConfiguration(data.getParseTreeCache())); resul...
@Test void assertSwapToYamlConfiguration() { SQLParserRuleConfiguration ruleConfig = new SQLParserRuleConfiguration(new CacheOption(2, 5L), new CacheOption(4, 7L)); YamlSQLParserRuleConfiguration actual = new YamlSQLParserRuleConfigurationSwapper().swapToYamlConfiguration(ruleConfig); assert...
public static void init(Class<?> clazz) { String rs = clazz.getResource("").toString(); if (rs.contains(SUFFIX_JAR)) { isJarContext = true; } }
@Test public void testInit() { DynamicContext.init(DynamicContext.class); }
public static double byte2MemorySize(final long byteNum, @MemoryConst.Unit final int unit) { if (byteNum < 0) return -1; return (double) byteNum / unit; }
@Test public void byte2MemorySize() throws Exception { Assert.assertEquals( 1024, ConvertKit.byte2MemorySize(MemoryConst.GB, MemoryConst.MB), 0.001 ); }
@Override public List<TransferItem> normalize(final List<TransferItem> roots) { final List<TransferItem> normalized = new ArrayList<>(); for(final TransferItem download : roots) { boolean duplicate = false; for(Iterator<TransferItem> iter = normalized.iterator(); iter.hasNext...
@Test public void testNormalize() { DownloadRootPathsNormalizer n = new DownloadRootPathsNormalizer(); final List<TransferItem> list = new ArrayList<>(); list.add(new TransferItem(new Path("/a", EnumSet.of(Path.Type.directory)), new NullLocal(System.getProperty("java.io.tmpdir"), "a"))); ...
public static Counter allocate( final Aeron aeron, final UnsafeBuffer tempBuffer, final long archiveId, final long recordingId, final int sessionId, final int streamId, final String strippedChannel, final String sourceIdentity) { tempBuffer.put...
@Test void allocateShouldAlignLabelByFourBytes() { final long archiveId = 888; final long recordingId = 1; final int sessionId = 30; final int streamId = 222; final String strippedChannel = "channel"; final String sourceIdentity = "source"; final UnsafeBuf...
void execute(Runnable runnable) { try { runnable.run(); } catch (Throwable t) { rethrowIfUnrecoverable(t); add(t); } }
@Test void rethrows_unrecoverable() { assertThrows(OutOfMemoryError.class, () -> collector.execute(() -> { throw new OutOfMemoryError(); })); }
public static double shuffleCompressionRatio( SparkSession spark, FileFormat outputFileFormat, String outputCodec) { if (outputFileFormat == FileFormat.ORC || outputFileFormat == FileFormat.PARQUET) { return columnarCompression(shuffleCodec(spark), outputCodec); } else if (outputFileFormat == FileFo...
@Test public void testOrcCompressionRatios() { configureShuffle("lz4", true); double ratio1 = shuffleCompressionRatio(ORC, "zlib"); assertThat(ratio1).isEqualTo(3.0); double ratio2 = shuffleCompressionRatio(ORC, "lz4"); assertThat(ratio2).isEqualTo(2.0); }
T call() throws IOException, RegistryException { String apiRouteBase = "https://" + registryEndpointRequestProperties.getServerUrl() + "/v2/"; URL initialRequestUrl = registryEndpointProvider.getApiRoute(apiRouteBase); return call(initialRequestUrl); }
@Test public void testCall_unknown() throws IOException, RegistryException { ResponseException responseException = mockResponseException(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); setUpRegistryResponse(responseException); try { endpointCaller.call(); Assert.fail("Call should have fail...
Path getTemporaryDirectory() { return cacheDirectory.resolve(TEMPORARY_DIRECTORY); }
@Test public void testGetTemporaryDirectory() { Assert.assertEquals( Paths.get("cache/directory/tmp"), TEST_CACHE_STORAGE_FILES.getTemporaryDirectory()); }
public static <T> Either<String, T> resolveImportDMN(Import importElement, Collection<T> dmns, Function<T, QName> idExtractor) { final String importerDMNNamespace = ((Definitions) importElement.getParent()).getNamespace(); final String importerDMNName = ((Definitions) importElement.getParent()).getName(...
@Test void locateInNSnoModelNameWithAlias2() { final Import i = makeImport("nsA", "boh", null); final List<QName> available = Arrays.asList(new QName("nsA", "m1"), new QName("nsA", "m2"), new QNam...
@Override public Collection<LocalDataQueryResultRow> getRows(final ShowDistVariableStatement sqlStatement, final ContextManager contextManager) { ShardingSphereMetaData metaData = contextManager.getMetaDataContexts().getMetaData(); String variableName = sqlStatement.getName(); if (isConfigur...
@Test void assertShowPropsVariableForTypedSPI() { when(contextManager.getMetaDataContexts().getMetaData().getProps()) .thenReturn(new ConfigurationProperties(PropertiesBuilder.build(new Property("proxy-frontend-database-protocol-type", "MySQL")))); ShowDistVariableExecutor executor =...
@Override public synchronized void editSchedule() { updateConfigIfNeeded(); long startTs = clock.getTime(); CSQueue root = scheduler.getRootQueue(); Resource clusterResources = Resources.clone(scheduler.getClusterResource()); containerBasedPreemptOrKill(root, clusterResources); if (LOG.isDe...
@Test public void testHierarchical() { int[][] qData = new int[][] { // / A B C D E F { 200, 100, 50, 50, 100, 10, 90 }, // abs { 200, 200, 200, 200, 200, 200, 200 }, // maxCap { 200, 110, 60, 50, 90, 90, 0 }, // used { 10, 0, 0, 0, 10, 0, 10 }, // pending...
public Account changeNumber(final Account account, final String number, @Nullable final IdentityKey pniIdentityKey, @Nullable final Map<Byte, ECSignedPreKey> deviceSignedPreKeys, @Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys, @Nullable final List<IncomingMessage> deviceMes...
@Test void changeNumberMissingData() { final Account account = mock(Account.class); when(account.getNumber()).thenReturn("+18005551234"); final List<Device> devices = new ArrayList<>(); for (byte i = 1; i <= 3; i++) { final Device device = mock(Device.class); when(device.getId()).thenRet...
public static OptionalInt getBucketNumber(String fileName) { for (Pattern pattern : BUCKET_PATTERNS) { Matcher matcher = pattern.matcher(fileName); if (matcher.matches()) { return OptionalInt.of(parseInt(matcher.group(1))); } } // Numerical...
@Test public void testGetBucketNumber() { assertEquals(getBucketNumber("0234_0"), OptionalInt.of(234)); assertEquals(getBucketNumber("000234_0"), OptionalInt.of(234)); assertEquals(getBucketNumber("0234_99"), OptionalInt.of(234)); assertEquals(getBucketNumber("0234_0.txt"), Optio...
@Override protected boolean isInfinite(Long number) { // Infinity never applies here because only types like Float and Double have Infinity return false; }
@Test void testIsInfinite() { LongSummaryAggregator ag = new LongSummaryAggregator(); // always false for Long assertThat(ag.isInfinite(-1L)).isFalse(); assertThat(ag.isInfinite(0L)).isFalse(); assertThat(ag.isInfinite(23L)).isFalse(); assertThat(ag.isInfinite(Long.MA...
@Override public Page download(Request request, Task task) { if (task == null || task.getSite() == null) { throw new NullPointerException("task or site can not be null"); } CloseableHttpResponse httpResponse = null; CloseableHttpClient httpClient = getHttpClient(task.getS...
@Test public void test_download_fail() { HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Task task = Site.me().setDomain("localhost").setCycleRetryTimes(5).toTask(); Request request = new Request(PAGE_ALWAYS_NOT_EXISTS); Page page = httpClientDownloader.downlo...
@Override protected Function3<EntityColumnMapping, Object[], Map<String, Object>, Object> compile(String sql) { StringBuilder builder = new StringBuilder(sql.length()); int argIndex = 0; for (int i = 0; i < sql.length(); i++) { char c = sql.charAt(i); if (c == '?') {...
@Test void testAddNull(){ SpelSqlExpressionInvoker invoker = new SpelSqlExpressionInvoker(); EntityColumnMapping mapping = Mockito.mock(EntityColumnMapping.class); Function3<EntityColumnMapping, Object[], Map<String, Object>, Object> func = invoker.compile("IFNULL(test,0) + ?"); ass...
public static InstrumentedThreadFactory defaultThreadFactory(MetricRegistry registry, String name) { return new InstrumentedThreadFactory(Executors.defaultThreadFactory(), registry, name); }
@Test public void testDefaultThreadFactory() throws Exception { final ThreadFactory threadFactory = InstrumentedExecutors.defaultThreadFactory(registry); threadFactory.newThread(new NoopRunnable()); final Field delegateField = InstrumentedThreadFactory.class.getDeclaredField("delegate"); ...
public static void cleanDirectory(File directory) throws IOException { if (!directory.exists()) { String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { String message = directory...
@Test void testCleanDirectoryForNonExistingDirectory() throws IOException { assertThrows(IllegalArgumentException.class, () -> { File nonexistentDir = new File("non_exist"); IoUtils.cleanDirectory(nonexistentDir); }); }
protected void addNode(NodeEvent event) { String nodeName = event.getNodeName(); String url = event.getUrl(); String username = event.getUsername(); String password = event.getPassword(); Map<String, DataSource> map = highAvailableDataSource.getDataSourceMap(); if (nodeN...
@Test public void testAddNode() { String url = "jdbc:derby:memory:foo;create=true"; String name = "foo"; addNode(url, name); String targetUrl = ((DruidDataSource) haDataSource.getDataSourceMap().get(name)).getUrl(); assertEquals(1, haDataSource.getDataSourceMap().size()); ...
@Override public synchronized Snapshot record(long duration, TimeUnit durationUnit, Outcome outcome) { totalAggregation.record(duration, durationUnit, outcome); moveWindowByOne().record(duration, durationUnit, outcome); return new SnapshotImpl(totalAggregation); }
@Test public void testSlidingWindowMetricsWithSlowCalls() { FixedSizeSlidingWindowMetrics metrics = new FixedSizeSlidingWindowMetrics(2); Snapshot snapshot = metrics.record(100, TimeUnit.MILLISECONDS, Metrics.Outcome.SLOW_ERROR); assertThat(snapshot.getTotalNumberOfCalls()).isEqualTo(1); ...
public void writeTo(OutputStream out, int offset, int length) throws IOException { out.write(buffer, offset, length); }
@Test public void testWriteTo() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); RandomAccessData stream = new RandomAccessData(); stream.asOutputStream().write(TEST_DATA_B); stream.writeTo(baos, 1, 2); assertArrayEquals(new byte[] {0x05, 0x04}, baos.toByteArray()); ...
@Override public Optional<InetAddress> getLocalInetAddress(Predicate<InetAddress> predicate) { try { return Collections.list(NetworkInterface.getNetworkInterfaces()).stream() .flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) .filter(a -> a.getHostAddress() != null) .fi...
@Test public void getLocalInetAddress_filters_local_addresses() { InetAddress address = underTest.getLocalInetAddress(InetAddress::isLoopbackAddress).get(); assertThat(address.isLoopbackAddress()).isTrue(); }
public void loadV2(SRMetaBlockReader reader) throws IOException, SRMetaBlockException, SRMetaBlockEOFException { try { // 1 json for myself AuthorizationMgr ret = reader.readJson(AuthorizationMgr.class); ret.globalStateMgr = globalStateMgr; ret.provider = Objects....
@Test public void testLoadV2() throws Exception { GlobalStateMgr masterGlobalStateMgr = ctx.getGlobalStateMgr(); AuthorizationMgr masterManager = masterGlobalStateMgr.getAuthorizationMgr(); UtFrameUtils.PseudoJournalReplayer.resetFollowerJournalQueue(); setCurrentUserAndRoles(ctx, U...
public ConfigurationProperty create(String key, String value, String encryptedValue, Boolean isSecure) { ConfigurationProperty configurationProperty = new ConfigurationProperty(); configurationProperty.setConfigurationKey(new ConfigurationKey(key)); if (isNotBlank(value) && isNotBlank(encrypte...
@Test public void shouldCreateWithErrorsIfBothPlainAndEncryptedTextInputAreSpecifiedForSecureProperty() { Property key = new Property("key"); key.with(Property.SECURE, true); ConfigurationProperty property = new ConfigurationPropertyBuilder().create("key", "value", "enc_value", true); ...
public Map<String, String> match(String text) { final HashMap<String, String> result = MapUtil.newHashMap(true); int from = 0; String key = null; int to; for (String part : patterns) { if (StrUtil.isWrap(part, "${", "}")) { // 变量 key = StrUtil.sub(part, 2, part.length() - 1); } else { to = t...
@Test public void matcherTest(){ final StrMatcher strMatcher = new StrMatcher("${name}-${age}-${gender}-${country}-${province}-${city}-${status}"); final Map<String, String> match = strMatcher.match("小明-19-男-中国-河南-郑州-已婚"); assertEquals("小明", match.get("name")); assertEquals("19", match.get("age")); assertEqu...
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void tableNamedMaterializedCountWithTopologyConfigShouldPreserveTopologyStructure() { // override the default store into in-memory final StreamsBuilder builder = new StreamsBuilder(overrideDefaultStore(StreamsConfig.IN_MEMORY)); builder.table("input-topic") .groupBy(...
@Override public void isEqualTo(@Nullable Object expected) { super.isEqualTo(expected); }
@Test public void isEqualTo_WithoutToleranceParameter_Fail_NotAnArray() { expectFailureWhenTestingThat(array(2.2f, 3.3f, 4.4f)).isEqualTo(new Object()); }
@ExecuteOn(TaskExecutors.IO) @Get(uri = "/{executionId}") @Operation(tags = {"Executions"}, summary = "Get an execution") public Execution get( @Parameter(description = "The execution id") @PathVariable String executionId ) { return executionRepository .findById(tenantService...
@Test void badDate() { HttpClientResponseException exception = assertThrows(HttpClientResponseException.class, () -> client.toBlocking().retrieve(GET("/api/v1/executions/search?startDate=2024-06-03T00:00:00.000%2B02:00&endDate=2023-06-05T00:00:00.000%2B02:00"), PagedResults.class)); asse...
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { char subCommand = safeReadLine(reader).charAt(0); String returnCommand = null; if (subCommand == ARRAY_GET_SUB_COMMAND_NAME) { returnCommand = getArray(reader); } else if (s...
@Test public void testSetNoneInPrimitiveArray() { String inputCommand = ArrayCommand.ARRAY_SET_SUB_COMMAND_NAME + "\n" + target2 + "\ni1\nn\ne\n"; try { command.execute("a", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!yv\n", sWriter.toString()); assertNull(Array.get(array2,...
@JsonProperty public abstract OptionalInt to();
@Test void doesNotSupportOnlyToParameter() { assertThatThrownBy(() -> RelativeRange.Builder.builder() .to(60) .build()) .isInstanceOf(InvalidRangeParametersException.class) .hasMessage("If `to` is specified, `from` must be specified to!"); ...
@Public @Deprecated public static String toString(ApplicationId appId) { return appId.toString(); }
@Test void testContainerIdWithEpoch() throws URISyntaxException { ContainerId id = TestContainerId.newContainerId(0, 0, 0, 25645811); String cid = id.toString(); assertEquals("container_0_0000_00_25645811", cid); ContainerId gen = ContainerId.fromString(cid); assertEquals(gen.toString(), id.toStri...
@Override @Deprecated public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier, final String... stateStoreNames) { Objects.requireNonNul...
@Test @SuppressWarnings("deprecation") public void shouldNotAllowNullTransformerSupplierOnFlatTransformWithNamed() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.flatTransform(null, Named.as("flatTransformer"))); assert...
@Override public Object adapt(final HttpAction action, final WebContext context) { if (action != null) { var code = action.getCode(); val response = ((JEEContext) context).getNativeResponse(); if (code < 400) { response.setStatus(code); } else...
@Test public void testActionWithLocation() { JEEHttpActionAdapter.INSTANCE.adapt(new FoundAction(TestsConstants.PAC4J_URL), context); verify(response).setStatus(302); verify(context).setResponseHeader(HttpConstants.LOCATION_HEADER, TestsConstants.PAC4J_URL); }
@SuppressWarnings("unchecked") public static void addNamedOutput(Job job, String namedOutput, Class<? extends OutputFormat> outputFormatClass, Schema keySchema) { addNamedOutput(job, namedOutput, outputFormatClass, keySchema, null); }
@Test void avroGenericOutput() throws Exception { Job job = Job.getInstance(); FileInputFormat.setInputPaths(job, new Path(getClass().getResource("/org/apache/avro/mapreduce/mapreduce-test-input.txt").toURI().toString())); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(Li...
@SuppressWarnings("unchecked") @Override public void execute(String mapName, Predicate predicate, Collection<Integer> partitions, Result result) { runUsingPartitionScanWithoutPaging(mapName, predicate, partitions, result); if (predicate instanceof PagingPredicateImpl pagingPredicate) { ...
@Test public void execute_success() throws Exception { IPartitionService partitionService = mock(IPartitionService.class); when(partitionService.getPartitionCount()).thenReturn(271); PartitionScanRunner runner = mock(PartitionScanRunner.class); ReflectionUtils.setFieldValueReflective...
@Override public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) { XmlStringBuilder xml = new XmlStringBuilder(this, enclosingNamespace); xml.rightAngleBracket(); xml.emptyElement(compressFailureError); xml.optElement(stanzaError); xm...
@Test public void withStanzaErrrorFailureTest() throws SAXException, IOException { StanzaError stanzaError = StanzaError.getBuilder() .setCondition(Condition.bad_request) .build(); Failure failure = new Failure(Failure.CompressFailureError.setup_failed...
public ConcurrentMap<Integer, Long> getOffsetTable() { return offsetTable; }
@Test public void testGetOffsetTable_ShouldReturnConcurrentHashMap() { ConcurrentMap<Integer, Long> offsetTable = wrapper.getOffsetTable(); assertNotNull("The offsetTable should not be null", offsetTable); }
public static <K, V> PerKeyDistinct<K, V> perKey() { return PerKeyDistinct.<K, V>builder().build(); }
@Test public void perKey() { final int cardinality = 1000; final int p = 15; final double expectedErr = 1.04 / Math.sqrt(p); List<Integer> stream = new ArrayList<>(); for (int i = 1; i <= cardinality; i++) { stream.addAll(Collections.nCopies(2, i)); } Collections.shuffle(stream); ...
public static DarkClusterConfigMap toConfig(Map<String, Object> properties) { DarkClusterConfigMap configMap = new DarkClusterConfigMap(); for (Map.Entry<String, Object> entry : properties.entrySet()) { String darkClusterName = entry.getKey(); DarkClusterConfig darkClusterConfig = new DarkClus...
@Test public void testBadStrategies() { Map<String, Object> props = new HashMap<>(); List<String> myStrategyList = new ArrayList<>(); myStrategyList.add("RELATIVE_TRAFFIC"); myStrategyList.add("BLAH_BLAH"); Map<String, Object> darkClusterMap = new HashMap<>(); darkClusterMap.put(PropertyKey...