focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void createGroupTombstoneRecords( String groupId, List<CoordinatorRecord> records ) { // At this point, we have already validated the group id, so we know that the group exists and that no exception will be thrown. createGroupTombstoneRecords(group(groupId), records); }
@Test public void testClassicGroupDelete() { GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .build(); context.createClassicGroup("group-id"); List<CoordinatorRecord> expectedRecords = Collections.singletonList(GroupCoordinatorRecordHelper...
protected FileAppender<E> buildAppender(LoggerContext context) { if (archive) { final RollingFileAppender<E> appender = new RollingFileAppender<>(); appender.setContext(context); appender.setFile(currentLogFilename); appender.setBufferSize(new FileSize(bufferSize....
@Test void validSetTotalSizeCapNoMaxFileSize() throws IOException, ConfigurationException { final YamlConfigurationFactory<FileAppenderFactory> factory = new YamlConfigurationFactory<>(FileAppenderFactory.class, validator, mapper, "dw"); final FileAppender appender = factory.build(new R...
public HttpResponse getLogs(ApplicationId applicationId, Optional<DomainName> hostname, Query apiParams) { Exception exception = null; for (var uri : getLogServerUris(applicationId, hostname)) { try { return logRetriever.getLogs(uri.withQuery(apiParams), activationTime(applic...
@Test public void getLogs() throws IOException { deployApp(testAppLogServerWithContainer); HttpResponse response = applicationRepository.getLogs(applicationId(), Optional.empty(), Query.empty()); assertEquals(200, response.getStatus()); ByteArrayOutputStream buffer = new ByteArrayOut...
@Override public ContainerReport getContainerReport(ContainerId containerId) throws YarnException, IOException { ApplicationReport appReport = getApplicationReport( containerId.getApplicationAttemptId().getApplicationId()); TimelineEntity entity = readerClient.getContainerEntity(containerId, ...
@Test public void testGetContainerReport() throws IOException, YarnException { final ApplicationId appId = ApplicationId.newInstance(0, 1); final ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); final ContainerId containerId = ContainerId.newContainerId(appAttemptId,...
List<TaskDirectory> listAllTaskDirectories() { return listTaskDirectories(pathname -> pathname.isDirectory() && TASK_DIR_PATH_NAME.matcher(pathname.getName()).matches()); }
@Test public void shouldReturnEmptyArrayIfListFilesReturnsNull() throws IOException { stateDir = new File(TestUtils.IO_TMP_DIR, "kafka-" + TestUtils.randomString(5)); directory = new StateDirectory( new StreamsConfig(new Properties() { { put(StreamsCon...
public static <E> LinkedList<E> newLinkedList() { return new LinkedList<>(); }
@Test public void testItrLinkedLists() { Set<String> set = new HashSet<>(); set.add("record1"); set.add("record2"); set.add("record3"); List<String> list = Lists.newLinkedList(set); list.add("record4"); Assert.assertEquals(4, list.size()); }
public CompletableFuture<Map<TopicIdPartition, ShareAcknowledgeResponseData.PartitionData>> acknowledge( String memberId, String groupId, Map<TopicIdPartition, List<ShareAcknowledgementBatch>> acknowledgeTopics ) { log.trace("Acknowledge request for topicIdPartitions: {} with groupId...
@Test public void testAcknowledgeIncorrectGroupId() { String groupId = "grp"; String groupId2 = "grp2"; String memberId = Uuid.randomUuid().toString(); TopicIdPartition tp = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("foo", 0)); SharePartition sp = mock(Share...
public static Throwable peel(@Nullable Throwable t) { while ((t instanceof CompletionException || t instanceof ExecutionException || t instanceof InvocationTargetException) && t.getCause() != null && t.getCause() != t ) { t = t....
@Test public void when_throwableIsRuntimeException_then_peelReturnsOriginal() { Throwable throwable = new RuntimeException("expected exception"); Throwable result = peel(throwable); assertEquals(throwable, result); }
public JmxCollector register() { return register(PrometheusRegistry.defaultRegistry); }
@Test public void testValueCaptureGroup() throws Exception { JmxCollector jc = new JmxCollector( "\n---\nrules:\n- pattern: `^hadoop<.+-500(10)>`\n name: foo\n value: $1" .replace('`', '"')) .re...
@Override public boolean isCancelled() { return original.isCancelled() || peel().isCancelled(); }
@Test public void isCancelled() throws Exception { ScheduledFuture<Object> outer = createScheduledFutureMock(); ScheduledFuture<Object> inner = createScheduledFutureMock(); when(outer.get()).thenReturn(inner); when(outer.isCancelled()).thenReturn(false); when(inner.isCancell...
public static byte[] readBytes(ByteBuffer buffer) { return readBytes(buffer, 0, buffer.remaining()); }
@Test public void readBytesFromArrayBackedByteBuffer() { final byte[] bytes = "FOOBAR".getBytes(StandardCharsets.US_ASCII); final ByteBuffer buffer1 = ByteBuffer.wrap(bytes); final ByteBuffer buffer2 = ByteBuffer.wrap(bytes); final byte[] readBytesComplete = ByteBufferUtils.readBytes...
@Override public void processElement2(StreamRecord<IN2> element) throws Exception { collector.setTimestamp(element); rwContext.setElement(element); userFunction.processBroadcastElement(element.getValue(), rwContext, collector); rwContext.setElement(null); }
@Test void testNoKeyedStateOnBroadcastSide() throws Exception { final ValueStateDescriptor<String> valueState = new ValueStateDescriptor<>("any", BasicTypeInfo.STRING_TYPE_INFO); try (TwoInputStreamOperatorTestHarness<String, Integer, String> testHarness = getInitial...
public synchronized void useBundles(List<FileReference> newFileReferences) { if (! readyForNewBundles) throw new IllegalStateException("Bundles must be committed or reverted before using new bundles."); obsoleteBundles = removeObsoleteReferences(newFileReferences); osgi.allowDuplica...
@Test void generation_must_be_marked_complete_before_using_new_bundles() { bundleLoader.useBundles(List.of(BUNDLE_1_REF)); assertThrows(IllegalStateException.class, () -> bundleLoader.useBundles(List.of(BUNDLE_1_REF))); }
@Override public Object getWrappedValue() { return predicate; }
@Test public void requireThatWrappedValueIsPredicate() { Predicate predicate = SimplePredicates.newPredicate(); PredicateFieldValue value = new PredicateFieldValue(predicate); assertSame(predicate, value.getWrappedValue()); }
public static SchemaAndValue parseString(String value) { if (value == null) { return NULL_SCHEMA_AND_VALUE; } if (value.isEmpty()) { return new SchemaAndValue(Schema.STRING_SCHEMA, value); } ValueParser parser = new ValueParser(new Parser(value)); ...
@Test public void shouldParseTimeStringAsTimeInMap() throws Exception { String keyStr = "k1"; String timeStr = "14:34:54.346Z"; String mapStr = "{\"" + keyStr + "\":" + timeStr + "}"; SchemaAndValue result = Values.parseString(mapStr); assertEquals(Type.MAP, result.schema().t...
@Override public Iterator<IndexKeyEntries> getSqlRecordIteratorBatch(@Nonnull Comparable value, boolean descending) { return getSqlRecordIteratorBatch(value, descending, null); }
@Test public void getRecordsWithCursorUsingExactValueAscending() { var expectedOrder = List.of(1, 4, 7); performCursorTest(expectedOrder, cursor -> store.getSqlRecordIteratorBatch(1, false, cursor)); }
public static List<FieldSchema> convert(Schema schema) { return schema.columns().stream() .map(col -> new FieldSchema(col.name(), convertToTypeString(col.type()), col.doc())) .collect(Collectors.toList()); }
@Test public void testConversionWithoutLastComment() { Schema expected = new Schema( optional(0, "customer_id", Types.LongType.get(), "customer comment"), optional(1, "first_name", Types.StringType.get(), null)); Schema schema = HiveSchemaUtil.convert( Arra...
public static Builder builder(String bucket, String testClassName, Credentials credentials) { checkArgument(!bucket.equals("")); checkArgument(!testClassName.equals("")); return new Builder(bucket, testClassName, credentials); }
@Test public void testBuilderWithEmptyBucket() { assertThrows( IllegalArgumentException.class, () -> GcsResourceManager.builder("", TEST_CLASS, null).build()); }
@Override public boolean isEmpty() { return false; }
@Test public void testIsEmpty() { IntSet rs = new SingletonIntSet(3); assertFalse(rs.isEmpty()); }
public JSONObject set(String key, Object value) throws JSONException { return set(key, value, null, false); }
@Test public void toBeanTest() { final JSONObject subJson = JSONUtil.createObj().set("value1", "strValue1").set("value2", "234"); final JSONObject json = JSONUtil.createObj().set("strValue", "strTest").set("intValue", 123) // 测试空字符串转对象 .set("doubleValue", "") .set("beanValue", subJson) .set("list", JSO...
public void project() { srcPotentialIndex = 0; trgPotentialIndex = 0; recurse(0, 0); BayesAbsorption.normalize(trgPotentials); }
@Test public void testProjection1() { // Projects from node1 into sep. A and B are in node1. A and B are in the sep. // this is a straight forward projection BayesVariable a = new BayesVariable<String>( "A", 0, new String[] {"A1", "A2"}, null); BayesVariable b = new BayesVariable<Str...
public static boolean acceptEndpoint(String endpointUrl) { return endpointUrl != null && endpointUrl.matches(ENDPOINT_PATTERN_STRING); }
@Test public void testAcceptEndpoint() { assertTrue(AMQPMessageConsumptionTask.acceptEndpoint("amqp://localhost/q/testQueue")); assertTrue(AMQPMessageConsumptionTask.acceptEndpoint("amqp://localhost/vHost/q/testQueue")); assertTrue(AMQPMessageConsumptionTask.acceptEndpoint("amqp://localhost:5671...
public String getName() { return name; }
@Test void testConstructor() { Method method = new Method("bar"); assertNotNull(method); assertEquals("bar", method.getName()); }
public static Expression rewrite(Expression expression, VariableAllocator variableAllocator) { return ExpressionTreeRewriter.rewriteWith(new Visitor(variableAllocator), expression, new Context()); }
@Test public void testRewriteBasicLambda() { final List<VariableReferenceExpression> variables = ImmutableList.of(new VariableReferenceExpression(Optional.empty(), "a", BIGINT), new VariableReferenceExpression(Optional.empty(), "x", BIGINT)); final VariableAllocator allocator = new VariableAlloc...
public ProviderBuilder port(Integer port) { this.port = port; return getThis(); }
@Test void port() { ProviderBuilder builder = ProviderBuilder.newBuilder(); builder.port(8080); Assertions.assertEquals(8080, builder.build().getPort()); }
public void validateAndMergeOutputParams(StepRuntimeSummary runtimeSummary) { Optional<String> externalJobId = extractExternalJobId(runtimeSummary); if (externalJobId.isPresent()) { Optional<OutputData> outputDataOpt = outputDataDao.getOutputDataForExternalJob(externalJobId.get(), ExternalJobTyp...
@Test public void testMissingOutputParams() { runtimeSummary = runtimeSummaryBuilder().artifacts(artifacts).build(); outputDataManager.validateAndMergeOutputParams(runtimeSummary); assertTrue(runtimeSummary.getParams().isEmpty()); }
public Optional<Snapshot> getSnapshotAndReset() { if (!dirty.getAndSet(false)) { return Optional.empty(); } ImmutableLongArray.Builder bucketsSnapshotBuilder = ImmutableLongArray.builder(buckets.length()); for (int i = 0; i < buckets.length(); i++) { bucketsSnapshotBuilder.add(bucke...
@Test public void testUpdateAndSnapshots_MultipleThreads() { int numRunnables = 200; ExecutorService executor = Executors.newFixedThreadPool(numRunnables); HistogramData.BucketType bucketType = HistogramData.ExponentialBuckets.of(1, 10); LockFreeHistogram histogram = new LockFreeHistogram(Met...
@Override public void updateNetworkPolicy(NetworkPolicy networkPolicy) { checkNotNull(networkPolicy, ERR_NULL_NETWORK_POLICY); checkArgument(!Strings.isNullOrEmpty(networkPolicy.getMetadata().getUid()), ERR_NULL_NETWORK_POLICY_UID); k8sNetworkPolicyStore.updateNetworkPolicy(...
@Test(expected = IllegalArgumentException.class) public void testUpdateUnregisteredNetworkPolicy() { target.updateNetworkPolicy(NETWORK_POLICY); }
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void testSinkSupportConcurrentExecutionAttempts() { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(new Configuration()); env.setRuntimeMode(RuntimeExecutionMode.BATCH); final DataStream<Integer> source = env.fromData(1, 2, 3)....
@Override public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { final EueApiClient client = new EueApiClient(session); if(status.isExists()) { ...
@Test public void testCopyFile() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final Path sourceFolder = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(AbstractPath.Type.directory)); final Path sourceFile = new Path(sourceFol...
@Nullable static String getHeaderIfString(Message message, String name) { MessageProperties properties = message.getMessageProperties(); if (properties == null) return null; Object o = properties.getHeader(name); if (o instanceof String) return o.toString(); return null; }
@Test void getHeaderIfString_null() { assertThat(MessageHeaders.getHeaderIfString(message, "b3")).isNull(); }
public static <T> T retry(Callable<T> callable, int retries) { return retry(callable, retries, Collections.emptyList()); }
@Test(expected = RuntimeException.class) public void retryRetriesFailed() throws Exception { // given given(callable.call()).willThrow(new RuntimeException()).willThrow(new RuntimeException()).willReturn(RESULT); // when RetryUtils.retry(callable, RETRIES); // t...
@Override public Object read(final MySQLPacketPayload payload, final boolean unsigned) throws SQLException { int length = payload.readInt1(); switch (length) { case 0: throw new SQLFeatureNotSupportedException("Can not support date format if year, month, day is absent.");...
@Test void assertReadWithFourBytes() throws SQLException { when(payload.readInt1()).thenReturn(4, 12, 31); when(payload.readInt2()).thenReturn(2018); LocalDateTime actual = LocalDateTime.ofInstant(Instant.ofEpochMilli(((Timestamp) new MySQLDateBinaryProtocolValue().read(payload, false)).getT...
@Override public Transfer withCache(final Cache<Path> cache) { this.cache = cache; return this; }
@Test public void testCacheResume() throws Exception { final AtomicInteger c1 = new AtomicInteger(); final AtomicInteger c2 = new AtomicInteger(); final NullLocal local = new NullLocal("t") { @Override public AttributedList<Local> list() { AttributedLi...
@VisibleForTesting static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) { return createStreamExecutionEnvironment( options, MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()), options.getFlinkConfDir()); }
@Test public void shouldFailOnNoStoragePathProvided() { FlinkPipelineOptions options = getDefaultPipelineOptions(); options.setStreaming(true); options.setStateBackend("unknown"); assertThrows( "State backend was set to 'unknown' but no storage path was provided.", IllegalArgumentExce...
@Override protected void rename( List<HadoopResourceId> srcResourceIds, List<HadoopResourceId> destResourceIds, MoveOptions... moveOptions) throws IOException { if (moveOptions.length > 0) { throw new UnsupportedOperationException("Support for move options is not yet implemented."); ...
@Test(expected = FileNotFoundException.class) public void testRenameMissingSource() throws Exception { fileSystem.rename( ImmutableList.of(testPath("missingFile")), ImmutableList.of(testPath("testFileA"))); }
static String encodeTokenValue(String value) throws URISyntaxException { return URISupport.createQueryString(Collections.singletonMap("x", value)).substring(2) .replace("+", "%2B") // sig is base64 .replace("%3A", ":"); // se has time separator }
@Test void encodeTokenValueShouldPreserveTimeSeparator() throws Exception { // e.g. for the se param on SAS token the encoding style must preserve ':' assertEquals("11:55:01", FilesURIStrings.encodeTokenValue("11:55:01")); }
@Override public void define(WebService.NewController context) { WebService.NewAction action = context .createAction("list") .setSince("4.2") .setDescription("List web services") .setResponseExample(getClass().getResource("list-example.json")) .setHandler(this); action .cr...
@Test public void list() { new MetricWs().define(context); String response = newRequest().execute().getInput(); assertJson(response).withStrictArrayOrder().isSimilarTo(getClass().getResource("list-example.json")); }
public final void setStrictness(Strictness strictness) { Objects.requireNonNull(strictness); this.strictness = strictness; }
@Test public void testEscapedNewlineNotAllowedInStrictMode() { String json = "\"\\\n\""; JsonReader reader = new JsonReader(reader(json)); reader.setStrictness(Strictness.STRICT); IOException expected = assertThrows(IOException.class, reader::nextString); assertThat(expected) .hasMessageT...
@Override public Optional<ShardingConditionValue> generate(final BinaryOperationExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) { String operator = predicate.getOperator().toUpperCase(); if (!isSupportedOperator(operator)) { ...
@SuppressWarnings("unchecked") @Test void assertGenerateConditionValueWithAtLeastOperator() { BinaryOperationExpression rightValue = new BinaryOperationExpression(0, 0, mock(ColumnSegment.class), new LiteralExpressionSegment(0, 0, 1), ">=", null); Optional<ShardingConditionValue> shardingConditi...
@Override public void start() { Optional<String> passcodeOpt = configuration.get(WEB_SYSTEM_PASS_CODE.getKey()) // if present, result is never empty string .map(StringUtils::trimToNull); if (passcodeOpt.isPresent()) { logState("enabled"); configuredPasscode = passcodeOpt.get(); } ...
@Test public void startup_logs_show_that_feature_is_disabled() { underTest.start(); assertThat(logTester.logs(Level.INFO)).contains("System authentication by passcode is disabled"); }
@Override public StreamsMaterializedTable nonWindowed() { if (windowInfo.isPresent()) { throw new UnsupportedOperationException("Table has windowed key"); } return new KsMaterializedTable(stateStore); }
@Test(expected = UnsupportedOperationException.class) public void shouldThrowOnNonWindowedIfWindowed() { // Given: givenWindowType(Optional.of(WindowType.SESSION)); // When: materialization.nonWindowed(); }
@Override @DSTransactional // 多数据源,使用 @DSTransactional 保证本地事务,以及数据源的切换 public void updateTenant(TenantSaveReqVO updateReqVO) { // 校验存在 TenantDO tenant = validateUpdateTenant(updateReqVO.getId()); // 校验租户名称是否重复 validTenantNameDuplicate(updateReqVO.getName(), updateReqVO.getId()); ...
@Test public void testUpdateTenant_notExists() { // 准备参数 TenantSaveReqVO reqVO = randomPojo(TenantSaveReqVO.class); // 调用, 并断言异常 assertServiceException(() -> tenantService.updateTenant(reqVO), TENANT_NOT_EXISTS); }
@Override public Data getValueData() { if (valueData == null) { valueData = serializationService.toData(valueObject); } return valueData; }
@Override @Test public void getValueData_caching() { QueryableEntry entry = createEntry("key", "value"); assertSame(entry.getValueData(), entry.getValueData()); }
@Override public URL getResource(String name) { ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name); log.trace("Received request to load resource '{}'", name); for (ClassLoadingStrategy.Source classLoadingSource : loadingStrategy.getSources()) { URL url = null; ...
@Test void parentFirstGetResourceExistsOnlyInPlugin() throws IOException, URISyntaxException { URL resource = parentFirstPluginClassLoader.getResource("META-INF/plugin-file"); assertFirstLine("plugin", resource); }
public void setPolicy(String policyName, NamespaceIsolationData policyData) { policyData.validate(); policies.put(policyName, (NamespaceIsolationDataImpl) policyData); }
@Test public void testSetPolicy() throws Exception { NamespaceIsolationPolicies policies = this.getDefaultTestPolicies(); // set a new policy String newPolicyJson = "{\"namespaces\":[\"pulsar/use/TESTNS.*\"],\"primary\":[\"prod1-broker[45].messaging.use.example.com\"],\"secondary\":[\"prod1-...
@Override @SuppressWarnings("checkstyle:npathcomplexity") public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AbstractRecord<?> that = (AbstractRecord<?>) o; if ...
@Test public void testEquals() { assertEquals(record, record); assertEquals(record, recordSameAttributes); assertNotEquals(null, record); assertNotEquals(new Object(), record); assertNotEquals(record, recordOtherVersion); assertNotEquals(record, recordOtherCreationT...
public static InternalLogger getInstance(Class<?> clazz) { return getInstance(clazz.getName()); }
@Test public void testInfo() { final InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.info("a"); verify(mockLogger).info("a"); }
public static String localIP() { if (!StringUtils.isEmpty(localIp)) { return localIp; } if (System.getProperties().containsKey(CLIENT_LOCAL_IP_PROPERTY)) { return localIp = System.getProperty(CLIENT_LOCAL_IP_PROPERTY, getAddress()); } localIp = getAddress(...
@Test void testLocalIpWithSpecifiedIp() { System.setProperty("com.alibaba.nacos.client.local.ip", "10.2.8.8"); assertEquals("10.2.8.8", NetUtils.localIP()); System.setProperty("com.alibaba.nacos.client.local.ip", "10.2.8.9"); assertEquals("10.2.8.8", NetUtils.localIP()); }
public HttpResult getBinary(String url) throws IOException, NotModifiedException { return getBinary(url, null, null); }
@Test void validFeed() throws Exception { this.mockServerClient.when(HttpRequest.request().withMethod("GET")) .respond(HttpResponse.response() .withBody(feedContent) .withContentType(MediaType.APPLICATION_ATOM_XML) .withHeader(HttpHeaders.LAST_MODIFIED, "123456") .withHeader(HttpHeaders.E...
public static RDA fit(double[][] x, int[] y, Properties params) { double alpha = Double.parseDouble(params.getProperty("smile.rda.alpha", "0.9")); double[] priori = Strings.parseDoubleArray(params.getProperty("smile.rda.priori")); double tol = Double.parseDouble(params.getProperty("smile.rda.tol...
@Test public void testBreastCancer() { System.out.println("Breast Cancer"); MathEx.setSeed(19650218); // to get repeatable results. ClassificationValidations<RDA> result = CrossValidation.classification(10, BreastCancer.x, BreastCancer.y, (x, y) -> RDA.fit(x, y, 0.9)); ...
@Override public int choosePartition(Message<?> msg, TopicMetadata topicMetadata) { // If the message has a key, it supersedes the round robin routing policy if (msg.hasKey()) { return signSafeMod(hash.makeHash(msg.getKey()), topicMetadata.numPartitions()); } if (isBatch...
@Test public void testChoosePartitionWithoutKeyWithBatching() { Message<?> msg = mock(Message.class); Mockito.when(msg.getKey()).thenReturn(null); // Fake clock, simulate 1 millisecond passes for each invocation Clock clock = new Clock() { private long current = 0; ...
@Override public Void handleResponse(Response response) throws IOException, UnexpectedBlobDigestException { blobSizeListener.accept(response.getContentLength()); try (OutputStream outputStream = new NotifyingOutputStream(destinationOutputStream, writtenByteCountListener)) { BlobDescriptor recei...
@Test public void testHandleResponse_unexpectedDigest() throws IOException { InputStream blobContent = new ByteArrayInputStream("some BLOB content".getBytes(StandardCharsets.UTF_8)); DescriptorDigest testBlobDigest = Digests.computeDigest(blobContent).getDigest(); blobContent.reset(); Respons...
public static Ip4Prefix valueOf(int address, int prefixLength) { return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfAddressTooLongPrefixLengthIPv4() { Ip4Address ipAddress; Ip4Prefix ipPrefix; ipAddress = Ip4Address.valueOf("1.2.3.4"); ipPrefix = Ip4Prefix.valueOf(ipAddress, 33); }
@Override public int intValue() { return value; }
@Test public void testIntValue() { assertEquals(100, MilliPct.ofMilliPct(100).intValue()); assertEquals(-100, MilliPct.ofMilliPct(-100).intValue()); }
private ImageConverter() {}
@Test public void testImageConverter() { ImmutableFeatureMap fmap = constructFeatureMap(); Example<MockOutput> e = constructExample(); // 3,3,2 ImageConverter first = new ImageConverter("test",3,3,2); FloatNdArray ndarray = (TFloat32) first.convert(e,fmap).getMap().get("test...
public static KTableHolder<GenericKey> build( final KGroupedStreamHolder groupedStream, final StreamAggregate aggregate, final RuntimeBuildContext buildContext, final MaterializedFactory materializedFactory) { return build( groupedStream, aggregate, buildContext, ...
@Test @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT") public void shouldBuildTumblingWindowedAggregateCorrectly() { // Given: givenTumblingWindowedAggregate(); // When: final KTableHolder<Windowed<GenericKey>> result = windowedAggregate.build(planBuilder, planInfo); // Then: ...
public static Builder builder() { return new Builder(); }
@Test // Test cases that are JSON that can be created via the Builder public void testRoundTripSerDe() throws JsonProcessingException { String fullJson = "{\"namespace\":[\"accounting\",\"tax\"],\"properties\":{\"owner\":\"Hank\"}}"; CreateNamespaceRequest req = CreateNamespaceRequest.builde...
@Override public void onMessage(final String result) { if (LOG.isDebugEnabled()) { LOG.debug("onMessage server[{}] result({})", this.getURI().toString(), result); } Map<String, Object> jsonToMap = JsonUtils.jsonToMap(result); Object eventType = jsonToMap.get(Runn...
@Test public void testOnMessage() { doNothing().when(pluginDataSubscriber).onSubscribe(any()); String json = GsonUtils.getInstance().toJson(websocketData); shenyuWebsocketClient.onMessage(json); verify(pluginDataSubscriber).onSubscribe(any()); }
public File getDataDirectory() { return dataDirectory; }
@Test public void override_data_dir() throws Exception { File sqHomeDir = temp.newFolder(); File tempDir = temp.newFolder(); File dataDir = temp.newFolder(); Props props = new Props(new Properties()); props.set(PATH_HOME.getKey(), sqHomeDir.getAbsolutePath()); props.set(PATH_TEMP.getKey(), tem...
public static <KLeftT, KRightT> KTableHolder<KLeftT> build( final KTableHolder<KLeftT> left, final KTableHolder<KRightT> right, final ForeignKeyTableTableJoin<KLeftT, KRightT> join, final RuntimeBuildContext buildContext ) { final LogicalSchema leftSchema = left.getSchema(); final Logi...
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void shouldDoLeftJoinOnKey() { // Given: givenLeftJoin(left, L_KEY); // When: final KTableHolder<Struct> result = join.build(planBuilder, planInfo); // Then: final ArgumentCaptor<KsqlKeyExtractor> ksqlKeyExtractor = Argument...
@Override public int generate(final Properties props) { int result = loadExistedWorkerId().orElseGet(this::generateNewWorkerId); logWarning(result, props); return result; }
@Test void assertGenerateWithoutExistedWorkerId() { ClusterPersistRepository repository = mock(ClusterPersistRepository.class); doAnswer((Answer<Object>) invocation -> Boolean.TRUE).when(repository).persistExclusiveEphemeral("/reservation/worker_id/0", "foo_id"); assertThat(new ClusterWorker...
public static SchemaPairCompatibility checkReaderWriterCompatibility(final Schema reader, final Schema writer) { final SchemaCompatibilityResult compatibility = new ReaderWriterCompatibilityChecker().getCompatibility(reader, writer); final String message; switch (compatibility.getCompatibility()) {...
@Test void validateArrayWriterSchema() { final Schema validReader = Schema.createArray(STRING_SCHEMA); final Schema invalidReader = Schema.createMap(STRING_SCHEMA); final SchemaCompatibility.SchemaPairCompatibility validResult = new SchemaCompatibility.SchemaPairCompatibility( SchemaCompatibility....
public synchronized void executeDdlStatement(String statement) throws IllegalStateException { checkIsUsable(); maybeCreateInstance(); maybeCreateDatabase(); LOG.info("Executing DDL statement '{}' on database {}.", statement, databaseId); try { databaseAdminClient .updateDatabaseDdl(...
@Test public void testExecuteDdlStatementShouldThrowExceptionWhenSpannerUpdateDatabaseFails() throws ExecutionException, InterruptedException { // arrange prepareCreateInstanceMock(); prepareCreateDatabaseMock(); when(spanner.getDatabaseAdminClient().updateDatabaseDdl(any(), any(), any(), any())...
@VisibleForTesting void recover() { try (DbSession dbSession = dbClient.openSession(false)) { Profiler profiler = Profiler.create(LOGGER).start(); long beforeDate = system2.now() - minAgeInMs; IndexingResult result = new IndexingResult(); Collection<EsQueueDto> items = dbClient.esQueueDao...
@Test public void do_not_stop_run_if_success_rate_is_greater_than_circuit_breaker() { IntStream.range(0, 10).forEach(i -> insertItem(FOO_TYPE, "" + i)); advanceInTime(); // 10 docs to process, by groups of 5. // Each group successfully recovers 4 docs --> below 30% of failures --> continue run Pa...
public static void main(String[] args) { var filterManager = new FilterManager(); filterManager.addFilter(new NameFilter()); filterManager.addFilter(new ContactFilter()); filterManager.addFilter(new AddressFilter()); filterManager.addFilter(new DepositFilter()); filterManager.addFilter(new Order...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public double dot(SGDVector other) { if (other.size() != size) { throw new IllegalArgumentException("Can't dot two vectors of different lengths, this = " + size + ", other = " + other.size()); } else if (other instanceof SparseVector) { double score = 0.0; ...
@Test public void emptyDot() { SparseVector a = generateVectorA(); SparseVector b = generateVectorB(); SparseVector c = generateVectorC(); SparseVector empty = generateEmptyVector(); assertEquals(a.dot(empty),empty.dot(a),1e-10); assertEquals(0.0, a.dot(empty),1e-10)...
private long getLastInsertId(final Collection<UpdateResult> updateResults, final Collection<Comparable<?>> autoIncrementGeneratedValues) { List<Long> lastInsertIds = new ArrayList<>(updateResults.size() + autoIncrementGeneratedValues.size()); for (UpdateResult each : updateResults) { if (eac...
@Test void assertGetLastInsertIdWhenExecuteResultIsNotEmpty() { UpdateResponseHeader actual = new UpdateResponseHeader(mock(SQLStatement.class), createExecuteUpdateResults()); assertThat(actual.getLastInsertId(), is(2L)); }
@Override public Stream<HoodieBaseFile> getLatestBaseFiles(String partitionPath) { return execute(partitionPath, preferredView::getLatestBaseFiles, (path) -> getSecondaryView().getLatestBaseFiles(path)); }
@Test public void testGetLatestBaseFiles() { Stream<HoodieBaseFile> actual; Stream<HoodieBaseFile> expected = testBaseFileStream; when(primary.getLatestBaseFiles()).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFiles(); assertEquals(expected, actual); verify(secondaryViewSuppli...
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void booleanFalseLiteral() { String inputExpression = "false"; BaseNode bool = parse( inputExpression ); assertThat( bool).isInstanceOf(BooleanNode.class); assertThat( bool.getResultType()).isEqualTo(BuiltInType.BOOLEAN); assertLocation( inputExpression, bool ); }
public final void containsNoneOf( @Nullable Object firstExcluded, @Nullable Object secondExcluded, @Nullable Object @Nullable ... restOfExcluded) { containsNoneIn(accumulate(firstExcluded, secondExcluded, restOfExcluded)); }
@Test public void iterableContainsNoneOfFailureWithDuplicateInExpected() { expectFailureWhenTestingThat(asList(1, 2, 3)).containsNoneOf(1, 2, 2, 4); assertFailureValue("but contained", "[1, 2]"); }
@Bean public ShenyuPlugin resilience4JPlugin() { return new Resilience4JPlugin(new CombinedExecutor(), new RateLimiterExecutor()); }
@Test public void testResilience4JPlugin() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(Resilience4JPluginConfiguration.class)) .withBean(Resilience4JPluginConfigurationTest.class) .withPropertyValues("debug=true") .run(context -> ...
@Override public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewKey(), "New name must not be null!"); byte[] k...
@Test public void testRename_keyNotExist() { Integer originalSlot = getSlotForKey(originalKey); newKey = getNewKeyForSlot(new String(originalKey.array()), getTargetSlot(originalSlot)); if (sameSlot) { // This is a quirk of the implementation - since same-slot renames use the non...
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldBuildCorrectSerde() { // Given: final ConfiguredStatement<InsertValues> statement = givenInsertValues( valueColumnNames(SCHEMA), ImmutableList.of( new StringLiteral("str"), new LongLiteral(2L) ) ); // When: executor.execute(s...
public void run() { try { InputStreamReader isr = new InputStreamReader( this.is ); BufferedReader br = new BufferedReader( isr ); String line = null; while ( ( line = br.readLine() ) != null ) { String logEntry = this.type + " " + line; switch ( this.logLevel ) { c...
@Test public void testLogBasic() { streamLogger = new ConfigurableStreamLogger( log, is, LogLevel.BASIC, PREFIX ); streamLogger.run(); Mockito.verify( log ).logBasic( OUT1 ); Mockito.verify( log ).logBasic( OUT2 ); }
public void setDerbyOpsEnabled(boolean derbyOpsEnabled) { this.derbyOpsEnabled = derbyOpsEnabled; }
@Test void testSetDerbyOpsEnabled() { assertFalse(commonConfig.isDerbyOpsEnabled()); commonConfig.setDerbyOpsEnabled(true); assertTrue(commonConfig.isDerbyOpsEnabled()); }
public static MockRepositoryImporter getMockRepositoryImporter(File mockRepository, ReferenceResolver referenceResolver) throws IOException { MockRepositoryImporter importer = null; // Analyse first lines of file content to guess repository type. String line = null; try (BufferedReader...
@Test void testGetMockRepositoryImporter() { // Load a SoapUI file. File soapUIProject = new File("../samples/HelloService-soapui-project.xml"); MockRepositoryImporter importer = null; try { importer = MockRepositoryImporterFactory.getMockRepositoryImporter(soapUIProject, null); ...
void runOnce() { if (transactionManager != null) { try { transactionManager.maybeResolveSequences(); RuntimeException lastError = transactionManager.lastError(); // do not continue sending if the transaction manager is in a failed state ...
@Test public void testEpochBumpOnOutOfOrderSequenceForNextBatchWhenThereIsNoBatchInFlight() throws Exception { // Verify that partitions without in-flight batches when the producer epoch // is bumped get their sequence number reset correctly. final long producerId = 343434L; Transact...
@Override @CacheEvict(cacheNames = RedisKeyConstants.OAUTH_CLIENT, allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 key,不好清理 public void deleteOAuth2Client(Long id) { // 校验存在 validateOAuth2ClientExists(id); // 删除 oauth2ClientMapper.deleteById(id); }
@Test public void testDeleteOAuth2Client_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> oauth2ClientService.deleteOAuth2Client(id), OAUTH2_CLIENT_NOT_EXISTS); }
public MessageReceiptHandle removeReceiptHandle(ProxyContext context, Channel channel, String group, String msgID, String receiptHandle) { ReceiptHandleGroup handleGroup = receiptHandleGroupMap.get(new ReceiptHandleGroupKey(channel, group)); if (handleGroup == null) { return null; } ...
@Test public void testRemoveReceiptHandle() { Channel channel = PROXY_CONTEXT.getVal(ContextVariable.CHANNEL); receiptHandleManager.addReceiptHandle(PROXY_CONTEXT, channel, GROUP, MSG_ID, messageReceiptHandle); receiptHandleManager.removeReceiptHandle(PROXY_CONTEXT, channel, GROUP, MSG_ID, r...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ListOptions)) { return false; } ListOptions that = (ListOptions) o; return Objects.equal(mRecursive, that.mRecursive); }
@Test public void equalsTest() throws Exception { CommonUtils.testEquals(ListOptions.class); }
public Grok cachedGrokForPattern(String pattern) { return cachedGrokForPattern(pattern, false); }
@Test public void cachedGrokForPattern() { final Grok grok = grokPatternRegistry.cachedGrokForPattern("%{TESTNUM}"); assertThat(grok.getPatterns()).containsEntry(GROK_PATTERN.name(), GROK_PATTERN.pattern()); }
public static byte zoomForBounds(Dimension dimension, BoundingBox boundingBox, int tileSize) { long mapSize = MercatorProjection.getMapSize((byte) 0, tileSize); double pixelXMax = MercatorProjection.longitudeToPixelX(boundingBox.maxLongitude, mapSize); double pixelXMin = MercatorProjection.longi...
@Test public void zoomForBoundsTest() { // TODO rewrite this unit tests to make it easier to understand Dimension[] dimensions = {new Dimension(200, 300), new Dimension(500, 400), new Dimension(1000, 600), new Dimension(3280, 1780), new Dimension(100, 200), new Dimension(500, 200)}; ...
public boolean createMetadataTable() { GCRules.GCRule gcRules = GCRules.GCRULES.maxVersions(1); if (tableAdminClient.exists(tableId)) { Table table = tableAdminClient.getTable(tableId); List<ColumnFamily> currentCFs = table.getColumnFamilies(); ModifyColumnFamiliesRequest request = ModifyColu...
@Test public void testNewColumnFamiliesAreAddedInExistingTable() { CreateTableRequest createTableRequest = CreateTableRequest.of(tableId); tableAdminClient.createTable(createTableRequest); Table table = tableAdminClient.getTable(tableId); assertEquals(0, table.getColumnFamilies().size()); assertF...
@Override public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException { checkParameterCount(parameters, MIN_PARAMETER_COUNT, MAX_PARAMETER_COUNT); values = parameters.toArray(new CompoundVariable[parameters.size()]); }
@Test public void testChangeCaseError() throws Exception { assertThrows( InvalidVariableException.class, () -> changeCase.setParameters(new ArrayList<>())); }
@Override public AccessPathStore<V> leastUpperBound(AccessPathStore<V> other) { ImmutableMap.Builder<AccessPath, V> resultHeap = ImmutableMap.builder(); for (AccessPath aPath : intersection(heap().keySet(), other.heap().keySet())) { resultHeap.put(aPath, heap().get(aPath).leastUpperBound(other.heap().ge...
@Test public void leastUpperBoundEmpty() { assertThat(newStore().leastUpperBound(newStore())).isEqualTo(newStore()); }
public static String getKey(String dataId, String group) { return getKey(dataId, group, ""); }
@Test public void testGetKey() { String dataId = "dataId"; String group = "group"; String expected = "dataId+group"; String key = GroupKey.getKey(dataId, group); Assert.isTrue(key.equals(expected)); }
@GET @Path("/{entityType}/{entityId}") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8 /* , MediaType.APPLICATION_XML */}) public TimelineEntity getEntity( @Context HttpServletRequest req, @Context HttpServletResponse res, @PathParam("entityType") String entityType, ...
@Test void testGetEventsWithYarnACLsEnabled() { AdminACLsManager oldAdminACLsManager = timelineACLsManager.setAdminACLsManager(adminACLsManager); try { // Put entity [5, 5] in domain 1 TimelineEntities entities = new TimelineEntities(); TimelineEntity entity = new TimelineEntity(); ...
@SuppressWarnings("unchecked") void openDB(final Map<String, Object> configs, final File stateDir) { // initialize the default rocksdb options final DBOptions dbOptions = new DBOptions(); final ColumnFamilyOptions columnFamilyOptions = new ColumnFamilyOptions(); userSpecifiedOptions...
@Test public void shouldThrowProcessorStateExceptionOnOpeningReadOnlyDir() { final File tmpDir = TestUtils.tempDirectory(); final InternalMockProcessorContext tmpContext = new InternalMockProcessorContext(tmpDir, new StreamsConfig(StreamsTestUtils.getStreamsConfig())); assertTrue(tmpDir.set...
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testMissingLeaderEpochInRecords() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); ByteBuffer buffer = ByteBuffer.allocate(1024); MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, RecordBatch.MAGIC_VALUE_V0, ...
@Override public BucketSpec apply(final Grouping grouping) { return Values.builder() .field(grouping.requestedField().name()) .type(Values.NAME) .limit(grouping.limit()) .build(); }
@Test void throwsNullPointerExceptionOnNullGrouping() { assertThrows(NullPointerException.class, () -> toTest.apply(null)); }
@Override public Committer closeForCommit() throws IOException { lock(); try { closeAndUploadPart(); return upload.snapshotAndGetCommitter(); } finally { unlock(); } }
@Test public void noWritesShouldResolveInAnEmptyFile() throws IOException { RecoverableFsDataOutputStream.Committer committer = streamUnderTest.closeForCommit(); committer.commit(); assertThat(multipartUploadUnderTest, hasContent(new byte[0])); }
public String sendExport( String filename, String type, String load ) throws Exception { // Request content will be retrieved directly from the input stream try ( InputStream is = KettleVFS.getInputStream( KettleVFS.getFileObject( filename ) ) ) { // Execute request HttpPost method = buildSendExport...
@Test( expected = NullPointerException.class ) public void testSendExport() throws Exception { slaveServer.setHostname( "hostNameStub" ); slaveServer.setUsername( "userNAmeStub" ); HttpPost httpPostMock = mock( HttpPost.class ); URI uriMock = new URI( "fake" ); doReturn( uriMock ).when( httpPostMo...
public List<String> getHeadersAsList(String name) { List<String> values = parent.headers().get(name); if(values == null) { return List.of(); } return parent.headers().get(name); }
@Test void testGetHeadersAsList() { URI uri = URI.create("http://localhost:8080/test"); HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1); DiscFilterRequest request = new DiscFilterRequest(httpReq); assertNotNull(request.getHeaderNamesAsList...
@Override public void fetchSegmentToLocal(URI downloadURI, File dest) throws Exception { // Create a RoundRobinURIProvider to round robin IP addresses when retry uploading. Otherwise may always try to // download from a same broken host as: 1) DNS may not RR the IP addresses 2) OS cache the DNS resoluti...
@Test public void testFetchSegmentToLocalSuccessAfterRetry() throws Exception { FileUploadDownloadClient client = mock(FileUploadDownloadClient.class); // The first two attempts failed and the last attempt succeeded when(client.downloadFile(any(), any(), any())).thenReturn(300).thenReturn(300).thenR...
public static StatementExecutorResponse execute( final ConfiguredStatement<DescribeFunction> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final DescribeFunction describeFunction = statement.getSta...
@Test public void shouldDescribeUDAFWithVarArgsInMiddle() { // When: final FunctionDescriptionList functionList = (FunctionDescriptionList) CustomExecutors.DESCRIBE_FUNCTION.execute( engine.configure("DESCRIBE FUNCTION MID_VAR_ARG;"), mock(SessionProperties....
@GetMapping("/hoteles/{hotelId}") public ResponseEntity<List<Calificacion>> listarCalificacionesPorHotelId (@PathVariable String hotelId) { return ResponseEntity.ok(calificacionService.getCalificacionesByHotelId(hotelId)); }
@Test void testListarCalificacionesPorHotelId() throws Exception { List<Calificacion> calificaciones = Arrays.asList(calificacion1, calificacion3); when(calificacionService.getCalificacionesByHotelId("hotel1")).thenReturn(calificaciones); mockMvc.perform(get("/calificaciones/hoteles/hotel1"...
@Override public double[] smoothDerivative(double[] input) { if (input.length < weights.length) { return averageDerivativeForVeryShortTrack(input); } double[] smoothed = new double[input.length]; int halfWindowFloored = weights.length / 2; // we want to exclude the cent...
@Test public void Derivative_FromShortTrack_ReturnAverageDerivative() { SavitzkyGolayFilter test = new SavitzkyGolayFilter(3.0); // note the time step double[] input = new double[]{10.0, 13.0, 16.0, 18.0, 21.0}; double[] actual = test.smoothDerivative(input); assertThat(actual.leng...
@Override public MapSettings setProperty(String key, String value) { return (MapSettings) super.setProperty(key, value); }
@Test public void getKeysStartingWith() { Settings settings = new MapSettings(); settings.setProperty("sonar.jdbc.url", "foo"); settings.setProperty("sonar.jdbc.username", "bar"); settings.setProperty("sonar.security", "admin"); assertThat(settings.getKeysStartingWith("sonar")).containsOnly("sona...
public static YamlProxyConfiguration load(final String path) throws IOException { YamlProxyServerConfiguration serverConfig = loadServerConfiguration(getGlobalConfigFile(path)); File configPath = getResourceFile(path); Collection<YamlProxyDatabaseConfiguration> databaseConfigs = loadDatabaseConf...
@Test void assertLoad() throws IOException { YamlProxyConfiguration actual = ProxyConfigurationLoader.load("/conf/config_loader/"); Iterator<YamlRuleConfiguration> actualGlobalRules = actual.getServerConfiguration().getRules().iterator(); // TODO assert mode // TODO assert authority ...