focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public PipelineOptions get() { return options; }
@Test public void testIndependence() throws Exception { SerializablePipelineOptions first = new SerializablePipelineOptions( PipelineOptionsFactory.fromArgs("--foo=first").as(MyOptions.class)); SerializablePipelineOptions firstCopy = SerializableUtils.clone(first); SerializablePipeline...
@Override public Num calculate(BarSeries series, Position position) { Num averageProfit = averageProfitCriterion.calculate(series, position); if (averageProfit.isZero()) { // only loosing positions means a ratio of 0 return series.zero(); } Num averageLoss = a...
@Test public void calculateProfitWithShortPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 85, 80, 70, 100, 95); TradingRecord tradingRecord = new BaseTradingRecord(Trade.sellAt(0, series), Trade.buyAt(1, series), Trade.sellAt(2, series), Trade.buyAt(5, series...
public static boolean isNative(RunnerApi.PTransform pTransform) { // TODO(https://github.com/apache/beam/issues/20192) Use default (context) classloader. Iterator<IsNativeTransform> matchers = ServiceLoader.load(IsNativeTransform.class, NativeTransforms.class.getClassLoader()) .iterator(); ...
@Test public void testNoMatch() { Assert.assertFalse(NativeTransforms.isNative(RunnerApi.PTransform.getDefaultInstance())); }
@SuppressWarnings( "LockAcquiredButNotSafelyReleased" ) public AutoCloseableLock lock() throws IllegalStateException { checkNotReleased(); lock.lock(); return autoCloseable; }
@Test(timeout = 1000) public void willUseDifferentLocksForDifferentClassesWithTheSamePart() { final AtomicBoolean lockAcquired = new AtomicBoolean(false); final AtomicInteger callCount = new AtomicInteger(0); thread1 = new Thread(() -> { try (final AutoCloseableReentrantLock.Au...
@Override public int size() { return values.length; }
@Test public void hasASize() throws Exception { assertThat(snapshot.size()) .isEqualTo(5); }
@Override public void transitionToActive(final StreamTask streamTask, final RecordCollector recordCollector, final ThreadCache newCache) { if (stateManager.taskType() != TaskType.ACTIVE) { throw new IllegalStateException("Tried to transition processor context to active but the state manager's " ...
@Test public void localSessionStoreShouldNotAllowInitOrClose() { foreachSetUp(); when(stateManager.taskType()).thenReturn(TaskType.ACTIVE); when(stateManager.getGlobalStore(anyString())).thenReturn(null); final SessionStore<String, Long> sessionStore = mock(SessionStore.class); ...
@Override public CheckForDecommissioningNodesResponse checkForDecommissioningNodes( CheckForDecommissioningNodesRequest request) throws YarnException, IOException { // Parameter check if (request == null) { RouterServerUtil.logAndThrowException("Missing checkForDecommissioningNodes request.", nul...
@Test public void testCheckForDecommissioningNodesRequest() throws Exception { // null request1. LambdaTestUtils.intercept(YarnException.class, "Missing checkForDecommissioningNodes request.", () -> interceptor.checkForDecommissioningNodes(null)); // null request2. CheckForDecommissioningNode...
public static DeleteAclsRequest parse(ByteBuffer buffer, short version) { return new DeleteAclsRequest(new DeleteAclsRequestData(new ByteBufferAccessor(buffer), version), version); }
@Test public void shouldRoundTripLiteralV0() { final DeleteAclsRequest original = new DeleteAclsRequest.Builder(requestData(LITERAL_FILTER)).build(V0); final ByteBuffer buffer = original.serialize(); final DeleteAclsRequest result = DeleteAclsRequest.parse(buffer, V0); assertReques...
static String getConfigValueAsString(ServiceConfiguration conf, String configProp) throws IllegalArgumentException { String value = getConfigValueAsStringImpl(conf, configProp); log.info("Configuration for [{}] is [{}]", configProp, value); return ...
@Test public void testGetConfigValueAsStringReturnsDefaultIfMissing() { Properties props = new Properties(); ServiceConfiguration config = new ServiceConfiguration(); config.setProperties(props); String actual = ConfigUtils.getConfigValueAsString(config, "prop1", "default"); ...
public int get(final int key) { final int initialValue = this.initialValue; final int[] entries = this.entries; @DoNotSub final int mask = entries.length - 1; @DoNotSub int index = Hashing.evenHash(key, mask); int value; while (initialValue != (value = entries[index ...
@Test void getShouldReturnInitialValueWhenEmpty() { assertEquals(INITIAL_VALUE, map.get(1)); }
public static <T extends Metric> T safelyRegister(MetricRegistry metricRegistry, String name, T metric) { try { return metricRegistry.register(name, metric); } catch (IllegalArgumentException ignored) { // safely ignore already existing metric, and simply return the one registere...
@Test public void safelyRegister() { final MetricRegistry metricRegistry = new MetricRegistry(); final Gauge<Long> longGauge = new Gauge<>() { @Override public Long getValue() { return 0L; } }; final Gauge<Long> newGauge = MetricU...
@Override public void checkServerTrusted(final X509Certificate[] certs, final String cipher) throws CertificateException { if((certs != null)) { if(log.isDebugEnabled()) { log.debug("Server certificate chain:"); for(int i = 0; i < certs.length; i++) { ...
@Test(expected = CertificateExpiredException.class) public void testCheckServerTrusted() throws Exception { final DefaultX509TrustManager m = new DefaultX509TrustManager(); InputStream inStream = new FileInputStream("src/test/resources/OXxlRDVcWqdPEvFm.cer"); CertificateFactory cf = Certific...
@VisibleForTesting public TaskAttemptEvent createContainerFinishedEvent(ContainerStatus cont, TaskAttemptId attemptId) { TaskAttemptEvent event; switch (cont.getExitStatus()) { case ContainerExitStatus.ABORTED: case ContainerExitStatus.PREEMPTED: case ContainerExitStatus.KILLED_BY_CONTAINER_...
@Test public void testCompletedContainerEvent() { RMContainerAllocator allocator = new RMContainerAllocator( mock(ClientService.class), mock(AppContext.class), new NoopAMPreemptionPolicy()); TaskAttemptId attemptId = MRBuilderUtils.newTaskAttemptId( MRBuilderUtils.newTaskId( ...
@Override public <K, T> UncommittedBundle<T> createKeyedBundle( StructuralKey<K> key, PCollection<T> output) { return new CloningBundle<>(underlying.createKeyedBundle(key, output)); }
@Test public void keyedBundleEncodeFailsAddFails() { PCollection<Record> pc = p.apply(Create.empty(new RecordNoEncodeCoder())); UncommittedBundle<Record> bundle = factory.createKeyedBundle(StructuralKey.of("foo", StringUtf8Coder.of()), pc); thrown.expect(UserCodeException.class); thrown.expec...
public int compareNodePositions() { if(beginPath.length == 0 && endPath.length == 0) return 0; if(beginPath.length == 0) return -1; if(endPath.length == 0) return 1; return Integer.compare(beginPath[0], endPath[0]); }
@Test public void compareDescendantNodeToParent(){ final NodeModel parent = root(); final NodeModel node1 = new NodeModel("node1", map); parent.insert(node1); final int compared = new NodeRelativePath(parent, node1).compareNodePositions(); assertTrue(compared < 0); }
public static boolean isNormalizedPathOutsideWorkingDir(String path) { final String normalize = FilenameUtils.normalize(path); final String prefix = FilenameUtils.getPrefix(normalize); return (normalize != null && StringUtils.isBlank(prefix)); }
@Test public void shouldReturnFalseIfGivenFolderWithRelativeTakesYouOutOfSandbox() { assertThat(FilenameUtil.isNormalizedPathOutsideWorkingDir("../tmp"), is(false)); assertThat(FilenameUtil.isNormalizedPathOutsideWorkingDir("tmp/../../../pavan"), is(false)); }
@SuppressWarnings("MethodLength") static void dissectControlRequest( final ArchiveEventCode eventCode, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder); ...
@Test void controlRequestConnect() { internalEncodeLogHeader(buffer, 0, 32, 64, () -> 5_600_000_000L); final ConnectRequestEncoder requestEncoder = new ConnectRequestEncoder(); requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder) .correlationId(88) ...
public static void prepareFilesForStaging(FileStagingOptions options) { List<String> filesToStage = options.getFilesToStage(); if (filesToStage == null || filesToStage.isEmpty()) { filesToStage = detectClassPathResourcesToStage(ReflectHelpers.findClassLoader(), options); LOG.info( "Pipelin...
@Test public void testPrepareFilesForStagingUndefinedFilesToStage() throws IOException { String temporaryLocation = tmpFolder.newFolder().getAbsolutePath(); FileStagingOptions options = PipelineOptionsFactory.create().as(FileStagingOptions.class); options.setTempLocation(temporaryLocation); Pipeline...
public void removeDataConnection(String name, boolean ifExists) { if (!dataConnectionStorage.removeDataConnection(name)) { if (!ifExists) { throw QueryException.error("Data connection does not exist: " + name); } } else { listeners.forEach(TableListene...
@Test public void when_removesNonExistingDataConnectionWithIfExists_then_succeeds() { // given String name = "name"; given(relationsStorage.removeDataConnection(name)).willReturn(false); // when // then dataConnectionResolver.removeDataConnection(name, true); }
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testForwardedPojo() { String[] forwardedFields = {"int1->int2; int3->int1; string1 "}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); SemanticPropUtil.getSemanticPropsSingleFromString( sp, forwardedFields, null, null, pojoType, pojoType); ...
@Override public CustomResponse<TokenResponse> refreshToken(TokenRefreshRequest tokenRefreshRequest) { return userServiceClient.refreshToken(tokenRefreshRequest); }
@Test void refreshToken_ValidTokenRefreshRequest_ReturnsCustomResponse() { // Given TokenRefreshRequest tokenRefreshRequest = TokenRefreshRequest.builder() .refreshToken("validRefreshToken") .build(); TokenResponse tokenResponse = TokenResponse.builder() ...
@Override public int hashCode() { int result = 1; result = 31 * result + Objects.hashCode(username); result = 31 * result + Objects.hashCode(getPasswordValue()); result = 31 * result + Objects.hashCode(getSocketAddress().get()); result = 31 * result + Boolean.hashCode(getNonProxyHostsValue()); result = 31 ...
@Test void differentAddresses() { assertThat(createProxy(ADDRESS_1, PASSWORD_1)).isNotEqualTo(createProxy(ADDRESS_2, PASSWORD_1)); assertThat(createProxy(ADDRESS_1, PASSWORD_1).hashCode()).isNotEqualTo(createProxy(ADDRESS_2, PASSWORD_1).hashCode()); }
public static String getInstanceIdByComputeNode(final String computeNodePath) { Pattern pattern = Pattern.compile(getComputeNodePath() + "(/status|/worker_id|/labels)" + "/([\\S]+)$", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(computeNodePath); return matcher.find() ? matcher.g...
@Test void assertGetInstanceIdByComputeNodePath() { assertThat(ComputeNode.getInstanceIdByComputeNode("/nodes/compute_nodes/status/foo_instance_1"), is("foo_instance_1")); assertThat(ComputeNode.getInstanceIdByComputeNode("/nodes/compute_nodes/worker_id/foo_instance_2"), is("foo_instance_2")); ...
public void batchAckMessageAsync( final String addr, final long timeOut, final AckCallback ackCallback, final String topic, final String consumerGroup, final List<String> extraInfoList ) throws RemotingException, MQBrokerException, InterruptedException { Strin...
@Test public void testBatchAckMessageAsync() throws MQBrokerException, RemotingException, InterruptedException { AckCallback callback = mock(AckCallback.class); List<String> extraInfoList = new ArrayList<>(); extraInfoList.add(String.format("%s %s %s %s %s %s %d %d", "1", "2", "3", "4", "5",...
public static MountTo to(final String target) { return new MountTo(checkNotNullOrEmpty(target, "Target should not be null")); }
@Test public void should_return_bad_request_for_nonexistence_file() throws Exception { server.mount(MOUNT_DIR, to("/dir")); assertThrows(HttpResponseException.class, () -> running(server, () -> helper.get(remoteUrl("/dir/unknown.response")))); }
@GetMapping(params = "beta=true") @Secured(action = ActionTypes.READ, signType = SignType.CONFIG) public RestResult<ConfigInfo4Beta> queryBeta(@RequestParam(value = "dataId") String dataId, @RequestParam(value = "group") String group, @RequestParam(value = "tenant", required = false, def...
@Test void testQueryBeta() throws Exception { ConfigInfoBetaWrapper configInfoBetaWrapper = new ConfigInfoBetaWrapper(); configInfoBetaWrapper.setDataId("test"); configInfoBetaWrapper.setGroup("test"); configInfoBetaWrapper.setContent("test"); when(configInf...
@Override public MergedResult decorate(final QueryResult queryResult, final SQLStatementContext sqlStatementContext, final MaskRule rule) { return new MaskMergedResult(maskRule, selectStatementContext, new TransparentMergedResult(queryResult)); }
@Test void assertDecorateMergedResult() throws SQLException { MergedResult mergedResult = mock(MergedResult.class); when(mergedResult.next()).thenReturn(true); MaskDQLResultDecorator decorator = new MaskDQLResultDecorator(mock(MaskRule.class), mock(SelectStatementContext.class)); Mer...
public static CreateSourceProperties from(final Map<String, Literal> literals) { try { return new CreateSourceProperties(literals, DurationParser::parse, false); } catch (final ConfigException e) { final String message = e.getMessage().replace( "configuration", "property" )...
@Test public void shouldThrowOnConstructionInvalidTimestampFormat() { // When: final Exception e = assertThrows( KsqlException.class, () -> from( of(TIMESTAMP_FORMAT_PROPERTY, new StringLiteral("invalid"))) ); // Then: assertThat(e.getMessage(), containsString("Invalid...
public void inputWatermark(Watermark watermark, int channelIndex, DataOutput<?> output) throws Exception { final SubpartitionStatus subpartitionStatus; if (watermark instanceof InternalWatermark) { int subpartitionStatusIndex = ((InternalWatermark) watermark).getSubpartitionIndex...
@Test void testSingleInputDecreasingWatermarksYieldsNoOutput() throws Exception { StatusWatermarkOutput valveOutput = new StatusWatermarkOutput(); StatusWatermarkValve valve = new StatusWatermarkValve(1); valve.inputWatermark(new Watermark(25), 0, valveOutput); assertThat(valveOutpu...
@Override public OpenstackVtap createVtap(Type type, OpenstackVtapCriterion vtapCriterion) { checkNotNull(type, VTAP_DESC_NULL, "type"); checkNotNull(vtapCriterion, VTAP_DESC_NULL, "vtapCriterion"); Set<DeviceId> txDevices = type.isValid(Type.VTAP_TX) ? getEdgeDevice(Type.VT...
@Test(expected = NullPointerException.class) public void testCreateNullVtap() { target.createVtap(null, null); }
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); gauges.put("total.init", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getInit() + mxBean.getNonHeapMemoryUsage().getInit()); gauges.put("total.used", (Gauge<Long>) () -...
@Test public void hasAGaugeForHeapCommitted() { final Gauge gauge = (Gauge) gauges.getMetrics().get("heap.committed"); assertThat(gauge.getValue()) .isEqualTo(10L); }
public static <T> Read<T> read() { return new AutoValue_JdbcIO_Read.Builder<T>() .setFetchSize(DEFAULT_FETCH_SIZE) .setOutputParallelization(true) .build(); }
@Test public void testReadWithCoderInference() { PCollection<TestRow> rows = pipeline.apply( JdbcIO.<TestRow>read() .withDataSourceConfiguration(DATA_SOURCE_CONFIGURATION) .withQuery(String.format("select name,id from %s where name = ?", READ_TABLE_NAME)) ...
@Override public int size() { return get(sizeAsync()); }
@Test public void testSize() { RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple"); set.add(0, 1); set.add(1, 2); set.add(2, 3); set.add(2, 3); set.add(3, 4); set.add(4, 5); set.add(4, 5); Assertions.assertEquals(5, set.size(...
public B filter(String filter) { this.filter = filter; return getThis(); }
@Test void filter() { InterfaceBuilder builder = new InterfaceBuilder(); builder.filter("mockfilter"); Assertions.assertEquals("mockfilter", builder.build().getFilter()); }
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) { if (statsEnabled) { stats.log(deviceStateServiceMsg); } stateService.onQueueMsg(deviceStateServiceMsg, callback); }
@Test public void givenStatsDisabled_whenForwardingInactivityMsgToStateService_thenStatsAreNotRecorded() { // GIVEN ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "stats", statsMock); ReflectionTestUtils.setField(defaultTbCoreConsumerServiceMock, "statsEnabled", false); ...
@Override public void upgrade() { migrationHelpers.removeBuiltinRole("Field Type Mappings Manager"); }
@Test void testRemovesProperRole() { toTest.upgrade(); verify(migrationHelpers).removeBuiltinRole("Field Type Mappings Manager"); verifyNoMoreInteractions(migrationHelpers); }
public static KeyPair loadKey(File f, String passwd) throws IOException, GeneralSecurityException { return loadKey(readPemFile(f), passwd); }
@Test public void loadKeyBroken() throws IOException, GeneralSecurityException { File file = new File(this.getClass().getResource("openssh-broken").getFile()); String password = "password"; assertThrows(IllegalArgumentException.class, () -> PrivateKeyProvider.loadKey(file, password)); }
protected static Map<String, String> appendParameters( Map<String, String> parameters, Map<String, String> appendParameters) { if (parameters == null) { parameters = new HashMap<>(); } parameters.putAll(appendParameters); return parameters; }
@Test void appendParameters() { Map<String, String> source = null; source = AbstractBuilder.appendParameter(source, "default.num", "one"); source = AbstractBuilder.appendParameter(source, "num", "ONE"); Assertions.assertTrue(source.containsKey("default.num")); Assertions.as...
public static Write write(String url, String token) { checkNotNull(url, "url is required."); checkNotNull(token, "token is required."); return write(StaticValueProvider.of(url), StaticValueProvider.of(token)); }
@Test @Category(NeedsRunner.class) public void successfulSplunkIOSingleBatchParallelismTest() { // Create server expectation for success. mockServerListening(200); int testPort = mockServerRule.getPort(); int testParallelism = 2; String url = Joiner.on(':').join("http://localhost", testPort); ...
public static String getGroupName(final String serviceNameWithGroup) { if (StringUtils.isBlank(serviceNameWithGroup)) { return StringUtils.EMPTY; } if (!serviceNameWithGroup.contains(Constants.SERVICE_INFO_SPLITER)) { return Constants.DEFAULT_GROUP; } retu...
@Test void testGetGroupNameWithEmpty() { assertEquals(StringUtils.EMPTY, NamingUtils.getGroupName(null)); }
@Override protected String convertToString(final String value) { return value; }
@Test void testConvertToString() throws Exception { final String expected = "test.jar"; final String toString = jarIdPathParameter.convertToString(expected); assertThat(toString).isEqualTo(expected); }
public void goOnlineFromConsuming(SegmentZKMetadata segmentZKMetadata) throws InterruptedException { _serverMetrics.setValueOfTableGauge(_clientId, ServerGauge.LLC_PARTITION_CONSUMING, 0); try { // Remove the segment file before we do anything else. removeSegmentFile(); _leaseExtender.re...
@Test public void testFileRemovedDuringOnlineTransition() throws Exception { FakeRealtimeSegmentDataManager segmentDataManager = createFakeSegmentManager(); SegmentCompletionProtocol.Response.Params params = new SegmentCompletionProtocol.Response.Params(); params.withStatus(SegmentCompletionProtoco...
public synchronized @Nullable WorkItemServiceState reportError(Throwable e) throws IOException { checkState(!finalStateSent, "cannot reportUpdates after sending a final state"); if (wasAskedToAbort) { LOG.info("Service already asked to abort work item, not reporting ignored progress."); return null;...
@Test public void reportError() throws IOException { RuntimeException error = new RuntimeException(); error.fillInStackTrace(); statusClient.reportError(error); verify(workUnitClient).reportWorkItemStatus(statusCaptor.capture()); WorkItemStatus workStatus = statusCaptor.getValue(); assertTha...
public List<JobVertex> getVerticesSortedTopologicallyFromSources() throws InvalidProgramException { // early out on empty lists if (this.taskVertices.isEmpty()) { return Collections.emptyList(); } List<JobVertex> sorted = new ArrayList<JobVertex>(this.taskVertice...
@Test public void testTopologicalSort1() { JobVertex source1 = new JobVertex("source1"); JobVertex source2 = new JobVertex("source2"); JobVertex target1 = new JobVertex("target1"); JobVertex target2 = new JobVertex("target2"); JobVertex intermediate1 = new JobVertex("intermed...
@Override public Integer doCall() throws Exception { List<Row> rows = new ArrayList<>(); JsonObject plugins = loadConfig().getMap("plugins"); plugins.forEach((key, value) -> { JsonObject details = (JsonObject) value; String name = details.getStringOrDefault("name", ...
@Test public void shouldGetPlugin() throws Exception { PluginHelper.enable(PluginType.CAMEL_K); PluginGet command = new PluginGet(new CamelJBangMain().withPrinter(printer)); command.doCall(); List<String> output = printer.getLines(); Assertions.assertEquals(2, output.size()...
public synchronized Schema create(URI id, String refFragmentPathDelimiters) { URI normalizedId = id.normalize(); if (!schemas.containsKey(normalizedId)) { URI baseId = removeFragment(id).normalize(); if (!schemas.containsKey(baseId)) { logger.debug("Reading sch...
@Test public void createWithAbsolutePath() throws URISyntaxException { URI schemaUri = getClass().getResource("/schema/address.json").toURI(); Schema schema = new SchemaStore().create(schemaUri, "#/."); assertThat(schema, is(notNullValue())); assertThat(schema.getId(), is(equalTo(...
public static String stripTrailingSlash(String path) { Preconditions.checkArgument(!Strings.isNullOrEmpty(path), "path must not be null or empty"); String result = path; while (!result.endsWith("://") && result.endsWith("/")) { result = result.substring(0, result.length() - 1); } return resul...
@Test public void testStripTrailingSlashWithInvalidPath() { String[] invalidPaths = new String[] {null, ""}; for (String invalidPath : invalidPaths) { assertThatThrownBy(() -> LocationUtil.stripTrailingSlash(invalidPath)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("pa...
public static void registerExternalConfigLoader(ExternalConfigLoader configLoader) { wLock.lock(); try { CONFIG_LOADERS.add(configLoader); CONFIG_LOADERS.sort(Comparator.comparingInt(ExternalConfigLoader::getOrder)); } finally { wLock.unlock(); } }
@Test public void registerExternalConfigLoader() throws Exception { }
String getPropertyName(String metricsName) { return new StringBuilder("timer") .append(":") .append(metricsName) .toString(); }
@Test public void testGetPropertyName() { assertThat(producer.getPropertyName(METRICS_NAME), is("timer" + ":" + METRICS_NAME)); }
@Override public void delete(K key) { long startNanos = Timer.nanos(); try { delegate.delete(key); } finally { deleteProbe.recordValue(Timer.nanosElapsed(startNanos)); } }
@Test public void delete() { String key = "somekey"; cacheStore.delete(key); verify(delegate).delete(key); assertProbeCalledOnce("delete"); }
@Override protected void onMessage(RedissonCountDownLatchEntry value, Long message) { if (message.equals(ZERO_COUNT_MESSAGE)) { Runnable runnableToExecute = value.getListeners().poll(); while (runnableToExecute != null) { runnableToExecute.run(); runna...
@Test public void testOnZeroMessageAllListenersExecuted(@Mocked Runnable listener) { int listenCount = 10; RedissonCountDownLatchEntry entry = new RedissonCountDownLatchEntry(null); for (int i = 0; i < listenCount; i++) { entry.addListener(listener); } countDownLatchPubSub.onMessage(entry, C...
@Override public boolean checkCredentials(String username, String password) { if (username == null || password == null) { return false; } Credentials credentials = new Credentials(username, password); if (validCredentialsCache.contains(credentials)) { return ...
@Test public void testPBKDF2WithHmacSHA1_lowerCaseWithoutColon() throws Exception { String algorithm = "PBKDF2WithHmacSHA1"; int iterations = 1000; int keyLength = 128; String hash = "17:87:CA:B9:14:73:60:36:8B:20:82:87:92:58:43:B8:A3:85:66:BC:C1:6D:C3:31:6C:1D:47:48:...
@Override public int positionedRead(long pos, byte[] b, int off, int len) throws IOException { if (!CachePerThreadContext.get().getCacheEnabled()) { MetricsSystem.meter(MetricKey.CLIENT_CACHE_BYTES_REQUESTED_EXTERNAL.getName()) .mark(len); MetricsSystem.counter(MetricKey.CLIENT_CACHE_EXTERNA...
@Test public void positionedReadPartialPage() throws Exception { int fileSize = mPageSize; byte[] testData = BufferUtils.getIncreasingByteArray(fileSize); ByteArrayCacheManager manager = new ByteArrayCacheManager(); LocalCacheFileInStream stream = setupWithSingleFile(testData, manager); int parti...
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) { if (null == source) { return null; } T target = ReflectUtil.newInstanceIfPossible(tClass); copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties)); return target; }
@Test public void copyPropertiesBeanToMapTest() { // 测试BeanToMap final SubPerson p1 = new SubPerson(); p1.setSlow(true); p1.setName("测试"); p1.setSubName("sub测试"); final Map<String, Object> map = MapUtil.newHashMap(); BeanUtil.copyProperties(p1, map); assertTrue((Boolean) map.get("slow")); assertEqua...
@SneakyThrows public static Optional<Date> nextExecutionDate( TimeTrigger trigger, Date startDate, String uniqueId) { CronTimeTrigger cronTimeTrigger = getCronTimeTrigger(trigger); if (cronTimeTrigger != null) { CronExpression cronExpression = TriggerHelper.buildCron(cronTimeTrigger.getC...
@Test public void testNextExecutionDateForPredefined() throws Exception { TimeTrigger trigger = loadObject("fixtures/time_triggers/sample-predefined-time-trigger.json", TimeTrigger.class); Optional<Date> actual = TriggerHelper.nextExecutionDate(trigger, Date.from(Instant.EPOCH), "test-id"); ...
public void write(CruiseConfig configForEdit, OutputStream output, boolean skipPreprocessingAndValidation) throws Exception { LOGGER.debug("[Serializing Config] Starting to write. Validation skipped? {}", skipPreprocessingAndValidation); MagicalGoConfigXmlLoader loader = new MagicalGoConfigXmlLoader(con...
@Test public void shouldNotWriteDuplicatedPipelines() { String xml = ConfigFileFixture.TWO_PIPELINES; CruiseConfig cruiseConfig = ConfigMigrator.loadWithMigration(xml).config; cruiseConfig.addPipeline("someGroup", PipelineConfigMother.pipelineConfig("pipeline1")); try { ...
@VisibleForTesting void validateDeptNameUnique(Long id, Long parentId, String name) { DeptDO dept = deptMapper.selectByParentIdAndName(parentId, name); if (dept == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的部门 if (id == null) { throw exception(DEPT_...
@Test public void testValidateNameUnique_duplicate() { // mock 数据 DeptDO deptDO = randomPojo(DeptDO.class); deptMapper.insert(deptDO); // 准备参数 Long id = randomLongId(); Long parentId = deptDO.getParentId(); String name = deptDO.getName(); // 调用, 并断言异...
@Override public Proxy find(final String target) { final String route = this.findNative(target); if(null == route) { if(log.isInfoEnabled()) { log.info(String.format("No proxy configuration found for target %s", target)); } // Direct re...
@Test public void testExcludedLocalHost() { final SystemConfigurationProxy proxy = new SystemConfigurationProxy(); assertEquals(Proxy.Type.DIRECT, proxy.find("http://cyberduck.local").getType()); }
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testGauntletNewPersonalBest() { ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Challenge duration: <col=ff0000>10:24</col> (new personal best).", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your Gauntlet com...
@Override public final ChannelHandler get(String name) { ChannelHandlerContext ctx = context(name); if (ctx == null) { return null; } else { return ctx.handler(); } }
@Test @Timeout(value = 5000, unit = TimeUnit.MILLISECONDS) public void testChannelInitializerException() throws Exception { final IllegalStateException exception = new IllegalStateException(); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); final CountDownLatch...
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_contains_success() { assertThat(array(1.0f, 2.0f, 3.0f)).usingExactEquality().contains(2.0f); }
public static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close) throws IOException { try { copyBytes(in, out, buffSize); if(close) { out.close(); out = null; in.close(); in = null; } } finally { ...
@Test public void testCopyBytesShouldCloseInputSteamWhenInputStreamCloseThrowsRunTimeException() throws Exception { InputStream inputStream = Mockito.mock(InputStream.class); OutputStream outputStream = Mockito.mock(OutputStream.class); Mockito.doReturn(-1).when(inputStream).read(new byte[1]); M...
public void writeBigSmart(int value) { Preconditions.checkArgument(value >= 0); if (value >= 32768) { ensureRemaining(4); this.writeInt((1 << 31) | value); } else { ensureRemaining(2); this.writeShort(value); } }
@Test public void testWriteBigSmart() { OutputStream os = new OutputStream(); os.writeBigSmart(42); os.writeBigSmart(70000); os.writeBigSmart(65535); InputStream is = new InputStream(os.getArray()); assertEquals(42, is.readBigSmart()); assertEquals(70000, is.readBigSmart()); assertEquals(65535, is.re...
public static PartitionKey createPartitionKey(List<String> values, List<Column> columns) throws AnalysisException { return createPartitionKey(values, columns, Table.TableType.HIVE); }
@Test public void testCreateJDBCPartitionKey() throws AnalysisException { PartitionKey partitionKey = createPartitionKey( Lists.newArrayList("1", "a", "3.0", JDBCTable.PARTITION_NULL_VALUE), partColumns, Table.TableType.JDBC); Assert.assertEquals("(\"1\", \"a\", \"3.0\", \"NULL\")", ...
public static <T> Opt<T> ofBlankAble(T value) { return StrUtil.isBlankIfStr(value) ? empty() : new Opt<>(value); }
@Test public void ofBlankAbleTest() { // ofBlankAble相对于ofNullable考虑了字符串为空串的情况 String hutool = Opt.ofBlankAble("").orElse("hutool"); assertEquals("hutool", hutool); }
public static Integer stringToInteger(String in) { if (in == null) { return null; } in = in.trim(); if (in.length() == 0) { return null; } try { return Integer.parseInt(in); } catch (NumberFormatException e) { LOG.w...
@Test public void testStringToInteger() { Assert.assertNull(StringUtils.stringToInteger("")); Assert.assertNull(StringUtils.stringToInteger(null)); Assert.assertNull(StringUtils.stringToInteger("a")); Assert.assertEquals(new Integer(3), StringUtils.stringToInteger("3")); }
@Override public List<IndexSegment> prune(List<IndexSegment> segments, QueryContext query) { if (segments.isEmpty()) { return segments; } // For LIMIT 0 case, keep one segment to create the schema int limit = query.getLimit(); if (limit == 0) { return Collections.singletonList(segment...
@Test public void testSelectionOnly() { List<IndexSegment> indexSegments = Arrays.asList(getIndexSegment(null, null, 10), getIndexSegment(0L, 10L, 10), getIndexSegment(-5L, 5L, 15)); // Should keep enough documents to fulfill the LIMIT requirement QueryContext queryContext = QueryContextConverter...
public static IntStream allLinesFor(DefaultIssue issue, String componentUuid) { DbIssues.Locations locations = issue.getLocations(); if (locations == null) { return IntStream.empty(); } Stream<DbCommons.TextRange> textRanges = Stream.concat( locations.hasTextRange() ? Stream.of(locations.ge...
@Test public void allLinesFor_returns_empty_if_no_locations_are_set() { DefaultIssue issue = new DefaultIssue().setLocations(null); assertThat(IssueLocations.allLinesFor(issue, "file1")).isEmpty(); }
public static DATA_TYPE getDATA_TYPE(final List<Field<?>> fields, String fieldName) { Optional<DATA_TYPE> toReturn = fields.stream() .filter(fld -> Objects.equals(fieldName,fld.getName())) .findFirst() .map(dataField -> DATA_TYPE.byName(dataField.getDataType().val...
@Test void getDataTypeNotFound() { assertThatExceptionOfType(KiePMMLInternalException.class).isThrownBy(() -> { final DataDictionary dataDictionary = new DataDictionary(); IntStream.range(0, 3).forEach(i -> { String fieldName = "field" + i; final DataF...
public long computeMemorySize(double fraction) { validateFraction(fraction); return (long) Math.floor(memoryBudget.getTotalMemorySize() * fraction); }
@Test void testComputeMemorySizeFailForZeroFraction() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> memoryManager.computeMemorySize(0.0)); }
@Override public boolean canRescaleMaxParallelism(int desiredMaxParallelism) { // Technically a valid parallelism value, but one that cannot be rescaled to if (desiredMaxParallelism == JobVertex.MAX_PARALLELISM_DEFAULT) { return false; } return !rescaleMaxValidator ...
@Test void canRescaleMaxAuto() { DefaultVertexParallelismInfo info = new DefaultVertexParallelismInfo(1, 1, ALWAYS_VALID); assertThat(info.canRescaleMaxParallelism(ExecutionConfig.PARALLELISM_AUTO_MAX)).isTrue(); }
@Override public boolean encode( @NonNull Resource<GifDrawable> resource, @NonNull File file, @NonNull Options options) { GifDrawable drawable = resource.get(); Transformation<Bitmap> transformation = drawable.getFrameTransformation(); boolean isTransformed = !(transformation instanceof UnitTransfor...
@Test public void testWritesBytesDirectlyToDiskIfTransformationIsUnitTransformation() { when(gifDrawable.getFrameTransformation()).thenReturn(UnitTransformation.<Bitmap>get()); String expected = "expected"; when(gifDrawable.getBuffer()).thenReturn(ByteBuffer.wrap(expected.getBytes())); encoder.encode...
@Override public List<Container> allocateContainers(ResourceBlacklistRequest blackList, List<ResourceRequest> oppResourceReqs, ApplicationAttemptId applicationAttemptId, OpportunisticContainerContext opportContext, long rmIdentifier, String appSubmitter) throws YarnException { // Update b...
@Test public void testRoundRobinSimpleAllocation() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); List<ResourceRequest> reqs = Arrays.asList( ResourceRequest.newBuilder().alloca...
public static TableRebalanceProgressStats.RebalanceStateStats getDifferenceBetweenTableRebalanceStates( Map<String, Map<String, String>> targetState, Map<String, Map<String, String>> sourceState) { TableRebalanceProgressStats.RebalanceStateStats rebalanceStats = new TableRebalanceProgressStats.Rebala...
@Test void testDifferenceBetweenTableRebalanceStates() { Map<String, Map<String, String>> target = new TreeMap<>(); target.put("segment1", SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host2", "host3"), ONLINE)); target.put("segment2", SegmentAssignmentUtils.getInstanc...
@Override public void write(final PostgreSQLPacketPayload payload, final Object value) { payload.writeInt8(((Number) value).longValue()); }
@Test void assertWrite() { byte[] actual = new byte[24]; PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(Unpooled.wrappedBuffer(actual).writerIndex(0), StandardCharsets.UTF_8); new PostgreSQLInt8BinaryProtocolValue().write(payload, -1); new PostgreSQLInt8BinaryProtocolV...
@Override public HashSlotCursor16byteKey cursor() { return new CursorLongKey2(); }
@Test public void testCursor_withManyValues() { final long factor = 123456; final int k = 1000; for (int i = 1; i <= k; i++) { long key1 = (long) i; long key2 = key1 * factor; insert(key1, key2); } boolean[] verifiedKeys = new boolean[k]; ...
public static Optional<JksOptions> buildJksKeyStoreOptions( final Map<String, String> props, final Optional<String> alias ) { final String location = getKeyStoreLocation(props); final String keyStorePassword = getKeyStorePassword(props); final String keyPassword = getKeyPassword(props); i...
@Test public void shouldReturnEmptyKeyStoreJksOptionsIfLocationIsEmpty() { // When final Optional<JksOptions> jksOptions = VertxSslOptionsFactory.buildJksKeyStoreOptions( ImmutableMap.of(), Optional.empty() ); // Then assertThat(jksOptions, is(Optional.empty())); }
@Override @NotNull public List<PartitionStatistics> sort(@NotNull List<PartitionStatistics> partitionStatistics) { return partitionStatistics.stream() .filter(p -> p.getCompactionScore() != null) .sorted(Comparator.comparingInt((PartitionStatistics stats) -> stats.getPrio...
@Test public void testPriority() { List<PartitionStatistics> statisticsList = new ArrayList<>(); PartitionStatistics statistics = new PartitionStatistics(new PartitionIdentifier(1, 2, 3)); statistics.setCompactionScore(Quantiles.compute(Arrays.asList(0.0, 0.0, 0.0))); statisticsList....
public String toCompactListString() { return id + COMMA + locType + COMMA + latOrY + COMMA + longOrX; }
@Test public void toCompactListStringEmptyArray() { String s = toCompactListString(); assertEquals("not empty string", "", s); }
@Override public Set<String> filterCatalogs(Identity identity, AccessControlContext context, Set<String> catalogs) { ImmutableSet.Builder<String> filteredCatalogs = ImmutableSet.builder(); for (String catalog : catalogs) { if (canAccessCatalog(identity, catalog, READ_ONLY)) { ...
@Test public void testCatalogOperationsReadOnly() throws IOException { TransactionManager transactionManager = createTestTransactionManager(); AccessControlManager accessControlManager = newAccessControlManager(transactionManager, "catalog_read_only.json"); transaction(transactionManage...
Packet toBackupAckPacket(long callId, boolean urgent) { byte[] bytes = new byte[BACKUP_RESPONSE_SIZE_IN_BYTES]; writeResponsePrologueBytes(bytes, BACKUP_ACK_RESPONSE, callId, urgent); return newResponsePacket(bytes, urgent); }
@Test public void toBackupAckPacket() { testToBackupAckPacket(1, false); testToBackupAckPacket(2, true); }
@Override public V load(K key) { long startNanos = Timer.nanos(); try { return delegate.load(key); } finally { loadProbe.recordValue(Timer.nanosElapsed(startNanos)); } }
@Test public void load() { String key = "key"; String value = "value"; when(delegate.load(key)).thenReturn(value); String result = cacheLoader.load(key); assertSame(value, result); assertProbeCalledOnce("load"); }
@Override public String resolve(Method method, Object[] arguments, String spelExpression) { if (StringUtils.isEmpty(spelExpression)) { return spelExpression; } if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) { return stringValueReso...
@Test public void testP0() throws Exception { String testExpression = "#p0"; String firstArgument = "test"; DefaultSpelResolverTest target = new DefaultSpelResolverTest(); Method testMethod = target.getClass().getMethod("testMethod", String.class); String result = sut.resol...
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception { return newGetter(object, parent, modifier, field.getType(), field::get, (t, et) -> new FieldGetter(parent, field, modifier, t, et)); }
@Test public void newFieldGetter_whenExtractingFromNull_Collection_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType() throws Exception { OuterObject object = new OuterObject("name", InnerObject.nullInner("inner")); Getter parentGetter = GetterFactory.newFieldGetter(object, null, ...
@Override public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { if(status.isExists()) { if(log.isWarnEnabled()) { log.warn(String.f...
@Test public void testCopyDirectory() throws Exception { final BoxFileidProvider fileid = new BoxFileidProvider(session); final Path directory = new BoxDirectoryFeature(session, fileid).mkdir(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService()...
@Override public TrackerClient getClient(String serviceName, URI uri) { Map<URI, TrackerClient> trackerClients = _trackerClients.get(serviceName); TrackerClient trackerClient = null; if (trackerClients != null) { trackerClient = trackerClients.get(uri); } else { warn(_log, "...
@Test(groups = { "small", "back-end" }) public void testGetClient() throws URISyntaxException { reset(); URI uri = URI.create("http://cluster-1/test"); List<String> schemes = new ArrayList<>(); Map<Integer, PartitionData> partitionData = new HashMap<>(1); partitionData.put(DefaultPartitionAcces...
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldThrowIfNotAnObject() { // Given: final byte[] bytes = serializeJson(BooleanNode.valueOf(true)); // When: final Exception e = assertThrows( SerializationException.class, () -> deserializer.deserialize(SOME_TOPIC, bytes) ); // Then: assertThat(e.getC...
public void start() { // Last minute init. Neither properties not annotations provided an // injector source. if (injector == null) { injector = createDefaultScenarioModuleInjectorSource().getInjector(); } scenarioScope = injector.getInstance(ScenarioScope.class); ...
@Test void factoryStartFailsIfScenarioScopeIsNotBound() { initFactory(Guice.createInjector()); ConfigurationException actualThrown = assertThrows(ConfigurationException.class, () -> factory.start()); assertThat("Unexpected exception message", actualThrown.getMessage(), containsS...
@VisibleForTesting public void validateDictTypeExists(String type) { DictTypeDO dictType = dictTypeService.getDictType(type); if (dictType == null) { throw exception(DICT_TYPE_NOT_EXISTS); } if (!CommonStatusEnum.ENABLE.getStatus().equals(dictType.getStatus())) { ...
@Test public void testValidateDictTypeExists_notExists() { assertServiceException(() -> dictDataService.validateDictTypeExists(randomString()), DICT_TYPE_NOT_EXISTS); }
@Override public ResultSet getVersionColumns(final String catalog, final String schema, final String table) throws SQLException { return createDatabaseMetaDataResultSet(getDatabaseMetaData().getVersionColumns(getActualCatalog(catalog), getActualSchema(schema), getActualTable(getActualCatalog(catalog), table...
@Test void assertGetVersionColumns() throws SQLException { when(databaseMetaData.getVersionColumns("test", null, null)).thenReturn(resultSet); assertThat(shardingSphereDatabaseMetaData.getVersionColumns("test", null, null), instanceOf(DatabaseMetaDataResultSet.class)); }
@Override public String toString() { if (stringified == null) { stringified = formatToString(); } return stringified; }
@Test void testStandardUtils() throws IOException { final MemorySize size = new MemorySize(1234567890L); final MemorySize cloned = CommonTestUtils.createCopySerializable(size); assertThat(cloned).isEqualTo(size); assertThat(cloned).hasSameHashCodeAs(size); assertThat(cloned)...
@InvokeOnHeader(Web3jConstants.DB_PUT_STRING) void dbPutString(Message message) throws IOException { String databaseName = message.getHeader(Web3jConstants.DATABASE_NAME, configuration::getDatabaseName, String.class); String keyName = message.getHeader(Web3jConstants.KEY_NAME, configuration::getKeyN...
@Test public void dbPutStringTest() throws Exception { DbPutString response = Mockito.mock(DbPutString.class); Mockito.when(mockWeb3j.dbPutString(any(), any(), any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.valueStored()).thenRet...
@Override public void deletePost(Long id) { // 校验是否存在 validatePostExists(id); // 删除部门 postMapper.deleteById(id); }
@Test public void testDeletePost_success() { // mock 数据 PostDO postDO = randomPostDO(); postMapper.insert(postDO); // 准备参数 Long id = postDO.getId(); // 调用 postService.deletePost(id); assertNull(postMapper.selectById(id)); }
public static BigDecimal cast(final Integer value, final int precision, final int scale) { if (value == null) { return null; } return cast(value.longValue(), precision, scale); }
@Test public void shouldCastDecimalNoOp() { // When: final BigDecimal decimal = DecimalUtil.cast(new BigDecimal("1.1"), 2, 1); // Then: assertThat(decimal, sameInstance(decimal)); }
@Override public void updateMember(ConsumerGroupMember newMember) { if (newMember == null) { throw new IllegalArgumentException("newMember cannot be null."); } ConsumerGroupMember oldMember = members.put(newMember.memberId(), newMember); maybeUpdateSubscribedTopicNamesAnd...
@Test public void testUpdateSubscriptionMetadata() { Uuid fooTopicId = Uuid.randomUuid(); Uuid barTopicId = Uuid.randomUuid(); Uuid zarTopicId = Uuid.randomUuid(); MetadataImage image = new MetadataImageBuilder() .addTopic(fooTopicId, "foo", 1) .addTopic(barT...
public static void writeIdlProtocol(Writer writer, Protocol protocol) throws IOException { final String protocolFullName = protocol.getName(); final int lastDotPos = protocolFullName.lastIndexOf("."); final String protocolNameSpace; if (lastDotPos < 0) { protocolNameSpace = protocol.getNamespace()...
@Test public void validateHappyFlowForProtocol() throws IOException { Protocol protocol = parseIdlResource("idl_utils_test_protocol.avdl").getProtocol(); StringWriter buffer = new StringWriter(); IdlUtils.writeIdlProtocol(buffer, protocol); assertEquals(getResourceAsString("idl_utils_test_protocol.a...
public static void ensureCorrectArgs( final FunctionName functionName, final Object[] args, final Class<?>... argTypes ) { if (args == null) { throw new KsqlFunctionException("Null argument list for " + functionName.text() + "."); } if (args.length != argTypes.length) { throw new KsqlFu...
@Test(expected = KsqlException.class) public void shouldFailIfArgCountIsTooFew() { final Object[] args = new Object[]{"TtestArg1", 10L}; UdfUtil.ensureCorrectArgs(FUNCTION_NAME, args, String.class, Boolean.class, String.class); }
public synchronized String get() { ConfidentialStore cs = ConfidentialStore.get(); if (secret == null || cs != lastCS) { lastCS = cs; try { byte[] payload = load(); if (payload == null) { payload = cs.randomBytes(length / 2); ...
@Test public void specifyLengthAndMakeSureItTakesEffect() { for (int n : new int[] {8, 16, 32, 256}) { assertEquals(n, new HexStringConfidentialKey("test" + n, n).get().length()); } }
public void replayCreateResource(Resource resource) throws DdlException { if (resource.needMappingCatalog()) { String type = resource.getType().name().toLowerCase(Locale.ROOT); String catalogName = getResourceMappingCatalogName(resource.getName(), type); if (nameToResource.c...
@Test public void testReplayCreateResource(@Injectable EditLog editLog, @Mocked GlobalStateMgr globalStateMgr) throws UserException { ResourceMgr mgr = new ResourceMgr(); type = "hive"; name = "hive0"; addHiveResource(mgr, editLog, globalStateMgr); Resource hiveR...
Map<ExecNode<?>, Integer> calculateMaximumDistance() { Map<ExecNode<?>, Integer> result = new HashMap<>(); Map<TopologyNode, Integer> inputsVisitedMap = new HashMap<>(); Queue<TopologyNode> queue = new LinkedList<>(); for (TopologyNode node : nodes.values()) { if (node.input...
@Test void testBoundedCalculateMaximumDistance() { Tuple2<TopologyGraph, TestingBatchExecNode[]> tuple2 = buildBoundedTopologyGraph(); TopologyGraph graph = tuple2.f0; TestingBatchExecNode[] nodes = tuple2.f1; Map<ExecNode<?>, Integer> result = graph.calculateMaximumDistance(); ...