focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public ByteBuf setLong(int index, long value) { throw new ReadOnlyBufferException(); }
@Test public void shouldRejectSetLong() { assertThrows(UnsupportedOperationException.class, new Executable() { @Override public void execute() { unmodifiableBuffer(EMPTY_BUFFER).setLong(0, 0); } }); }
@Benchmark @Threads(512) public void testTinyBundleHarnessStateSampler(HarnessStateTracker state, Blackhole bh) throws Exception { state.tracker.start("processBundleId"); for (int i = 0; i < 3; ) { state.state1.activate(); state.state2.activate(); state.state3.activate(); // tr...
@Test public void testTinyBundleHarnessStateSampler() throws Exception { HarnessStateSampler state = new HarnessStateSampler(); HarnessStateTracker threadState = new HarnessStateTracker(); threadState.setup(state); new ExecutionStateSamplerBenchmark().testTinyBundleHarnessStateSampler(threadState, bla...
@WithSpan @Override public SearchResponse apply(SearchResponse searchResponse) { final List<ResultMessageSummary> summaries = searchResponse.messages().stream() .map(summary -> { // Do not touch the message if the field does not exist. if (!summary...
@Test public void testDecorator() throws Exception { final DecoratorImpl decorator = DecoratorImpl.create("id", SyslogSeverityMapperDecorator.class.getCanonicalName(), ImmutableMap.of("source_field", "level", "target_field", "severity"), Optional.empty(), ...
public static void load(String originalName, ClassLoader loader) { String mangledPackagePrefix = calculateMangledPackagePrefix(); String name = mangledPackagePrefix + originalName; List<Throwable> suppressed = new ArrayList<Throwable>(); try { // first try to load from java.l...
@Test @EnabledOnOs(LINUX) @EnabledIf("is_x86_64") void testMultipleResourcesWithSameContentInTheClassLoader() throws MalformedURLException { URL url1 = new File("src/test/data/NativeLibraryLoader/1").toURI().toURL(); URL url2 = new File("src/test/data/NativeLibraryLoader/2").toURI().toURL();...
@SuppressWarnings("unchecked") public static synchronized <T extends Cache> T createSerializingCache(String name, Class keyClass, Class valueClass) { T cache = (T) caches.get(name); if (cache != null) { return cache; } final Cache<String, String> delegate = (Cache<String...
@Test public void testSerializingCacheCreation() throws Exception { // Setup test fixture. // Execute system under test. final Cache result = CacheFactory.createSerializingCache("unittest-serializingcache-creation", String.class, String.class); // Verify results. assert...
@Override public JSONObject getIdentities() { return new JSONObject(); }
@Test public void getIdentities() { Assert.assertEquals(0, mSensorsAPI.getIdentities().length()); }
public void updateRules(Map<String, List<R>> rulesMap) { originalRules = rulesMap; Map<Pattern, List<R>> regexRules = new HashMap<>(); Map<String, List<R>> simpleRules = new HashMap<>(); for (Map.Entry<String, List<R>> entry : rulesMap.entrySet()) { String resource = entry.ge...
@Test public void testUpdateRules() throws Exception { // Setup final Map<String, List<FlowRule>> rulesMap = generateFlowRules(true); // Run the test ruleManager.updateRules(rulesMap); // Verify the results assertEquals(ruleManager.getRules().size(), 2); Fie...
public List<TerminalNode> addRule(RuleImpl rule, InternalRuleBase kBase, Collection<InternalWorkingMemory> workingMemories) throws InvalidPatternException { // the list of terminal nodes final List<TerminalNode> termNodes = new ArrayList<>(); // transform rule and gets the array of subrules ...
@Test public void testAddRuleWithPatterns() { final RuleImpl rule = new RuleImpl( "only patterns" ); final Pattern c1 = new Pattern( 0, new ClassObjectType( String.class ) ); final Pattern c2 = new Pattern( 1, new ClassObjectTyp...
@Description("sine") @ScalarFunction @SqlType(StandardTypes.DOUBLE) public static double sin(@SqlType(StandardTypes.DOUBLE) double num) { return Math.sin(num); }
@Test public void testSin() { for (double doubleValue : DOUBLE_VALUES) { assertFunction("sin(" + doubleValue + ")", DOUBLE, Math.sin(doubleValue)); assertFunction("sin(REAL '" + (float) doubleValue + "')", DOUBLE, Math.sin((float) doubleValue)); } assertFunction("...
public static Date parseTM(TimeZone tz, String s, DatePrecision precision) { return parseTM(tz, s, false, precision); }
@Test public void testParseTM() { DatePrecision precision = new DatePrecision(); assertEquals(0, DateUtils.parseTM(tz, "020000.000", precision).getTime()); assertEquals(Calendar.MILLISECOND, precision.lastField); }
@Override public void configureLevel() { add(platform, properties); addExtraRootComponents(); Version apiVersion = MetadataLoader.loadApiVersion(System2.INSTANCE); Version sqVersion = MetadataLoader.loadSQVersion(System2.INSTANCE); SonarEdition edition = MetadataLoader.loadEdition(System2.INSTANCE...
@Test public void no_missing_dependencies_between_components() { underTest.configureLevel(); assertThat(underTest.getContainer().context().getBeanDefinitionNames()).isNotEmpty(); }
public static String getMultistageReverseProxyIp(String ip) { // 多级反向代理检测 if (ip != null && StrUtil.indexOf(ip, ',') > 0) { final List<String> ips = StrUtil.splitTrim(ip, ','); for (final String subIp : ips) { if (false == isUnknown(subIp)) { ip = subIp; break; } } } return ip; }
@Test public void issueI64P9JTest() { // 获取结果应该去掉空格 final String ips = "unknown, 12.34.56.78, 23.45.67.89"; final String ip = NetUtil.getMultistageReverseProxyIp(ips); assertEquals("12.34.56.78", ip); }
public static SerdeFeatures of(final SerdeFeature... features) { return new SerdeFeatures(ImmutableSet.copyOf(features)); }
@Test public void shouldDeserializeFromValue() throws Exception { // Given: final String json = "[\"UNWRAP_SINGLES\"]"; // When: final SerdeFeatures result = MAPPER.readValue(json, SerdeFeatures.class); // Then: assertThat(result, is(SerdeFeatures.of(UNWRAP_SINGLES))); }
P next(final Aeron aeron) { final int cursor = nextCursor(); final String endpoint = endpoints[cursor]; final ChannelUri channelUri = ChannelUri.parse(channelTemplate); channelUri.put(ENDPOINT_PARAM_NAME, endpoint); final String channel = channelUri.toString(); Clos...
@Test void shouldUseAllPublicationsInListWhenGettingNextPublication() { publicationGroup.next(mockAeron); publicationGroup.next(mockAeron); publicationGroup.next(mockAeron); verify(mockAeron).addExclusivePublication("aeron:udp?endpoint=localhost:1001|term-length=64k", streamId);...
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor( DoFn<InputT, OutputT> fn) { return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn); }
@Test public void testBundleFinalizer() { class BundleFinalizerDoFn extends DoFn<String, String> { @ProcessElement public void processElement(BundleFinalizer bundleFinalizer) { bundleFinalizer.afterBundleCommit(Instant.ofEpochSecond(42L), null); } } BundleFinalizer mockBundleFin...
public static GlobalConfig readConfig() throws IOException, InvalidGlobalConfigException { return readConfig(getConfigDir()); }
@Test public void testReadConfig() throws IOException, InvalidGlobalConfigException { String json = "{\"disableUpdateCheck\":true, \"registryMirrors\":[" + "{ \"registry\": \"registry-1.docker.io\"," + " \"mirrors\": [\"mirror.gcr.io\", \"localhost:5000\"] }," + "{ \"r...
public boolean containsInsertColumns() { InsertStatement insertStatement = getSqlStatement(); return !insertStatement.getColumns().isEmpty() || insertStatement.getSetAssignment().isPresent(); }
@Test void assertContainsInsertColumnsWithSetAssignmentForMySQL() { MySQLInsertStatement insertStatement = new MySQLInsertStatement(); insertStatement.setSetAssignment(new SetAssignmentSegment(0, 0, Collections.emptyList())); insertStatement.setTable(new SimpleTableSegment(new TableNameSegme...
public ProviderBuilder payload(Integer payload) { this.payload = payload; return getThis(); }
@Test void payload() { ProviderBuilder builder = ProviderBuilder.newBuilder(); builder.payload(40); Assertions.assertEquals(40, builder.build().getPayload()); }
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testIncrementalFromSnapshotTimestampWithEmptyTable() { ScanContext scanContextWithInvalidSnapshotId = ScanContext.builder() .startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_SNAPSHOT_TIMESTAMP) .startSnapshotTimestamp(1L) .build(); Conti...
public static TieredStorageTopicId convertId(IntermediateDataSetID intermediateDataSetID) { return new TieredStorageTopicId(intermediateDataSetID.getBytes()); }
@Test void testConvertSubpartitionId() { int subpartitionId = 2; TieredStorageSubpartitionId tieredStorageSubpartitionId = TieredStorageIdMappingUtils.convertId(subpartitionId); int convertedSubpartitionId = TieredStorageIdMappingUtils.convertId(tieredStorageS...
@GET @Path("/jwks.json") @Produces(MediaType.APPLICATION_JSON) public Response jwks() { var key = keyStore.signingKey().toPublicJWK(); var cacheControl = new CacheControl(); cacheControl.setMaxAge((int) Duration.ofMinutes(30).getSeconds()); return Response.ok(new JWKSet(List.of(key))).cacheContr...
@Test void jwks() throws ParseException { var key = ECKey.parse( """ {"kty":"EC","use":"sig","crv":"P-256","x":"yi3EF1QZS1EiAfAAfjoDyZkRnf59H49gUyklmfwKwSY","y":"Y_SGRGjwacDuT8kbcaX1Igyq8aRfJFNBMKLb2yr0x18"} """); var keyStore = mock(KeyStore.class); when(keyStore.signingK...
@Transactional(readOnly = true) public void existsGeneralSignUpUser(String phone) { readGeneralSignUpUser(phone); }
@DisplayName("Oauth 유저의 번호로 비밀번호 찾기 인증요청이 올 경우 UserErrorException을 발생시킨다.") @Test void findPasswordVerificationIfUserOauth() { // given String phone = "010-1234-5678"; User user = UserFixture.OAUTH_USER.toUser(); given(userService.readUserByPhone(phone)).willReturn(Optional.of(us...
@Override public void callExtensionPoint( LogChannelInterface log, Object object ) throws KettleException { AbstractMeta meta; if ( object instanceof Trans ) { meta = ( (Trans) object ).getTransMeta(); } else if ( object instanceof JobExecutionExtension ) { meta = ( (JobExecutionExtension) objec...
@Test public void testCallExtensionPointWithTrans() throws Exception { MetastoreLocatorOsgi mockMetastoreLocator = new MetastoreLocatorImpl(); LogChannelInterface logChannelInterface = mock( LogChannelInterface.class ); TransMeta mockTransMeta = mock( TransMeta.class ); Trans mockTrans = mock( Trans.c...
void commitClusterState(ClusterStateChange newState, Address initiator, UUID txnId) { commitClusterState(newState, initiator, txnId, false); }
@Test(expected = IllegalArgumentException.class) public void test_changeLocalClusterState_IN_TRANSITION() throws Exception { clusterStateManager.commitClusterState(ClusterStateChange.from(IN_TRANSITION), newAddress(), TXN); }
@Override public void purgeMappings(Type type, DeviceId deviceId) { store.purgeMappingEntry(type, deviceId); }
@Test public void purgeMappings() { addMapping(MAP_DATABASE, 1); addMapping(MAP_DATABASE, 2); addMapping(MAP_DATABASE, 3); assertEquals("3 mappings should exist", 3, mappingCount(MAP_DATABASE)); adminService.purgeMappings(MAP_DATABASE, LISP_DID); assertEquals("0 map...
public static boolean isValidApi(ApiDefinition apiDefinition) { return apiDefinition != null && StringUtil.isNotBlank(apiDefinition.getApiName()) && apiDefinition.getPredicateItems() != null; }
@Test public void testIsValidApi() { ApiDefinition bad1 = new ApiDefinition(); ApiDefinition bad2 = new ApiDefinition("foo"); ApiDefinition good1 = new ApiDefinition("foo") .setPredicateItems(Collections.<ApiPredicateItem>singleton(new ApiPathPredicateItem() .setP...
@Override public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo, List<String> partNames, boolean areAllPartsFound) throws MetaException { checkStatisticsList(colStatsWithSourceInfo); ColumnStatisticsObj statsObj = null; String colType = null; String colName...
@Test public void testAggregateMultiStatsWhenAllAvailable() throws MetaException { List<String> partitions = Arrays.asList("part1", "part2", "part3"); ColumnStatisticsData data1 = new ColStatsBuilder<>(String.class).numNulls(1).numDVs(3).avgColLen(20.0 / 3).maxColLen(13) .hll(S_1, S_2, S_3).build(); ...
public static Read read() { return new AutoValue_HCatalogIO_Read.Builder() .setDatabase(DEFAULT_DATABASE) .setPartitionCols(new ArrayList<>()) .build(); }
@Test public void testReadTransformCanBeSerializedMultipleTimes() throws Exception { ReaderContext context = getReaderContext(getConfigPropertiesAsMap(service.getHiveConf())); HCatalogIO.Read spec = HCatalogIO.read() .withConfigProperties(getConfigPropertiesAsMap(service.getHiveConf())) ...
public static boolean isAppSecured(ApplicationId appId) { SecurityAdminService service = getSecurityService(); if (service != null) { if (!service.isSecured(appId)) { System.out.println("\n*******************************"); System.out.println(" SM-ONOS AP...
@Test public void testIsAppSecured() { assertFalse(service.isSecured(appId)); }
public <T> HttpRestResult<T> getLarge(String url, Header header, Query query, Object body, Type responseType) throws Exception { return execute(url, HttpMethod.GET_LARGE, new RequestHttpEntity(header, query, body), responseType); }
@Test void testGetLarge() throws Exception { when(requestClient.execute(any(), eq("GET-LARGE"), any())).thenReturn(mockResponse); when(mockResponse.getStatusCode()).thenReturn(200); when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes())); HttpRestResult<S...
@Override public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) { ApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id); if (errorLog == null) { throw exception(API_ERROR_LOG_NOT_FOUND); } if (!ApiErrorLogProcessStatusEnum.INIT.getSt...
@Test public void testUpdateApiErrorLogProcess_notFound() { // 准备参数 Long id = randomLongId(); Integer processStatus = randomEle(ApiErrorLogProcessStatusEnum.values()).getStatus(); Long processUserId = randomLongId(); // 调用,并断言异常 assertServiceException(() -> ...
@VisibleForTesting static SingleSegmentAssignment getNextSingleSegmentAssignment(Map<String, String> currentInstanceStateMap, Map<String, String> targetInstanceStateMap, int minAvailableReplicas, boolean lowDiskMode, Map<String, Integer> numSegmentsToOffloadMap, Map<Pair<Set<String>, Set<String>>, Set<Str...
@Test public void testTwoMinAvailableReplicasWithLowDiskMode() { // With 3 common instances, first assignment should keep the common instances and remove the not common instance Map<String, String> currentInstanceStateMap = SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host2", "ho...
public void scheduleHeartbeat() { startedHeartbeat = executorService.schedule(heartbeatTask, DEFAULT_HEARTBEAT_PERIOD, TimeUnit.SECONDS); }
@Test public void flush_exceptionIsPropagated() throws IOException { when(servletResponse.getOutputStream()).thenThrow(new IOException("mock exception")); when(executorService.schedule(any(HeartbeatTask.class), anyLong(), any(TimeUnit.class))).thenReturn(task); underTest.scheduleHeartbeat(); assertTh...
int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } }
@Test void getStrengthShouldReturnCurrentStrengthIfCurrentDurationCloserToGoal() { // given // when int actual = bcCryptWorkFactorService.getStrength(960, 1021, 5); // then assertThat(actual).isEqualTo(5); }
public void byteOrder(final ByteOrder byteOrder) { if (null == byteOrder) { throw new IllegalArgumentException("byteOrder cannot be null"); } this.byteOrder = byteOrder; }
@Test void shouldThrowExceptionWhenCannotReadString() throws Throwable { final UnsafeBuffer buffer = toUnsafeBuffer((out) -> out.writeShort(42)); final DirectBufferDataInput dataInput = new DirectBufferDataInput(buffer); dataInput.byteOrder(byteOrder()); assertThrows(EOFExcepti...
public JobRunrConfiguration useBackgroundJobServer() { return useBackgroundJobServerIf(true); }
@Test void backgroundJobServerThrowsExceptionIfNoStorageProviderIsAvailable() { assertThatThrownBy(() -> JobRunr.configure() .useBackgroundJobServer() ) .isInstanceOf(IllegalArgumentException.class) .hasMessage("A StorageProvider is required to use a B...
public static SerializableFunction<GenericRecord, Row> getGenericRecordToRowFunction( @Nullable Schema schema) { return new GenericRecordToRowFn(schema); }
@Test public void testGenericRecordToRowFunction() { SerializableUtils.ensureSerializable(AvroUtils.getGenericRecordToRowFunction(Schema.of())); SerializableUtils.ensureSerializable(AvroUtils.getGenericRecordToRowFunction(null)); }
@Override public double readDouble(@Nonnull String fieldName) throws IOException { FieldDefinition fd = cd.getField(fieldName); if (fd == null) { return 0d; } switch (fd.getType()) { case DOUBLE: return super.readDouble(fieldName); ...
@Test(expected = IncompatibleClassChangeError.class) public void testReadDouble_IncompatibleClass() throws Exception { reader.readDouble("string"); }
public static String getFileName(String compressedName) { compressedName = compressedName.toLowerCase(); boolean hasFileName = compressedName.contains("."); if (hasFileName && (isZip(compressedName) || isTar(compressedName) || isRar(compressedName) || is7zip(compr...
@Test public void getFileNameTest() throws Exception { assertEquals("test", CompressedHelper.getFileName("test.zip")); assertEquals("test", CompressedHelper.getFileName("test.rar")); assertEquals("test", CompressedHelper.getFileName("test.tar")); assertEquals("test", CompressedHelper.getFileName("test...
public static void refreshModuleConnectionCount(Map<String, Integer> connectionCnt) { // refresh all existed module connection cnt and add new module connection count connectionCnt.forEach((module, cnt) -> { AtomicInteger integer = moduleConnectionCnt.get(module); // if exists ...
@Test void testRefreshModuleConnectionCount() { // refresh Map<String, Integer> map = new HashMap<>(); map.put("naming", 10); MetricsMonitor.refreshModuleConnectionCount(map); assertEquals(1, MetricsMonitor.getModuleConnectionCnt().size()); assertEquals(10, MetricsMon...
public final <T extends ChannelHandler> T removeIfExists(String name) { return removeIfExists(context(name)); }
@Test public void testRemoveIfExists() { DefaultChannelPipeline pipeline = new DefaultChannelPipeline(new LocalChannel()); ChannelHandler handler1 = newHandler(); ChannelHandler handler2 = newHandler(); ChannelHandler handler3 = newHandler(); pipeline.addLast("handler1", ha...
static Counter getServicesCounter() { return SERVICES_COUNTER; }
@Test public void testGetServicesCounter() { assertNotNull("getServicesCounter", MonitoringProxy.getServicesCounter()); }
@Override public Properties info(RedisClusterNode node) { Map<String, String> info = execute(node, RedisCommands.INFO_ALL); Properties result = new Properties(); for (Entry<String, String> entry : info.entrySet()) { result.setProperty(entry.getKey(), entry.getValue()); } ...
@Test public void testInfo() { RedisClusterNode master = getFirstMaster(); Properties info = connection.info(master); assertThat(info.size()).isGreaterThan(10); }
public static Builder route() { return new RouterFunctionBuilder(); }
@Test void and() { HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build(); RouterFunction<ServerResponse> routerFunction1 = request -> Mono.empty(); RouterFunction<ServerResponse> routerFunction2 = request -> Mono.just(handlerFunction); RouterFunction<ServerResponse> result =...
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) { return new DateTime(dateStr, dateFormat); }
@Test public void parseTest5() { // 测试时间解析 //noinspection ConstantConditions String time = DateUtil.parse("22:12:12").toString(DatePattern.NORM_TIME_FORMAT); assertEquals("22:12:12", time); //noinspection ConstantConditions time = DateUtil.parse("2:12:12").toString(DatePattern.NORM_TIME_FORMAT); assertEq...
public static void updateTmpDirectoriesInConfiguration( Configuration configuration, @Nullable String defaultDirs) { if (configuration.contains(CoreOptions.TMP_DIRS)) { LOG.info( "Overriding Flink's temporary file directories with those " +...
@Test void testUpdateTmpDirectoriesInConfiguration() { Configuration config = new Configuration(); // test that default value is taken BootstrapTools.updateTmpDirectoriesInConfiguration(config, "default/directory/path"); assertThat(config.get(CoreOptions.TMP_DIRS)).isEqualTo("defaul...
@Override public synchronized Optional<ListenableFuture<V>> schedule( Checkable<K, V> target, K context) { if (checksInProgress.containsKey(target)) { return Optional.empty(); } final LastCheckResult<V> result = completedChecks.get(target); if (result != null) { final long msSinceLa...
@Test(timeout=60000) public void testContextIsPassed() throws Exception { final NoOpCheckable target1 = new NoOpCheckable(); final FakeTimer timer = new FakeTimer(); ThrottledAsyncChecker<Boolean, Boolean> checker = new ThrottledAsyncChecker<>(timer, MIN_ERROR_CHECK_GAP, 0, getExecutor...
@Override public void initializeIfNeeded() { if (state() == State.CREATED) { StateManagerUtil.registerStateStores(log, logPrefix, topology, stateMgr, stateDirectory, processorContext); // with and without EOS we would check for checkpointing at each commit during running, ...
@Test public void shouldThrowLockExceptionIfFailedToLockStateDirectory() throws IOException { stateDirectory = mock(StateDirectory.class); when(stateDirectory.lock(taskId)).thenReturn(false); when(stateManager.taskType()).thenReturn(TaskType.STANDBY); task = createStandbyTask(); ...
@SuppressWarnings("serial") public List<String> getPrimaryKeyOnlyName() { List<String> list = new ArrayList<>(); for (Entry<String, ColumnMeta> entry : getPrimaryKeyMap().entrySet()) { list.add(entry.getKey()); } return list; }
@Test public void testGetPrimaryKeyOnlyName() { List<String> pksName = tableMeta.getPrimaryKeyOnlyName(); assertEquals(2, pksName.size()); assertTrue(pksName.contains("col1")); assertTrue(pksName.contains("col2")); }
abstract void execute(Admin admin, Namespace ns, PrintStream out) throws Exception;
@Test public void testFindHangingLookupTopicPartitionsForBroker() throws Exception { int brokerId = 5; String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "find-hanging", "--broker-id", String.valueOf(brokerId) };...
public long getLastAccessTime() { return lastAccessTime; }
@Test public void testConstructorSetsLastAccessTime() { long lastAccessTime = iterator.getLastAccessTime(); assertThat(lastAccessTime).isGreaterThan(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1)); assertThat(lastAccessTime).isLessThanOrEqualTo(System.currentTimeMillis()); }
public static void setOffloadDriverMetadata(LedgerInfo.Builder infoBuilder, String driverName, Map<String, String> offloadDriverMetadata) { infoBuilder.getOffloadContextBuilder() .getDriverMetadataBuilder...
@Test void testOffloadMetadataShouldClearBeforeSet() { MLDataFormats.ManagedLedgerInfo.LedgerInfo.Builder builder = MLDataFormats.ManagedLedgerInfo.LedgerInfo.newBuilder(); builder.setLedgerId(1L); Map<String, String> map = new HashMap<>(); map.put("key1", "value1");...
public CompressionProvider getCompressionProvider() { return compressionProvider; }
@Test public void getCompressionProvider() { CompressionProvider provider = outStream.getCompressionProvider(); assertEquals( provider.getName(), PROVIDER_NAME ); }
@Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { List<Header> warnings = Arrays.stream(response.getHeaders("Warning")).filter(header -> !this.isDeprecationMessage(header.getValue())).collect(Collectors.toList()); response.remov...
@Test public void testInterceptorMultipleHeaderFilteredWarning() throws IOException, HttpException { ElasticsearchFilterDeprecationWarningsInterceptor interceptor = new ElasticsearchFilterDeprecationWarningsInterceptor(); HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new Protoco...
@Override @SuppressWarnings("rawtypes") public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String,...
@Test public void reportsGaugeValues() throws Exception { final Gauge<Integer> gauge = () -> 1; reporter.report(map("gauge", gauge), map(), map(), map(), map()); assertThat(consoleOutput()) .isEqualTo(lines( ...
public <InputT, OutputT> DoFn<InputT, OutputT> get() throws Exception { Thread currentThread = Thread.currentThread(); return (DoFn<InputT, OutputT>) outstanding.get(currentThread); }
@Test public void setupOnGet() throws Exception { TestFn obtained = (TestFn) mgr.get(); assertThat(obtained, not(theInstance(fn))); assertThat(obtained.setupCalled, is(true)); assertThat(obtained.teardownCalled, is(false)); }
public static Locale localeFromString(String s) { if (!s.contains(LOBAR)) { return new Locale(s); } String[] items = s.split(LOBAR); return new Locale(items[0], items[1]); }
@Test public void localeFromStringFrCA() { title("localeFromStringFrCA"); locale = LionUtils.localeFromString("fr_CA"); checkLanguageCountry(locale, "fr", "CA"); }
public boolean isEmpty() { return messagesProcessed == 0 && errorsOccurred == 0; }
@Test void testNotEmpty() { assertThat(new StatsPersistMsg(1, 0, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID).isEmpty()).isFalse(); assertThat(new StatsPersistMsg(0, 1, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID).isEmpty()).isFalse(); assertThat(new StatsPersistMsg(1, 1, TenantId.SYS_...
public boolean isRegisteredUser(@Nonnull final JID user, final boolean checkRemoteDomains) { if (xmppServer.isLocal(user)) { try { getUser(user.getNode()); return true; } catch (final UserNotFoundException e) { return false; ...
@Test public void isRegisteredUserFalseWillReturnFalseForLocalNonUsers() { final boolean result = userManager.isRegisteredUser(new JID("unknown-user", Fixtures.XMPP_DOMAIN, null), false); assertThat(result, is(false)); }
@Override public String toString() { return MoreObjects.toStringHelper("Load").add("rate", rate()) .add("latest", latest()).toString(); }
@Test public void testToString() { DefaultLoad load = new DefaultLoad(20, 10); String s = load.toString(); assertThat(s, containsString("Load{rate=1, latest=20}")); }
@Override public PageResult<SocialUserDO> getSocialUserPage(SocialUserPageReqVO pageReqVO) { return socialUserMapper.selectPage(pageReqVO); }
@Test public void testGetSocialUserPage() { // mock 数据 SocialUserDO dbSocialUser = randomPojo(SocialUserDO.class, o -> { // 等会查询到 o.setType(SocialTypeEnum.GITEE.getType()); o.setNickname("芋艿"); o.setOpenid("yudaoyuanma"); o.setCreateTime(buildTime(2020...
public static BaseDataCache getInstance() { return INSTANCE; }
@Test public void testGetInstance() { BaseDataCache baseDataCache = BaseDataCache.getInstance(); assertNotNull(baseDataCache); }
@Benchmark @Threads(16) // Use several threads since we expect contention during bundle processing. public void testStateWithoutCaching(StatefulTransform statefulTransform) throws Exception { testState(statefulTransform, statefulTransform.nonCachingStateRequestHandler); }
@Test public void testStateWithoutCaching() throws Exception { StatefulTransform transform = new StatefulTransform(); transform.elementsEmbedding = elementsEmbedding; new ProcessBundleBenchmark().testStateWithoutCaching(transform); transform.tearDown(); }
public void shiftOffsetsBy(final Consumer<byte[], byte[]> client, final Set<TopicPartition> inputTopicPartitions, final long shiftBy) { final Map<TopicPartition, Long> endOffsets = client.endOffsets(inputTopicPartitions); final Map<TopicParti...
@Test public void testShiftOffsetByWhenAfterEndOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 3L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOff...
public static String getMaskedStatement(final String query) { try { final ParseTree tree = DefaultKsqlParser.getParseTree(query); return new Visitor().visit(tree); } catch (final Exception | StackOverflowError e) { return fallbackMasking(query); } }
@Test public void shouldMaskValidCreateConnectorWithComment() { final String query = "--this is a comment. \n" + "CREATE SOURCE CONNECTOR `test-connector` WITH (" + " \"connector.class\" = 'PostgresSource', \n" + " 'connection.url' = 'jdbc:postgresql://localhost:5432/my.db',\n" ...
@Override public String toString() { String simpleName = getClass().getSimpleName(); if (getClass().getEnclosingClass() != null) { simpleName = getClass().getEnclosingClass().getSimpleName() + "." + simpleName; } if (subTriggers == null || subTriggers.isEmpty()) { return simpleName; } ...
@Test public void testTriggerToString() throws Exception { assertEquals( "AfterWatermark.pastEndOfWindow()", AfterWatermarkStateMachine.pastEndOfWindow().toString()); assertEquals( "Repeatedly.forever(AfterWatermark.pastEndOfWindow())", RepeatedlyStateMachine.forever(AfterWater...
public void addEntry( String filename, String extension ) throws IOException { // Default no-op behavior }
@Test public void testAddEntry() throws IOException { CompressionProvider provider = outStream.getCompressionProvider(); ByteArrayOutputStream out = new ByteArrayOutputStream(); outStream = new DummyCompressionOS( out, provider ); outStream.addEntry( null, null ); }
public static <X extends Throwable> void isNull(Object object, Supplier<X> errorSupplier) throws X { if (null != object) { throw errorSupplier.get(); } }
@Test public void isNullTest() { String a = null; cn.hutool.core.lang.Assert.isNull(a); }
public static void main(String[] args) { /* Initialising the printer queue with jobs */ printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A4, 5, false, false)); printerQueue.addPrinterItem(new PrinterItem(PaperSizes.A3, 2, false, false)); printerQueue.addPrinterItem(new PrinterItem(PaperS...
@Test void executesWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public static Optional<String> getTableNameByRowPath(final String rowPath) { Pattern pattern = Pattern.compile(getShardingSphereDataNodePath() + "/([\\w\\-]+)/schemas/([\\w\\-]+)/tables" + "/([\\w\\-]+)?", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(rowPath); return matcher.find...
@Test void assertGetTableNameByRowPathHappyPath() { assertThat(ShardingSphereDataNode.getTableNameByRowPath("/statistics/databases/db_name/schemas/db_schema/tables/tbl_name"), is(Optional.of("tbl_name"))); }
public static <T> T[] replaceFirst(T[] src, T oldValue, T[] newValues) { int index = indexOf(src, oldValue); if (index == -1) { return src; } T[] dst = (T[]) Array.newInstance(src.getClass().getComponentType(), src.length - 1 + newValues.length); // copy the first p...
@Test public void replace_whenNewValuesEmpty() { Integer[] result = replaceFirst(new Integer[]{1, 2, 10, 3, 4}, 10, new Integer[]{}); System.out.println(Arrays.toString(result)); assertArrayEquals(new Integer[]{1, 2, 3, 4}, result); }
public AstNode rewrite(final AstNode node, final C context) { return rewriter.process(node, context); }
@Test public void shouldRewritePartitionBy() { // Given: final PartitionBy partitionBy = new PartitionBy( location, ImmutableList.of(expression) ); when(expressionRewriter.apply(expression, context)).thenReturn(rewrittenExpression); // When: final AstNode rewritten = rewriter....
public static SetAssignmentSegment bind(final SetAssignmentSegment segment, final SQLStatementBinderContext binderContext, final Map<String, TableSegmentBinderContext> tableBinderContexts, final Map<String, TableSegmentBinderContext> outerTableBinderContexts) { return...
@Test void assertBindAssignmentSegment() { Collection<ColumnAssignmentSegment> assignments = new LinkedList<>(); ColumnSegment boundOrderIdColumn = new ColumnSegment(0, 0, new IdentifierValue("order_id")); boundOrderIdColumn.setColumnBoundInfo(new ColumnSegmentBoundInfo(new IdentifierValue(D...
@Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { MainSettingsActivity mainSettingsActivity = (MainSettingsActivity) getActivity(); if (mainSettingsActivity == null) return super.onOptionsItemSelected(item); if (item.getItemId() == R.id.add_user_word) { createEmptyItemForAdd()...
@Test public void testTwiceAddNewWordFromMenuNotAtEmptyState() { // adding a few words to the dictionary UserDictionary userDictionary = new UserDictionary(getApplicationContext(), "en"); userDictionary.loadDictionary(); userDictionary.addWord("hello", 1); userDictionary.addWord("you", 2); use...
@Override public ConfigDef config() { return CONFIG_DEF; }
@Test public void testConnectorConfigValidation() { List<ConfigValue> configValues = connector.config().validate(sourceProperties); for (ConfigValue val : configValues) { assertEquals(0, val.errorMessages().size(), "Config property errors: " + val.errorMessages()); } }
public static SourceOperationResponse performSplit( SourceSplitRequest request, PipelineOptions options) throws Exception { return performSplitWithApiLimit( request, options, DEFAULT_NUM_BUNDLES_LIMIT, DATAFLOW_SPLIT_RESPONSE_API_SIZE_LIMIT); }
@Test public void testLargeSerializedSizeResplits() throws Exception { final long apiSizeLimitForTest = 5 * 1024; // Figure out how many splits of CountingSource are needed to exceed the API limits, using an // extra factor of 2 to ensure that we go over the limits. BoundedSource<Long> justForSizing =...
public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = ...
@Test void testListJsonObjectToListMap() throws Exception { Method method = PojoUtilsTest.class.getMethod("setListMap", List.class); assertNotNull(method); JSONObject jsonObject = new JSONObject(); jsonObject.put("1", "test"); List<JSONObject> list = new ArrayList<>(1); ...
public int getNextSetBitOffset(int bitOffset) { int byteOffset = bitOffset / Byte.SIZE; int bitOffsetInFirstByte = bitOffset % Byte.SIZE; int firstByte = (_dataBuffer.getByte(byteOffset) << bitOffsetInFirstByte) & BYTE_MASK; if (firstByte != 0) { return bitOffset + FIRST_BIT_SET[firstByte]; } ...
@Test public void testGetNextSetBitOffset() throws IOException { int[] setBitOffsets = new int[NUM_ITERATIONS]; int bitOffset = RANDOM.nextInt(10); for (int i = 0; i < NUM_ITERATIONS; i++) { setBitOffsets[i] = bitOffset; bitOffset += RANDOM.nextInt(10) + 1; } int dataBufferSize =...
@Override public Collection<String> getLogicTableNames() { return logicalTableNames; }
@Test void assertGetLogicTableMapper() { assertThat(new LinkedList<>(ruleAttribute.getLogicTableNames()), is(Collections.singletonList("foo_tbl"))); }
abstract List<String> parseJobID() throws IOException;
@Test public void testParseHive() throws IOException { String errFileName = "src/test/data/status/hive"; HiveJobIDParser hiveJobIDParser = new HiveJobIDParser(errFileName, new Configuration()); List<String> jobs = hiveJobIDParser.parseJobID(); Assert.assertEquals(jobs.size(), 1); }
@Override public void updateMailSendResult(Long logId, String messageId, Exception exception) { // 1. 成功 if (exception == null) { mailLogMapper.updateById(new MailLogDO().setId(logId).setSendTime(LocalDateTime.now()) .setSendStatus(MailSendStatusEnum.SUCCESS.getStatus...
@Test public void testUpdateMailSendResult_success() { // mock 数据 MailLogDO log = randomPojo(MailLogDO.class, o -> { o.setSendStatus(MailSendStatusEnum.INIT.getStatus()); o.setSendTime(null).setSendMessageId(null).setSendException(null) .setTemplateParams(...
public Result execute( final Params params ) throws Throwable { return execute( params, null ); }
@Test public void testExecuteWithInvalidRepository() { // Create Mock Objects Params params = mock( Params.class ); KitchenCommandExecutor kitchenCommandExecutor = new KitchenCommandExecutor( Kitchen.class ); try ( MockedStatic<BaseMessages> baseMessagesMockedStatic = mockStatic( BaseMessages.class )...
static void sanityCheckResources(Builder builder) { int numSetResources = builder._numBrokers != DEFAULT_OPTIONAL_INT ? 1 : 0; if (builder._numRacks != DEFAULT_OPTIONAL_INT) { numSetResources++; } if (builder._numDisks != DEFAULT_OPTIONAL_INT) { numSetResources++; } if (builder._numP...
@Test public void testSanityCheckResources() { // Set multiple resources assertThrows(IllegalArgumentException.class, () -> ProvisionRecommendation.sanityCheckResources( new ProvisionRecommendation.Builder(ProvisionStatus.UNDER_PROVISIONED).numBrokers(1).numRacks(1))); // Set numPartitions under ...
public static CumulativeWindowAssigner of(Duration maxSize, Duration step) { return new CumulativeWindowAssigner(maxSize.toMillis(), step.toMillis(), 0, true); }
@Test public void testInvalidParameters3() { assertThatThrownBy( () -> CumulativeWindowAssigner.of( Duration.ofSeconds(5000), Duration.ofSeconds(2000))) .isInstanceOf(IllegalArgumentException.clas...
public ExecutorService getSharedExecutor() { return sharedExecutor; }
@Test void testSharedExecutor() throws Exception { ExecutorService sharedExecutor = frameworkExecutorRepository.getSharedExecutor(); CountDownLatch latch = new CountDownLatch(3); CountDownLatch latch1 = new CountDownLatch(1); sharedExecutor.execute(() -> { latch.countDown...
public Analysis analyze(Statement statement) { return analyze(statement, false); }
@Test public void testHaving() { // TODO: verify output analyze("SELECT sum(a) FROM t1 HAVING avg(a) - avg(b) > 10"); }
boolean isEncodable(DiscreteResource resource) { return resource.valueAs(Object.class) .map(Object::getClass) .map(codecs::containsKey) .orElse(Boolean.FALSE); }
@Test public void isRootNonEncodable() { DiscreteResource resource = Resource.ROOT; assertThat(sut.isEncodable(resource), is(false)); }
public long getMillis(HazelcastProperty property) { TimeUnit timeUnit = property.getTimeUnit(); return timeUnit.toMillis(getLong(property)); }
@Test(expected = IllegalArgumentException.class) public void getTimeUnit_noTimeUnitProperty() { defaultProperties.getMillis(ClusterProperty.EVENT_THREAD_COUNT); }
@Override public String convertDestination(ProtocolConverter converter, Destination d) { if (d == null) { return null; } ActiveMQDestination activeMQDestination = (ActiveMQDestination)d; String physicalName = activeMQDestination.getPhysicalName(); String rc = con...
@Test(timeout = 10000) public void testConvertTemporaryTopic() throws Exception { ActiveMQDestination destination = translator.convertDestination(converter, "/temp-topic/test", false); assertFalse(destination.isComposite()); assertEquals(ActiveMQDestination.TEMP_TOPIC_TYPE, destination.getD...
@Override public void run() { try { coordinator.start(); } catch (Exception e) { LOG.error("Coordinator error during start, exiting thread", e); terminated = true; } while (!terminated) { try { coordinator.process(); } catch (Exception e) { LOG.error("Coo...
@Test public void testRun() { Coordinator coordinator = mock(Coordinator.class); CoordinatorThread coordinatorThread = new CoordinatorThread(coordinator); coordinatorThread.start(); verify(coordinator, timeout(1000)).start(); verify(coordinator, timeout(1000).atLeast(1)).process(); verify(co...
public static RawPrivateTransaction decode(final String hexTransaction) { final byte[] transaction = Numeric.hexStringToByteArray(hexTransaction); final TransactionType transactionType = getPrivateTransactionType(transaction); if (transactionType == TransactionType.EIP1559) { return...
@Test public void testDecodingSigned1559() throws Exception { final BigInteger nonce = BigInteger.ZERO; final long chainId = 2018; final BigInteger gasLimit = BigInteger.TEN; final BigInteger maxPriorityFeePerGas = BigInteger.ONE; final BigInteger maxFeePerGas = BigInteger.ON...
static String getAbbreviation(Exception ex, Integer statusCode, String storageErrorMessage) { String result = null; for (RetryReasonCategory retryReasonCategory : rankedReasonCategories) { final String abbreviation = retryReasonCategory.captureAndGetAbbreviation(ex, statusC...
@Test public void test503UnknownRetryReason() { Assertions.assertThat(RetryReason.getAbbreviation(null, HTTP_UNAVAILABLE, null)).isEqualTo( "503" ); }
public static String[] splitString( String string, String separator ) { /* * 0123456 Example a;b;c;d --> new String[] { a, b, c, d } */ // System.out.println("splitString ["+path+"] using ["+separator+"]"); List<String> list = new ArrayList<>(); if ( string == null || string.length() == 0 ) {...
@Test public void testSplitStringNullWithDelimiterNullAndEnclosureNullRemoveEnclosure() { String[] result = Const.splitString( null, null, null, true ); assertNull( result ); }
@Override public boolean createEmptyObject(String key) { try { ObjectMetadata objMeta = new ObjectMetadata(); objMeta.setContentLength(0L); mClient.putObject(mBucketName, key, new ByteArrayInputStream(new byte[0]), objMeta); return true; } catch (ObsException e) { LOG.error("Fail...
@Test public void testCreateEmptyObject() { // test successful create empty object Mockito.when(mClient.putObject(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(InputStream.class), ArgumentMatchers.any(ObjectMetadata.class))) .thenReturn(null); boolean...
@Nonnull public <T> T getInstance(@Nonnull Class<T> type) { return getInstance(new Key<>(type)); }
@Test public void autoFactory_factoryMethodsCreateNewInstances() throws Exception { injector = builder.bind(Umm.class, MyUmm.class).build(); FooFactory factory = injector.getInstance(FooFactory.class); Foo chauncey = factory.create("Chauncey"); assertThat(chauncey.name).isEqualTo("Chauncey"); Foo...
@Override public ConsumerBuilder<T> topics(List<String> topicNames) { checkArgument(topicNames != null && !topicNames.isEmpty(), "Passed in topicNames list should not be null or empty."); topicNames.stream().forEach(topicName -> checkArgument(StringUtils.isNotBlank(to...
@Test(expectedExceptions = IllegalArgumentException.class) public void testConsumerBuilderImplWhenTopicNamesHasNullTopic() { List<String> topicNames = Arrays.asList("my-topic", null); consumerBuilderImpl.topics(topicNames); }
@Override public OUT nextRecord(OUT record) throws IOException { OUT returnRecord = null; do { returnRecord = super.nextRecord(record); } while (returnRecord == null && !reachedEnd()); return returnRecord; }
@Test void testDoubleFields() { try { final String fileContent = "11.1|22.2|33.3|44.4|55.5\n66.6|77.7|88.8|99.9|00.0|\n"; final FileInputSplit split = createTempFile(fileContent); final TupleTypeInfo<Tuple5<Double, Double, Double, Double, Double>> typeInfo = ...
public boolean isRegisteredUser(@Nonnull final JID user, final boolean checkRemoteDomains) { if (xmppServer.isLocal(user)) { try { getUser(user.getNode()); return true; } catch (final UserNotFoundException e) { return false; ...
@Test public void isRegisteredUserFalseWillReturnFalseForUnknownRemoteUsers() { final AtomicReference<IQResultListener> iqListener = new AtomicReference<>(); doAnswer(invocationOnMock -> { final IQResultListener listener = invocationOnMock.getArgument(1); iqListener.set(list...
@Override public void execute() { BatchGetItemResponse result = ddbClient.batchGetItem(BatchGetItemRequest.builder().requestItems(determineBatchItems()).build()); HashMap<Object, Object> tmp = new HashMap<>(); tmp.put(Ddb2Constants.BATCH_RESPONSE, result.responses()); ...
@SuppressWarnings("unchecked") @Test public void execute() { Map<String, AttributeValue> key = new HashMap<>(); key.put("1", AttributeValue.builder().s("Key_1").build()); Map<String, AttributeValue> unprocessedKey = new HashMap<>(); unprocessedKey.put("1", AttributeValue.builder(...
public long getUncompressedLen() { return uncompressed_len; }
@Test public void testGetUncompressedLen() { assertEquals(TestParameters.VP_RES_TBL_UNCOMP_LENGTH, chmLzxcResetTable.getUncompressedLen()); }