focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public RowData nextRecord(RowData reuse) { // return the next row row.setRowId(this.nextRow++); return row; }
@Test void testReachEnd() throws Exception { FileInputSplit[] splits = createSplits(testFileFlat, 1); try (OrcColumnarRowSplitReader reader = createReader(new int[] {0, 1}, testSchemaFlat, new HashMap<>(), splits[0])) { while (!reader.reachedEnd()) { reade...
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) { ProjectMeasuresQuery query = new ProjectMeasuresQuery(); Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids); criteria.forEach(criterion -> processCriterion(criterion, query));...
@Test public void fail_to_create_query_having_q_with_other_operator_than_equals() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("query").setOperator(LT).setValue("java").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) ...
@Override public Set<String> getMetricKeys(QualityGate gate) { Set<String> metricKeys = new HashSet<>(); metricKeys.add(CoreMetrics.NEW_LINES_KEY); for (Condition condition : gate.getConditions()) { metricKeys.add(condition.getMetricKey()); } return metricKeys; }
@Test public void getMetricKeys_includes_metrics_from_qgate() { Set<String> metricKeys = ImmutableSet.of("foo", "bar", "baz"); Set<Condition> conditions = metricKeys.stream().map(key -> { Condition condition = mock(Condition.class); when(condition.getMetricKey()).thenReturn(key); return cond...
@NonNull public static List<VideoStream> getSortedStreamVideosList( @NonNull final Context context, @Nullable final List<VideoStream> videoStreams, @Nullable final List<VideoStream> videoOnlyStreams, final boolean ascendingOrder, final boolean preferVideoO...
@Test public void getSortedStreamVideosExceptHighResolutionsTest() { //////////////////////////////////// // Don't show Higher resolutions // ////////////////////////////////// final List<VideoStream> result = ListHelper.getSortedStreamVideosList(MediaFormat.MPEG_4, ...
public static org.apache.avro.Schema toAvroSchema( Schema beamSchema, @Nullable String name, @Nullable String namespace) { final String schemaName = Strings.isNullOrEmpty(name) ? "topLevelRecord" : name; final String schemaNamespace = namespace == null ? "" : namespace; String childNamespace = ...
@Test public void testJdbcLogicalVarCharRowDataToAvroSchema() { String expectedAvroSchemaJson = "{ " + " \"name\": \"topLevelRecord\", " + " \"type\": \"record\", " + " \"fields\": [{ " + " \"name\": \"my_varchar_field\", " + " \"type\": {\"t...
public void writeTo(T object, DataWriter writer) throws IOException { writeTo(object, 0, writer); }
@Test(expected = IOException.class) public void testNotExportedBeanFailing() throws IOException { ExportConfig config = new ExportConfig().withFlavor(Flavor.JSON).withExportInterceptor(new ExportInterceptor2()).withSkipIfFail(true); StringWriter writer = new StringWriter(); ExportableBean b ...
public static String executeDockerCommand(DockerCommand dockerCommand, String containerId, Map<String, String> env, PrivilegedOperationExecutor privilegedOperationExecutor, boolean disableFailureLogging, Context nmContext) throws ContainerExecutionException { PrivilegedOperation dockerOp = d...
@Test public void testExecuteDockerCommand() throws Exception { DockerStopCommand dockerStopCommand = new DockerStopCommand(MOCK_CONTAINER_ID); DockerCommandExecutor.executeDockerCommand(dockerStopCommand, cId.toString(), env, mockExecutor, false, nmContext); List<PrivilegedOperation> ops ...
protected boolean isIntegralNumber(String field, FieldPresence presence, long... minMax) { return isIntegralNumber(object, field, presence, minMax); }
@Test public void isIntegralNumber() { assertTrue("is not proper number", cfg.isIntegralNumber(LONG, MANDATORY)); assertTrue("is not proper number", cfg.isIntegralNumber(LONG, MANDATORY, 0)); assertTrue("is not proper number", cfg.isIntegralNumber(LONG, MANDATORY, 0, 10)); assertTrue...
public List<Cookie> decodeAll(String header) { List<Cookie> cookies = new ArrayList<Cookie>(); decode(cookies, header); return Collections.unmodifiableList(cookies); }
@Test public void testDecodingAllMultipleCookies() { String c1 = "myCookie=myValue;"; String c2 = "myCookie=myValue2;"; String c3 = "myCookie=myValue3;"; List<Cookie> cookies = ServerCookieDecoder.STRICT.decodeAll(c1 + c2 + c3); assertEquals(3, cookies.size()); Itera...
public String createNote(String notePath, AuthenticationInfo subject) throws IOException { return createNote(notePath, interpreterSettingManager.getDefaultInterpreterSetting().getName(), subject); }
@Test void testScheduleDisabledWithName() throws InterruptedException, IOException { zConf.setProperty(ConfVars.ZEPPELIN_NOTEBOOK_CRON_FOLDERS.getVarName(), "/System"); final int timeout = 30; final String everySecondCron = "* * * * * ?"; // each run starts a new JVM and the job takes about ~5 second...
@VisibleForTesting public void validateDictDataValueUnique(Long id, String dictType, String value) { DictDataDO dictData = dictDataMapper.selectByDictTypeAndValue(dictType, value); if (dictData == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的字典数据 if (id == null) ...
@Test public void testValidateDictDataValueUnique_success() { // 调用,成功 dictDataService.validateDictDataValueUnique(randomLongId(), randomString(), randomString()); }
@Override public Connection connectToServer(ServerInfo serverInfo) { // the newest connection id String connectionId = ""; try { if (grpcExecutor == null) { this.grpcExecutor = createGrpcExecutor(serverInfo.getServerIp()); } int port = serv...
@Test void testConnectToServerFailed() { assertNull(grpcClient.connectToServer(serverInfo)); }
@SuppressWarnings("unchecked") public static void addNamedOutput(Job job, String namedOutput, Class<? extends OutputFormat> outputFormatClass, Schema keySchema) { addNamedOutput(job, namedOutput, outputFormatClass, keySchema, null); }
@Test void avroSpecificOutput() throws Exception { Job job = Job.getInstance(); FileInputFormat.setInputPaths(job, new Path(getClass().getResource("/org/apache/avro/mapreduce/mapreduce-test-input.txt").toURI().toString())); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(L...
public static BytesInput fromUnsignedVarLong(long longValue) { return new UnsignedVarLongBytesInput(longValue); }
@Test public void testFromUnsignedVarLong() throws IOException { long value = RANDOM.nextInt(Integer.MAX_VALUE); ByteArrayOutputStream baos = new ByteArrayOutputStream(4); BytesUtils.writeUnsignedVarLong(value, baos); byte[] data = baos.toByteArray(); Supplier<BytesInput> factory = () -> BytesInpu...
public MapConfig setCacheDeserializedValues(CacheDeserializedValues cacheDeserializedValues) { this.cacheDeserializedValues = cacheDeserializedValues; return this; }
@Test @Ignore(value = "this MapStoreConfig does not override equals/hashcode -> this cannot pass right now") public void givenSetCacheDeserializedValuesIsINDEX_ONLY_whenComparedWithOtherConfigWhereCacheIsINDEX_ONLY_thenReturnTrue() { // given MapConfig mapConfig = new MapConfig(); mapCon...
@Override public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException { if (metric == null) { throw new NullPointerException("metric == null"); } return metric; }
@Test public void registeringACounterTriggersNoNotification() { assertThat(registry.register("thing", counter)).isEqualTo(counter); verify(listener, never()).onCounterAdded("thing", counter); }
@Override public Name getLocation(final Path file) throws BackgroundException { if(StringUtils.isNotBlank(session.getHost().getRegion())) { return new S3Region(session.getHost().getRegion()); } final Path bucket = containerService.getContainer(file); return this.getLocati...
@Test public void testGetLocation() throws Exception { final RegionEndpointCache cache = session.getClient().getRegionEndpointCache(); final S3LocationFeature feature = new S3LocationFeature(session, cache); assertEquals(new S3LocationFeature.S3Region("eu-west-1"), feature.getLocation( ...
static final String addFunctionParameter(ParameterDescriptor descriptor, RuleBuilderStep step) { final String parameterName = descriptor.name(); // parameter name needed by function final Map<String, Object> parameters = step.parameters(); if (Objects.isNull(parameters)) { return nul...
@Test public void addFunctionParameterSyntaxOk_WhenNumericParameterValueIsSet() { String parameterName = "foo"; var parameterValue = 42; RuleBuilderStep step = mock(RuleBuilderStep.class); Map<String, Object> params = Map.of(parameterName, parameterValue); when(step.parameter...
public void replayTruncateTable(TruncateTableInfo info) { Database db = getDb(info.getDbId()); Locker locker = new Locker(); locker.lockDatabase(db, LockType.WRITE); try { OlapTable olapTable = (OlapTable) db.getTable(info.getTblId()); truncateTableInternal(olapTa...
@Test public void testReplayTruncateTable() throws DdlException { Database db = connectContext.getGlobalStateMgr().getDb("test"); OlapTable table = (OlapTable) db.getTable("t1"); Partition p = table.getPartitions().stream().findFirst().get(); TruncateTableInfo info = new TruncateTabl...
@Override public int get(TemporalField field) { return offsetTime.get(field); }
@Test void get() { Arrays.stream(ChronoField.values()) .filter(offsetTime::isSupported) .filter(field -> field != ChronoField.NANO_OF_DAY && field != ChronoField.MICRO_OF_DAY) // Unsupported by offsettime.get() .forEach(field -> assertEquals(offsetTime.get(fie...
public double p(int[] o, int[] s) { return Math.exp(logp(o, s)); }
@Test public void testJointP() { System.out.println("joint p"); int[] o = {0, 0, 1, 1, 0, 1, 1, 0}; int[] s = {0, 0, 1, 1, 1, 1, 1, 0}; HMM hmm = new HMM(pi, Matrix.of(a), Matrix.of(b)); double expResult = 7.33836e-05; double result = hmm.p(o, s); assertEquals...
@SuppressWarnings({"CastCanBeRemovedNarrowingVariableType", "unchecked"}) public E relaxedPoll() { final E[] buffer = consumerBuffer; final long index = consumerIndex; final long mask = consumerMask; final long offset = modifiedCalcElementOffset(index, mask); Object e = lvElement(buffer, offset);...
@Test(dataProvider = "empty") public void relaxedPoll_whenEmpty(MpscGrowableArrayQueue<Integer> queue) { assertThat(queue.relaxedPoll()).isNull(); }
public static <T> GoConfigClassLoader<T> classParser(Element e, Class<T> aClass, ConfigCache configCache, GoCipher goCipher, final ConfigElementImplementationRegistry registry, ConfigReferenceElements configReferenceElements) { return new GoConfigClassLoader<>(e, aClass, configCache, goCipher, registry, configR...
@Test public void shouldErrorOutWhenAttributeAwareConfigTagClassHasConfigAttributeWithSameName() { final Element element = new Element("example"); element.setAttribute("type", "example-type"); when(configCache.getFieldCache()).thenReturn(new ClassAttributeCache.FieldCache()); final ...
public static FuryBuilder builder() { return new FuryBuilder(); }
@Test public void testSerializePackageLevelBeanJIT() { Fury fury = Fury.builder() .withLanguage(Language.JAVA) .withCodegen(true) .requireClassRegistration(false) .build(); PackageLevelBean o = new PackageLevelBean(); o.f1 = 10; o.f2 = 1; ser...
private RestLiResponseAttachments(final RestLiResponseAttachments.Builder builder) { _multiPartMimeWriterBuilder = builder._multiPartMimeWriterBuilder; }
@Test public void testRestLiResponseAttachments() { //In this test we simply add a few attachments and verify the size of the resulting MultiPartMIMEWriter. //More detailed tests can be found in TestAttachmentUtils. final RestLiResponseAttachments emptyAttachments = new RestLiResponseAttachments.Builde...
@VisibleForTesting static int checkJar(Path file) throws Exception { final URI uri = file.toUri(); int numSevereIssues = 0; try (final FileSystem fileSystem = FileSystems.newFileSystem( new URI("jar:file", uri.getHost(), uri.getPath(), uri.getFragment...
@Test void testForbiddenLGPLongTextDetected(@TempDir Path tempDir) throws Exception { assertThat( JarFileChecker.checkJar( createJar( tempDir, Entry.fileEntry(VALID_NOTICE_...
public V setValue(V value, long ttlMillis) { access(); return setValueInternal(value, ttlMillis); }
@Test public void testSetValue() { assertEquals(0, replicatedRecord.getHits()); assertEquals("value", replicatedRecord.getValueInternal()); replicatedRecord.setValue("newValue", 0); assertEquals(1, replicatedRecord.getHits()); assertEquals("newValue", replicatedRecord.getVa...
@Operation(summary = "get challenge", tags = { SwaggerConfig.ACTIVATE_WEBSITE, SwaggerConfig.REQUEST_ACCOUNT_AND_APP, SwaggerConfig.ACTIVATE_SMS, SwaggerConfig.ACTIVATE_LETTER, SwaggerConfig.ACTIVATE_RDA, SwaggerConfig.ACTIVATE_WITH_APP, SwaggerConfig.RS_ACTIVATE_WITH_APP}, operationId = "challenge_response", p...
@Test void validateIfCorrectProcessesAreCalledChallengeResponse() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException { ChallengeResponseRequest request = new ChallengeResponseRequest(); request.setAppPublicKey("not-null")...
public static <T> Stream<T> stream(Enumeration<T> e) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize( new Iterator<T>() { public T next() { return e.nextElement(); }...
@Test public void test_count_stream_from_enumeration() { Enumeration<Integer> someEnumeration = Collections.enumeration(Arrays.asList(1, 2, 3)); assertThat(EnumerationUtil.stream(someEnumeration).count()).isEqualTo(3); }
private CompletionStage<RestResponse> pushStateStatus(RestRequest request) { return statusOperation(request, PUSH_STATE_STATUS); }
@Test public void testPushAllCaches() { RestClient restClientLon = clientPerSite.get(LON); RestClient restClientSfo = clientPerSite.get(SFO); RestCacheClient cache1Lon = restClientLon.cache(CACHE_1); RestCacheClient cache2Lon = restClientLon.cache(CACHE_2); RestCacheClient cache1Sfo =...
@Override public void callBeforeLog() { if ( parent != null ) { parent.callBeforeLog(); } }
@Test public void testJobCallBeforeLog() { Trans trans = new Trans(); LoggingObjectInterface parent = mock( LoggingObjectInterface.class ); setInternalState( trans, "parent", parent ); trans.callBeforeLog(); verify( parent, times( 1 ) ).callBeforeLog(); }
@GET @Path("{id}/stats") @Timed @ApiOperation(value = "Get index set statistics") @ApiResponses(value = { @ApiResponse(code = 403, message = "Unauthorized"), @ApiResponse(code = 404, message = "Index set not found"), }) public IndexSetStats indexSetStatistics(@ApiParam(na...
@Test public void indexSetStatisticsDenied() { notPermitted(); expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Not authorized to access resource id <id>"); try { indexSetsResource.indexSetStatistics("id"); } finally { ...
public JmxCollector register() { return register(PrometheusRegistry.defaultRegistry); }
@Test(expected = IllegalStateException.class) public void testDelayedStartNotReady() throws Exception { JmxCollector jc = new JmxCollector("---\nstartDelaySeconds: 1").register(prometheusRegistry); assertNull(getSampleValue("boolean_Test_True", new String[] {}, new String[] {})); ...
public void deleteDatabaseNameListenerAssisted(final String databaseName) { repository.delete(ListenerAssistedNodePath.getDatabaseNameNodePath(databaseName)); }
@Test void assertDeleteDatabaseNameListenerAssisted() { new ListenerAssistedPersistService(repository).deleteDatabaseNameListenerAssisted("foo_db"); verify(repository).delete("/listener_assisted/foo_db"); }
public boolean isLaunchIntentsActivity(Activity activity) { final Intent helperIntent = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName()); final String activityName = activity.getComponentName().getClassName(); final String launchIntentActivityName = helperIntent....
@Test public void isLaunchIntentsActivity_activityIsMainLauncherActivity_returnTrue() throws Exception { Activity activity = getActivityMock(APP_MAIN_ACTIVITY_NAME); final AppLaunchHelper uut = getUUT(); boolean result = uut.isLaunchIntentsActivity(activity); assertTrue(result); ...
public CronPattern(String pattern) { this.pattern = pattern; this.matchers = PatternParser.parse(pattern); }
@Test public void cronPatternTest() { CronPattern pattern; // 12:11匹配 pattern = CronPattern.of("39 11 12 * * *"); assertMatch(pattern, "12:11:39"); // 每5分钟匹配,匹配分钟为:[0,5,10,15,20,25,30,35,40,45,50,55] pattern = CronPattern.of("39 */5 * * * *"); assertMatch(pattern, "12:00:39"); assertMatch(pattern, "1...
@Udf public String extractQuery( @UdfParameter(description = "a valid URL to extract a query from") final String input) { return UrlParser.extract(input, URI::getQuery); }
@Test public void shouldReturnNullIfNoQuery() { assertThat(extractUdf.extractQuery("https://current/ksql/docs/syntax-reference.html#scalar-functions"), nullValue()); }
public static Builder newBuilder() { return new Builder(); }
@Test public void argumentValidation_withSampleUpdateFrequency_lteqSamplePeriod() { RpcQosOptions.newBuilder() .withSamplePeriod(Duration.millis(5)) .withSamplePeriodBucketSize(Duration.millis(5)) .validateRelatedFields(); try { RpcQosOptions.newBuilder() .withSamplePer...
public static String buildGlueExpression(Map<Column, Domain> partitionPredicates) { List<String> perColumnExpressions = new ArrayList<>(); int expressionLength = 0; for (Map.Entry<Column, Domain> partitionPredicate : partitionPredicates.entrySet()) { String columnName = partition...
@Test public void testBuildGlueExpressionTupleDomainEqualAndRangeLong() { Map<Column, Domain> predicates = new PartitionFilterBuilder(HIVE_TYPE_TRANSLATOR) .addBigintValues("col1", 3L) .addRanges("col1", Range.greaterThan(BIGINT, 100L)) .addRanges("col1", ...
public static int checkNotNegative(int value, String paramName) { if (value < 0) { throw new IllegalArgumentException(paramName + " is " + value + " but must be >= 0"); } return value; }
@Test public void test_checkPositive_whenPositive() { checkNotNegative(1, "foo"); }
public String decode(byte[] val) { return codecs[0].decode(val, 0, val.length); }
@Test public void testDecodeChinesePersonNameUTF8() { assertEquals(CHINESE_PERSON_NAME_UTF8, utf8().decode(CHINESE_PERSON_NAME_UTF8_BYTES)); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("box.listing.chunksize")); }
@Test(expected = NotfoundException.class) public void testNotFound() throws Exception { final BoxFileidProvider fileid = new BoxFileidProvider(session); new BoxListService(session, fileid).list(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(directory)), new DisabledListProgressL...
public abstract int release(byte[] array);
@Test public void testAllocateRecycle() throws Exception { final int countThreshold = 4; final int countLimit = 8; final long countResetTimePeriodMs = 200L; final ByteArrayManager.Impl bam = new ByteArrayManager.Impl( new ByteArrayManager.Conf( countThreshold, countLimit, countRese...
public String build() { return build(null, Maps.<String, Object>newHashMap()); }
@Test public void testScheme() { UriSpec spec = new UriSpec("{scheme}://foo.com"); ServiceInstanceBuilder<Void> builder = new ServiceInstanceBuilder<Void>(); builder.id("x"); builder.name("foo"); builder.port(5); ServiceInstance<Void> instance = builder.build(); ...
public ImmutableList<T> append(T element) { ArgumentUtil.notNull(element, "element"); return new ImmutableList<>(element, this); }
@Test public void testAppend() { ImmutableList<String> empty = ImmutableList.empty(); ImmutableList<String> a = empty.append("a"); ImmutableList<String> ab = a.append("b"); ImmutableList<String> abc = ab.append("c"); assertEquals(a.size(), 1); assertEquals(ab.size(), 2); assertEquals(a...
@Override public InputStream open(String path) throws IOException { return new URL(path).openStream(); }
@Test void readsFileContents() throws Exception { try (InputStream input = provider.open(getClass().getResource("/example.txt").toString())) { assertThat(new String(input.readAllBytes(), StandardCharsets.UTF_8).trim()) .isEqualTo("whee"); } }
SuspensionLimit getConcurrentSuspensionLimit(ClusterApi clusterApi) { // Possible service clusters on a node as of 2024-06-09: // // CLUSTER ID SERVICE TYPE HEALTH ASSOCIATION // 1 CCN-controllers container-clustercontrollers Slobrok ...
@Test public void testSlobrokSuspensionLimit() { when(clusterApi.clusterId()).thenReturn(VespaModelUtil.ADMIN_CLUSTER_ID); when(clusterApi.serviceType()).thenReturn(ServiceType.SLOBROK); assertEquals(SuspensionLimit.fromAllowedDown(1), policy.getConcurrentSuspensionLimit...
public static <T> CommonPager<T> result(final PageParameter pageParameter, final Supplier<Integer> countSupplier, final Supplier<List<T>> listSupplier) { Integer count = countSupplier.get(); if (Objects.nonNull(count) && count > 0) { return new CommonPager<>(new PageParameter(pageParameter.g...
@Test public void testEmptyResult() { final PageParameter pageParameter = new PageParameter(1, 10, 0); final CommonPager<String> result = PageResultUtils.result(pageParameter, () -> 0, ArrayList::new); assertEquals(result.getDataList().size(), 0); }
public static File applyBaseDirIfRelative(File baseDir, File actualFileToUse) { if (actualFileToUse == null) { return baseDir; } if (actualFileToUse.isAbsolute()) { return actualFileToUse; } if (StringUtils.isBlank(baseDir.getPath())) { return...
@Test void shouldUseSpecifiedFolderIfBaseDirIsEmpty() { assertThat(FileUtil.applyBaseDirIfRelative(new File(""), new File("zx"))).isEqualTo(new File("zx")); }
@Override public double[] smooth(double[] input) { if (input.length < weights.length) { return input; } double[] smoothed = new double[input.length]; int halfWindowFloored = weights.length / 2; // we want to exclude the center point fillSmoothedLeftSide(smoothe...
@Test public void Smooth_FromFakeTrackWithOutlier_RemoveBumps() { SavitzkyGolayFilter test = new SavitzkyGolayFilter(1.0); double[] input = new double[]{ 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 13.0, // <-- outlier 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0 }; ...
public static String pickBestEncoding(String acceptHeader, Set<String> customMimeTypesSupported) { return pickBestEncoding(acceptHeader, null, customMimeTypesSupported); }
@Test(dataProvider = "successfulMatch") public void testPickBestEncodingWithValidMimeTypes(String header, String result) { Assert.assertEquals(RestUtils.pickBestEncoding(header, Collections.emptySet()), result); }
@Override public ExecuteContext onThrow(ExecuteContext context) { ThreadLocalUtils.removeRequestTag(); ThreadLocalUtils.removeRequestData(); return context; }
@Test public void testOnThrow() { ThreadLocalUtils.setRequestData(new RequestData(Collections.emptyMap(), "", "")); interceptor.onThrow(context); Assert.assertNull(ThreadLocalUtils.getRequestData()); }
public static MongoSinkConfig load(String yamlFile) throws IOException { final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); final MongoSinkConfig cfg = mapper.readValue(new File(yamlFile), MongoSinkConfig.class); return cfg; }
@Test public void testLoadMapConfigUrlFromSecret() throws IOException { final Map<String, Object> commonConfigMap = TestHelper.createCommonConfigMap(); commonConfigMap.put("batchSize", TestHelper.BATCH_SIZE); commonConfigMap.put("batchTimeMs", TestHelper.BATCH_TIME); commonConfigMap....
public DefaultIssue setLine(@Nullable Integer l) { Preconditions.checkArgument(l == null || l > 0, "Line must be null or greater than zero (got %s)", l); this.line = l; return this; }
@Test void setLine_whenLineIsZero_shouldThrowException() { assertThatThrownBy(() -> issue.setLine(0)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Line must be null or greater than zero (got 0)"); }
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testEthSign() throws Exception { web3j.ethSign( "0x8a3106a3e50576d4b6794a0e74d3bb5f8c9acaab", "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470") .send(); verifyResult( "{\"jsonrpc\":...
@GetMapping(value = "/simple/nodes") @Secured(resource = Commons.NACOS_CORE_CONTEXT + "/cluster", action = ActionTypes.READ, signType = SignType.CONSOLE) public RestResult<Collection<String>> listSimpleNodes() { return RestResultUtils.success(memberManager.getMemberAddressInfos()); }
@Test void testListSimpleNodes() { Mockito.when(serverMemberManager.getMemberAddressInfos()).thenReturn(Collections.singleton("1.1.1.1")); RestResult<Collection<String>> result = nacosClusterController.listSimpleNodes(); assertEquals(1, result.getData().size()); }
@Override public void showPreviewForKey( Keyboard.Key key, Drawable icon, View parentView, PreviewPopupTheme previewPopupTheme) { KeyPreview popup = getPopupForKey(key, parentView, previewPopupTheme); Point previewPosition = mPositionCalculator.calculatePositionForPreview( key, previ...
@Test public void testSetupPopupLayoutForKeyDrawable() { final Drawable drawable = getApplicationContext().getDrawable(R.drawable.ic_accept); KeyPreviewsManager underTest = new KeyPreviewsManager(getApplicationContext(), mPositionCalculator, 3); underTest.showPreviewForKey(mTestKeys[0], drawable, ...
void readEntries(ReadHandle lh, long firstEntry, long lastEntry, boolean shouldCacheEntry, final AsyncCallbacks.ReadEntriesCallback callback, Object ctx) { final PendingReadKey key = new PendingReadKey(firstEntry, lastEntry); Map<PendingReadKey, PendingRead> pendingReadsForLedger =...
@Test public void simpleConcurrentReadMissingLeft() throws Exception { long firstEntry = 100; long endEntry = 199; long firstEntrySecondRead = firstEntry - 10; long endEntrySecondRead = endEntry; boolean shouldCacheEntry = false; PreparedReadFromStorage read1 = ...
@Operation(summary = "Gets the status of ongoing database migrations, if any", description = "Return the detailed status of ongoing database migrations" + " including starting date. If no migration is ongoing or needed it is still possible to call this endpoint and receive appropriate information.") @GetMapping ...
@Test void getStatus_migrationNotNeeded_returnUpToDateStatus() throws Exception { when(databaseVersion.getStatus()).thenReturn(DatabaseVersion.Status.UP_TO_DATE); when(migrationState.getStatus()).thenReturn(NONE); mockMvc.perform(get(DATABASE_MIGRATIONS_ENDPOINT)).andExpectAll(status().isOk(), cont...
public static <T extends Writable> WritableCoder<T> of(Class<T> clazz) { return new WritableCoder<>(clazz); }
@Test public void testNullWritableEncoding() throws Exception { NullWritable value = NullWritable.get(); WritableCoder<NullWritable> coder = WritableCoder.of(NullWritable.class); CoderProperties.coderDecodeEncodeEqual(coder, value); }
@Override public InputStream open(String path) throws IOException { try (InputStream in = delegate.open(path)) { final String config = new String(in.readAllBytes(), StandardCharsets.UTF_8); final String substituted = substitutor.replace(config); return new ByteArrayInput...
@Test void shouldSubstituteCorrectly() throws IOException { StringLookup dummyLookup = (x) -> "baz"; DummySourceProvider dummyProvider = new DummySourceProvider(); SubstitutingSourceProvider provider = new SubstitutingSourceProvider(dummyProvider, new StringSubstitutor(dummyLookup)); ...
@Override public void acknowledgeMessage(List<Position> positions, AckType ackType, Map<String, Long> properties) { cursor.updateLastActive(); Position previousMarkDeletePosition = cursor.getMarkDeletedPosition(); if (ackType == AckType.Cumulative) { if (positions.size() != 1) ...
@Test public void testAcknowledgeUpdateCursorLastActive() throws Exception { doAnswer((invocationOnMock) -> { ((AsyncCallbacks.DeleteCallback) invocationOnMock.getArguments()[1]) .deleteComplete(invocationOnMock.getArguments()[2]); return null; }).when(cur...
@Override public WebhookPayload create(ProjectAnalysis analysis) { Writer string = new StringWriter(); try (JsonWriter writer = JsonWriter.of(string)) { writer.beginObject(); writeServer(writer); writeTask(writer, analysis.getCeTask()); writeAnalysis(writer, analysis, system2); w...
@Test public void create_payload_for_no_analysis_date() { CeTask ceTask = new CeTask("#1", CeTask.Status.FAILED); ProjectAnalysis analysis = newAnalysis(ceTask, null, null, null, emptyMap()); WebhookPayload payload = underTest.create(analysis); assertThat(payload.getProjectKey()).isEqualTo(PROJECT_K...
public static byte[] encode(Predicate predicate) { Objects.requireNonNull(predicate, "predicate"); Slime slime = new Slime(); encode(predicate, slime.setObject()); return com.yahoo.slime.BinaryFormat.encode(slime); }
@Test void requireThatUnknownNodeThrows() { try { BinaryFormat.encode(SimplePredicates.newString("foo")); fail(); } catch (UnsupportedOperationException e) { } }
@Override public void resolveDiscardMsg(MessageExt msgExt) { log.error("MsgExt:{} has been checked too many times, so discard it by moving it to system topic TRANS_CHECK_MAXTIME_TOPIC", msgExt); try { MessageExtBrokerInner brokerInner = toMessageExtBrokerInner(msgExt); PutMe...
@Test public void sendCheckMessage() { listener.resolveDiscardMsg(createMessageExt()); }
public List<Long> availableWindows() { return getWindowList(_oldestWindowIndex, _currentWindowIndex - 1); }
@Test public void testAvailableWindows() { MetricSampleAggregator<String, IntegerEntity> aggregator = new MetricSampleAggregator<>(NUM_WINDOWS, WINDOW_MS, MIN_SAMPLES_PER_WINDOW, 0, _metricDef); assertTrue(aggregator.availableWindows().isEmpty()); CruiseControl...
@Override public NSImage fileIcon(final Local file, final Integer size) { NSImage icon = null; if(file.exists()) { icon = this.load(file.getAbsolute(), size); if(null == icon) { return this.cache(file.getName(), this.convert(file.getNam...
@Test public void testIconForPathFolder() throws Exception { final Path f = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); final NSImageIconCache cache = new NSImageIconCache(); NSImage icon = cache.fileIcon(f, 16); assertNotNull(icon); ...
@Override public InputStream getInputStream(final int columnIndex, final String type) throws SQLException { throw new SQLFeatureNotSupportedException("getInputStream"); }
@Test void assertGetInputStream() { LocalDataMergedResult actual = new LocalDataMergedResult(Collections.singletonList(new LocalDataQueryResultRow("value"))); assertThrows(SQLFeatureNotSupportedException.class, () -> actual.getInputStream(1, "Ascii")); }
public static void checkTypeMatch(SelTypes lhs, SelTypes rhs) { if (lhs != rhs) { throw new IllegalArgumentException( "Type mismatch, lhs type: " + lhs + ", rhs object type: " + rhs); } }
@Test public void testTypeMatch() { SelTypeUtil.checkTypeMatch(SelTypes.NULL, SelTypes.NULL); }
public static String buildUrl(boolean isHttps, String serverAddr, String... subPaths) { StringBuilder sb = new StringBuilder(); if (isHttps) { sb.append(HTTPS_PREFIX); } else { sb.append(HTTP_PREFIX); } sb.append(serverAddr); String pre = null; ...
@Test void testBuildHttpUrl2() { assertThrows(IllegalArgumentException.class, () -> { String targetUrl = HttpUtils.buildUrl(false, "127.0.0.1:8080", "//v1/api/test"); assertNotEquals(exceptUrl, targetUrl); }); }
@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 hasAGaugeForTotalCommitted() { final Gauge gauge = (Gauge) gauges.getMetrics().get("total.committed"); assertThat(gauge.getValue()) .isEqualTo(11L); }
@Override public ParDoFn create( PipelineOptions options, CloudObject cloudUserFn, @Nullable List<SideInputInfo> sideInputInfos, TupleTag<?> mainOutputTag, Map<TupleTag<?>, Integer> outputTupleTagsToReceiverIndices, DataflowExecutionContext<?> executionContext, DataflowOperat...
@Test public void testFactorySimultaneousUse() throws Exception { PipelineOptions options = PipelineOptionsFactory.create(); CounterSet counters = new CounterSet(); TestDoFn initialFn = new TestDoFn(Collections.<TupleTag<String>>emptyList()); CloudObject cloudObject = getCloudObject(initialFn); Pa...
public Chooser(K uniqueKey) { this(uniqueKey, new ArrayList<>()); }
@Test void testChooser() { //Test the correctness of Chooser, the weight of the final selected instance must be greater than 0 List<Instance> hosts = getInstanceList(); Instance target = getRandomInstance(hosts); assertTrue(hosts.contains(target) && target.getWeight() > 0); }
@Override protected String buildUndoSQL() { TableRecords afterImage = sqlUndoLog.getAfterImage(); List<Row> afterImageRows = afterImage.getRows(); if (CollectionUtils.isEmpty(afterImageRows)) { throw new ShouldNeverHappenException("Invalid UNDO LOG"); } return gen...
@Test public void buildUndoSQL() { String sql = executor.buildUndoSQL().toUpperCase(); Assertions.assertNotNull(sql); Assertions.assertTrue(sql.contains("DELETE")); Assertions.assertTrue(sql.contains("TABLE_NAME")); Assertions.assertTrue(sql.contains("ID")); }
public Connection getConnectionById(Long id) { Optional<Connection> con = connectionRepository.findById(id); if (con.isEmpty()) { throw new NotFoundException("Could not find connection with id: " + id); } return con.get(); }
@Test void connectionNotFound() { Optional<Connection> connectionOptional = Optional.empty(); when(connectionRepositoryMock.findById(anyLong())).thenReturn(connectionOptional); assertThrows(NotFoundException.class, () -> connectionServiceMock.getConnectionById(anyLong())); }
@Override public int getMajorJavaVersion() { JavaVersion version = JavaVersion.current(); JavaPluginExtension javaPluginExtension = project.getExtensions().findByType(JavaPluginExtension.class); if (javaPluginExtension != null) { version = javaPluginExtension.getTargetCompatibility(); } ...
@Test public void testGetMajorJavaVersion_jvm8() { Assume.assumeThat(JavaVersion.current(), CoreMatchers.is(JavaVersion.VERSION_1_8)); assertThat(gradleProjectProperties.getMajorJavaVersion()).isEqualTo(8); }
@Override public TYPE getType() { return Delta.TYPE.CHANGE; }
@Test void testGetType() { // given Chunk<String> chunk = new Chunk<>(1, EMPTY_LIST); Delta<String> delta = new ChangeDelta<>(chunk, chunk); // when Delta.TYPE type = delta.getType(); // then assertThat(type).isEqualTo(Delta.TYPE.CHANGE); }
private boolean ldapLogin(String username, String password) throws AuthenticationException { return ldapTemplate.authenticate("", "(" + filterPrefix + "=" + username + ")", password); }
@Test void testldapLogin() { try { Boolean result = (Boolean) ldapLogin.invoke(ldapAuthenticationProvider, adminUserName, defaultPassWord); assertTrue(result); } catch (IllegalAccessException e) { fail(); } catch (InvocationTargetException e) { ...
@Override public MapSettings setProperty(String key, String value) { return (MapSettings) super.setProperty(key, value); }
@Test public void setStringArrayWithNullValues() { Settings settings = new MapSettings(definitions); settings.setProperty("multi_values", new String[]{"A,B", null, "C,D"}); String[] array = settings.getStringArray("multi_values"); assertThat(array).isEqualTo(new String[]{"A,B", "", "C,D"}); }
@ShellMethod(key = "compactions showarchived", value = "Shows compaction details for specified time window") public String compactionsShowArchived( @ShellOption(value = {"--includeExtraMetadata"}, help = "Include extra metadata", defaultValue = "false") final boolean includeExtraMetadata, @Shell...
@Test public void testCompactionsShowArchived() throws IOException { generateCompactionInstances(); generateArchive(); Object result = shell.evaluate(() -> "compactions showarchived --startTs 001 --endTs 005"); // generate result Map<String, Integer> fileMap = new HashMap<>(); fileMap.put("...
public boolean shouldRestartTask(TaskStatus status) { return includeTasks && (!onlyFailed || status.state() == AbstractStatus.State.FAILED); }
@Test public void restartOnlyFailedTasks() { RestartRequest restartRequest = new RestartRequest(CONNECTOR_NAME, true, true); assertTrue(restartRequest.shouldRestartTask(createTaskStatus(AbstractStatus.State.FAILED))); assertFalse(restartRequest.shouldRestartTask(createTaskStatus(AbstractStat...
public static TableSchema toSchema(RowType rowType) { TableSchema.Builder builder = TableSchema.builder(); for (RowType.RowField field : rowType.getFields()) { builder.field(field.getName(), TypeConversions.fromLogicalToDataType(field.getType())); } return builder.build(); }
@Test public void testConvertFlinkSchemaWithPrimaryKeys() { Schema icebergSchema = new Schema( Lists.newArrayList( Types.NestedField.required(1, "int", Types.IntegerType.get()), Types.NestedField.required(2, "string", Types.StringType.get())), Sets.n...
public static void mergeMap(boolean decrypt, Map<String, Object> config) { merge(decrypt, config); }
@Test public void testMap_valueCastToBoolean() { Map<String, Object> testMap = new HashMap<>(); testMap.put("key", "${TEST.boolean: true}"); CentralizedManagement.mergeMap(true, testMap); Assert.assertTrue(testMap.get("key") instanceof Boolean); }
@Nullable static String channelKind(@Nullable Destination destination) { if (destination == null) return null; return isQueue(destination) ? "queue" : "topic"; }
@Test void channelKind_queueAndTopic_null() { assertThat(MessageParser.channelKind(null)).isNull(); }
@CheckForNull public String clientSecret() { return config.get(CONSUMER_SECRET).orElse(null); }
@Test public void return_client_secret() { settings.setProperty("sonar.auth.bitbucket.clientSecret.secured", "secret"); assertThat(underTest.clientSecret()).isEqualTo("secret"); }
@Override public double mean() { return mu; }
@Test public void testMean() { System.out.println("mean"); LogisticDistribution instance = new LogisticDistribution(2.0, 1.0); instance.rand(); assertEquals(2.0, instance.mean(), 1E-7); }
@Override public PayloadSerializer getSerializer(Schema schema, Map<String, Object> tableParams) { Class<? extends Message> protoClass = getClass(tableParams); inferAndVerifySchema(protoClass, schema); SimpleFunction<byte[], Row> toRowFn = ProtoMessageSchema.getProtoBytesToRowFn(protoClass); return Pa...
@Test public void serialize() throws Exception { byte[] bytes = provider .getSerializer( SHUFFLED_SCHEMA, ImmutableMap.of("protoClass", PayloadMessages.TestMessage.class.getName())) .serialize(ROW); PayloadMessages.TestMessage result = PayloadMes...
public boolean isTerminated() { if (getInternalResource().getStatus() != null) { final boolean podFailed = PodPhase.Failed.name().equals(getInternalResource().getStatus().getPhase()); final boolean containersFailed = getInternalResource().getStatus...
@Test void testIsTerminatedShouldReturnTrueWhenPodFailed() { final Pod pod = new PodBuilder().build(); pod.setStatus( new PodStatusBuilder() .withPhase(KubernetesPod.PodPhase.Failed.name()) .withMessage("Pod Node didn't have enough reso...
@Override public Collection<SQLToken> generateSQLTokens(final SelectStatementContext sqlStatementContext) { Collection<SQLToken> result = new LinkedHashSet<>(); ShardingSphereSchema schema = sqlStatementContext.getTablesContext().getSchemaName().map(schemas::get).orElseGet(() -> defaultSchema); ...
@Test void assertGenerateSQLTokens() { assertThat(generator.generateSQLTokens(buildSelectStatementContext()).size(), is(1)); }
public RemotingDesc parserRemotingServiceInfo(Object bean, String beanName, RemotingParser remotingParser) { if (remotingServiceMap.containsKey(bean)) { return remotingServiceMap.get(bean); } RemotingDesc remotingBeanDesc = remotingParser.getServiceDesc(bean, beanName); if (r...
@Test public void testParserRemotingServiceInfoFail() { SimpleBean simpleBean = new SimpleBean(); assertNull(remotingParser.parserRemotingServiceInfo(simpleBean, simpleBean.getClass().getName(), new SimpleRemotingParser())); }
public Optional<String> getNameByActiveVersion(final String path) { Matcher matcher = activeVersionPathPattern.matcher(path); return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty(); }
@Test void assertGetNameByActiveVersion() { Optional<String> actual = converter.getNameByActiveVersion("/metadata/foo_db/rules/foo/tables/foo_table/active_version"); assertTrue(actual.isPresent()); assertThat(actual.get(), is("foo_table")); }
public static HttpRequest toNettyRequest(RestRequest request) throws Exception { HttpMethod nettyMethod = HttpMethod.valueOf(request.getMethod()); URL url = new URL(request.getURI().toString()); String path = url.getFile(); // RFC 2616, section 5.1.2: // Note that the absolute path cannot be emp...
@Test public void testRestToNettyRequest() throws Exception { RestRequestBuilder restRequestBuilder = new RestRequestBuilder(new URI(ANY_URI)); restRequestBuilder.setMethod("POST"); restRequestBuilder.setEntity(ByteString.copyString(ANY_ENTITY, Charset.defaultCharset())); restRequestBuilder.setHeade...
public MetadataBlockType getType() { return _errCodeToExceptionMap.isEmpty() ? MetadataBlockType.EOS : MetadataBlockType.ERROR; }
@Test public void v2EosWithoutStatsIsReadInV1AsEosWithoutStats() throws IOException { ByteBuffer stats = ByteBuffer.wrap(new byte[]{0, 0, 0, 0}); MetadataBlock metadataBlock = new MetadataBlock(Lists.newArrayList(stats)); byte[] bytes = metadataBlock.toBytes(); // This is how V1 blocks were de...
@Override public void process(Exchange exchange) throws Exception { JsonElement json = getBodyAsJsonElement(exchange); String operation = exchange.getIn().getHeader(CouchDbConstants.HEADER_METHOD, String.class); if (ObjectHelper.isEmpty(operation)) { Response<DocumentResult> save...
@Test void testBodyMandatory() throws Exception { when(msg.getMandatoryBody()).thenThrow(InvalidPayloadException.class); assertThrows(InvalidPayloadException.class, () -> { producer.process(exchange); }); }
@Override public TopicAssignment place( PlacementSpec placement, ClusterDescriber cluster ) throws InvalidReplicationFactorException { RackList rackList = new RackList(random, cluster.usableBrokers()); throwInvalidReplicationFactorIfNonPositive(placement.numReplicas()); t...
@Test public void testRackListNotEnoughBrokers() { MockRandom random = new MockRandom(); RackList rackList = new RackList(random, Arrays.asList( new UsableBroker(11, Optional.of("1"), false), new UsableBroker(10, Optional.of("1"), false)).iterator()); assertEq...
public static <K, V> MutableMultimap<K, V> groupBy( Iterable<V> iterable, Function<? super V, ? extends K> function) { return FJIterate.groupBy(iterable, function, FJIterate.DEFAULT_MIN_FORK_SIZE, FJIterate.FORK_JOIN_POOL); }
@Test public void groupBy() { FastList<String> source = FastList.newListWith("Ted", "Sally", "Mary", "Bob", "Sara"); Multimap<Character, String> result1 = FJIterate.groupBy(source, StringFunctions.firstLetter(), 1); Multimap<Character, String> result2 = FJIterate.groupBy(Collections.sync...
void processJob() { boolean success = false; UUID jobId = JobMetadata.getJobId(); monitor.debug(() -> format("Begin processing jobId: %s", jobId), EventCode.WORKER_JOB_STARTED); try { markJobStarted(jobId); hooks.jobStarted(jobId); PortabilityJob job = store.findJob(jobId); Job...
@Test public void processJobGetsErrorsEvenWhenCopyThrows() throws CopyException, IOException { Mockito.doThrow(new CopyException("error", new Exception())).when(copier) .copy(importAuthData, exportAuthData, jobId, Optional.of(exportInfo)); processor.processJob(); Mockito.verify(copier).getErrors(j...
@Override public DescriptiveUrl toUrl(final Host bookmark) { try { // Run password flow final TokenResponse response; try { final Host target = new Host(new DAVSSLProtocol(), "oauth.freenet.de"); final X509TrustManager trust = new KeychainX...
@Test public void testToUrl() { final FreenetAuthenticatedUrlProvider provider = new FreenetAuthenticatedUrlProvider(new DefaultHostPasswordStore() { @Override public String getPassword(final String serviceName, final String accountName) throws LocalAccessDeniedException { ...
protected abstract String getGroupId(T request);
@Test public void testManyNodes() { Node node1 = Mockito.mock(Node.class); Mockito.when(node1.getGroupId()).thenReturn("test"); Mockito.when(node1.getNodeId()).thenReturn(new NodeId("test", new PeerId("localhost", 8081))); NodeOptions opts = new NodeOptions(); Mockito.when(no...
@Override public PTransformOverrideFactory.PTransformReplacement< PCollection<? extends InputT>, PCollection<OutputT>> getReplacementTransform( AppliedPTransform< PCollection<? extends InputT>, PCollection<OutputT>, SingleOutput<InputT, O...
@Test public void getReplacementTransformGetSideInputs() { PCollectionView<Long> sideLong = pipeline .apply("LongSideInputVals", Create.of(-1L, -2L, -4L)) .apply("SideLongView", Sum.longsGlobally().asSingletonView()); PCollectionView<List<String>> sideStrings = pipeline...