focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static boolean isOrHasCause(Throwable t, Class<?> classToFind) { while (t != null && t.getCause() != t && !classToFind.isAssignableFrom(t.getClass())) { t = t.getCause(); } return t != null && classToFind.isAssignableFrom(t.getClass()); }
@Test public void test_isOrHasCause_when_exceptionHasExpectedType() { RuntimeException e = new RuntimeException("foo"); assertTrue(isOrHasCause(e, RuntimeException.class)); }
public static <K, V> V getOrPutSynchronized(ConcurrentMap<K, V> map, K key, final Object mutex, ConstructorFunction<K, V> func) { if (mutex == null) { throw new NullPointerException(); } V value = map.get(key); if (value == null...
@Test public void testGetOrPutSynchronized_withMutexFactory() { int result = ConcurrencyUtil.getOrPutSynchronized(map, 5, mutexFactory, constructorFunction); assertEquals(1005, result); assertEquals(1, constructorFunction.getConstructions()); }
public OptimizerParserContext getParserContext(final String databaseName) { return parserContexts.get(databaseName); }
@Test void assertGetParserContext() { OptimizerContext actual = OptimizerContextFactory.create(Collections.singletonMap(DefaultDatabase.LOGIC_NAME, createShardingSphereDatabase())); assertThat(actual.getParserContext(DefaultDatabase.LOGIC_NAME), instanceOf(OptimizerParserContext.class)); }
public static JavaToSqlTypeConverter javaToSqlConverter() { return JAVA_TO_SQL_CONVERTER; }
@Test public void shouldThrowOnUnknownJavaType() { // When: final Exception e = assertThrows( KsqlException.class, () -> javaToSqlConverter().toSqlType(double.class) ); // Then: assertThat(e.getMessage(), containsString("Unexpected java type: " + double.class)); }
public static Map<String, String> setLoggerLevel(String loggerName, String logLevel) { Level level; try { level = Level.valueOf(logLevel); } catch (Exception e) { throw new RuntimeException("Unrecognized logger level - " + logLevel, e); } LoggerContext context = (LoggerContext) LogManage...
@Test public void testChangeLoggerLevelWithExceptions() { try { LoggerUtils.setLoggerLevel("notExistLogger", "INFO"); fail("Shouldn't reach here"); } catch (RuntimeException e) { assertEquals(e.getMessage(), "Logger - notExistLogger not found"); } try { LoggerUtils.setLoggerLev...
@Override public ExecuteContext after(ExecuteContext context) { ThreadLocalUtils.removeRequestData(); LogUtils.printHttpRequestAfterPoint(context); return context; }
@Test public void testAfter() { ThreadLocalUtils.setRequestData(new RequestData(Collections.emptyMap(), "", "")); interceptor.after(context); Assert.assertNull(ThreadLocalUtils.getRequestData()); }
public static String name2desc(String name) { StringBuilder sb = new StringBuilder(); int c = 0, index = name.indexOf('['); if (index > 0) { c = (name.length() - index) / 2; name = name.substring(0, index); } while (c-- > 0) { sb.append('['); ...
@Test void testName2desc() { // name2desc assertEquals("Z", ReflectUtils.name2desc(ReflectUtils.getName(boolean.class))); assertEquals("[[[I", ReflectUtils.name2desc(ReflectUtils.getName(int[][][].class))); assertEquals("[[Ljava/lang/Object;", ReflectUtils.name2desc(ReflectUtils.getN...
public static boolean isDockerInstalled(Path dockerExecutable) { return Files.exists(dockerExecutable); }
@Test public void testIsDockerInstalled_fail() { Assert.assertFalse(CliDockerClient.isDockerInstalled(Paths.get("path/to/nonexistent/file"))); }
@Override public void write(T record) { recordConsumer.startMessage(); try { messageWriter.writeTopLevelMessage(record); } catch (RuntimeException e) { Message m = (record instanceof Message.Builder) ? ((Message.Builder) record).build() : (Message) record; LOG.error("Cannot write message...
@Test public void testProto3RepeatedIntMessage() throws Exception { RecordConsumer readConsumerMock = Mockito.mock(RecordConsumer.class); ProtoWriteSupport<TestProto3.RepeatedIntMessage> instance = createReadConsumerInstance(TestProto3.RepeatedIntMessage.class, readConsumerMock); TestProto3.Repea...
@Override public boolean isDetected() { return environmentVariableIsTrue("CI") && environmentVariableIsTrue("BITRISE_IO"); }
@Test public void isDetected() { assertThat(underTest.isDetected()).isFalse(); setEnvVariable("CI", "true"); assertThat(underTest.isDetected()).isFalse(); setEnvVariable("CI", "true"); setEnvVariable("BITRISE_IO", "false"); assertThat(underTest.isDetected()).isFalse(); setEnvVariable("...
public static <T extends PipelineOptions> T as(Class<T> klass) { return new Builder().as(klass); }
@Test public void testMissingGetterThrows() throws Exception { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage( "Expected getter for property [object] of type [java.lang.Object] on " + "[org.apache.beam.sdk.options.PipelineOptionsFactoryTest$Missin...
public CompletableFuture<VertexThreadInfoStats> triggerThreadInfoRequest( Map<ImmutableSet<ExecutionAttemptID>, CompletableFuture<TaskExecutorThreadInfoGateway>> executionsWithGateways, int numSamples, Duration delayBetweenSamples, int maxStackTraceDep...
@Test void testThreadInfoRequestWithException() throws Exception { Map<ImmutableSet<ExecutionAttemptID>, CompletableFuture<TaskExecutorThreadInfoGateway>> executionWithGateways = createMockSubtaskWithGateways( CompletionType.SUCCESSFULL...
public static AccessTokenValidator create(Map<String, ?> configs) { return create(configs, (String) null); }
@Test public void testConfigureThrowsExceptionOnAccessTokenValidatorClose() { OAuthBearerLoginCallbackHandler handler = new OAuthBearerLoginCallbackHandler(); AccessTokenRetriever accessTokenRetriever = new AccessTokenRetriever() { @Override public void close() throws IOExcep...
public static List<String> stripDotPathComponents(List<String> input) { List<String> output = new ArrayList<>(); for (String string : input) { if (string.equals("..")) { if (!output.isEmpty()) { output.remove(output.size() - 1); } ...
@Test public void testStripDotPathComponents() { //double dots assertEquals(Arrays.asList("keep", "keep2"), CommandUtils.stripDotPathComponents(Arrays.asList("..", "keep", "keep2"))); //single dots assertEquals(Arrays.asList("keep", "keep2"), CommandUtils.stripDotPathComponents(Arra...
public static UNewClass create( UExpression enclosingExpression, List<? extends UExpression> typeArguments, UExpression identifier, List<UExpression> arguments, @Nullable UClassDecl classBody) { return new AutoValue_UNewClass( enclosingExpression, ImmutableList.copyOf(t...
@Test public void serialization() { SerializableTester.reserializeAndAssert( UNewClass.create(UClassIdent.create("java.lang.String"), ULiteral.stringLit("123"))); }
@Override public void updateSmsReceiveResult(Long id, Boolean success, LocalDateTime receiveTime, String apiReceiveCode, String apiReceiveMsg) { SmsReceiveStatusEnum receiveStatus = Objects.equals(success, true) ? SmsReceiveStatusEnum.SUCCESS : SmsRecei...
@Test public void testUpdateSmsReceiveResult() { // mock 数据 SmsLogDO dbSmsLog = randomSmsLogDO( o -> o.setReceiveStatus(SmsReceiveStatusEnum.INIT.getStatus())); smsLogMapper.insert(dbSmsLog); // 准备参数 Long id = dbSmsLog.getId(); Boolean success = random...
public static Duration between(LocalDateTime startTimeInclude, LocalDateTime endTimeExclude) { return TemporalUtil.between(startTimeInclude, endTimeExclude); }
@Test public void between() { final Duration between = LocalDateTimeUtil.between( LocalDateTimeUtil.parse("2019-02-02T00:00:00"), LocalDateTimeUtil.parse("2020-02-02T00:00:00")); assertEquals(365, between.toDays()); }
private void putCache(String key, CacheData cache) { synchronized (cacheMap) { Map<String, CacheData> copy = new HashMap<>(this.cacheMap.get()); copy.put(key, cache); cacheMap.set(copy); } }
@Test void testPutCache() throws Exception { // 反射调用私有方法putCacheIfAbsent Method putCacheMethod = ClientWorker.class.getDeclaredMethod("putCache", String.class, CacheData.class); putCacheMethod.setAccessible(true); Properties prop = new Properties(); ConfigFilterChainManager f...
@Override public boolean test(Pair<Point, Point> pair) { if (timeDeltaIsSmall(pair.first().time(), pair.second().time())) { return distIsSmall(pair); } else { /* * reject points with large time deltas because we don't want to rely on a numerically *...
@Test public void testCase2() { DistanceFilter filter = newTestFilter(); LatLong position1 = new LatLong(0.0, 0.0); double notTooFarInNm = MAX_DISTANCE_IN_FEET * 0.5 / Spherical.feetPerNM(); Point p1 = new PointBuilder() .latLong(position1) .time(Instant.EP...
@Override public Mono<RemoveDeviceResponse> removeDevice(final RemoveDeviceRequest request) { if (request.getId() == Device.PRIMARY_ID) { throw Status.INVALID_ARGUMENT.withDescription("Cannot remove primary device").asRuntimeException(); } final AuthenticatedDevice authenticatedDevice = Authenticat...
@Test void removeDeviceNonPrimaryMismatchAuthenticated() { mockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, (byte) (Device.PRIMARY_ID + 1)); assertStatusException(Status.PERMISSION_DENIED, () -> authenticatedServiceStub().removeDevice(RemoveDeviceRequest.newBuilder() .setId(17...
@Override public void close() { if (metrics != null) { metrics.removeSensor(errorSensor.name()); } logger.close(); }
@Test public void shouldRemoveSensorOnClose() { // When: meteredProcessingLogger.close(); // Then: verify(metrics).removeSensor(sensorName); verify(processingLogger).close(); }
@VisibleForTesting static CPUResource getDefaultCpus(Configuration configuration) { double fallback = configuration.get(KubernetesConfigOptions.TASK_MANAGER_CPU); return TaskExecutorProcessUtils.getCpuCoresWithFallback(configuration, fallback); }
@Test void testGetCpuCoresKubernetesOption() { final Configuration configuration = new Configuration(); configuration.set(KubernetesConfigOptions.TASK_MANAGER_CPU, 2.0); configuration.set(KubernetesConfigOptions.TASK_MANAGER_CPU_LIMIT_FACTOR, 1.5); configuration.set(TaskManagerOption...
public final Sensor threadLevelSensor(final String threadId, final String sensorSuffix, final RecordingLevel recordingLevel, final Sensor... parents) { final String sensorPrefix = thread...
@Test public void shouldGetExistingThreadLevelSensor() { final Metrics metrics = mock(Metrics.class); final RecordingLevel recordingLevel = RecordingLevel.INFO; setupGetExistingSensorTest(metrics); final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, CLIENT_ID, V...
private static Map<String, Object> toJsonMap( final Token<? extends TokenIdentifier> token) throws IOException { if (token == null) { return null; } final Map<String, Object> m = new TreeMap<String, Object>(); m.put("urlString", token.encodeToUrlString()); return m; }
@Test public void testToDatanodeInfoWithName() throws Exception { Map<String, Object> response = new HashMap<String, Object>(); // Older servers (1.x, 0.23, etc.) sends 'name' instead of ipAddr // and xferPort. String name = "127.0.0.1:1004"; response.put("name", name); response.put("hostName...
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { if(file.isPlaceholder()) { final DescriptiveUrl link = new DriveUrlProvider().toUrl(file).find(DescriptiveUrl.Type.http); if(DescriptiveUrl....
@Test public void testReadRevision() throws Exception { final DriveFileIdProvider fileid = new DriveFileIdProvider(session); final Path directory = new DriveDirectoryFeature(session, fileid).mkdir( new Path(MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(Pa...
@Override public void close() { client.close(); EVENT_LISTENER_EXECUTOR.shutdown(); }
@Test void assertClose() { repository.close(); verify(client).close(); }
public static Host parse(final String url) throws HostParserException { final Host parsed = new HostParser().get(url); if(log.isDebugEnabled()) { log.debug(String.format("Parsed %s as %s", url, parsed)); } return parsed; }
@Test public void parse() throws HostParserException { final Host host = new HostParser(new ProtocolFactory(Collections.singleton(new TestProtocol(Scheme.https)))) .get("https://t%40u@host:443/key"); assertEquals("host", host.getHostname()); assertEquals(443, host.getPort()); ...
public boolean isPathValid(String path) { return path == null || XmlUtils.matchUsingRegex(PATH_PATTERN_REGEX, path); }
@Test public void shouldEnsurePathIsRelative() { assertThat(filePathTypeValidator.isPathValid(".."), is(false)); assertThat(filePathTypeValidator.isPathValid("../a"), is(false)); assertThat(filePathTypeValidator.isPathValid(" "), is(false)); assertThat(filePathTypeValidator.isPathVal...
@Override public void onNotificationClearRequest(int id) { final NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(id); }
@Test public void onNotificationClearRequest_clearSpecificNotification() throws Exception { createUUT().onNotificationClearRequest(666); verify(mNotificationManager).cancel(eq(666)); verify(mNotificationManager, never()).cancelAll(); }
public static String jsonFromMap(Map<String, Object> jsonData) { try { JsonDocument json = new JsonDocument(); json.startGroup(); for (String key : jsonData.keySet()) { Object data = jsonData.get(key); if (data instanceof Map) { ...
@Test void testSimpleTwo() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); jsonData.put("myKey", "myValue"); jsonData.put("myKey2", "myValue2"); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"myKey\":\"myValue\",\"myKey2\":\"myVa...
@Override public void registerService(String serviceName, String groupName, Instance instance) throws NacosException { getExecuteClientProxy(instance).registerService(serviceName, groupName, instance); }
@Test void testRegisterEphemeralServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); instance.setServiceName(serviceName); instance.setClusterName(groupName); instance.setIp("1.1.1.1"...
@VisibleForTesting Map<String, List<Operation>> computeOperations(SegmentDirectory.Reader segmentReader) throws Exception { Map<String, List<Operation>> columnOperationsMap = new HashMap<>(); // Does not work for segment versions < V3. if (_segmentDirectory.getSegmentMetadata().getVersion().compare...
@Test public void testComputeOperationEnableDictionary() throws Exception { // Setup SegmentMetadataImpl existingSegmentMetadata = new SegmentMetadataImpl(_segmentDirectory); SegmentDirectory segmentLocalFSDirectory = new SegmentLocalFSDirectory(_segmentDirectory, existingSegmentMetadata, Re...
public LeadControllerManager(String helixControllerInstanceId, HelixManager helixManager, ControllerMetrics controllerMetrics) { _helixControllerInstanceId = helixControllerInstanceId; _helixManager = helixManager; _controllerMetrics = controllerMetrics; _leadForPartitions = ConcurrentHashMap.newK...
@Test public void testLeadControllerManager() { LeadControllerManager leadControllerManager = new LeadControllerManager(HELIX_CONTROLLER_INSTANCE_ID, _helixManager, _controllerMetrics); String tableName = "leadControllerTestTable"; int expectedPartitionIndex = LeadControllerUtils.getPartitionIdFor...
public static void main(String[] args) throws Exception { System.setProperty("bookkeeper.metadata.bookie.drivers", PulsarMetadataBookieDriver.class.getName()); System.setProperty("bookkeeper.metadata.client.drivers", PulsarMetadataClientDriver.class.getName()); Arguments arguments = new Argumen...
@Test public void testMainGenerateDocs() throws Exception { PrintStream oldStream = System.out; try { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(baoStream)); Class argumentsClass = Class.forNam...
@Override public int getLineHashesVersion(Component component) { if (significantCodeRepository.getRangesPerLine(component).isPresent()) { return LineHashVersion.WITH_SIGNIFICANT_CODE.getDbValue(); } else { return LineHashVersion.WITHOUT_SIGNIFICANT_CODE.getDbValue(); } }
@Test public void should_return_version_of_line_hashes_with_significant_code_in_the_report() { LineRange[] lineRanges = {new LineRange(0, 1), null, new LineRange(1, 5)}; when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.of(lineRanges)); assertThat(underTest.getLineHashesVersion(fi...
public <T> void execute(final AsyncTask<T> task) { try { // some small tasks such as validation can be performed here. task.onPreCall(); } catch (Exception e) { task.onError(e); return; } service.submit(new FutureTask<>(task) { @Override protected void done() { ...
@Test void testPreCallException() { final var exception = new IllegalStateException(); doThrow(exception).when(task).onPreCall(); service.execute(task); verify(task, timeout(2000)).onError(eq(exception)); final var inOrder = inOrder(task); inOrder.verify(task, times(1)).onPreCall(); inOr...
@Override public List<QualityProfile> load(String projectKey) { StringBuilder url = new StringBuilder(WS_URL + "?project=").append(encodeForUrl(projectKey)); return handleErrors(url, () -> String.format("Failed to load the quality profiles of project '%s'", projectKey), true); }
@Test public void load_throws_MessageException_if_no_profiles_are_available_for_specified_project() throws IOException { prepareCallWithEmptyResults(); assertThatThrownBy(() -> underTest.load("project")) .isInstanceOf(MessageException.class) .hasMessageContaining("No quality profiles"); }
@Override public long skip(long n) throws IOException { int bufSize = (int) Math.min(n, SKIP_SIZE); byte[] buf = new byte[bufSize]; long bytesSkipped = 0; int bytesRead = 0; while (bytesSkipped < n && bytesRead != -1) { int len = (int) Math.min(bufSize, n - bytes...
@Test public void testSkip() throws IOException { final int tailSize = 128; final int count = 1024; final int skipCount = 512; TailStream stream = new TailStream(generateStream(0, count), tailSize); assertEquals(skipCount, stream.skip(skipCount), "Wrong skip result"); ...
public static List<TargetInfo> parseOptTarget(CommandLine cmd, AlluxioConfiguration conf) throws IOException { String[] targets; if (cmd.hasOption(TARGET_OPTION_NAME)) { String argTarget = cmd.getOptionValue(TARGET_OPTION_NAME); if (StringUtils.isBlank(argTarget)) { throw new IOExcepti...
@Test public void parseEmbeddedHAJobMasterTarget() throws Exception { mConf.set(PropertyKey.JOB_MASTER_EMBEDDED_JOURNAL_ADDRESSES, "masters-1:19200,masters-2:19200"); CommandLine mockCommandLine = mock(CommandLine.class); String[] mockArgs = new String[]{"--target", "job_master"}; when(mockCommandLin...
public static IpPrefix valueOf(int address, int prefixLength) { return new IpPrefix(IpAddress.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfStringTooLongPrefixLengthIPv4() { IpPrefix ipPrefix; ipPrefix = IpPrefix.valueOf("1.2.3.4/33"); }
public static void validateConfig(Object config, Class annotationClass) { for (Field field : config.getClass().getDeclaredFields()) { Object value = null; field.setAccessible(true); try { value = field.get(config); } catch (IllegalAccessException e...
@Test public void testMapEntry() { TestConfig testConfig = createGoodConfig(); testConfig.stringIntegerMap = testStringStringMap; Exception e = expectThrows(IllegalArgumentException.class, () -> ConfigValidation.validateConfig(testConfig)); assertTrue(e.getMessage().contains("stringI...
public static void notNullOrEmpty(String string) { notNullOrEmpty(string, String.format("string [%s] is null or empty", string)); }
@Test public void testNotNull1NotEmpty5() { assertThrows(IllegalArgumentException.class, () -> Precondition.notNullOrEmpty("\t\r\n")); }
@Override public boolean isSimilar(PiMeterCellConfig onosMeter, PiMeterCellConfig deviceMeter) { final PiMeterBand onosCommittedBand = onosMeter.committedBand(); final PiMeterBand onosPeakBand = onosMeter.peakBand(); final PiMeterBand deviceCommittedBand = deviceMeter.committedBand(); ...
@Test public void testWrongIsBurstSimilar() { PiMeterBand onosMeterBand; PiMeterBand deviceMeterBand; PiMeterCellConfig onosMeter; PiMeterCellConfig deviceMeter; for (Map.Entry<Long, Long> entry : WRONG_BURSTS.entrySet()) { onosMeterBand = new PiMeterBand(PiMeterB...
protected void saveAndRunJobFilters(List<Job> jobs) { if (jobs.isEmpty()) return; try { jobFilterUtils.runOnStateElectionFilter(jobs); storageProvider.save(jobs); jobFilterUtils.runOnStateAppliedFilters(jobs); } catch (ConcurrentJobModificationException concu...
@Test void onConcurrentJobModificationExceptionTaskTriesToResolveAndThrowsExceptionIfNotResolved() { Job jobInProgress = aJobInProgress().build(); Job enqueuedJob = aCopyOf(jobInProgress).withEnqueuedState(now()).build(); when(storageProvider.save(anyList())).thenThrow(new ConcurrentJobModi...
public static BoundingBox getBoundingBox(Tile upperLeft, Tile lowerRight) { BoundingBox ul = upperLeft.getBoundingBox(); BoundingBox lr = lowerRight.getBoundingBox(); return ul.extendBoundingBox(lr); }
@Test public void getBoundingBoxTest() { for (byte zoom = (byte) 0; zoom < 25; zoom++) { Tile tile1 = new Tile(0, 0, zoom, TILE_SIZE); if (zoom == 0) { Assert.assertTrue(tile1.getBoundingBox().equals(new BoundingBox(MercatorProjection.LATITUDE_MIN, ...
@Override public ExecuteContext before(ExecuteContext context) throws Exception { final Object rawEvent = context.getArguments()[0]; if (rawEvent instanceof ContextClosedEvent) { tryShutdown((ContextClosedEvent) rawEvent); } return context; }
@Test public void before() throws Exception { final SpringCloseEventInterceptor springCloseEventInterceptor = new SpringCloseEventInterceptor(); springCloseEventInterceptor.before(buildContext(new Object[]{"test"})); Mockito.verify(registryService, Mockito.times(0)).shutdown(); sprin...
@Override public Position position(int major, int minor) { return new Pos(major, minor); }
@Test public void testNegativeOffsetWithBackwardBias() { Position pos = navigator.position(4, 10); pos = pos.offsetBy(-10, Backward); assertEquals(3, pos.getMajor()); assertEquals(10, pos.getMinor()); }
public static Builder builder() { return new Builder(); }
@Test public void testLogicalType() { Schema schema1 = Schema.builder().addLogicalTypeField("logical", new TestType("id", "arg")).build(); Schema schema2 = Schema.builder().addLogicalTypeField("logical", new TestType("id", "arg")).build(); assertEquals(schema1, schema2); // Logical types a...
@Override protected CloudBlobClient connect(final ProxyFinder proxyfinder, final HostKeyCallback callback, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { try { // Client configured with no credentials final URI uri = new URI(String.format("%s://...
@Test(expected = LoginCanceledException.class) public void testConnectInvalidKey() throws Exception { final Host host = new Host(new AzureProtocol(), "kahy9boj3eib.blob.core.windows.net", new Credentials( PROPERTIES.get("azure.user"), "6h9BmTcabGajIE/AVGzgu9JcC15JjrzkjdAIe+2daRK8XlyVdYT6zHtF...
static Collection<String> getIssueKeys(ChangeLogSet<?> changelog, Pattern issuePattern) { Set<String> issueKeys = new HashSet<>(); for (ChangeLogSet.Entry entry : changelog) { issueKeys.addAll(BlueJiraIssue.findIssueKeys(entry.getMsg(), issuePattern)); } return issueKeys; ...
@Test public void uniqueIssueKeys() throws Exception { ChangeLogSet<ChangeLogSet.Entry> entries = build( "TST-123", "TST-123", "TST-123", "TST-124", "TST-123", "TST-124", "TST-125"); Collection<String> keys = JiraSCMListener.getIssueKeys( ent...
@Override public ObjectNode encode(OpenstackNode node, CodecContext context) { checkNotNull(node, "Openstack node cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(HOST_NAME, node.hostname()) .put(TYPE, node.type().name()) ...
@Test public void testOpenstackComputeNodeEncode() { OpenstackPhyInterface phyIntf1 = DefaultOpenstackPhyInterface.builder() .network("mgmtnetwork") .intf("eth3") .build(); OpenstackPhyInterface phyIntf2...
public static Color fromString(String string) { try { int i = Integer.decode(string); return new Color(i, true); } catch (NumberFormatException e) { return null; } }
@Test public void fromString() { String WHITE_MAX_ALPHA = "-1"; String WHITE_ZERO_ALPHA = "0xffffff"; String TOO_LARGE = "0xffffffff"; String INVALID_FORMAT = "ffffff"; assertEquals(Color.WHITE, ColorUtil.fromString(WHITE_MAX_ALPHA)); assertEquals(ColorUtil.colorWithAlpha(Color.WHITE, 0), ColorUtil.fromS...
private Gamma() { }
@Test public void testGamma() { System.out.println("gamma"); assertTrue(Double.isInfinite(Gamma.gamma(0))); assertEquals(1.0, Gamma.gamma(1), 1E-7); assertEquals(1.0, Gamma.gamma(2), 1E-7); assertEquals(2.0, Gamma.gamma(3), 1E-7); assertEquals(6.0, Gamma.gamma(4), 1E...
@Override public String topic() { throw new UnsupportedOperationException("StateStores can't access topic."); }
@Test public void shouldThrowOnTopic() { assertThrows(UnsupportedOperationException.class, () -> context.topic()); }
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception { return fromXmlPartial(toInputStream(partial, UTF_8), o); }
@Test void shouldLoadGetFromSvnPartialForDir() throws Exception { String buildXmlPartial = """ <jobs> <job name="functional"> <tasks> <fetchartifact artifactOrigin='gocd' stage='de...
@Override public TableSchema parse(ReadonlyConfig readonlyConfig) { ReadonlyConfig schemaConfig = readonlyConfig .getOptional(TableSchemaOptions.SCHEMA) .map(ReadonlyConfig::fromMap) .orElseThrow( ...
@Test void parseField() throws FileNotFoundException, URISyntaxException { ReadonlyConfig config = getReadonlyConfig(FIELD_CONFIG); ReadonlyConfigParser readonlyConfigParser = new ReadonlyConfigParser(); TableSchema tableSchema = readonlyConfigParser.parse(config); assertPrimaryKey(...
@Override public void persistInstance(final InstanceEntity instance) { String instanceNodeName = buildInstanceNodeName(instance); String instancePath = InstancePathConstants.buildInstanceParentPath(instance.getAppName()); String realNode = InstancePathConstants.buildRealNode(instancePath, in...
@Test public void testPersistInstance() { InstanceEntity data = InstanceEntity.builder() .appName("shenyu-test") .host("shenyu-host") .port(9195) .build(); final String realNode = "/shenyu/register/instance/shenyu-test/shenyu-host:9195...
public Optional<Projection> createProjection(final ProjectionSegment projectionSegment) { if (projectionSegment instanceof ShorthandProjectionSegment) { return Optional.of(createProjection((ShorthandProjectionSegment) projectionSegment)); } if (projectionSegment instanceof ColumnProj...
@Test void assertCreateProjectionWhenProjectionSegmentInstanceOfColumnProjectionSegment() { ColumnProjectionSegment columnProjectionSegment = new ColumnProjectionSegment(new ColumnSegment(0, 10, new IdentifierValue("name"))); columnProjectionSegment.setAlias(new AliasSegment(0, 0, new IdentifierValu...
public BackgroundException map(final IOException failure, final Path directory) { return super.map("Connection failed", failure, directory); }
@Test public void testSSLHandshakeCertificateDismissed() { final SSLHandshakeException c = new SSLHandshakeException("f"); c.initCause(new CertificateException("c")); assertEquals(ConnectionCanceledException.class, new DefaultIOExceptionMappingService().map(c).getClass()); }
public String getStringData(final String path) throws Exception { byte[] bytes = getData(path); if (bytes != null) { return new String(bytes, StandardCharsets.UTF_8); } return null; }
@Test public void testGetStringData() throws Exception { String node1 = "/node1"; String node2 = "/node2"; assertFalse(curator.exists(node1)); curator.create(node1); assertNull(curator.getStringData(node1)); byte[] setData = "setData".getBytes(StandardCharsets.UTF_8); curator.setData(node...
@SuppressWarnings("unchecked") void openDB(final Map<String, Object> configs, final File stateDir) { // initialize the default rocksdb options final DBOptions dbOptions = new DBOptions(); final ColumnFamilyOptions columnFamilyOptions = new ColumnFamilyOptions(); userSpecifiedOptions...
@Test public void shouldNotSetStatisticsInValueProvidersWhenUserProvidesStatistics() { rocksDBStore = getRocksDBStoreWithRocksDBMetricsRecorder(); context = getProcessorContext(RecordingLevel.DEBUG, RocksDBConfigSetterWithUserProvidedStatistics.class); rocksDBStore.openDB(context.appConfigs...
public Port port() { return port; }
@Override @Test public void withTime() { Device device = createDevice(); Port port = new DefaultPort(device, PortNumber.portNumber(123), true); DeviceEvent event = new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, device, port, 123L); validateEvent(event, DeviceEvent...
@Override public List<String> getPrimaryBrokers() { return this.primary; }
@Test public void testGetPrimaryBrokers() throws Exception { List<String> primaryBrokers = this.getDefaultPolicy().getPrimaryBrokers(); assertEquals(primaryBrokers.size(), 1); assertEquals(primaryBrokers.get(0), "prod1-broker[1-3].messaging.use.example.com"); }
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) { Objects.requireNonNull(metric); if (batchMeasure == null) { return Optional.empty(); } Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder(); switch (metric.getType().getValueType()) { ...
@Test public void toMeasure_returns_no_value_if_dto_has_invalid_string_value_for_LEVEL_Metric() { Optional<Measure> measure = underTest.toMeasure(ScannerReport.Measure.newBuilder().setStringValue(StringValue.newBuilder().setValue("trololo")).build(), SOME_LEVEL_METRIC); assertThat(measure).isPresent(); a...
@Override public void execute(ComputationStep.Context context) { taskResultHolder.setResult(new CeTaskResultImpl(analysisMetadataHolder.getUuid())); }
@Test public void execute_populate_TaskResultHolder_with_a_TaskResult_with_snapshot_id_of_the_root_taken_from_DbIdsRepository() { analysisMetadataHolder.setUuid(AN_ANALYSIS_UUID); underTest.execute(new TestComputationStepContext()); assertThat(taskResultHolder.getResult().getAnalysisUuid()).contains(AN_...
@Override protected Map<String, Object> toJsonMap(IAccessEvent event) { return new MapBuilder(timestampFormatter, customFieldNames, additionalFields, includes.size()) .addNumber("port", isIncluded(AccessAttribute.LOCAL_PORT), event::getLocalPort) .addNumber("contentLength", isInclude...
@Test void testAddAdditionalFields() { final Map<String, Object> additionalFields = Map.of( "serviceName", "user-service", "serviceVersion", "1.2.3"); accessJsonLayout = new AccessJsonLayout(jsonFormatter, timestampFormatter, includes, Collections.emptyMap(), ...
@Override public double getValue(double quantile) { if (quantile < 0.0 || quantile > 1.0 || Double.isNaN( quantile )) { throw new IllegalArgumentException(quantile + " is not in [0..1]"); } if (values.length == 0) { return 0.0; } int posx = Arrays.bi...
@Test public void bigQuantilesAreTheLastValue() throws Exception { assertThat(snapshot.getValue(1.0)) .isEqualTo(5.0, offset(0.1)); }
@Udf(description = "Returns the inverse (arc) sine of an INT value") public Double asin( @UdfParameter( value = "value", description = "The value to get the inverse sine of." ) final Integer value ) { return asin(value == null ? null : value.doubleValue())...
@Test public void shouldHandlePositive() { assertThat(udf.asin(0.43), closeTo(0.444492776935819, 0.000000000000001)); assertThat(udf.asin(0.5), closeTo(0.5235987755982989, 0.000000000000001)); assertThat(udf.asin(1.0), closeTo(1.5707963267948966, 0.000000000000001)); assertThat(udf.asin(1), closeTo(1....
public static <T> T[] clone(final T[] array) { if (array == null) { return null; } return array.clone(); }
@Test public void assertClone() { Assert.isNull(ArrayUtil.clone(null)); String[] array = new String[0]; Assert.isTrue(array != ArrayUtil.clone(array)); Assert.isTrue(array.length == ArrayUtil.clone(array).length); }
public void setJobLauncher(JobLauncher jobLauncher) { this.jobLauncher = jobLauncher; }
@Test public void shouldUseJobLauncherFromComponent() throws Exception { // Given SpringBatchComponent batchComponent = new SpringBatchComponent(); batchComponent.setJobLauncher(alternativeJobLauncher); context.addComponent("customBatchComponent", batchComponent); // When ...
public Long asLong(Map<String, ValueReference> parameters) { switch (valueType()) { case LONG: if (value() instanceof Number) { return ((Number) value()).longValue(); } throw new IllegalStateException("Expected value reference of ty...
@Test public void asLong() { assertThat(ValueReference.of(42L).asLong(Collections.emptyMap())).isEqualTo(42L); assertThatThrownBy(() -> ValueReference.of("Test").asLong(Collections.emptyMap())) .isInstanceOf(IllegalStateException.class) .hasMessage("Expected value ref...
@Override public void visit(Entry target) { final EntryAccessor entryAccessor = new EntryAccessor(); final Component component = (Component) entryAccessor.removeComponent(target); if (component != null) { if(component instanceof AbstractButton) ((AbstractButton)component).setAction(null); removeMenuCom...
@Test public void ignoresEntriesWithoutComponents() throws Exception { final JComponentRemover componentRemover = JComponentRemover.INSTANCE; final Entry entry = new Entry(); componentRemover.visit(entry); }
public URI flowUrl(Execution execution) { return this.build("/ui/" + (execution.getTenantId() != null ? execution.getTenantId() + "/" : "") + "flows/" + execution.getNamespace() + "/" + execution.getFlowId()); }
@Test void flowUrl() { Flow flow = TestsUtils.mockFlow(); Execution execution = TestsUtils.mockExecution(flow, ImmutableMap.of()); assertThat(uriProvider.executionUrl(execution).toString(), containsString("mysuperhost.com/subpath/ui")); assertThat(uriProvider.flowUrl(execution).toSt...
public boolean isEmpty() { return messagesProcessed == 0 && errorsOccurred == 0; }
@Test void testIsEmpty() { StatsPersistMsg emptyStats = new StatsPersistMsg(0, 0, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID); assertThat(emptyStats.isEmpty()).isTrue(); }
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testFetchResponseMetricsWithOnePartitionError() { buildFetcher(); assignFromUser(mkSet(tp0, tp1)); subscriptions.seek(tp0, 0); subscriptions.seek(tp1, 0); Map<MetricName, KafkaMetric> allMetrics = metrics.metrics(); KafkaMetric fetchSizeAverage = al...
@Override public boolean isSupported() { try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { return false; } return OAIDRom.sysProperty("persist.sys.identifierid.supported", "0").equals("1"); } catch (Throwable throwable) { SALog...
@Test public void isSupported() { VivoImpl vivo = new VivoImpl(mApplication); Assert.assertFalse(vivo.isSupported()); }
protected static List<LastOpenedDTO> filterForExistingIdAndCapAtMaximum(final LastOpenedForUserDTO loi, final GRN grn, final long max) { return loi.items().stream().filter(i -> !i.grn().equals(grn)).limit(max - 1).toList(); }
@Test public void testRemoveIfExistsInList() { var _1 = grnRegistry.newGRN(GRNTypes.DASHBOARD, "1"); LastOpenedForUserDTO dto = new LastOpenedForUserDTO("userId", List.of(new LastOpenedDTO(_1, DateTime.now(DateTimeZone.UTC)))); var result = StartPageService.filterForExistingIdAndCapAtMaxim...
@SuppressWarnings("unchecked") public static <S, F> S visit(final SqlType type, final SqlTypeWalker.Visitor<S, F> visitor) { final BiFunction<SqlTypeWalker.Visitor<?, ?>, SqlType, Object> handler = HANDLER .get(type.baseType()); if (handler == null) { throw new UnsupportedOperationException("Un...
@Test public void shouldThrowByDefaultFromNonStructured() { // Given: visitor = new Visitor<String, Integer>() { }; nonStructuredTypes().forEach(type -> { try { // When: SqlTypeWalker.visit(type, visitor); fail(); } catch (final UnsupportedOperationException e) ...
public HashRange partition(int index, int count) { if (count <= 0) { throw new IllegalArgumentException("Count must be a strictly positive value"); } if (index < 0 || index >= count) { throw new IllegalArgumentException("Index must be between 0 and " + count); } ...
@Test public void partition() { HashRange range = HashRange.range(1000, 2000); assertEquals(HashRange.range(1000, 1500), range.partition(0, 2)); assertEquals(HashRange.range(1500, 2000), range.partition(1, 2)); range = range("0", "170141183460469231731687303715884105728"); a...
@Override public int compareTo(ColumnDescriptor o) { int length = path.length < o.path.length ? path.length : o.path.length; for (int i = 0; i < length; i++) { int compareTo = path[i].compareTo(o.path[i]); if (compareTo != 0) { return compareTo; } } return path.length - o.pat...
@Test public void testComparesTo() throws Exception { assertEquals(column("a").compareTo(column("a")), 0); assertEquals(column("a", "b").compareTo(column("a", "b")), 0); assertEquals(column("a").compareTo(column("b")), -1); assertEquals(column("b").compareTo(column("a")), 1); assertEquals(column(...
public static OpenstackNode getGwByInstancePort(Set<OpenstackNode> gateways, InstancePort instPort) { OpenstackNode gw = null; if (instPort != null && instPort.deviceId() != null) { gw = getGwByComputeDevId(gateways, instPort.deviceId()); ...
@Test public void testGetGwByInstancePort() { Set<OpenstackNode> gws = Sets.newConcurrentHashSet(); gws.add(genGateway(1)); gws.add(genGateway(2)); gws.add(genGateway(3)); int expectedGwIndex = 2; OpenstackNode gw = getGwByInstancePort(gws, instancePort1); ...
public static RandomForest fit(Formula formula, DataFrame data) { return fit(formula, data, new Properties()); }
@Test public void testBreastCancer() { System.out.println("Breast Cancer"); MathEx.setSeed(19650218); // to get repeatable results for cross validation. ClassificationValidations<RandomForest> result = CrossValidation.classification(10, BreastCancer.formula, BreastCancer.data, ...
@Override public byte getByte(int index) { checkIndex(index); return _getByte(index); }
@Test public void testGetByteAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().getByte(0); } }); }
@Override public UfsFileStatus copy() { return new UfsFileStatus(this); }
@Test public void copy() { Random random = new Random(); String contentHash = CommonUtils.randomAlphaNumString(10); long contentLength = random.nextLong(); long lastModifiedTimeMs = random.nextLong(); short mode = 077; long blockSize = random.nextLong(); UfsFileStatus statusToCopy = ...
public Optional<DateTime> nextTime(JobTriggerDto trigger) { return nextTime(trigger, trigger.nextTime()); }
@Test public void intervalNextTimeAfter() { final JobTriggerDto trigger = JobTriggerDto.builderWithClock(clock) .jobDefinitionId("abc-123") .jobDefinitionType("event-processor-execution-v1") .schedule(IntervalJobSchedule.builder() .inte...
@Override public OutputT expand(InputT input) { OutputT res = delegate().expand(input); if (res instanceof PCollection) { PCollection pc = (PCollection) res; try { pc.setCoder(delegate().getDefaultOutputCoder(input, pc)); } catch (CannotProvideCoderException e) { // Let coder...
@Test public void getDefaultOutputCoderDelegates() throws Exception { @SuppressWarnings("unchecked") PCollection<Integer> input = PCollection.createPrimitiveOutputInternal( null /* pipeline */, WindowingStrategy.globalDefault(), PCollection.IsBounded.BOUNDED, ...
public static String toString(RedisCommand<?> command, Object... params) { if (RedisCommands.AUTH.equals(command)) { return "command: " + command + ", params: (password masked)"; } return "command: " + command + ", params: " + LogHelper.toString(params); }
@Test public void toStringWithNestedBigCollections() { List<String> strings = Collections.nCopies(15, "0"); List<Integer> ints = Collections.nCopies(15, 1); List<Long> longs = Collections.nCopies(15, 2L); List<Double> doubles = Collections.nCopies(15, 3.1D); List<Float> fl...
public static double of(double[] truth, double[] prediction) { if (truth.length != prediction.length) { throw new IllegalArgumentException(String.format("The vector sizes don't match: %d != %d.", truth.length, prediction.length)); } int n = truth.length; double rss = 0.0; ...
@Test public void test() { System.out.println("RSS"); double[] truth = { 83.0, 88.5, 88.2, 89.5, 96.2, 98.1, 99.0, 100.0, 101.2, 104.6, 108.4, 110.8, 112.6, 114.2, 115.7, 116.9 }; double[] prediction = { 83.60082, 86.94973, 88.09677, 90.7306...
public Optional<User> login(String nameOrEmail, String password) { if (nameOrEmail == null || password == null) { return Optional.empty(); } User user = userDAO.findByName(nameOrEmail); if (user == null) { user = userDAO.findByEmail(nameOrEmail); } if (user != null && !user.isDisabled()) { boolean...
@Test void apiLoginShouldReturnUserIfUserFoundFromApikeyLookupNotDisabled() { Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(normalUser); Optional<User> returnedUser = userService.login("apikey"); Assertions.assertEquals(normalUser, returnedUser.get()); }
String getSafeModeTip() { StringBuilder msg = new StringBuilder(); boolean isBlockThresholdMet = false; synchronized (this) { isBlockThresholdMet = (blockSafe >= blockThreshold); if (!isBlockThresholdMet) { msg.append(String.format( "The reported blocks %d needs additional %...
@Test(timeout = 30000) public void testGetSafeModeTip() throws Exception { bmSafeMode.activate(BLOCK_TOTAL); String tip = bmSafeMode.getSafeModeTip(); assertTrue(tip.contains( String.format( "The reported blocks %d needs additional %d blocks to reach the " + "threshold ...
@Override public Map<String, Object> processCsvFile(String encodedCsvData, boolean dryRun) throws JsonProcessingException { services = new HashMap<>(); serviceParentChildren = new HashMap<>(); Map<String, Object> result = super.processCsvFile(encodedCsvData, dryRun); if (!services.is...
@Test void processCsvFileFailUniqueEntityIdAndNameTest() throws IOException { String csvData = """SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS...
public MessageListener messageListener(MessageListener messageListener, boolean addConsumerSpan) { if (messageListener instanceof TracingMessageListener) return messageListener; return new TracingMessageListener(messageListener, this, addConsumerSpan); }
@Test void messageListener_wrapsInput() { assertThat(jmsTracing.messageListener(mock(MessageListener.class), false)) .isInstanceOf(TracingMessageListener.class); }
@Override public void execute() { boolean debugMode = ExtensibleLoadManagerImpl.debug(conf, log); if (debugMode) { log.info("Load balancer enabled: {}, Split enabled: {}.", conf.isLoadBalancerEnabled(), conf.isLoadBalancerAutoBundleSplitEnabled()); } ...
@Test(timeOut = 30 * 1000) public void testExecuteSuccess() { AtomicReference<List<Metrics>> reference = new AtomicReference(); SplitCounter counter = new SplitCounter(); SplitManager manager = mock(SplitManager.class); SplitScheduler scheduler = new SplitScheduler(pulsar, channel, m...
@Override public Iterator<T> iterator() { return new LinkedSetIterator(); }
@Test public void testRemoveAll() { LOG.info("Test remove all"); for (Integer i : list) { assertTrue(set.add(i)); } for (int i = 0; i < NUM; i++) { assertTrue(set.remove(list.get(i))); } // the deleted elements should not be there for (int i = 0; i < NUM; i++) { assertFal...
@Override public Publisher<Exchange> to(String uri, Object data) { String streamName = requestedUriToStream.computeIfAbsent(uri, camelUri -> { try { String uuid = context.getUuidGenerator().generateUuid(); RouteBuilder.addRoutes(context, rb -> rb.from("reactive-st...
@Test public void testTo() throws Exception { context.start(); AtomicInteger value = new AtomicInteger(); CountDownLatch latch = new CountDownLatch(1); Flowable.just(1, 2, 3).flatMap(e -> crs.to("bean:hello", e, String.class)) .doOnNext(res -> assertEquals("Hello " ...
@Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isLessThan(criterionValue2); }
@Test public void betterThan() { AnalysisCriterion criterion = getCriterion(); assertTrue(criterion.betterThan(numOf(3), numOf(6))); assertFalse(criterion.betterThan(numOf(7), numOf(4))); }
@Override public int getTcpReceiveBufferSize() { return clientConfig.getPropertyAsInteger(IClientConfigKey.Keys.ReceiveBufferSize, DEFAULT_BUFFER_SIZE); }
@Test void testGetTcpReceiveBufferSize() { assertEquals(ConnectionPoolConfigImpl.DEFAULT_BUFFER_SIZE, connectionPoolConfig.getTcpReceiveBufferSize()); }
public static File copy(String srcPath, String destPath, boolean isOverride) throws IORuntimeException { return copy(file(srcPath), file(destPath), isOverride); }
@Test @Disabled public void copyTest2(){ final File copy = FileUtil.copy("d:/test/qrcodeCustom.png", "d:/test/pic", false); // 当复制文件到目标目录的时候,返回复制的目标文件,而非目录 Console.log(copy); }
public static List<DataType> getFieldDataTypes(DataType dataType) { final LogicalType type = dataType.getLogicalType(); if (type.is(LogicalTypeRoot.DISTINCT_TYPE)) { return getFieldDataTypes(dataType.getChildren().get(0)); } else if (isCompositeType(type)) { return dataTy...
@Test void testGetFieldDataTypes() { assertThat( DataType.getFieldDataTypes( ROW( FIELD("c0", BOOLEAN()), FIELD("c1", DOUBLE()), FIE...
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 optifineIsNotCompatibleWithForge3() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/optifine_is_not_compatible_with_forge4.txt")), CrashReportAnalyzer.Rule.OPTIFINE_IS_NOT_COMPATIBLE_WITH_...