focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Object[] cast(Class<?> type, Object arrayObj) throws NullPointerException, IllegalArgumentException { if (null == arrayObj) { throw new NullPointerException("Argument [arrayObj] is null !"); } if (false == arrayObj.getClass().isArray()) { throw new IllegalArgumentException("Argument [arrayObj]...
@Test public void castTest() { Object[] values = {"1", "2", "3"}; String[] cast = (String[]) ArrayUtil.cast(String.class, values); assertEquals(values[0], cast[0]); assertEquals(values[1], cast[1]); assertEquals(values[2], cast[2]); }
@SuppressWarnings("unchecked") @Override public synchronized ProxyInfo<T> getProxy() { if (currentUsedHandler != null) { return currentUsedHandler; } Map<String, ProxyInfo<T>> targetProxyInfos = new HashMap<>(); StringBuilder combinedInfo = new StringBuilder("["); for (int i = 0; i < proxi...
@Test public void testRequestNNAfterOneSuccess() throws Exception { final AtomicInteger goodCount = new AtomicInteger(0); final AtomicInteger badCount = new AtomicInteger(0); final ClientProtocol goodMock = mock(ClientProtocol.class); when(goodMock.getStats()).thenAnswer(new Answer<long[]>() { @...
@Override public BackgroundException map(final SSLException failure) { final StringBuilder buffer = new StringBuilder(); for(Throwable cause : ExceptionUtils.getThrowableList(failure)) { if(cause instanceof SocketException) { // Connection has been shutdown: javax.net.ssl...
@Test public void testMap() { final BackgroundException f = new SSLExceptionMappingService().map(new SSLException( "Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe", new SSLException("javax.net.ssl.SSLException: java.net.SocketE...
@Override public void disconnectTaskManager(final ResourceID resourceId, final Exception cause) { closeTaskManagerConnection(resourceId, cause) .ifPresent(ResourceManager.this::stopWorkerIfSupported); }
@Test void testDisconnectTaskManager() throws Exception { final ResourceID taskExecutorId = ResourceID.generate(); final CompletableFuture<Exception> disconnectFuture = new CompletableFuture<>(); final CompletableFuture<ResourceID> stopWorkerFuture = new CompletableFuture<>(); final...
@Override public List<BlockWorkerInfo> getPreferredWorkers(WorkerClusterView workerClusterView, String fileId, int count) throws ResourceExhaustedException { if (workerClusterView.size() < count) { throw new ResourceExhaustedException(String.format( "Not enough workers in the cluster %d work...
@Test public void getMultipleWorkers() throws Exception { WorkerLocationPolicy policy = WorkerLocationPolicy.Factory.create(mConf); assertTrue(policy instanceof ConsistentHashPolicy); // Prepare a worker list WorkerClusterView workers = new WorkerClusterView(Arrays.asList( new WorkerInfo() ...
@VisibleForTesting static String truncateLongClasspath(ImmutableList<String> imageEntrypoint) { List<String> truncated = new ArrayList<>(); UnmodifiableIterator<String> iterator = imageEntrypoint.iterator(); while (iterator.hasNext()) { String element = iterator.next(); truncated.add(element);...
@Test public void testTruncateLongClasspath_shortClasspath() { ImmutableList<String> entrypoint = ImmutableList.of( "java", "-Dmy-property=value", "-cp", "/app/classes:/app/libs/*", "com.example.Main"); Assert.assertEquals( "[java, -Dmy-property=value, -cp, /app/classes:/app/libs/...
@Override public <K, V> void forward(final K key, final V value) { throw new StreamsException(EXPLANATION); }
@Test public void shouldThrowOnForward() { assertThrows(StreamsException.class, () -> context.forward("key", "value")); }
public static Labels fromString(String stringLabels) throws IllegalArgumentException { Map<String, String> labels = new HashMap<>(); try { if (stringLabels != null && !stringLabels.isEmpty()) { String[] labelsArray = stringLabels.split(","); for (String label...
@Test public void testParseInvalidLabels3() { assertThrows(IllegalArgumentException.class, () -> { String invalidLabels = "key2"; Labels.fromString(invalidLabels); }); }
@Description("Scrub runtime information such as plan estimates and variable names from the query plan, leaving the structure of the plan intact") @ScalarFunction("json_presto_query_plan_scrub") @SqlType(StandardTypes.JSON) @SqlNullable public static Slice jsonScrubPlan(@SqlType(StandardTypes.JSON) Slice...
@Test public void testJsonScrubPlan() { assertFunction("json_presto_query_plan_scrub(json '" + TestJsonPrestoQueryPlanFunctionUtils.joinPlan.replaceAll("'", "''") + "')", JSON, TestJsonPrestoQueryPlanFunctionUtils.scrubbedJoinPlan); }
@Override public Map<MetricName, Metric> getMetrics() { final Map<MetricName, Metric> gauges = new HashMap<>(); gauges.put(MetricName.build("name"), (Gauge<String>) runtime::getName); gauges.put(MetricName.build("vendor"), (Gauge<String>) () -> String.format(Locale.US, ...
@Test public void hasASetOfGauges() throws Exception { assertThat(gauges.getMetrics().keySet()) .containsOnly( MetricName.build("vendor"), MetricName.build("name"), MetricName.build("uptime")); }
@Operation(summary = "Get collect metadata process errors by connection metadata process result id") @GetMapping(value = "collect_metadata/errors/{result_id}", produces = "application/json") @ResponseBody public Page<SamlMetadataProcessError> findBySamlMetadataProcessResultId(@RequestParam(name = "page") in...
@Test public void findBySamlMetadataProcessResultId() { when(metadataRetrieverServiceMock.getSamlMetadataById(anyLong(), anyInt(), anyInt())).thenReturn(MetadataProcessHelper.getPageSamlMetadataProcessError()); Page<SamlMetadataProcessError> result = controllerMock.findBySamlMetadataProcessResultId...
public static AfterProcessingTimeStateMachine pastFirstElementInPane() { return new AfterProcessingTimeStateMachine(IDENTITY); }
@Test public void testAfterProcessingTimeWithMergingWindow() throws Exception { SimpleTriggerStateMachineTester<IntervalWindow> tester = TriggerStateMachineTester.forTrigger( AfterProcessingTimeStateMachine.pastFirstElementInPane() .plusDelayOf(Duration.millis(5)), ...
public void retrieveDocuments() throws DocumentRetrieverException { boolean first = true; String route = params.cluster.isEmpty() ? params.route : resolveClusterRoute(params.cluster); MessageBusParams messageBusParams = createMessageBusParams(params.configId, params.timeout, route); doc...
@Test void testClusterLookup() throws DocumentRetrieverException { final String cluster = "storage", expectedRoute = "[Content:cluster=storage]"; ClientParameters params = createParameters() .setCluster(cluster) .build(); ClusterList clusterL...
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { if(containerService.isContainer(folder)) { final S3BucketCreateService service = new S3BucketCreateService(session); service.create(folder, StringUtils.isBlank(status.getRegion())...
@Test @Ignore public void testCreateBucket() throws Exception { final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final S3DirectoryFeature feature = new S3DirectoryFeature(session, new S3WriteFeature(session, acl), acl); for(Location.Name region : session.ge...
@Override public String toString() { return format(); }
@Test public void formatTest2() { BetweenFormatter formater = new BetweenFormatter(584, Level.SECOND, 1); assertEquals(formater.toString(), "0秒"); }
@Override public String getName() { return name; }
@Test public void testConstructor_withName() { config = new NearCacheConfig("foobar"); assertEquals("foobar", config.getName()); }
protected boolean isClusterVersionUnknownOrGreaterThan(Version version) { Version clusterVersion = getNodeEngine().getClusterService().getClusterVersion(); return clusterVersion.isUnknownOrGreaterThan(version); }
@Test public void testClusterVersion_isUnknownGreaterThan_previousVersion() { assertTrue(object.isClusterVersionUnknownOrGreaterThan(VersionsTest.getPreviousClusterVersion())); }
@VisibleForTesting static Map<Stack, List<String>> deduplicateThreadStacks( Map<Thread, StackTraceElement[]> allStacks) { Map<Stack, List<String>> stacks = new HashMap<>(); for (Map.Entry<Thread, StackTraceElement[]> entry : allStacks.entrySet()) { Thread thread = entry.getKey(); if (thread ...
@Test public void testDeduping() throws Exception { Map<Thread, StackTraceElement[]> stacks = ImmutableMap.of( new Thread("Thread1"), new StackTraceElement[] {new StackTraceElement("Class", "Method1", "File", 11)}, new Thread("Thread2"), new StackTraceElemen...
public void insertChanges(IssueChangeMapper mapper, DefaultIssue issue, UuidFactory uuidFactory) { for (DefaultIssueComment comment : issue.defaultIssueComments()) { if (comment.isNew()) { IssueChangeDto changeDto = IssueChangeDto.of(comment, issue.projectUuid()); changeDto.setUuid(uuidFactory...
@Test public void when_newIssueWithAnticipatedTransitionInserted_twoChangelogCreated() { when(uuidFactory.create()).thenReturn("uuid"); String issueKey = "ABCDE"; String commentText = "comment for new issue"; DefaultIssueComment comment = DefaultIssueComment.create(issueKey, "user_uuid", commentText)...
Settings.Builder getSettings() { return settings; }
@Test @UseDataProvider("indexWithAndWithoutRelations") public void in_standalone_searchReplicas_is_not_overridable(Index index) { settings.setProperty(SEARCH_REPLICAS.getKey(), "5"); NewIndex newIndex = new SimplestNewIndex(IndexType.main(index, "foo"), defaultSettingsConfiguration); assertThat(newInde...
public FEELFnResult<Object> invoke(@ParameterName("list") List list) { if ( list == null || list.isEmpty() ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null or empty")); } else { try { return FEELFnResult.ofResult(C...
@Test void invokeArrayOfStrings() { FunctionTestUtil.assertResult(minFunction.invoke(new Object[]{"a"}), "a"); FunctionTestUtil.assertResult(minFunction.invoke(new Object[]{"a", "b", "c"}), "a"); FunctionTestUtil.assertResult(minFunction.invoke(new Object[]{"b", "a", "c"}), "a"); Fun...
@Override public ByteBuf unwrap() { return buffer; }
@Test public void testUnwrap() { ByteBuf buf = buffer(1); assertSame(buf, unmodifiableBuffer(buf).unwrap()); }
@Override public <T> CompletableFuture<T> submit(Callable<T> callable) { final CompletableFuture<T> promise = new CompletableFuture<>(); try { CompletableFuture.supplyAsync(ContextPropagator.decorateSupplier(config.getContextPropagator(),() -> { try { ...
@Test public void testRunnableThreadLocalContextPropagator() { TestThreadLocalContextHolder.put("ValueShouldCrossThreadBoundary"); AtomicReference<String> reference = new AtomicReference<>(); fixedThreadPoolBulkhead .submit(() -> reference.set((String) TestThreadLocalContextHol...
public BundleProcessor getProcessor( BeamFnApi.ProcessBundleDescriptor descriptor, List<RemoteInputDestination> remoteInputDesinations) { checkState( !descriptor.hasStateApiServiceDescriptor(), "The %s cannot support a %s containing a state %s.", BundleProcessor.class.getSimpleNa...
@Test public void testNewBundleNoDataDoesNotCrash() throws Exception { CompletableFuture<InstructionResponse> processBundleResponseFuture = new CompletableFuture<>(); when(fnApiControlClient.handle(any(BeamFnApi.InstructionRequest.class))) .thenReturn(processBundleResponseFuture); FullWindowedVal...
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } ...
@Test public void incompleteForgeInstallation6() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/incomplete_forge_installation6.txt")), CrashReportAnalyzer.Rule.INCOMPLETE_FORGE_INSTALLATION); }
@Override public int getDegree(int vertex) { if (digraph) { return getIndegree(vertex) + getOutdegree(vertex); } else { return getOutdegree(vertex); } }
@Test public void testGetDegree() { System.out.println("getDegree"); assertEquals(0, g1.getDegree(1)); assertEquals(2, g2.getDegree(1)); g2.addEdge(1, 1); assertEquals(4, g2.getDegree(1)); assertEquals(4, g3.getDegree(1)); assertEquals(4, g3.getDegree(2)); ...
@Override @Deprecated public <VR> KStream<K, VR> flatTransformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, Iterable<VR>> valueTransformerSupplier, final String... stateStoreNames) { Objects.requireNonNull(valueTransf...
@Test @SuppressWarnings("deprecation") public void shouldNotAllowNullStoreNamesOnFlatTransformValuesWithFlatValueWithKeySupplier() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.flatTransformValues( flatValueTra...
@Override public void configure(Map<String, ?> configs, boolean isKey) { if (listClass != null || inner != null) { log.error("Could not configure ListDeserializer as some parameters were already set -- listClass: {}, inner: {}", listClass, inner); throw new ConfigException("List dese...
@Test public void testListValueDeserializerNoArgConstructorsShouldThrowKafkaExceptionDueInvalidInnerClass() { props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_TYPE_CLASS, ArrayList.class); props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_INNER_CLASS, new FakeObject()); final Kafk...
@Override public long connectionDelay(Node node, long now) { return connectionStates.connectionDelay(node.idString(), now); }
@Test public void testConnectionDelayConnected() { awaitReady(client, node); long now = time.milliseconds(); long delay = client.connectionDelay(node, now); assertEquals(Long.MAX_VALUE, delay); }
@POST @Path("{nodeId}/reset") @ApiOperation("Reset a removed node to rejoin the cluster") @AuditEvent(type = DATANODE_RESET) @RequiresPermissions(RestPermissions.DATANODE_RESET) public DataNodeDto resetNode(@ApiParam(name = "nodeId", required = true) @PathParam("nodeId") String nodeId) { try...
@Test public void verifyResetServiceCalled() throws NodeNotFoundException { classUnderTest.resetNode(NODEID); verify(dataNodeCommandService).resetNode(NODEID); }
public void schedule(BeanContainer container, String id, String cron, String interval, String zoneId, String className, String methodName, List<JobParameter> parameterList) { JobScheduler scheduler = container.beanInstance(JobScheduler.class); String jobId = getId(id); String optionalCronExpress...
@Test void scheduleSchedulesCronJobWithJobRunr() { final String id = "my-job-id"; final JobDetails jobDetails = jobDetails().build(); final String cron = "*/15 * * * *"; final String interval = null; final String zoneId = null; jobRunrRecurringJobRecorder.schedule(be...
public static String replaceInternalStorage( RunContext runContext, @Nullable String command, boolean replaceWithRelativePath ) throws IOException { if (command == null) { return ""; } return INTERNAL_STORAGE_PATTERN .matcher(command) ...
@Test void uploadInputFiles() throws IOException { var runContext = runContextFactory.of(); Path path = Path.of("/tmp/unittest/file.txt"); if (!path.toFile().exists()) { Files.createFile(path); } List<File> filesToDelete = new ArrayList<>(); String inter...
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 testExpiryOfFirstBatchShouldCauseEpochBumpIfFutureBatchesFail() throws Exception { final long producerId = 343434L; TransactionManager transactionManager = createTransactionManager(); setupWithTransactionState(transactionManager); prepareAndReceiveInitProducerId(pro...
public void pullMessage(final PullRequest pullRequest) { final ProcessQueue processQueue = pullRequest.getProcessQueue(); if (processQueue.isDropped()) { log.info("the pull request[{}] is dropped.", pullRequest.toString()); return; } pullRequest.getProcessQueue()...
@Test public void testPullMessageWithStateNotOk() { when(pullRequest.getProcessQueue()).thenReturn(processQueue); defaultMQPushConsumerImpl.pullMessage(pullRequest); }
@Override public int getGlyphId(int characterCode) { Integer glyphId = characterCodeToGlyphId.get(characterCode); return glyphId == null ? 0 : glyphId; }
@Test void testVerticalSubstitution() throws IOException { File ipaFont = new File("target/fonts/ipag00303", "ipag.ttf"); TrueTypeFont ttf = new TTFParser().parse(new RandomAccessReadBufferedFile(ipaFont)); CmapLookup unicodeCmapLookup1 = ttf.getUnicodeCmapLookup(); int ...
@Override public void trackAppInstall(JSONObject properties, boolean disableCallback) { }
@Test public void trackAppInstall() { mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); return false; } }); ...
public static void main(String[] args) { // simple troll LOGGER.info("A simple looking troll approaches."); var troll = new SimpleTroll(); troll.attack(); troll.fleeBattle(); LOGGER.info("Simple troll power: {}.\n", troll.getAttackPower()); // change the behavior of the simple troll by add...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public static void processElectLeadersResult(ElectLeadersResult result, Set<TopicPartition> deletedTopicPartitions) { if (result == null) { return; } try { Map<TopicPartition, Optional<Throwable>> partitions = result.partitions().get(); Set<TopicPartition> noElectionNeeded = new HashSet<>(...
@Test public void testProcessElectLeadersResult() throws Exception { // Case 1: Handle null result input. Expect no side effect. ExecutionUtils.processElectLeadersResult(null, Collections.emptySet()); KafkaFutureImpl<Map<TopicPartition, Optional<Throwable>>> partitions = EasyMock.mock(KafkaFutureImpl.cla...
public String managementAddress() { return get(MANAGEMENT_ADDRESS, null); }
@Test public void testSetManagementAddress() { SW_BDC.managementAddress(MANAGEMENT_ADDRESS_NEW); assertEquals("Incorrect managementAddress", MANAGEMENT_ADDRESS_NEW, SW_BDC.managementAddress()); }
@Override public Mono<SaveResult> save(Publisher<DictionaryItemEntity> entityPublisher) { return super.save(this.fillOrdinal(entityPublisher)) .doOnSuccess(r -> eventPublisher.publishEvent(ClearDictionaryCacheEvent.of())); }
@Test public void testAutoOrdinal() { //自动填充ordinal DictionaryItemEntity itemEntity = createItem("test-auto"); itemEntity.setOrdinal(null); DictionaryItemEntity itemEntity2 = createItem("test-auto"); itemEntity2.setOrdinal(null); defaultDictionaryItemService ...
public static ConnectedComponents findComponentsRecursive(Graph graph, EdgeTransitionFilter edgeTransitionFilter, boolean excludeSingleEdgeComponents) { return new EdgeBasedTarjanSCC(graph, edgeTransitionFilter, excludeSingleEdgeComponents).findComponentsRecursive(); }
@Test public void linearSingle() { // 0 - 1 g.edge(0, 1).setDistance(1).set(speedEnc, 10, 10); ConnectedComponents result = EdgeBasedTarjanSCC.findComponentsRecursive(g, fwdAccessFilter, false); assertEquals(2, result.getEdgeKeys()); assertEquals(1, result.getTotalComponents(...
@Override public boolean removeAll(Collection<?> c) { return get(removeAllAsync(c)); }
@Test public void testRemoveAll() { RSetCache<Integer> set = redisson.getSetCache("set"); set.add(1); set.add(2, 10, TimeUnit.SECONDS); set.add(3); assertThat(set.removeAll(Arrays.asList(1, 3))).isTrue(); assertThat(set.removeAll(Arrays.asList(1, 3))).isFalse...
Mono<Post> getById(UUID id) { return client.get() .uri(uriBuilder -> uriBuilder.path("/posts/{id}").build(id)) .accept(MediaType.APPLICATION_JSON) .exchangeToMono(response -> { if (response.statusCode().equals(HttpStatus.OK)) { ...
@SneakyThrows @Test public void testGetPostById() { var id = UUID.randomUUID(); var data = new Post(id, "title1", "content1", Status.DRAFT, LocalDateTime.now()); stubFor(get("/posts/" + id) .willReturn( aResponse() ...
void addHits(CounterRequest counterRequest) { if (counterRequest.getHits() > 0) { // clone pour être thread-safe ici final CounterRequest newRequest = counterRequest.clone(); final CounterRequest request = getCounterRequestInternal(newRequest.getName()); synchronized (request) { request.addHits(newReq...
@Test public void testAddHits() { final CounterRequest counterRequest = createCounterRequest(); counter.addHits(counterRequest); final List<CounterRequest> before = counter.getOrderedRequests(); counter.addHits(counterRequest); counter.addHits(new CounterRequest("test", counter.getName())); final List<Coun...
public static String getLocalhostStr() { InetAddress localhost = getLocalhost(); if (null != localhost) { return localhost.getHostAddress(); } return null; }
@Test @Disabled public void getLocalhostStrTest() { final String localhost = NetUtil.getLocalhostStr(); assertNotNull(localhost); }
@Operation(summary = "unauthorizedUser", description = "UNAUTHORIZED_USER_NOTES") @Parameters({ @Parameter(name = "alertgroupId", description = "ALERT_GROUP_ID", required = true, schema = @Schema(implementation = String.class)) }) @GetMapping(value = "/unauth-user") @ResponseStatus(HttpStatu...
@Disabled @Test public void testUnauthorizedUser() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("alertgroupId", "1"); MvcResult mvcResult = mockMvc.perform(get("/users/unauth-user") .header(SESSION_ID, sessionId)...
@Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof DependencyVersion)) { return false; } if (this == obj) { return true; } final DependencyVersion other = (DependencyVersion) obj; final int minVersionMatchLength =...
@Test public void testEquals() { DependencyVersion obj = new DependencyVersion("1.2.3.r1"); DependencyVersion instance = new DependencyVersion("1.2.3"); boolean expResult = false; boolean result = instance.equals(obj); assertEquals(expResult, result); obj = new Depend...
public final void fillContext(String dataId, String group) { this.dataId = dataId; this.group = group; }
@Test void testFillContext() { assertEquals(0, receivedMap.size()); MockShardListener listener = new MockShardListener(); listener.receiveConfigInfo(CONFIG_CONTENT); assertEquals(2, receivedMap.size()); assertNull(receivedMap.get("group")); assertNull(receivedMap.get(...
@Override protected void decode(ChannelHandlerContext context, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < SslUtils.SSL_RECORD_HEADER_LENGTH) { return; } if (SslHandler.isEncrypted(in)) { handleSsl(context); } else { h...
@Test public void handlerReplaced() throws Exception { final ChannelHandler nonSslHandler = Mockito.mock(ChannelHandler.class); OptionalSslHandler handler = new OptionalSslHandler(sslContext) { @Override protected ChannelHandler newNonSslHandler(ChannelHandlerContext context)...
public Optional<Number> evaluate(final List<KiePMMLDefineFunction> defineFunctions, final List<KiePMMLDerivedField> derivedFields, final List<KiePMMLOutputField> outputFields, final Map<String, Object> inputDa...
@Test void evaluate() { Double initialScore = 25.23; KiePMMLCharacteristics kiePMMLCharacteristics = new KiePMMLCharacteristics("NAME", Collections.emptyList(), getKiePMMLCharacteristicList()); PMMLRuntimeContextTest pmmlContextTest = new PMMLRuntimeContextTest(); Opt...
public Optional<YamlRuleConfiguration> swapToYamlRuleConfiguration(final Collection<RepositoryTuple> repositoryTuples, final Class<? extends YamlRuleConfiguration> toBeSwappedType) { RepositoryTupleEntity tupleEntity = toBeSwappedType.getAnnotation(RepositoryTupleEntity.class); if (null == tupleEntity) ...
@Test void assertSwapToYamlRuleConfigurationWithEmptyNodeYamlRuleConfiguration() { Optional<YamlRuleConfiguration> actual = new RepositoryTupleSwapperEngine().swapToYamlRuleConfiguration( Collections.singleton(new RepositoryTuple("/metadata/foo_db/rules/node/string_value/versions/0", "")), N...
@ConstantFunction(name = "int_divide", argTypes = {SMALLINT, SMALLINT}, returnType = SMALLINT) public static ConstantOperator intDivideSmallInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createSmallInt((short) (first.getSmallint() / second.getSmallint())); }
@Test public void intDivideSmallInt() { assertEquals(1, ScalarOperatorFunctions.intDivideSmallInt(O_SI_10, O_SI_10).getSmallint()); }
public static Timestamp previous(Timestamp timestamp) { if (timestamp.equals(Timestamp.MIN_VALUE)) { return timestamp; } final int nanos = timestamp.getNanos(); final long seconds = timestamp.getSeconds(); if (nanos - 1 >= 0) { return Timestamp.ofTimeSecondsAndNanos(seconds, nanos - 1);...
@Test public void testPreviousDecrementsNanosWhenPossible() { assertEquals( Timestamp.ofTimeSecondsAndNanos(10L, 0), TimestampUtils.previous(Timestamp.ofTimeSecondsAndNanos(10L, 1))); }
@Override public IcebergEnumeratorState snapshotState(long checkpointId) { return new IcebergEnumeratorState( enumeratorPosition.get(), assigner.state(), enumerationHistory.snapshot()); }
@Test public void testThrottlingDiscovery() throws Exception { // create 10 splits List<IcebergSourceSplit> splits = SplitHelpers.createSplitsFromTransientHadoopTable(temporaryFolder, 10, 1); TestingSplitEnumeratorContext<IcebergSourceSplit> enumeratorContext = new TestingSplitEnumeratorC...
@Override protected boolean hasPluginInfo() { return metadataStore().getPluginInfo(getPluginId()) != null; }
@Test public void shouldReturnFalseIfPluginInfoIsDefined() { final ArtifactStore artifactStore = new ArtifactStore("id", "plugin_id"); assertFalse(artifactStore.hasPluginInfo()); }
public static String generateReleaseKey(Namespace namespace) { return generate(namespace.getAppId(), namespace.getClusterName(), namespace.getNamespaceName()); }
@Test public void testGenerateReleaseKey() throws Exception { String someAppId = "someAppId"; String someCluster = "someCluster"; String someNamespace = "someNamespace"; String anotherAppId = "anotherAppId"; Namespace namespace = MockBeanFactory.mockNamespace(someAppId, someCluster, someNamespac...
void fetchPluginSettingsMetaData(GoPluginDescriptor pluginDescriptor) { String pluginId = pluginDescriptor.id(); List<ExtensionSettingsInfo> allMetadata = findSettingsAndViewOfAllExtensionsIn(pluginId); List<ExtensionSettingsInfo> validMetadata = allSettingsAndViewPairsWhichAreValid(allMetadata)...
@Test public void shouldFailWhenAPluginWithMultipleExtensionsHasMoreThanOneExtensionRespondingWithSettings() { PluginSettingsConfiguration configuration = new PluginSettingsConfiguration(); configuration.add(new PluginSettingsProperty("k1").with(Property.REQUIRED, true).with(Property.SECURE, false))...
public static <T> String join(final String... elements) { return join(elements, EMPTY_STRING); }
@Test public void testStringJoinWithJavaImpl() { assertNull(StringUtils.join(",", null)); assertEquals("", String.join(",", Collections.singletonList(""))); assertEquals(",", String.join(",", Arrays.asList("", ""))); assertEquals("a,", String.join(",", Arrays.asList("a", ""))); }
public static Pair<Optional<Method>, Optional<TypedExpression>> resolveMethodWithEmptyCollectionArguments( final MethodCallExpr methodExpression, final MvelCompilerContext mvelCompilerContext, final Optional<TypedExpression> scope, List<TypedExpression> arguments, ...
@Test public void resolveMethodWithEmptyCollectionArgumentsEmptyCollectionIndexesAreNull() { Assertions.assertThatThrownBy( () -> MethodResolutionUtils.resolveMethodWithEmptyCollectionArguments( new MethodCallExpr(), new...
void registerSelfToCluster(String groupId, PeerId selfIp, Configuration conf) { while (!isShutdown) { try { List<PeerId> peerIds = cliService.getPeers(groupId, conf); if (peerIds.contains(selfIp)) { return; } Status ...
@Test void testRegisterSelfToCluster() { PeerId selfPeerId = new PeerId("4.4.4.4", 8080); server.registerSelfToCluster(groupId, selfPeerId, conf); verify(cliServiceMock).addPeer(groupId, conf, selfPeerId); }
public ConsumerFilterData get(final String topic, final String consumerGroup) { if (!this.filterDataByTopic.containsKey(topic)) { return null; } if (this.filterDataByTopic.get(topic).getGroupFilterData().isEmpty()) { return null; } return this.filterDataB...
@Test public void testPersist() { ConsumerFilterManager filterManager = gen(10, 10); try { filterManager.persist(); ConsumerFilterData filterData = filterManager.get("topic9", "CID_9"); assertThat(filterData).isNotNull(); assertThat(filterData.isDea...
public static LockTime unset() { return LockTime.ofBlockHeight(0); }
@Test public void unset() { LockTime unset = LockTime.unset(); assertTrue(unset instanceof HeightLock); assertEquals(0, unset.rawValue()); }
@Override public String execute(CommandContext commandContext, String[] args) { if (args.length > 0) { return "Unsupported parameter " + Arrays.toString(args) + " for pwd."; } String service = commandContext.getRemote().attr(ChangeTelnet.SERVICE_KEY).get(); ...
@Test void testService() throws RemotingException { defaultAttributeMap .attr(ChangeTelnet.SERVICE_KEY) .set("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); String result = pwdTelnet.execute(mockCommandContext, new String[0]); assertEquals("org.apa...
@Override public boolean add(final Long value) { return add(value.longValue()); }
@Test public void testLongArrayConstructor() { long[] items = {42L, 43L}; long missingValue = -1L; final LongHashSet hashSet = new LongHashSet(items, missingValue); set.add(42L); set.add(43L); assertEquals(set, hashSet); }
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test public void testSiblingsOnResourceRequestBody() { Reader reader = new Reader(new SwaggerConfiguration().openAPI(new OpenAPI()).openAPI31(true)); OpenAPI openAPI = reader.read(SiblingsResourceRequestBody.class); String yaml = "openapi: 3.1.0\n" + "paths:\n" + ...
@Override public void subscribe(final Collection<String> topics) { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); if (topics == null) throw new IllegalArgumentException("Topic collection to subscribe to cannot be null"); if (top...
@Test public void testSubscriptionOnEmptyTopic() { consumer = newConsumer(); String emptyTopic = " "; assertThrows(IllegalArgumentException.class, () -> consumer.subscribe(singletonList(emptyTopic))); }
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { try { final EueApiClient client = new EueApiClient(session); // Move to trash first as precondition of delete this.dele...
@Test public void testDeleteMultipleFiles() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final Path folder = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(AbstractPath.Type.directory)); final Path file1 = new Path(folder, n...
@Override public byte[] contents() { return blob.getContent(); }
@Test public void testContents() { byte[] contents = new byte[] {0, 1, 2}; when(blob.getContent()).thenReturn(contents); assertThat(artifact.contents()).isEqualTo(contents); }
public void flush() { ByteBuffer bf = localBuffer.get(); bf.position(0); bf.limit(wheelLength); mappedByteBuffer.position(0); mappedByteBuffer.limit(wheelLength); for (int i = 0; i < wheelLength; i++) { if (bf.get(i) != mappedByteBuffer.get(i)) { ...
@Test(expected = RuntimeException.class) public void testRecoveryFixedTTL() throws Exception { timerWheel.flush(); TimerWheel tmpWheel = new TimerWheel(baseDir, slotsTotal + 1, precisionMs); }
public static GradientTreeBoost fit(Formula formula, DataFrame data) { return fit(formula, data, new Properties()); }
@Test public void testPenDigits() { System.out.println("Pen Digits"); MathEx.setSeed(19650218); // to get repeatable results. ClassificationValidations<GradientTreeBoost> result = CrossValidation.classification(10, PenDigits.formula, PenDigits.data, (f, x) -> GradientTreeBoo...
static AnnotatedClusterState generatedStateFrom(final Params params) { final ContentCluster cluster = params.cluster; final ClusterState workingState = ClusterState.emptyState(); final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>(); for (final NodeInfo nodeInfo : cluster....
@Test void crash_count_exceeding_limit_marks_node_as_down() { final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp(); final ClusterStateGenerator.Params params = fixture.generatorParams().maxPrematureCrashes(10); final NodeInfo nodeInfo = fixture.cluster.getN...
@VisibleForTesting static boolean isUriValid(String uri) { Matcher matcher = URI_PATTERN.matcher(uri); return matcher.matches(); }
@Test public void testValidUri() { assertThat( HttpCacheServerHandler.isUriValid( "http://some-path.co.uk:8080/ac/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")) .isTrue(); assertThat( HttpCacheServerHandler.isUriValid( "http:...
@Override public byte[] fromConnectData(String topic, Schema schema, Object value) { if (schema == null && value == null) { return null; } JsonNode jsonValue = config.schemasEnabled() ? convertToJsonWithEnvelope(schema, value) : convertToJsonWithoutEnvelope(schema, value); ...
@Test public void doubleToJson() { JsonNode converted = parse(converter.fromConnectData(TOPIC, Schema.FLOAT64_SCHEMA, 12.34)); validateEnvelope(converted); assertEquals(parse("{ \"type\": \"double\", \"optional\": false }"), converted.get(JsonSchema.ENVELOPE_SCHEMA_FIELD_NAME)); asse...
public static boolean isPrimitiveClassName(@Nullable String name) { if (name == null) return false; for (Type prim : PRIMITIVES) if (prim.getClassName().equals(name)) return true; return false; }
@Test void testIsPrimitiveClassName() { assertTrue(Types.isPrimitiveClassName("void")); assertTrue(Types.isPrimitiveClassName("boolean")); assertTrue(Types.isPrimitiveClassName("byte")); assertTrue(Types.isPrimitiveClassName("char")); assertTrue(Types.isPrimitiveClassName("short")); assertTrue(Types.isPrim...
@Override public boolean supportsSetMaxRows() { return false; }
@Test public void testSupportsSetMaxRows() throws Exception { assertFalse( dbMeta.supportsSetMaxRows() ); }
public static boolean validateCSConfiguration( final Configuration oldConfParam, final Configuration newConf, final RMContext rmContext) throws IOException { // ensure that the oldConf is deep copied Configuration oldConf = new Configuration(oldConfParam); QueueMetrics.setConfigurationVa...
@Test public void testValidateCSConfigStopANonLeafQueueInvalid() { Configuration oldConfig = CapacitySchedulerConfigGeneratorForTest .createBasicCSConfiguration(); Configuration newConfig = new Configuration(oldConfig); newConfig .set("yarn.scheduler.capacity.root.state", "STOPPED"...
@Override public boolean edgeExists(String source, String target) { checkId(source); checkId(target); NodeDraftImpl sourceNode = getNode(source); NodeDraftImpl targetNode = getNode(target); if (sourceNode != null && targetNode != null) { boolean undirected = edgeD...
@Test public void testEdgeExistsUndirected() { ImportContainerImpl importContainer = new ImportContainerImpl(); generateTinyUndirectedGraph(importContainer); Assert.assertTrue(importContainer.edgeExists("1")); Assert.assertTrue(importContainer.edgeExists("1", "2")); Assert.as...
void print(List<Line> lines, AnsiEscapes... border) { int maxLength = lines.stream().map(Line::length).max(comparingInt(a -> a)) .orElseThrow(NoSuchElementException::new); StringBuilder out = new StringBuilder(); Format borderFormat = monochrome ? monochrome() : color(border); ...
@Test void printsAnsiBanner() throws UnsupportedEncodingException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); Banner banner = new Banner(new PrintStream(bytes, false, StandardCharsets.UTF_8.name()), false); banner.print(asList( new Banner.Line("Bla"), ...
@Override public <I, K, V> Map<K, V> mapToPair(List<I> data, SerializablePairFunction<I, K, V> func, Integer parallelism) { return data.stream().map(throwingMapToPairWrapper(func)).collect( Collectors.toMap(Pair::getLeft, Pair::getRight, (oldVal, newVal) -> newVal) ); }
@Test public void testMapToPair() { List<String> mapList = Arrays.asList("hudi_flink", "hudi_spark", "hudi_java"); Map<String, String> resultMap = context.mapToPair(mapList, x -> { String[] splits = x.split("_"); return new ImmutablePair<>(splits[0], splits[1]); }, 2); Assertions.assertN...
public double getWidth() { return this.right - this.left; }
@Test public void getWidthTest() { Rectangle rectangle = create(1, 2, 3, 4); Assert.assertEquals(2, rectangle.getWidth(), 0); }
public void startAsync() { try { udfLoader.load(); ProcessingLogServerUtils.maybeCreateProcessingLogTopic( serviceContext.getTopicClient(), processingLogConfig, ksqlConfig); if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) { log.warn...
@Test(expected = RuntimeException.class) public void shouldThrowIfExecuteThrows() { // Given: when(ksqlEngine.execute(any(), any(ConfiguredStatement.class))) .thenThrow(new RuntimeException("Boom!")); // When: standaloneExecutor.startAsync(); }
public static java.util.regex.Pattern compilePattern(String expression) { return compilePattern(expression, 0); }
@Test void testCompilePatternOK() { Pattern pattern = JMeterUtils.compilePattern("some.*"); assertTrue(pattern.matcher("something").matches()); }
@Override public void createFunction(SqlInvokedFunction function, boolean replace) { checkCatalog(function); checkFunctionLanguageSupported(function); checkArgument(!function.hasVersion(), "function '%s' is already versioned", function); QualifiedObjectName functionName = functi...
@Test public void testCreateFunctionFailedDuplicate() { createFunction(FUNCTION_POWER_TOWER_DOUBLE, true); assertPrestoException(() -> createFunction(FUNCTION_POWER_TOWER_DOUBLE, false), ALREADY_EXISTS, ".*Function already exists: unittest\\.memory\\.power_tower\\(double\\)"); assertPres...
public static Config getConfig( Configuration configuration, @Nullable HostAndPort externalAddress) { return getConfig( configuration, externalAddress, null, PekkoUtils.getForkJoinExecutorConfig( ActorSystemBoots...
@Test void getConfigHandlesIPv6Address() { final String ipv6AddressString = "2001:db8:10:11:12:ff00:42:8329"; final Config config = PekkoUtils.getConfig(new Configuration(), new HostAndPort(ipv6AddressString, 1234)); assertThat(config.getString("pekko.remote.classic.netty.tc...
@Override public long getEndToEndDuration() { return Math.max(0, failureTimestamp - triggerTimestamp); }
@Test void testEndToEndDuration() { long duration = 123912931293L; long triggerTimestamp = 10123; long failureTimestamp = triggerTimestamp + duration; Map<JobVertexID, TaskStateStats> taskStats = new HashMap<>(); JobVertexID jobVertexId = new JobVertexID(); taskStats...
@Override public MaskTableRuleConfiguration swapRuleItemConfiguration(final AlterRuleItemEvent event, final String yamlContent) { return new YamlMaskTableRuleConfigurationSwapper().swapToObject(YamlEngine.unmarshal(yamlContent, YamlMaskTableRuleConfiguration.class)); }
@Test void assertSwapRuleItemConfiguration() { assertThat(new MaskTableChangedProcessor().swapRuleItemConfiguration(mock(AlterRuleItemEvent.class), "name: test_table").getName(), is("test_table")); }
@VisibleForTesting void stripXFFHeaders(HttpRequest req) { HttpHeaders headers = req.headers(); for (AsciiString headerName : HEADERS_TO_STRIP) { headers.remove(headerName); } }
@Test void strip_match() { StripUntrustedProxyHeadersHandler stripHandler = getHandler(AllowWhen.MUTUAL_SSL_AUTH); headers.add("x-forwarded-for", "abcd"); stripHandler.stripXFFHeaders(msg); assertFalse(headers.contains("x-forwarded-for")); }
@Cacheable("digid-app") public boolean digidAppSwitchEnabled(){ return isEnabled("Koppeling met DigiD app"); }
@Test void checkSwitchDisabled() { var switchObject = createSwitch(appSwitchName, "Description van de switch A", SwitchStatus.INACTIVE, 1, ZonedDateTime.now()); when(switchRepository.findByName(appSwitchName)).thenReturn(Optional.of(switchObject)); assertFalse(service.digidAppSwitchEnabled()...
public Marshaller createMarshaller(Class<?> clazz) throws JAXBException { Marshaller marshaller = getContext(clazz).createMarshaller(); setMarshallerProperties(marshaller); if (marshallerEventHandler != null) { marshaller.setEventHandler(marshallerEventHandler); } marshaller.setSchema(marshall...
@Test void buildsMarshallerWithFormattedOutputProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build(); Marshaller marshaller = factory.createMarshaller(Object.class); assertThat((Boolean) marshaller.getProperty(Marsha...
@Override public CompletableFuture<Void> prepareSnapshot( ChannelStateWriter channelStateWriter, long checkpointId) throws CheckpointException { for (Map.Entry< InputChannelInfo, SpillingAdaptiveSpanningRecordDeserializer< ...
@Test void testSnapshotAfterEndOfPartition() throws Exception { int numInputChannels = 1; int channelId = 0; int checkpointId = 0; VerifyRecordsDataOutput<Long> output = new VerifyRecordsDataOutput<>(); LongSerializer inSerializer = LongSerializer.INSTANCE; StreamTes...
@Override public boolean cleanUnusedTopic(String cluster) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, MQClientException, InterruptedException { return defaultMQAdminExtImpl.cleanUnusedTopic(cluster); }
@Test public void testCleanUnusedTopic() throws InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException { boolean result = defaultMQAdminExt.cleanUnusedTopic("default-cluster"); assertThat(result).isFalse(); }
public static String[] splitString( String string, String separator ) { /* * 0123456 Example a;b;c;d --> new String[] { a, b, c, d } */ // System.out.println("splitString ["+path+"] using ["+separator+"]"); List<String> list = new ArrayList<>(); if ( string == null || string.length() == 0 ) {...
@Test public void testSplitStringWithDelimiterAndEmptyEnclosureMultiCharRemoveEnclosure() { String mask = "Hello%s world"; String[] chunks = {"Hello", " world"}; String stringToSplit = String.format( mask, DELIMITER2 ); String [] result = Const.splitString( stringToSplit, DELIMITER2, "", true ); ...
@Override public HandlerStatus onRead() throws Exception { src.flip(); try { while (src.hasRemaining()) { Packet packet = packetReader.readFrom(src); if (packet == null) { break; } onPacketComplete(packet...
@Test public void whenNormalPacket() throws Exception { ByteBuffer src = ByteBuffer.allocate(1000); Packet packet = new Packet(serializationService.toBytes("foobar")); new PacketIOHelper().writeTo(packet, src); decoder.src(src); decoder.onRead(); assertEquals(1, dis...
public int getEffectiveLayoutVersion() { return getEffectiveLayoutVersion(isRollingUpgrade(), fsImage.getStorage().getLayoutVersion(), NameNodeLayoutVersion.MINIMUM_COMPATIBLE_LAYOUT_VERSION, NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION); }
@Test public void testGetEffectiveLayoutVersion() { assertEquals(-63, FSNamesystem.getEffectiveLayoutVersion(true, -60, -61, -63)); assertEquals(-61, FSNamesystem.getEffectiveLayoutVersion(true, -61, -61, -63)); assertEquals(-62, FSNamesystem.getEffectiveLayoutVersion(true, -62, -6...
public static DwrfTableEncryptionProperties forTable(String encryptTable, String encryptionAlgorithm, String encryptionProvider) { return new DwrfTableEncryptionProperties(Optional.of(encryptTable), Optional.empty(), encryptionAlgorithm, encryptionProvider); }
@Test public void testEncryptTable() { DwrfTableEncryptionProperties properties = forTable("abcd", "test_algo", "test_prov"); assertEquals(properties.toHiveProperties(), ImmutableMap.of( ENCRYPT_TABLE_KEY, "abcd", DWRF_ENCRYPTION_PROVIDER_KEY, "test_prov", ...
public TreeCache start() throws Exception { Preconditions.checkState(treeState.compareAndSet(TreeState.LATENT, TreeState.STARTED), "already started"); if (createParentNodes) { client.createContainers(root.path); } client.getConnectionStateListenable().addListener(connectionSt...
@Test public void testKilledSession() throws Exception { client.create().forPath("/test"); cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); assertEvent(TreeCacheEvent.Type.INITIALIZED); client.c...
@Udf(description = "Converts an INT value in degrees to a value in radians") public Double radians( @UdfParameter( value = "value", description = "The value in degrees to convert to radians." ) final Integer value ) { return radians(value == null ? null : ...
@Test public void shouldHandlePositive() { assertThat(udf.radians(180.0), closeTo(Math.PI, 0.000000000000001)); assertThat(udf.radians(360.0), closeTo(2 * Math.PI, 0.000000000000001)); assertThat(udf.radians(70.73163980890013), closeTo(1.2345, 0.000000000000001)); assertThat(udf.radians(114), closeTo(...
public static TypeParameterMatcher find( final Object object, final Class<?> parametrizedSuperclass, final String typeParamName) { final Map<Class<?>, Map<String, TypeParameterMatcher>> findCache = InternalThreadLocalMap.get().typeParameterMatcherFindCache(); final Class<?> ...
@Test public void testUnsolvedParameter() throws Exception { assertThrows(IllegalStateException.class, new Executable() { @Override public void execute() { TypeParameterMatcher.find(new TypeQ(), TypeX.class, "B"); } }); }
public void load() { Set<CoreExtension> coreExtensions = serviceLoaderWrapper.load(getClass().getClassLoader()); ensureNoDuplicateName(coreExtensions); coreExtensionRepository.setLoadedCoreExtensions(coreExtensions); if (!coreExtensions.isEmpty()) { LOG.info("Loaded core extensions: {}", coreExte...
@Test public void load_has_no_effect_if_there_is_no_ServiceLoader_for_CoreExtension_class() { when(serviceLoaderWrapper.load(any())).thenReturn(Collections.emptySet()); underTest.load(); verify(serviceLoaderWrapper).load(CoreExtensionsLoader.class.getClassLoader()); verify(coreExtensionRepository).s...
public void openFolder( boolean write ) throws KettleException { openFolder( null, true, write ); }
@Test public void openFolderTest() throws KettleException, MessagingException { conn.openFolder( "a/b", false, false ); Folder folder = conn.getFolder(); Assert.assertEquals( "Folder B is opened", "B", folder.getFullName() ); }