focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Collection<ComputeNode> getAllWorkers() { if (hasComputeNode) { return availableID2ComputeNode.values(); } else { return ImmutableList.copyOf(availableID2Backend.values()); } }
@Test public void testGetWorkersPreferringComputeNode() { DefaultWorkerProvider workerProvider; workerProvider = new DefaultWorkerProvider(id2Backend, id2ComputeNode, availableId2Backend, availableId2ComputeNode, true); assertThat(workerProvider.getAl...
public String anonymize(final ParseTree tree) { return build(tree); }
@Test public void shouldAnonymizeCreateTableCorrectly() { final String output = anon.anonymize( "CREATE TABLE my_table (profileId VARCHAR, latitude DOUBLE, longitude DOUBLE)\n" + "WITH (kafka_topic='locations', value_format='json', partitions=1);"); Approvals.verify(output); }
@Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); }
@Test public void nonStandardDust() { Transaction standardTx = new Transaction(); standardTx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)); standardTx.addOutput(COIN, key1); assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, st...
@Override public BytesStreamMessage getStreamMessage(int index) { return _messages.get(index); }
@Test public void testMessageBatchNoStitching() { PulsarConfig config = mock(PulsarConfig.class); when(config.getEnableKeyValueStitch()).thenReturn(false); List<BytesStreamMessage> streamMessages = List.of(PulsarUtils.buildPulsarStreamMessage(_message, config)); PulsarMessageBatch messageBatch = new P...
public void startAsync() { try { udfLoader.load(); ProcessingLogServerUtils.maybeCreateProcessingLogTopic( serviceContext.getTopicClient(), processingLogConfig, ksqlConfig); if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) { log.warn...
@Test public void shouldNotThrowIfNullValueInKsqlConfig() { standaloneExecutor = new StandaloneExecutor( serviceContext, processingLogConfig, new KsqlConfig(Collections.singletonMap("test", null)), ksqlEngine, queriesFile.toString(), udfLoader, false, ...
public Type getType() { return token.getType(); }
@Test public void testTypeDescriptorNested() throws Exception { TypeRememberer<String> rememberer = new TypeRememberer<String>() {}; assertEquals(new TypeToken<String>() {}.getType(), rememberer.descriptorByClass.getType()); assertEquals(new TypeToken<String>() {}.getType(), rememberer.descriptorByInstanc...
public static InetSocketAddress getInetSocketAddressFromRpcURL(String rpcURL) throws Exception { // Pekko URLs have the form schema://systemName@host:port/.... if it's a remote Pekko URL try { final Address address = getAddressFromRpcURL(rpcURL); if (address.host().isDefined() &...
@Test void getHostFromRpcURLHandlesIPv6Addresses() throws Exception { final String ipv6Address = "2001:db8:10:11:12:ff00:42:8329"; final int port = 1234; final InetSocketAddress address = new InetSocketAddress(ipv6Address, port); final String url = "pekko://flink@[" + ipv6Address + ...
public static RuleDescriptionSectionContextDto of(String key, String displayName) { return new RuleDescriptionSectionContextDto(key, displayName); }
@Test void check_of_instantiate_object() { RuleDescriptionSectionContextDto context = RuleDescriptionSectionContextDto.of(CONTEXT_KEY, CONTEXT_DISPLAY_NAME); assertThat(context).extracting(RuleDescriptionSectionContextDto::getKey, RuleDescriptionSectionContextDto::getDisplayName).contains(CONTEXT_KEY, ...
@VisibleForTesting Set<ConsumedPartitionGroup> getCrossRegionConsumedPartitionGroups() { return Collections.unmodifiableSet(crossRegionConsumedPartitionGroups); }
@Test void testComputingCrossRegionConsumedPartitionGroupsCorrectly() throws Exception { final JobVertex v1 = createJobVertex("v1", 4); final JobVertex v2 = createJobVertex("v2", 3); final JobVertex v3 = createJobVertex("v3", 2); v2.connectNewDataSetAsInput( v1, Dist...
public static String format(Integer id) { return format(id, " "); }
@Test public void testFormat() { assertEquals(AreaUtils.format(110105), "北京 北京市 朝阳区"); assertEquals(AreaUtils.format(1), "中国"); assertEquals(AreaUtils.format(2), "蒙古"); }
@Override public boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) { return isPrimitiveType(type); }
@Test void testAccept() { assertTrue(builder.accept(processingEnv, zField.asType())); assertTrue(builder.accept(processingEnv, bField.asType())); assertTrue(builder.accept(processingEnv, cField.asType())); assertTrue(builder.accept(processingEnv, sField.asType())); assertTrue...
@Override public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException { SQLStatement dalStatement = sqlStatementContext.getSq...
@Test void assertMergeForDescribeStatement() throws SQLException { DALStatement dalStatement = new MySQLExplainStatement(); SQLStatementContext sqlStatementContext = mockSQLStatementContext(dalStatement); ShardingDALResultMerger resultMerger = new ShardingDALResultMerger(DefaultDatabase.LOGI...
public static CronPattern of(String pattern) { return new CronPattern(pattern); }
@Test public void lastTest() { // 每月最后一天的任意时间 CronPattern pattern = CronPattern.of("* * * L * ?"); assertMatch(pattern, "2017-07-31 04:20:00"); assertMatch(pattern, "2017-02-28 04:20:00"); // 最后一个月的任意时间 pattern = CronPattern.of("* * * * L ?"); assertMatch(pattern, "2017-12-02 04:20:00"); // 任意天的最后时间 ...
@Override public Result start( WorkflowSummary workflowSummary, Step step, StepRuntimeSummary runtimeSummary) { try { Artifact artifact = createArtifact(workflowSummary, runtimeSummary); return new Result( State.DONE, Collections.singletonMap(artifact.getType().key(), artifac...
@Test public void testForeachCreateArtifactWithRestartFromSpecificNotAlongRestartPath() { int restartIterationId = 2; Map<String, Object> evaluatedResult = new LinkedHashMap<>(); evaluatedResult.put("loop_param", new long[] {1, 2, 3}); Map<String, Parameter> params = new LinkedHashMap<>(); params...
@Override public void beforeJob(JobExecution jobExecution) { LOG.debug("sending before job execution event [{}]...", jobExecution); producerTemplate.sendBodyAndHeader(endpointUri, jobExecution, EventType.HEADER_KEY, EventType.BEFORE.name()); LOG.debug("sent before job execution event"); ...
@Test public void shouldSetBeforeJobEventHeader() throws Exception { // When jobExecutionListener.beforeJob(jobExecution); // Then Exchange beforeJobEvent = consumer().receive("seda:eventQueue"); assertEquals(CamelJobExecutionListener.EventType.BEFORE.name(), ...
@Override public void run() { Optional<RoutingTable> table = tableSupplier.get(); table.ifPresent(this::reportHealth); reportConfigAge(); }
@Test public void config_age_metric() throws Exception { reporter.run(); // No files exist assertEquals(0D, getMetric(NginxMetricsReporter.CONFIG_AGE_METRIC), Double.MIN_VALUE); // Only temporary file exists Path configRoot = fileSystem.getPath("/opt/vespa/var/vespa-hosted/r...
public List<ReceivedMessage> fetchMessages() { List<ReceivedMessage> messageList = new ArrayList<>(); try (SubscriberStub subscriber = pubsubQueueClient.getSubscriber(subscriberStubSettings)) { String subscriptionName = ProjectSubscriptionName.format(googleProjectId, pubsubSubscriptionId); long star...
@Test public void testFetchMessagesZeroTimeout() throws IOException { doNothing().when(mockSubscriber).close(); when(mockPubsubQueueClient.getSubscriber(any())).thenReturn(mockSubscriber); when(mockPubsubQueueClient.getNumUnAckedMessages(SUBSCRIPTION_ID)).thenReturn(100L); PubsubMessagesFetcher fetche...
public void ensureActiveGroup() { while (!ensureActiveGroup(time.timer(Long.MAX_VALUE))) { log.warn("still waiting to ensure active group"); } }
@Test public void testWakeupAfterJoinGroupSent() throws Exception { setupCoordinator(); mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); mockClient.prepareResponse(new MockClient.RequestMatcher() { private int invocations = 0; @Override ...
public boolean setCodeVariants(DefaultIssue issue, Set<String> currentCodeVariants, IssueChangeContext context) { Set<String> newCodeVariants = getNewCodeVariants(issue); if (!currentCodeVariants.equals(newCodeVariants)) { issue.setFieldChange(context, CODE_VARIANTS, currentCodeVariants.isEmpty() ...
@Test void setCodeVariants_whenCodeVariantAdded_shouldBeUpdated() { Set<String> currentCodeVariants = new HashSet<>(Arrays.asList("linux")); Set<String> newCodeVariants = new HashSet<>(Arrays.asList("linux", "windows")); issue.setCodeVariants(newCodeVariants); boolean updated = underTest.setCodeVaria...
public WebServerResponse getWebserverUrls() { return new WebServerResponse("OK", List.of(new WebService("Mijn DigiD", protocol + "://" + host + "/authn_app"))); }
@Test void getWebServerUrlsTest() { ConfigService configService = new ConfigService("http", "SSSSSSSSSSSSSSS", sharedServiceClient, switchService); WebServerResponse webServerResponse = configService.getWebserverUrls(); Assertions.assertEquals("OK", webServerResponse.getStatus()); ...
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test public void testDecodeMultipleDynamicStruct() { String rawInput = "0x00000000000000000000000000000000000000000000000000000000000000a0" + "0000000000000000000000000000000000000000000000000000000000000001" + "0000000000000000000000000000000...
@Override public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) throws Http2Exception { long currentNano = System.nanoTime(); if (currentNano - lastRstFrameNano >= nanosPerWindow) { lastRstFrameNano = currentNano; receivedRstInWindow = 1; ...
@Test public void testRstFrames() throws Exception { listener = new Http2MaxRstFrameListener(frameListener, 1, 1); listener.onRstStreamRead(ctx, 1, Http2Error.STREAM_CLOSED.code()); Thread.sleep(1100); listener.onRstStreamRead(ctx, 1, Http2Error.STREAM_CLOSED.code()); verify(...
@Override public boolean syncData(DistroData data, String targetServer) { if (isNoExistTarget(targetServer)) { return true; } DistroDataRequest request = new DistroDataRequest(data, data.getType()); Member member = memberManager.find(targetServer); if (checkTarget...
@Test void testSyncDataForMemberUnhealthy() throws NacosException { when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenReturn(member); assertFalse(transportAgent.syncData(new DistroData(), member.getAddress())); veri...
@Override public VersionManager getVersionManager() { return original.getVersionManager(); }
@Test public void getVersionManager() { assertEquals(pluginManager.getVersionManager(), wrappedPluginManager.getVersionManager()); }
public String getExternalCacheDirectoryPath() { return this.context != null ? absPath(this.context.getExternalCacheDir()) : ""; }
@Test public void getExternalCacheDirectoryPathIsNotEmpty() { assertThat(contextUtil.getExternalCacheDirectoryPath(), containsString("/external-cache")); }
List<TaskDirectory> listAllTaskDirectories() { return listTaskDirectories(pathname -> pathname.isDirectory() && TASK_DIR_PATH_NAME.matcher(pathname.getName()).matches()); }
@Test public void shouldReturnEmptyArrayIfStateDirDoesntExist() throws IOException { cleanup(); assertFalse(stateDir.exists()); assertTrue(directory.listAllTaskDirectories().isEmpty()); }
public void init(String keyId, String applicationKey, String exportService) throws BackblazeCredentialsException, IOException { // Fetch all the available buckets and use that to find which region the user is in ListBucketsResponse listBucketsResponse = null; String userRegion = null; // The Key ...
@Test public void testInitListBucketException() throws BackblazeCredentialsException, IOException { when(s3Client.listBuckets()).thenThrow(S3Exception.builder().statusCode(403).build()); BackblazeDataTransferClient client = createDefaultClient(); assertThrows(BackblazeCredentialsException.class, () -> { ...
@Override public void onResponse(Call call, okhttp3.Response okHttpResponse) { try { final Response response = OkHttpHttpClient.convertResponse(okHttpResponse); try { @SuppressWarnings("unchecked") final T t = converter == null ? (T) response : conver...
@Test public void shouldReportOAuthException() { handler = new OAuthAsyncCompletionHandler<>(callback, OAUTH_EXCEPTION_RESPONSE_CONVERTER, future); call.enqueue(handler); final Request request = new Request.Builder().url("http://localhost/").build(); final okhttp3.Response response ...
public static UpdateRequirement fromJson(String json) { return JsonUtil.parse(json, UpdateRequirementParser::fromJson); }
@Test public void testUpdateRequirementWithoutRequirementTypeCannotParse() { List<String> invalidJson = ImmutableList.of( "{\"type\":null,\"uuid\":\"2cc52516-5e73-41f2-b139-545d41a4e151\"}", "{\"uuid\":\"2cc52516-5e73-41f2-b139-545d41a4e151\"}"); for (String json : invalidJson...
public int length() { return mName.length(); }
@Test public void length() throws Exception { assertEquals(PropertyKey.Name.HOME.length(), PropertyKey.HOME.length()); }
public static String getOnlineInstanceNodePath(final String instanceId, final InstanceType instanceType) { return String.join("/", "", ROOT_NODE, COMPUTE_NODE, ONLINE_NODE, instanceType.name().toLowerCase(), instanceId); }
@Test void assertGetOnlineInstanceNodePath() { assertThat(ComputeNode.getOnlineInstanceNodePath("foo_instance_1", InstanceType.PROXY), is("/nodes/compute_nodes/online/proxy/foo_instance_1")); assertThat(ComputeNode.getOnlineInstanceNodePath("foo_instance_2", InstanceType.JDBC), is("/nodes/compute_no...
public ConfigCenterBuilder address(String address) { this.address = address; return getThis(); }
@Test void address() { ConfigCenterBuilder builder = ConfigCenterBuilder.newBuilder(); builder.address("address"); Assertions.assertEquals("address", builder.build().getAddress()); }
@CheckForNull public String getDecoratedSourceAsHtml(@Nullable String sourceLine, @Nullable String highlighting, @Nullable String symbols) { if (sourceLine == null) { return null; } DecorationDataHolder decorationDataHolder = new DecorationDataHolder(); if (StringUtils.isNotBlank(highlighting)) ...
@Test public void should_ignore_missing_highlighting() { String sourceLine = " if (toto < 42) {"; assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, null, null)).isEqualTo(" if (toto &lt; 42) {"); assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, "", null)).isEqualTo(" ...
@Override public SQLToken generateSQLToken(final InsertStatementContext insertStatementContext) { Optional<InsertValuesToken> result = findPreviousSQLToken(); Preconditions.checkState(result.isPresent()); Optional<GeneratedKeyContext> generatedKey = insertStatementContext.getGeneratedKeyCont...
@Test void assertGenerateSQLToken() { InsertStatementContext insertStatementContext = mock(InsertStatementContext.class); GeneratedKeyContext generatedKeyContext = getGeneratedKeyContext(); when(insertStatementContext.getGeneratedKeyContext()).thenReturn(Optional.of(generatedKeyContext)); ...
public static int[] getCutIndices(String s, String splitChar, int index) { int found = 0; char target = splitChar.charAt(0); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == target) { found++; } if (found == index) { ...
@Test public void testCutIndicesWithLastToken() throws Exception { String s = "<10> 07 Aug 2013 somesubsystem"; int[] result = SplitAndIndexExtractor.getCutIndices(s, " ", 4); assertEquals(17, result[0]); assertEquals(s.length(), result[1]); }
@VisibleForTesting public KMSClientProvider[] getProviders() { return providers; }
@Test public void testCreation() throws Exception { Configuration conf = new Configuration(); KeyProvider kp = new KMSClientProvider.Factory().createProvider(new URI( "kms://http@host1:9600/kms/foo"), conf); assertTrue(kp instanceof LoadBalancingKMSClientProvider); KMSClientProvider[] provider...
@Override public void commit(TableMetadata base, TableMetadata metadata) { boolean isStageCreate = Boolean.parseBoolean(metadata.properties().get(CatalogConstants.IS_STAGE_CREATE_KEY)); super.commit(base, metadata); if (isStageCreate) { disableRefresh(); /* disable forced refresh */ } ...
@Test void testDoCommitDoesntPersistForStagedTable() { TableMetadata metadata = BASE_TABLE_METADATA.replaceProperties( ImmutableMap.of(CatalogConstants.IS_STAGE_CREATE_KEY, "true")); openHouseInternalTableOperations.commit(null, metadata); // Assert TableMetadata is already set for Tab...
public static void retainMatching(Collection<String> values, String... patterns) { retainMatching(values, Arrays.asList(patterns)); }
@Test public void testRetainMatchingWithMatchingPattern() throws Exception { Collection<String> values = stringToList("A"); StringCollectionUtil.retainMatching(values, "A"); assertTrue(values.contains("A")); }
@Override public void loadData(Priority priority, DataCallback<? super T> callback) { this.callback = callback; serializer.startRequest(priority, url, this); }
@Test public void testRequestComplete_whenCancelledAndUnauthorized_callsCallbackWithNullError() throws Exception { UrlResponseInfo info = getInfo(0, HttpURLConnection.HTTP_FORBIDDEN); fetcher.loadData(Priority.HIGH, callback); Callback urlCallback = urlRequestListenerCaptor.getValue(); urlCallba...
@Override public ObjectNode encode(K8sIpam ipam, CodecContext context) { checkNotNull(ipam, "Kubernetes IPAM cannot be null"); return context.mapper().createObjectNode() .put(IPAM_ID, ipam.ipamId()) .put(IP_ADDRESS, ipam.ipAddress().toString()) .put(N...
@Test public void testK8sIpamEncode() { K8sIpam ipam = new DefaultK8sIpam("network-1-10.10.10.10", IpAddress.valueOf("10.10.10.10"), "network-1"); ObjectNode nodeJson = k8sIpamCodec.encode(ipam, context); assertThat(nodeJson, matchesK8sIpam(ipam)); }
@Override public ByteBuf setFloat(int index, float value) { setInt(index, Float.floatToRawIntBits(value)); return this; }
@Test public void testSetFloatAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().setFloat(0, 1); } }); }
@Override @Nonnull public ListIterator<T> listIterator(final int initialIndex) { final Iterator<T> initialIterator; try { initialIterator = iterator(initialIndex); } catch (NoSuchElementException ex) { throw new IndexOutOfBoundsException(); } return new ...
@Test public void testAlternatingIteration() { ListIterator<Integer> iter = list.listIterator(50); for (int i=0; i<10; i++) { Assert.assertTrue(iter.hasNext()); Assert.assertTrue(iter.hasPrevious()); Assert.assertEquals(50, iter.nextIndex()); Assert.a...
public void setProperty(String name, String value) { if (value == null) { return; } Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("No setter for property [" + name + "] in " + objClass.getName() + "."); } else { ...
@Test public void testDuration() { setter.setProperty("duration", "1.4 seconds"); assertEquals(1400, house.getDuration().getMilliseconds()); }
protected Authorization parseAuthLine(String line) throws ParseException { String[] tokens = line.split("\\s+"); String keyword = tokens[0].toLowerCase(); switch (keyword) { case "topic": return createAuthorization(line, tokens); case "user": ...
@Test public void testParseAuthLineValid_topic_with_space() throws ParseException { Authorization expected = new Authorization(new Topic("/weather/eastern italy/anemometer")); Authorization authorization = authorizator.parseAuthLine("topic readwrite /weather/eastern italy/anemometer"); // V...
@Override public int serializeKV(DataOutputStream out, SizedWritable<?> key, SizedWritable<?> value) throws IOException { return serializePartitionKV(out, -1, key, value); }
@Test public void testSerializeKV() throws IOException { final DataOutputStream dataOut = Mockito.mock(DataOutputStream.class); Mockito.when(dataOut.hasUnFlushedData()).thenReturn(true); Mockito.when(dataOut.shortOfSpace(key.length + value.length + Constants.SIZEOF_K...
@NonNull public AuthorizationResponse auth(@NonNull AuthorizationRequest request) { validateAuthorizationRequest(request); var verifier = generatePkceCodeVerifier(); var codeChallenge = calculateS256CodeChallenge(verifier); var relyingPartyCallback = baseUri.resolve("/auth/callback"); var ste...
@Test void auth_badScopes() { var rpConfig = new RelyingPartyConfig(null, List.of(REDIRECT_URI)); var sut = new AuthService(BASE_URI, rpConfig, null, null, null, null); var scope = "openid email"; var state = UUID.randomUUID().toString(); var nonce = UUID.randomUUID().toString(); var respon...
@Override public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer) { return aggregate(initializer, Materialized.with(null, null)); }
@Test public void namedParamShouldSetName() { final StreamsBuilder builder = new StreamsBuilder(); final KStream<String, String> stream = builder.stream(TOPIC, Consumed .with(Serdes.String(), Serdes.String())); groupedStream = stream.groupByKey(Grouped.with(Serdes.String(), S...
@Override public String getServiceId() { return serviceId; }
@Test public void testGetNacosServiceId() { String groupName = "group"; String format = "%s__%s"; when(nacosContextProperties.getGroup()).thenReturn(groupName); String serviceId = polarisRegistration1.getServiceId(); assertThat(String.format(format, groupName, SERVICE_PROVIDER).equals(serviceId)); }
@Override public Float getFloat(K name) { return null; }
@Test public void testGetFloat() { assertNull(HEADERS.getFloat("name1")); }
public void set(int index) { Preconditions.checkArgument(index < bitLength && index >= 0); int byteIndex = index >>> 3; byte current = memorySegment.get(offset + byteIndex); current |= (1 << (index & BYTE_INDEX_MASK)); memorySegment.put(offset + byteIndex, current); }
@TestTemplate void verifyInputIndex2() { assertThatThrownBy(() -> bitSet.set(-1)).isInstanceOf(IllegalArgumentException.class); }
<K> OperationNode createPartialGroupByKeyOperation( Network<Node, Edge> network, ParallelInstructionNode node, PipelineOptions options, DataflowExecutionContext<?> executionContext, DataflowOperationContext operationContext) throws Exception { ParallelInstruction instruction = n...
@Test public void testCreatePartialGroupByKeyOperation() throws Exception { int producerIndex = 1; int producerOutputNum = 2; ParallelInstructionNode instructionNode = ParallelInstructionNode.create( createPartialGroupByKeyInstruction(producerIndex, producerOutputNum), Exe...
@Override public ConcurrentJobModificationResolveResult resolve(Job localJob, Job storageProviderJob) { //why: we use the JobVersioner to bump the version so it matched the one from the DB new JobVersioner(localJob); storageProvider.save(localJob); return ConcurrentJobModificationRes...
@Test void ifJobHasEnqueuedStateAndWasScheduledTooEarlyByJobZooKeeperItWillResolveLocalJobAndSaveIt() { final Job scheduledJob = aJob() .withFailedState() .withScheduledState() .withVersion(5) .build(); final Job enqueuedJob = aCopyOf(s...
Optional<PriorityAndResource> getPriorityAndResource( final TaskExecutorProcessSpec taskExecutorProcessSpec) { tryAdaptAndAddTaskExecutorResourceSpecIfNotExist(taskExecutorProcessSpec); return Optional.ofNullable( taskExecutorProcessSpecToPriorityAndResource.get(taskExecutorP...
@Test void testExternalResourceFailHadoopVersionNotSupported() { assumeThat(isExternalResourceSupported()).isFalse(); assertThatThrownBy( () -> getAdapterWithExternalResources( SUPPORTED_EXTERNAL_...
public void write(D datum, Encoder out) throws IOException { Objects.requireNonNull(out, "Encoder cannot be null"); try { write(root, datum, out); } catch (TracingNullPointException | TracingClassCastException | TracingAvroTypeException e) { throw e.summarize(root); } }
@Test void unionUnresolvedExceptionExplicitWhichField() throws IOException { Schema s = schemaWithExplicitNullDefault(); GenericRecord r = new GenericData.Record(s); r.put("f", 100); ByteArrayOutputStream bao = new ByteArrayOutputStream(); try { new GenericDatumWriter<>(s).write(r, EncoderFa...
@Override public int indexOfMax() { int index = 0; double value = Double.NEGATIVE_INFINITY; for (int i = 0; i < elements.length; i++) { double tmp = get(i); if (tmp > value) { index = i; value = tmp; } } retu...
@Test public void maxIndex() { DenseVector s = generateVectorB(); assertEquals(5,s.indexOfMax()); }
@Override public void init(DatabaseMetaData metaData) throws SQLException { checkDbVersion(metaData, MIN_SUPPORTED_VERSION); }
@Test public void init_throws_MessageException_if_mssql_2012() throws Exception { assertThatThrownBy(() -> { DatabaseMetaData metadata = newMetadata( 11, 0); underTest.init(metadata); }) .isInstanceOf(MessageException.class) .hasMessage("Unsupported mssql version: 11.0. Minimal support...
public String render(Object o) { StringBuilder result = new StringBuilder(template.length()); render(o, result); return result.toString(); }
@Test(expected = IllegalArgumentException.class) public void missingFieldShouldException() { Template template = new Template("Hello {{wtf}} "); template.render(foo); }
public static <InputT, OutputT> MapElements<InputT, OutputT> via( final InferableFunction<InputT, OutputT> fn) { return new MapElements<>(fn, fn.getInputTypeDescriptor(), fn.getOutputTypeDescriptor()); }
@Test public void testPolymorphicSimpleFunction() throws Exception { pipeline.enableAbandonedNodeEnforcement(false); pipeline .apply(Create.of(1, 2, 3)) // This is the function that needs to propagate the input T to output T .apply("Polymorphic Identity", MapElements.via(new Polymorp...
public static <K, V> WithKeys<K, V> of(SerializableFunction<V, K> fn) { checkNotNull( fn, "WithKeys constructed with null function. Did you mean WithKeys.of((Void) null)?"); return new WithKeys<>(fn, null); }
@Test @Category(NeedsRunner.class) public void testExtractKeys() { PCollection<String> input = p.apply(Create.of(Arrays.asList(COLLECTION)).withCoder(StringUtf8Coder.of())); PCollection<KV<Integer, String>> output = input.apply(WithKeys.of(new LengthAsKey())); PAssert.that(output).containsInAn...
@VisibleForTesting public void updateSlowDiskReportAsync(long now) { if (isUpdateInProgress.compareAndSet(false, true)) { lastUpdateTime = now; new Thread(new Runnable() { @Override public void run() { slowDisksReport = getSlowDisks(diskIDLatencyMap, maxDisksToR...
@Test public void testEmptyReports() { tracker.updateSlowDiskReportAsync(timer.monotonicNow()); assertTrue(getSlowDisksReportForTesting(tracker).isEmpty()); }
private void setRequestId(Message message, Request<?, ?> request) { final Long id = message.getHeader(Web3jConstants.ID, Long.class); LOG.debug("setRequestId {}", id); if (id != null) { request.setId(id); } }
@Test public void setRequestIdTest() throws Exception { Web3ClientVersion response = Mockito.mock(Web3ClientVersion.class); Mockito.when(mockWeb3j.web3ClientVersion()).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Exchange exchange = createExchangeWithBodyA...
@Override public DarkClusterConfigMap getDarkClusterConfigMap(String clusterName) throws ServiceUnavailableException { FutureCallback<DarkClusterConfigMap> darkClusterConfigMapFutureCallback = new FutureCallback<>(); getDarkClusterConfigMap(clusterName, darkClusterConfigMapFutureCallback); try { ...
@Test public void testClusterInfoProviderGetDarkClustersNoCluster() throws InterruptedException, ExecutionException, ServiceUnavailableException { MockStore<ServiceProperties> serviceRegistry = new MockStore<>(); MockStore<ClusterProperties> clusterRegistry = new MockStore<>(); MockStore<UriProperti...
public static boolean isDirectory(URL resourceURL) throws URISyntaxException { final String protocol = resourceURL.getProtocol(); switch (protocol) { case "jar": try { final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection(); ...
@Test void isDirectoryReturnsFalseForFilesWithSpacesInJars() throws Exception { final URL url = new URL("jar:" + resourceJar.toExternalForm() + "!/file with space.txt"); assertThat(url.getProtocol()).isEqualTo("jar"); assertThat(ResourceURL.isDirectory(url)).isFalse(); }
@Override public UpdateStatistics removeStatistics(long snapshotId) { statisticsToSet.put(snapshotId, Optional.empty()); return this; }
@TestTemplate public void testRemoveStatistics() { // Create a snapshot table.newFastAppend().commit(); assertThat(version()).isEqualTo(1); TableMetadata base = readMetadata(); long snapshotId = base.currentSnapshot().snapshotId(); GenericStatisticsFile statisticsFile = new GenericSta...
@Override @CheckForNull public Instant forkDate(String referenceBranchName, Path projectBaseDir) { return null; }
@Test public void forkDate_returns_null() { assertThat(newScmProvider().forkDate("unknown", worktree)).isNull(); }
@Override public int get(PageId pageId, int pageOffset, int bytesToRead, ReadTargetBuffer target, CacheContext cacheContext) { getOrUpdateShadowCache(pageId, bytesToRead, cacheContext); return mCacheManager.get(pageId, pageOffset, bytesToRead, target, cacheContext); }
@Test public void getNotExist() throws Exception { assertEquals(0, mCacheManager.get(PAGE_ID1, PAGE1.length, mBuf, 0)); }
public static String getInstanceWorkerIdNodePath(final String instanceId) { return String.join("/", "", ROOT_NODE, COMPUTE_NODE, WORKER_ID, instanceId); }
@Test void assertGetInstanceWorkerIdNodePath() { assertThat(ComputeNode.getInstanceWorkerIdNodePath("foo_instance"), is("/nodes/compute_nodes/worker_id/foo_instance")); }
@Transactional @PreAuthorize(value = "@permissionValidator.isSuperAdmin()") @PostMapping(value = "/consumers") public ConsumerInfo create( @RequestBody ConsumerCreateRequestVO requestVO, @RequestParam(value = "expires", required = false) @DateTimeFormat(pattern = "yyyyMMddHHmmss") Date expires ...
@Test void createWithBadRequest() { ConsumerService consumerService = Mockito.mock(ConsumerService.class); ConsumerController consumerController = new ConsumerController(consumerService); ConsumerCreateRequestVO requestVO = new ConsumerCreateRequestVO(); // blank appId assertThrows(BadRequestExce...
protected void setMethod() { boolean activateBody = RestMeta.isActiveBody( wMethod.getText() ); boolean activateParams = RestMeta.isActiveParameters( wMethod.getText() ); wlBody.setEnabled( activateBody ); wBody.setEnabled( activateBody ); wApplicationType.setEnabled( activateBody ); wlParamet...
@Test public void testSetMethod_HEAD() { doReturn( RestMeta.HTTP_METHOD_HEAD ).when( method ).getText(); dialog.setMethod(); verify( bodyl, times( 1 ) ).setEnabled( false ); verify( body, times( 1 ) ).setEnabled( false ); verify( type, times( 1 ) ).setEnabled( false ); verify( paramsl, time...
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 optifineIsNotCompatibleWithForge() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/optifine_is_not_compatible_with_forge.txt")), CrashReportAnalyzer.Rule.OPTIFINE_IS_NOT_COMPATIBLE_WITH_FO...
public boolean offer(Serializable event) { if (queue == null) { throw new IllegalStateException("client has no event queue"); } return queue.offer(event); }
@Test public void testOfferEventSequenceAndRun() throws Exception { for (int i = 0; i < 10; i++) { client.offer(TEST_EVENT + i); } Thread thread = new Thread(client); thread.start(); thread.join(1000); assertFalse(thread.isAlive()); ObjectInputStream ois = new ObjectInputStream( ...
@Override public boolean contains(CharSequence name, CharSequence value) { return contains(name, value, false); }
@Test public void testContainsName() { Http2Headers headers = new DefaultHttp2Headers(); headers.add(CONTENT_LENGTH, "36"); assertFalse(headers.contains("Content-Length")); assertTrue(headers.contains("content-length")); assertTrue(headers.contains(CONTENT_LENGTH)); h...
private static MethodDescriptor.MethodType getMethodType(final MethodDescriptor.MethodType methodType) { MethodDescriptor.MethodType grpcMethodType; switch (methodType) { case UNARY: grpcMethodType = MethodDescriptor.MethodType.UNARY; break; case ...
@Test public void getMethodTypeTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { final Method getMethodType = JsonMessage.class.getDeclaredMethod("getMethodType", MethodDescriptor.MethodType.class); getMethodType.setAccessible(true); assertEquals(Method...
public static void partitionSort(List<Map.Entry<String, ? extends Comparable>> arr, int k) { int start = 0; int end = arr.size() - 1; int target = k - 1; while (start < end) { int lo = start; int hi = end; int mid = lo; var pivot = arr.get(...
@Test public void testPartitionSort() { Random rand = new Random(); List<Map.Entry<String, ? extends Comparable>> actual = new ArrayList<>(); List<Map.Entry<String, ? extends Comparable>> expected = new ArrayList<>(); for (int j = 0; j < 100; j++) { Map<String, Integer>...
@Get(uri = "icons") @ExecuteOn(TaskExecutors.IO) @Operation(tags = {"Plugins"}, summary = "Get plugins icons") public MutableHttpResponse<Map<String, PluginIcon>> icons() { Map<String, PluginIcon> icons = pluginRegistry.plugins() .stream() .flatMap(plugin -> Stream.of( ...
@Test void icons() throws URISyntaxException { Helpers.runApplicationContext((applicationContext, embeddedServer) -> { ReactorHttpClient client = ReactorHttpClient.create(embeddedServer.getURL()); Map<String, PluginIcon> list = client.toBlocking().retrieve( HttpReque...
@Override public <T> T convert(DataTable dataTable, Type type) { return convert(dataTable, type, false); }
@Test void convert_to_map_of_string_to_map() { DataTable table = parse("", "| | lat | lon |", "| KMSY | 29.993333 | -90.258056 |", "| KSFO | 37.618889 | -122.375 |", "| KSEA | 47.448889 | -122.309444 |", "| KJFK | 40.639722 |...
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { char subCommand = safeReadLine(reader).charAt(0); String returnCommand = null; if (subCommand == ARRAY_GET_SUB_COMMAND_NAME) { returnCommand = getArray(reader); } else if (s...
@Test public void testGet() { String inputCommand = ArrayCommand.ARRAY_GET_SUB_COMMAND_NAME + "\n" + target + "\ni1\ne\n"; try { command.execute("a", new BufferedReader(new StringReader(inputCommand)), writer); assertEquals("!ys111\n", sWriter.toString()); } catch (Exception e) { e.printStackTrace(); ...
public CompletableFuture<Map<ExecutionAttemptID, Collection<ThreadInfoSample>>> requestThreadInfoSamples( Map<Long, ExecutionAttemptID> threads, final ThreadInfoSamplesRequest requestParams) { checkNotNull(threads, "threads must not be null"); checkNot...
@Test void testSampleTaskThreadInfo() throws Exception { Set<IdleTestTask> tasks = new HashSet<>(); executeWithTerminationGuarantee( () -> { tasks.add(new IdleTestTask()); tasks.add(new IdleTestTask()); Thread.sleep(2000); ...
public static Status unblock( final UnsafeBuffer logMetaDataBuffer, final UnsafeBuffer termBuffer, final int blockedOffset, final int tailOffset, final int termId) { Status status = NO_ACTION; int frameLength = frameLengthVolatile(termBuffer, blockedOffset); ...
@Test void shouldTakeNoActionIfMessageNonCommittedAfterScan() { final int messageLength = HEADER_LENGTH * 4; final int termOffset = 0; final int tailOffset = messageLength * 2; when(mockTermBuffer.getIntVolatile(termOffset)) .thenReturn(0) .thenReturn(-me...
public Schema getSchema() { return context.getSchema(); }
@Test public void testNestedSchema() { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(Nested.getDescriptor()); Schema schema = schemaProvider.getSchema(); assertEquals(NESTED_SCHEMA, schema); }
public static DataSchema avroToDataSchema(String avroSchemaInJson, AvroToDataSchemaTranslationOptions options) throws IllegalArgumentException { ValidationOptions validationOptions = SchemaParser.getDefaultSchemaParserValidationOptions(); validationOptions.setAvroUnionMode(true); SchemaParserFactory ...
@Test public void testAvroUnionModeChaining() throws IOException { String expectedSchema = "{ " + " \"type\" : \"record\", " + " \"name\" : \"A\", " + " \"namespace\" : \"com.linkedin.pegasus.test\", " + " \"fields\" : [ " + " { " + " \"name\" : \"some...
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception { return fromXmlPartial(toInputStream(partial, UTF_8), o); }
@Test void shouldLoadPartialConfigWithPipeline() throws Exception { String partialConfigWithPipeline = (""" <cruise schemaVersion='%d'> <pipelines group="first"> <pipeline name="pipeline"> <mate...
public static void main(String[] args) { if (args.length < 1 || args[0].equals("-h") || args[0].equals("--help")) { System.out.println(usage); return; } // Copy args, because CommandFormat mutates the list. List<String> argsList = new ArrayList<String>(Arrays.asList(args)); CommandForma...
@Test public void testJar() throws IOException { File file = new File(TEST_DIR, "classpath.jar"); Classpath.main(new String[] { "--jar", file.getAbsolutePath() }); assertTrue(stdout.toByteArray().length == 0); assertTrue(stderr.toByteArray().length == 0); assertTrue(file.exists()); assertJar(f...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() != ChatMessageType.SPAM) { return; } var message = event.getMessage(); if (FISHING_CATCH_REGEX.matcher(message).find()) { session.setLastFishCaught(Instant.now()); spotOverlay.setHidden(false); fishingSpotMinimapOve...
@Test public void testCormorant() { ChatMessage chatMessage = new ChatMessage(); chatMessage.setType(ChatMessageType.SPAM); chatMessage.setMessage("Your cormorant returns with its catch."); fishingPlugin.onChatMessage(chatMessage); assertNotNull(fishingPlugin.getSession().getLastFishCaught()); }
@Override public int compare( Object data1, Object data2 ) throws KettleValueException { InetAddress inet1 = getInternetAddress( data1 ); InetAddress inet2 = getInternetAddress( data2 ); int cmp = 0; if ( inet1 == null ) { if ( inet2 == null ) { cmp = 0; } else { cmp = -1; ...
@Test public void testCompare() throws UnknownHostException, KettleValueException { ValueMetaInternetAddress vm = new ValueMetaInternetAddress(); InetAddress smaller = InetAddress.getByName( "127.0.0.1" ); InetAddress larger = InetAddress.getByName( "127.0.1.1" ); assertTrue( vm.isSortedAscending() )...
protected String getTag(ILoggingEvent event) { // format tag based on encoder layout; truncate if max length // exceeded (only necessary for isLoggable(), which throws // IllegalArgumentException) String tag = (this.tagEncoder != null) ? this.tagEncoder.getLayout().doLayout(event) : event.getLoggerName(...
@Test public void longTagAllowedIfNotCheckLoggable() { LoggingEvent event = new LoggingEvent(); event.setMessage(TAG); boolean checkLoggable = false; setTagPattern(TAG, checkLoggable); String actualTag = logcatAppender.getTag(event); assertThat(TRUNCATED_TAG, is(not(actualTag))); assertT...
@Override public boolean readyToExecute() throws UserException { if (checkReadyToExecuteFast()) { return true; } KafkaRoutineLoadJob kafkaRoutineLoadJob = (KafkaRoutineLoadJob) job; Map<Integer, Long> latestOffsets = KafkaUtil.getLatestOffsets(kafkaRoutineLoadJob.getBrok...
@Test public void testReadyToExecute(@Injectable KafkaRoutineLoadJob kafkaRoutineLoadJob) throws Exception { new MockUp<RoutineLoadMgr>() { @Mock public RoutineLoadJob getJob(long jobId) { return kafkaRoutineLoadJob; } }; new MockUp<KafkaU...
@Override public void addDocInfo(final UpstreamInstance instance, final String docInfoJson, final String oldMd5, final Consumer<DocInfo> callback) { if (StringUtils.isEmpty(docInfoJson)) { return; } String newMd5 = DigestUtils.md5DigestAsHex(docInfoJson.getBytes(StandardCharsets....
@Test public void testAddDocInfo() { UpstreamInstance instance = new UpstreamInstance(); instance.setContextPath("/testClusterName"); AtomicBoolean atomicBoolean = new AtomicBoolean(false); docManager.addDocInfo(instance, SwaggerDocParserTest.DOC_INFO_JSON, "", docInfo -> { ...
@Override public void replaceNode(ResourceId path, DataNode node) { super.replaceNode(toAbsoluteId(path), node); }
@Test public void testReplaceNode() { view.replaceNode(relIntf, node); assertTrue(ResourceIds.isPrefix(rid, realPath)); }
@Override public boolean isEnabled() { return true; }
@Test public void isEnabled_returnsTrue() { assertThat(underTest.isEnabled()).isTrue(); }
@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 workerAddrUpdateWithIdUnchanged() throws Exception { ConsistentHashPolicy policy = new ConsistentHashPolicy(mConf); List<WorkerInfo> workers = new ArrayList<>(); workers.add(new WorkerInfo().setIdentity(WorkerIdentityTestUtils.ofLegacyId(1L)) .setAddress(new WorkerNetAddress().se...
@Override public long extractWatermark(IcebergSourceSplit split) { return split.task().files().stream() .map( scanTask -> { Preconditions.checkArgument( scanTask.file().lowerBounds() != null && scanTask.file().lowerBounds().get(eventTimeFie...
@TestTemplate public void testEmptyStatistics() throws IOException { assumeThat(columnName).isEqualTo("timestamp_column"); // Create an extractor for a column we do not have statistics ColumnStatsWatermarkExtractor extractor = new ColumnStatsWatermarkExtractor(10, "missing_field"); assertThat...
@Override public PendingSplitsCheckpoint<FileSourceSplit> snapshotState(long checkpointId) throws Exception { final PendingSplitsCheckpoint<FileSourceSplit> checkpoint = PendingSplitsCheckpoint.fromCollectionSnapshot( splitAssigner.remainingSplits(), paths...
@Test void testDiscoverSplitWhenNoReaderRegistered() throws Exception { final TestingFileEnumerator fileEnumerator = new TestingFileEnumerator(); final TestingSplitEnumeratorContext<FileSourceSplit> context = new TestingSplitEnumeratorContext<>(4); final ContinuousFileSplitEn...
long getNodeResultLimit(int ownedPartitions) { return isQueryResultLimitEnabled ? (long) ceil(resultLimitPerPartition * ownedPartitions) : Long.MAX_VALUE; }
@Test public void testNodeResultLimitSinglePartition() { initMocksWithConfiguration(200000, 3); assertEquals(849, limiter.getNodeResultLimit(1)); }
@Override public UserCodeNamespaceConfig setName(@Nonnull String name) { Objects.requireNonNull(name, "Namespace name cannot be null"); this.name = name; return this; }
@Test (expected = NullPointerException.class) public void testNullName() { userCodeNamespaceConfig.setName(null); }
public void setPrefix(String prefix) { this.prefix = prefix; }
@Test public void customMetricsPrefix() throws Exception { iqtp.setPrefix(PREFIX); iqtp.start(); assertThat(metricRegistry.getNames()) .overridingErrorMessage("Custom metrics prefix doesn't match") .allSatisfy(name -> assertThat(name).startsWith(PREFIX)); ...
@Udf public <T> boolean contains( @UdfParameter final List<T> array, @UdfParameter final T val ) { return array != null && array.contains(val); }
@Test public void shouldFindDoublesInList() { assertTrue(udf.contains(Arrays.asList(1.0, 2.0, 3.0), 2.0)); assertFalse(udf.contains(Arrays.asList(1.0, 2.0, 3.0), 4.0)); assertFalse(udf.contains(Arrays.asList(1.0, 2.0, 3.0), "1")); assertFalse(udf.contains(Arrays.asList(1.0, 2.0, 3.0), "aaa")); }
public boolean isReusableTable() { return isReusableTable; }
@Test public void testIsReusableTable() { assertTrue(CONFIGURATION_1.isReusableTable()); assertFalse(CONFIGURATION_2.isReusableTable()); }
public void addChild(Entry entry) { childEntries.add(entry); entry.setParent(this); }
@Test public void findsAncestorComponent(){ Component component = mock(Component.class); Entry structureWithEntry = new Entry(); new EntryAccessor().setComponent(structureWithEntry, component); final Entry level1child = new Entry(); structureWithEntry.addChild(level1child); final Entry level2child = ne...
@Override public void registerStore(final StateStore store, final StateRestoreCallback stateRestoreCallback, final CommitCallback commitCallback) { final String storeName = store.name(); // TODO (KAFKA-12887): we should not trigger user's ...
@Test public void shouldThrowIllegalArgumentExceptionOnRegisterWhenStoreHasAlreadyBeenRegistered() { final ProcessorStateManager stateManager = getStateManager(Task.TaskType.ACTIVE); stateManager.registerStore(persistentStore, persistentStore.stateRestoreCallback, null); assertThrows(Illeg...