focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static String readFile(String path, String fileName) { File file = openFile(path, fileName); if (file.exists()) { return readFile(file); } return null; }
@Test void testReadFile() { assertNotNull(DiskUtils.readFile(testFile)); }
@Override public RangeBoundary getHighBoundary() { return highBoundary; }
@Test void getHighBoundary() { final Range.RangeBoundary highBoundary = Range.RangeBoundary.CLOSED; final RangeImpl rangeImpl = new RangeImpl(Range.RangeBoundary.OPEN, 10, 15, highBoundary); assertThat(rangeImpl.getHighBoundary()).isEqualTo(highBoundary); }
@Override protected Collection<Address> getPossibleAddresses() { Iterable<DiscoveryNode> discoveredNodes = checkNotNull(discoveryService.discoverNodes(), "Discovered nodes cannot be null!"); MemberImpl localMember = node.nodeEngine.getLocalMember(); Set<Address> localAddress...
@Test public void test_DiscoveryJoiner_returns_private_address_and_enrich_member_with_public_address() { DiscoveryJoiner joiner = new DiscoveryJoiner(getNode(hz), service, false); doReturn(discoveryNodes).when(service).discoverNodes(); Collection<Address> addresses = joiner.getPossibleAddres...
public void configure(SSLConfigurable socket) { socket.setEnabledProtocols(enabledProtocols( socket.getSupportedProtocols(), socket.getDefaultProtocols())); socket.setEnabledCipherSuites(enabledCipherSuites( socket.getSupportedCipherSuites(), socket.getDefaultCipherSuites())); if (isNeedClie...
@Test public void testPassDefaultProtocols() throws Exception { final String[] protocols = new String[] { "A" }; configurable.setDefaultProtocols(protocols); configuration.configure(configurable); assertTrue(Arrays.equals(protocols, configurable.getEnabledProtocols())); }
public void close() { runWithLock( () -> { closed = true; if (!udfFinished) { cacheNotEmpty.signalAll(); waitUDFFinished(); } udfExecutor.shutdown(); })...
@Test void testInitialize() throws ExecutionException, InterruptedException { CompletableFuture<Object> result = new CompletableFuture<>(); MapPartitionIterator<String> iterator = new MapPartitionIterator<>(stringIterator -> result.complete(null)); result.get(); asser...
public static TableElements parse(final String schema, final TypeRegistry typeRegistry) { return new SchemaParser(typeRegistry).parse(schema); }
@Test public void shouldParseQuotedSchema() { // Given: final String schema = "`END` VARCHAR"; // When: final TableElements elements = parser.parse(schema); // Then: assertThat(elements, hasItem( new TableElement(ColumnName.of("END"), new Type(SqlTypes.STRING)) )); }
@Override public Tuple zPopMin(byte[] key) { Assert.notNull(key, "Key must not be null!"); return write(key, ByteArrayCodec.INSTANCE, ZPOPMIN, (Object) key); }
@Test public void testZPopMin() { connection.zAdd("key".getBytes(), 1, "value1".getBytes()); connection.zAdd("key".getBytes(), 2, "value2".getBytes()); RedisZSetCommands.Tuple r = connection.zPopMin("key".getBytes()); assertThat(r.getValue()).isEqualTo("value1".getBytes()); ...
public static Collection<Inet6Address> getPossibleInetAddressesFor(final Inet6Address inet6Address) { if ((!inet6Address.isSiteLocalAddress() && !inet6Address.isLinkLocalAddress()) || inet6Address.getScopeId() > 0 || inet6Address.getScopedInterface() != null) { return Collections.sin...
@Test public void testGetPossibleInetAddressesFor_whenNotLocalAddress() throws UnknownHostException { Inet6Address inet6Address = (Inet6Address) Inet6Address.getByName(SOME_NOT_LOCAL_ADDRESS); assertThat(inet6Address.isSiteLocalAddress()).isFalse(); assertThat(inet6Address.isLinkLocalAddress...
@Override public byte[] echo(byte[] message) { return read(null, ByteArrayCodec.INSTANCE, ECHO, message); }
@Test public void testEcho() { assertThat(connection.echo("test".getBytes())).isEqualTo("test".getBytes()); }
@Override public boolean verify(final Host host, final PublicKey key) throws BackgroundException { if(null == database) { log.warn(String.format("Missing database %s", database)); return super.verify(host, key); } final KeyType type = KeyType.fromKey(key); if(...
@Test public void testReadFailure() throws Exception { final AtomicBoolean unknown = new AtomicBoolean(); final OpenSSHHostKeyVerifier v = new OpenSSHHostKeyVerifier(new Local("/t") { @Override public InputStream getInputStream() throws AccessDeniedException { ...
public static String replaceAllChars(String source, char search, String replace) { int indexOf = source.indexOf(search); if (indexOf == -1) { return source; } int offset = 0; char[] chars = source.toCharArray(); StringBuilder sb = new StringBuilder(source.len...
@Test public void testreplaceAllChars() { assertEquals("", JOrphanUtils.replaceAllChars("", ' ', "+")); assertEquals("source", JOrphanUtils.replaceAllChars("source", ' ', "+")); assertEquals("so+rce", JOrphanUtils.replaceAllChars("source", 'u', "+")); assertEquals("+so+urc+", JOrphan...
public boolean readable(final SelectableChannel channel) { return readable((Object) channel); }
@Test(timeout = 5000) public void testReadable() { ZContext ctx = new ZContext(); ZPoller poller = new ZPoller(ctx); try { Socket socket = ctx.createSocket(SocketType.XPUB); poller.register(socket, new EventsHandlerAdapter()); boolean rc = poller.read...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); final DSTOffset offset = readDSTOffset(data, 0); if (offset == null) { onInvalidDataReceived(device, data); return; } onDSTOffsetReceived(device, offset); }
@Test public void onDSTOffsetReceived_daylight() { final Data data = new Data(new byte[] { 4 }); callback.onDataReceived(null, data); assertTrue(success); assertSame(DSTOffsetCallback.DSTOffset.DAYLIGHT_TIME, result); }
public static EnsemblePlacementPolicyConfig decode(byte[] data) throws ParseEnsemblePlacementPolicyConfigException { try { return ENSEMBLE_PLACEMENT_CONFIG_READER.readValue(data); } catch (IOException e) { throw new ParseEnsemblePlacementPolicyConfigException("Failed to decode fr...
@Test public void testDecodeFailed() { byte[] configBytes = new byte[0]; try { EnsemblePlacementPolicyConfig.decode(configBytes); Assert.fail("should failed parse the config from bytes"); } catch (EnsemblePlacementPolicyConfig.ParseEnsemblePlacementPolicyConfigExcepti...
public static Read<JmsRecord> read() { return new AutoValue_JmsIO_Read.Builder<JmsRecord>() .setMaxNumRecords(Long.MAX_VALUE) .setCoder(SerializableCoder.of(JmsRecord.class)) .setCloseTimeout(DEFAULT_CLOSE_TIMEOUT) .setRequiresDeduping(false) .setMessageMapper( ne...
@Test public void testDefaultAutoscaler() throws IOException { JmsIO.Read spec = JmsIO.read() .withConnectionFactory(connectionFactory) .withUsername(USERNAME) .withPassword(PASSWORD) .withQueue(QUEUE); JmsIO.UnboundedJmsSource source = new JmsIO.Unbound...
public static AvroGenericCoder of(Schema schema) { return AvroGenericCoder.of(schema); }
@Test public void testAvroCoderEncoding() throws Exception { AvroCoder<Pojo> coder = AvroCoder.of(Pojo.class); CoderProperties.coderSerializable(coder); AvroCoder<Pojo> copy = SerializableUtils.clone(coder); Pojo pojo = new Pojo("foo", 3, DATETIME_A); Pojo equalPojo = new Pojo("foo", 3, DATETIME_...
public Map<String, String> gitTags(Map<String, String> tags) { return MetricsSupport.gitTags(tags); }
@Test void gitTags() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; applicationModel .getApplicationConfigManager() .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ...
@Override public void execute(ComputationStep.Context context) { new PathAwareCrawler<>( FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor(List.of(duplicationFormula))) .visit(treeRootHolder.getRoot()); }
@Test public void compute_duplicated_lines_counts_lines_from_original_and_ignores_InProjectDuplicate() { TextBlock original = new TextBlock(1, 1); duplicationRepository.addDuplication(FILE_1_REF, original, FILE_2_REF, new TextBlock(2, 2)); setNewLines(FILE_1); underTest.execute(new TestComputationSte...
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void parseEdgATest(){ // https://gitee.com/dromara/hutool/issues/I4MCBP final String uaStr = "userAgent: Mozilla/5.0 (Linux; Android 11; MI 9 Transparent Edition) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Mobile Safari/537.36 EdgA/96.0.1054.36"; final UserAgent ua = UserAgentUtil.pa...
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { final boolean exists = Files.exists(session.toPath(file), LinkOption.NOFOLLOW_LINKS); if(exists) { if(Files.isSymbolicLink(session.toPath(file))) { return true...
@Test public void testFindDirectory() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallb...
@Override public URL mergeUrl(URL remoteUrl, Map<String, String> localParametersMap) { Map<String, String> map = new HashMap<>(); Map<String, String> remoteMap = remoteUrl.getParameters(); if (remoteMap != null && remoteMap.size() > 0) { map.putAll(remoteMap); // Re...
@Test void testMergeUrl() { URL providerURL = URL.valueOf("dubbo://localhost:55555"); providerURL = providerURL.setPath("path").setUsername("username").setPassword("password"); providerURL = URLBuilder.from(providerURL) .addParameter(GROUP_KEY, "dubbo") .addP...
@SuppressWarnings({ "nullness" // TODO(https://github.com/apache/beam/issues/20497) }) @Override protected SchemaTransform from(KafkaReadSchemaTransformConfiguration configuration) { return new KafkaReadSchemaTransform(configuration); }
@Test public void testBuildTransformWithJsonSchema() throws IOException { ServiceLoader<SchemaTransformProvider> serviceLoader = ServiceLoader.load(SchemaTransformProvider.class); List<SchemaTransformProvider> providers = StreamSupport.stream(serviceLoader.spliterator(), false) .fi...
public static String optimizeErrorMessage(String msg) { if (msg == null) { return null; } if (SERVER_ID_CONFLICT.matcher(msg).matches()) { // Optimize the error msg when server id conflict msg += "\nThe 'server-id' in the mysql cdc connecto...
@Test public void testOptimizeErrorMessageWhenMissingBinlogPositionInSource() { assertEquals( "Cannot replicate because the source purged required binary logs. Replicate the missing transactions from elsewhere, or provision a new slave from backup. Consider increasing the master's binary log...
public static String normalize(final String name) { if (name == null) { throw new IllegalArgumentException("name cannot be null"); } StringBuilder sb = new StringBuilder(); for (char c : name.toCharArray()) { if (RESERVED.contains(c)) { sb.append...
@Test public void normalizeWithNotPrintableChars() throws Exception { final String TEST_NAME = new String( new char[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, '.', 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}); final String EXPE...
@Override protected String transform(ILoggingEvent event, String in) { AnsiElement element = ELEMENTS.get(getFirstOption()); List<Marker> markers = event.getMarkerList(); if ((markers != null && !markers.isEmpty() && markers.get(0).contains(CRLF_SAFE_MARKER)) || isLoggerSafe(event)) { ...
@Test void transformShouldReplaceNewlinesAndCarriageReturnsWithAnsiStringWhenMarkersDoNotContainCRLFSafeMarkerAndLoggerIsNotSafeAndAnsiElementIsNotNull() { ILoggingEvent event = mock(ILoggingEvent.class); List<Marker> markers = Collections.emptyList(); when(event.getMarkerList()).thenReturn(...
@Override public Num calculate(BarSeries series, Position position) { int beginIndex = position.getEntry().getIndex(); int endIndex = series.getEndIndex(); return criterion.calculate(series, createEnterAndHoldTrade(series, beginIndex, endIndex)); }
@Test public void calculateWithOnePositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105); Position position = new Position(Trade.buyAt(0, series), Trade.sellAt(1, series)); // buy and hold of ReturnCriterion AnalysisCriterion buyAndHoldReturn = getCriterion(ne...
public static int getInt(String key, int def) { String value = get(key); if (value == null) { return def; } value = value.trim(); try { return Integer.parseInt(value); } catch (Exception e) { // Ignore } logger.warn( ...
@Test public void getIntWithPropertValueIsInt() { System.setProperty("key", "123"); assertEquals(123, SystemPropertyUtil.getInt("key", 1)); }
public Future<KafkaVersionChange> reconcile() { return getPods() .compose(this::detectToAndFromVersions) .compose(i -> prepareVersionChange()); }
@Test public void testExistingClusterWithRemovedMetadataVersion(VertxTestContext context) { VersionChangeCreator vcc = mockVersionChangeCreator( mockKafka(VERSIONS.defaultVersion().version(), "3.4-IV2", null), mockRos(mockUniformPods(VERSIONS.defaultVersion().version())) ...
public static WriteStreams writeStreams() { return new AutoValue_RedisIO_WriteStreams.Builder() .setConnectionConfiguration(RedisConnectionConfiguration.create()) .setMaxLen(0L) .setApproximateTrim(true) .build(); }
@Test public void testWriteStreams() { /* test data is 10 keys (stream IDs), each with two entries, each entry having one k/v pair of data */ List<String> redisKeys = IntStream.range(0, 10).boxed().map(idx -> UUID.randomUUID().toString()).collect(toList()); Map<String, String> fooValues = Immuta...
@VisibleForTesting void checkRemoteFoldernameField( String remoteFoldernameFieldName, SFTPPutData data ) throws KettleStepException { // Remote folder fieldname remoteFoldernameFieldName = environmentSubstitute( remoteFoldernameFieldName ); if ( Utils.isEmpty( remoteFoldernameFieldName ) ) { // remo...
@Test( expected = KettleStepException.class ) public void checkRemoteFoldernameField_NameIsBlank() throws Exception { SFTPPutData data = new SFTPPutData(); step.checkRemoteFoldernameField( "", data ); }
public Canvas canvas() { Canvas canvas = new Canvas(getLowerBound(), getUpperBound()); canvas.add(this); if (name != null) { canvas.setTitle(name); } return canvas; }
@Test public void testSparseMatrix() throws Exception { System.out.println("Sparse Matrix"); var sparse = SparseMatrix.text(Paths.getTestData("matrix/mesh2em5.txt")); var canvas = SparseMatrixPlot.of(sparse).canvas(); canvas.setTitle("mesh2em5"); canvas.window(); }
@Override public void onProjectsDeleted(Set<DeletedProject> projects) { checkNotNull(projects, "projects can't be null"); if (projects.isEmpty()) { return; } Arrays.stream(listeners) .forEach(safelyCallListener(listener -> listener.onProjectsDeleted(projects))); }
@Test @UseDataProvider("oneOrManyDeletedProjects") public void onProjectsDeleted_calls_all_listeners_even_if_one_throws_an_Error(Set<DeletedProject> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); doThrow(new Error("Faking listener2 throwing an Error")) .when(listener2)...
@Override public byte[] decrypt(byte[] bytes, KeyType keyType) { // 在非使用BC库情况下,blockSize使用默认的算法 if (this.decryptBlockSize < 0 && null == GlobalBouncyCastleProvider.INSTANCE.getProvider()) { // 加密数据长度 <= 模长-11 this.decryptBlockSize = ((RSAKey) getKeyByType(keyType)).getModulus().bitLength() / 8; } return ...
@Test public void rsaBase64Test() { final String textBase = "我是一段特别长的测试"; final StringBuilder text = new StringBuilder(); for (int i = 0; i < 10; i++) { text.append(textBase); } final RSA rsa = new RSA(); // 公钥加密,私钥解密 final String encryptStr = rsa.encryptBase64(text.toString(), KeyType.PublicKey); ...
protected FileSystem createFileSystem(Configuration namenodeConf) throws IOException { String user = UserGroupInformation.getCurrentUser().getShortUserName(); CachedFileSystem newCachedFS = new CachedFileSystem(purgeTimeout); CachedFileSystem cachedFS = fsCache.putIfAbsent(user, newCachedFS); if (ca...
@Test @TestDir @TestHdfs public void createFileSystem() throws Exception { String dir = TestDirHelper.getTestDir().getAbsolutePath(); String services = StringUtils.join(",", Arrays.asList(InstrumentationService.class.getName(), SchedulerService.class.getName(), ...
@Override protected void write(final PostgreSQLPacketPayload payload) { payload.getByteBuf().writeBytes(PREFIX); payload.getByteBuf().writeByte(status); }
@Test void assertReadWriteWithInTransaction() { ByteBuf byteBuf = ByteBufTestUtils.createByteBuf(6); PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(byteBuf, StandardCharsets.UTF_8); PostgreSQLReadyForQueryPacket packet = PostgreSQLReadyForQueryPacket.IN_TRANSACTION; pa...
@Override public boolean createReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException { LOG.info("placing the following ReservationRequest: " + contract); try { boolean res = planner.createReservation(reservationId, use...
@Test public void testOrderNoGapImpossible() throws PlanningException { prepareBasicPlan(); // create a completely utilized segment at time 30 int[] f = { 100, 100 }; ReservationDefinition rDef = ReservationSystemTestUtil .createSimpleReservationDefinition(30, 30 * step + f.length * step, ...
private boolean concurrentSQL() { return Boolean.parseBoolean(getProperty("zeppelin.spark.concurrentSQL")); }
@Test void testConcurrentSQL() throws InterpreterException, InterruptedException { sparkInterpreter.interpret("spark.udf.register(\"sleep\", (e:Int) => {Thread.sleep(e*1000); e})", context); Thread thread1 = new Thread() { @Override public void run() { try { InterpreterResult re...
public FEELFnResult<List<Object>> invoke(@ParameterName("list") Object[] lists) { if ( lists == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } // spec requires us to return a new list final List<Object> result = n...
@Test void invokeArrayWithoutList() { FunctionTestUtil.assertResultList(concatenateFunction.invoke(new Object[]{"test", 2, BigDecimal.valueOf(25.3)}), Arrays.asList("test", 2, BigDecimal.valueOf(25.3))); }
public boolean overlap(final Window other) throws IllegalArgumentException { if (getClass() != other.getClass()) { throw new IllegalArgumentException("Cannot compare windows of different type. Other window has type " + other.getClass() + "."); } final SessionWindow ot...
@Test public void shouldNotOverlapIfOtherWindowIsBeforeThisWindow() { /* * This: [-------] * Other: [---] */ assertFalse(window.overlap(new SessionWindow(0, 25))); assertFalse(window.overlap(new SessionWindow(0, start - 1))); assertFalse(window.overl...
public static String getAllExceptionMsg(Throwable e) { Throwable cause = e; StringBuilder strBuilder = new StringBuilder(); while (cause != null && !StringUtils.isEmpty(cause.getMessage())) { strBuilder.append("caused: ").append(cause.getMessage()).append(';'); c...
@Test void testGetAllExceptionMsg() { String msg = ExceptionUtil.getAllExceptionMsg(nacosRuntimeException); assertEquals("caused: errCode: 500, errMsg: Test ;caused: I'm caused exception.;", msg); }
@SuppressWarnings({"SimplifyBooleanReturn"}) public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) { if (params == null || params.isEmpty()) { return params; } Map<String, ParamDefinition> mapped = params.entrySet().stream() .collect( ...
@Test public void testParameterConversionRemoveInternalModeNestedMap() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'tomergemap1': {'type': 'MAP', 'internal_mode': 'RESERVED', 'value': {'tomerge1': {'type': 'STRING','value': 'hello', 'internal_m...
@PostConstruct public void synchronize() throws IOException { try { synchronizeTask(); } catch (NonTransientDataAccessException | StaleStateException e) { logger.error("Database exception while synchronizing tasks", e); } }
@Test public void synchronizeTasksBetweenYamlAndDatabase() throws IOException { Task conf1 = new Task(); conf1.setName("1"); conf1.setCron("1"); Task conf2 = new Task(); conf2.setName("2"); conf2.setCron("200"); Task conf3 = new Task(); conf3.setName("...
@Override public String getName() { if (_distinctResult == 1) { return TransformFunctionType.IS_DISTINCT_FROM.getName(); } return TransformFunctionType.IS_NOT_DISTINCT_FROM.getName(); }
@Test public void testDistinctFromLeftNull() throws Exception { ExpressionContext expression = RequestContextUtils.getExpression(String.format(_expression, INT_SV_NULL_COLUMN, INT_SV_COLUMN)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); Ass...
@Override public List<ImportValidationFeedback> verifyRule( Object subject ) { List<ImportValidationFeedback> feedback = new ArrayList<>(); if ( !isEnabled() || !( subject instanceof TransMeta ) ) { return feedback; } TransMeta transMeta = (TransMeta) subject; String description = transMe...
@Test public void testVerifyRule_NullParameter_DisabledRule() { TransformationHasDescriptionImportRule importRule = getImportRule( 10, false ); List<ImportValidationFeedback> feedbackList = importRule.verifyRule( null ); assertNotNull( feedbackList ); assertTrue( feedbackList.isEmpty() ); }
@Override public boolean contains(PipelineConfig o) { for (PipelineConfigs part : this.parts) { if (part.contains(o)) return true; } return false; }
@Test public void shouldReturnTrueWhenContainsPipeline() { PipelineConfig pipe1 = PipelineConfigMother.pipelineConfig("pipeline1"); PipelineConfigs group = new MergePipelineConfigs( new BasicPipelineConfigs(pipe1), new BasicPipelineConfigs()); assertThat(group...
@Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final GenericRow that = (GenericRow) o; return Objects.equals(this.values, that.values); }
@SuppressWarnings("UnstableApiUsage") @Test public void testEquals() { new EqualsTester(). addEqualityGroup( new GenericRow(), new GenericRow(10) ) .addEqualityGroup( GenericRow.genericRow(new Object()) ) .addEqualityGroup( ...
public boolean isEmpty() { return numBytes == 0; }
@Test public void testEmpty() { GapEncodedVariableLengthIntegerReader reader = reader(20); Assert.assertFalse(reader.isEmpty()); reader = reader(); Assert.assertTrue(reader.isEmpty()); Assert.assertTrue(EMPTY_READER.isEmpty()); }
public long createSessionFromExisting(ApplicationId applicationId, boolean internalRedeploy, TimeoutBudget timeoutBudget, DeployLogger deployLogger) { Tenant tenant = getTenant(applicati...
@Test public void createFromActiveSession() { long originalSessionId = deployApp(testApp).sessionId(); long sessionId = createSessionFromExisting(applicationId(), timeoutBudget); ApplicationMetaData originalApplicationMetaData = getApplicationMetaData(applicationId(), originalSessionId); ...
public TopicList getTopicsByCluster(String cluster) { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); Set<String> brokerNameSet = this.clusterAddrTable.get(cluster); for (String brokerName : brokerNa...
@Test public void testGetTopicsByCluster() { byte[] topicList = routeInfoManager.getTopicsByCluster("default-cluster").encode(); assertThat(topicList).isNotNull(); }
@Override public void clearLastScreenUrl() { }
@Test public void clearLastScreenUrl() { mSensorsAPI.clearLastScreenUrl(); Assert.assertNull(mSensorsAPI.getLastScreenUrl()); }
String load() { return loadQuery; }
@Test public void testLoadIsQuoted() { Queries queries = new Queries(mapping, idColumn, columnMetadata); String result = queries.load(); assertEquals("SELECT * FROM \"mymapping\" WHERE \"id\" = ?", result); }
@Override public List<AdminUserDO> getUserListByStatus(Integer status) { return userMapper.selectListByStatus(status); }
@Test public void testGetUserListByStatus() { // mock 数据 AdminUserDO user = randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); userMapper.insert(user); // 测试 status 不匹配 userMapper.insert(randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.ENABLE.getSta...
public static MetaDataContexts create(final MetaDataPersistService persistService, final ContextManagerBuilderParameter param, final ComputeNodeInstanceContext computeNodeInstanceContext) throws SQLException { return persistService.getDatabaseMetaDataService().loadAllDa...
@Test void assertCreateWithProxyInstanceMetaData() throws SQLException { when(databaseMetaDataPersistService.loadAllDatabaseNames()).thenReturn(Collections.singletonList("foo_db")); when(metaDataPersistService.getDatabaseMetaDataService()).thenReturn(databaseMetaDataPersistService); try (Met...
public Map<String, String> getAllConfigPropsWithSecretsObfuscated() { final Map<String, String> allPropsCleaned = new HashMap<>(); // build a properties map with obfuscated values for sensitive configs. // Obfuscation is handled by ConfigDef.convertToString allPropsCleaned.putAll(getKsqlConfigPropsWithS...
@Test public void shouldFilterPropertiesForWhichTypeUnknown() { final KsqlConfig ksqlConfig = new KsqlConfig(Collections.singletonMap("you.shall.not.pass", "wizard")); assertThat( ksqlConfig.getAllConfigPropsWithSecretsObfuscated().keySet(), not(hasItem("you.shall.not.pass"))); }
@Override public double sd() { return Math.sqrt(1 - p) / p; }
@Test public void testSd() { System.out.println("sd"); GeometricDistribution instance = new GeometricDistribution(0.3); instance.rand(); assertEquals(2.788867, instance.sd(), 1E-6); }
public void subscribeRegistryConfig(String serviceName) { ConfigSubscriber subscriber; final RegisterConfig registerConfig = PluginConfigManager.getPluginConfig(RegisterConfig.class); final RegisterServiceCommonConfig registerCommonConfig = PluginConfigManager.getPluginConfig(Reg...
@Test public void subscribeRegistryConfig() { final RegistryConfigSubscribeServiceImpl mock = Mockito.mock(RegistryConfigSubscribeServiceImpl.class); String serviceName = "test"; mock.subscribeRegistryConfig(serviceName); Mockito.verify(mock, Mockito.times(1)).subscribeRegistryConfig...
public static InetSocketAddress getInetSocketAddressFromRpcURL(String rpcURL) throws Exception { // Pekko URLs have the form schema://systemName@host:port/.... if it's a remote Pekko URL try { final Address address = getAddressFromRpcURL(rpcURL); if (address.host().isDefined() &...
@Test void getHostFromRpcURLHandlesAkkaSslTcpProtocol() throws Exception { final String url = "pekko.ssl.tcp://flink@localhost:1234/user/jobmanager"; final InetSocketAddress expected = new InetSocketAddress("localhost", 1234); final InetSocketAddress result = PekkoUtils.getInetSocketAddress...
@Override public void flush() throws IOException { mLocalOutputStream.flush(); }
@Test @PrepareForTest(COSOutputStream.class) public void testFlush() throws Exception { PowerMockito.whenNew(BufferedOutputStream.class) .withArguments(any(DigestOutputStream.class)).thenReturn(mLocalOutputStream); COSOutputStream stream = new COSOutputStream("testBucketName", "testKey", mCosClient,...
@Override public ResultSet executeQuery(String sql) throws SQLException { validateState(); try { if (!DriverUtils.queryContainsLimitStatement(sql)) { sql += " " + LIMIT_STATEMENT + " " + _maxRows; } String enabledSql = DriverUtils.enableQueryOptions(sql, _connection.getQueryOpt...
@Test public void testSetEnableNullHandling() throws Exception { Properties props = new Properties(); props.put(QueryOptionKey.ENABLE_NULL_HANDLING, "true"); PinotConnection pinotConnection = new PinotConnection(props, "dummy", _dummyPinotClientTransport, "dummy", _dummyPinotControllerTransp...
@Override public Collection<Subscriber> getFuzzySubscribers(String namespaceId, String serviceName) { Collection<Subscriber> result = new LinkedList<>( subscriberServiceLocal.getFuzzySubscribers(namespaceId, serviceName)); if (memberManager.getServerList().size() > 1) { g...
@Test void testGetFuzzySubscribersByServiceWithLocal() { Collection<Subscriber> actual = aggregation.getFuzzySubscribers(service); assertEquals(1, actual.size()); assertEquals("local", actual.iterator().next().getAddrStr()); }
private String mainHelp() { final TTable tTable = new TTable(new TTable.ColumnDefine[] { new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(80, false, TTable.Align.LEFT) }); final List<Class<?>> classes = commandHelper.getAllCommandClass(); Collections.so...
@Test void testMainHelp() { Help help = new Help(FrameworkModel.defaultModel()); String output = help.execute(Mockito.mock(CommandContext.class), null); assertThat(output, containsString("greeting")); assertThat(output, containsString("help")); assertThat(output, containsStri...
public void reportCheckpointMetrics( long id, ExecutionAttemptID attemptId, CheckpointMetrics metrics) { statsTracker.reportIncompleteStats(id, attemptId, metrics); }
@Test void testAbortedCheckpointStatsUpdatedAfterFailure() throws Exception { testReportStatsAfterFailure( 1L, (coordinator, execution, metrics) -> { coordinator.reportCheckpointMetrics(1L, execution.getAttemptId(), metrics); return nul...
@Override // mappedStatementId 参数,暂时没有用。以后,可以基于 mappedStatementId + DataPermission 进行缓存 public List<DataPermissionRule> getDataPermissionRule(String mappedStatementId) { // 1. 无数据权限 if (CollUtil.isEmpty(rules)) { return Collections.emptyList(); } // 2. 未配置,则默认开启 D...
@Test public void testGetDataPermissionRule_03() { // 准备参数 String mappedStatementId = randomString(); // mock 方法 DataPermissionContextHolder.add(AnnotationUtils.findAnnotation(TestClass03.class, DataPermission.class)); // 调用 List<DataPermissionRule> result = dataPerm...
public static Node getDOM(String text) { log.debug("Start : getDOM1"); Node node = getParser() .parseDOM( new ByteArrayInputStream( text.getBytes(StandardCharsets.UTF_8)), null); if (log.isDebugEnabled()) { log...
@Test public void testGetDom() throws Exception { HtmlParsingUtils.getDOM("<HTML></HTML>"); HtmlParsingUtils.getDOM(""); }
@Override public void openExisting(final ProcessorContext context, final long streamTime) { metricsRecorder.init(ProcessorContextUtils.metricsImpl(context), context.taskId()); super.openExisting(context, streamTime); }
@Test public void shouldUpdateSegmentFileNameFromOldColonFormatToNewFormat() throws Exception { final String storeDirectoryPath = stateDirectory.getAbsolutePath() + File.separator + storeName; final File storeDirectory = new File(storeDirectoryPath); //noinspection ResultOfMethodCallIgnored ...
public KiePMMLDroolsType declareType(Field field) { String generatedType = getGeneratedClassName(field.getName()); String fieldName =field.getName(); String fieldType = field.getDataType().value(); fieldTypeMap.put(fieldName, new KiePMMLOriginalTypeGeneratedType(fieldType, generatedType)...
@Test void declareType() { DataField dataField = getTypeDataField(); final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap = new HashMap<>(); KiePMMLDroolsType retrieved = KiePMMLDataDictionaryASTFactory.factory(fieldTypeMap).declareType(dataField); assertThat(retrieved).i...
@Override public Result apply(PathData item, int depth) throws IOException { String name = getPath(item).getName(); if (!caseSensitive) { name = StringUtils.toLowerCase(name); } if (globPattern.matches(name)) { return Result.PASS; } else { return Result.FAIL; } }
@Test public void applyGlob() throws IOException { setup("n*e"); PathData item = new PathData("/directory/path/name", mockFs.getConf()); assertEquals(Result.PASS, name.apply(item, -1)); }
public static Checksum crc32c() { return Crc32c.INSTANCE; }
@EnabledForJreRange(min = JAVA_9) @Test void crc32c() { assertSame(Crc32c.INSTANCE, Checksums.crc32c()); }
public static Config resolve(Config config) { var resolveSystemProperty = System.getenv("KORA_SYSTEM_PROPERTIES_RESOLVE_ENABLED"); if (resolveSystemProperty == null) { resolveSystemProperty = System.getProperty("kora.system.properties.resolve.enabled", "true"); } var ctx = ne...
@Test void testNullableReference() { var config = fromMap(Map.of( "reference", "${?object.field}" )).resolve(); assertThat(config.get("reference")).isInstanceOf(ConfigValue.NullValue.class); }
public void add(QueryCacheEventData entry) { events.add(entry); }
@Test public void testAdd() { batchEventData.add(otherEventData); assertEquals(2, batchEventData.size()); Collection<QueryCacheEventData> events = batchEventData.getEvents(); assertContains(events, eventData); assertContains(events, otherEventData); }
public static String normalizeFilter(String projection, String filter) { if (isNullOrWhitespaceOnly(projection) || isNullOrWhitespaceOnly(filter)) { return filter; } SqlSelect sqlSelect = parseProjectionExpression(projection); if (sqlSelect.getSelectList().isEmpty()) { ...
@Test public void testNormalizeFilter() { Assertions.assertThat(TransformParser.normalizeFilter("a, b, c, d", "a > 0 and b > 0")) .isEqualTo("`a` > 0 AND `b` > 0"); Assertions.assertThat(TransformParser.normalizeFilter("a, b, c, d", null)).isEqualTo(null); Assertions.assertTh...
public DoubleArrayAsIterable usingExactEquality() { return new DoubleArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_containsAnyOf_primitiveDoubleArray_success() { assertThat(array(1.1, 2.2, 3.3)).usingExactEquality().containsAnyOf(array(99.99, 2.2)); }
public Future<Set<Integer>> brokersInUse(Reconciliation reconciliation, Vertx vertx, TlsPemIdentity coTlsPemIdentity, AdminClientProvider adminClientProvider) { try { String bootstrapHostname = KafkaResources.bootstrapServiceName(reconciliation.name()) + "." + reconciliation.namespace() + ".svc:" + ...
@Test public void testKafkaClientFailure(VertxTestContext context) { Admin admin = mock(Admin.class); AdminClientProvider mock = mock(AdminClientProvider.class); when(mock.createAdminClient(anyString(), any(), any())).thenReturn(admin); // Mock list topics when(admin.listTop...
public static TypeRef<?> getElementType(TypeRef<?> typeRef) { Type type = typeRef.getType(); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (parameterizedType.getRawType() == List.class) { // fastpath Type[] actualTypeArguments = (...
@Test public void getSubclassElementTypeTest() { abstract class A implements Collection<List<String>> {} Assert.assertEquals( TypeUtils.getElementType(TypeRef.of(A.class)), new TypeRef<List<String>>() {}); }
public static void verifyHostnames(String[] names) throws UnknownHostException { for (String name: names) { if (name == null) { throw new UnknownHostException("null hostname found"); } // The first check supports URL formats (e.g. hdfs://, etc.). // java.net.URI requires a schema, s...
@Test public void testVerifyHostnamesNoException() throws UnknownHostException { String[] names = {"valid.host.com", "1.com"}; NetUtils.verifyHostnames(names); }
@Override public Integer call() throws Exception { return this.call( Template.class, yamlFlowParser, modelValidator, (Object object) -> { Template template = (Template) object; return template.getNamespace() + " / " + template.g...
@Test void runLocal() { URL directory = TemplateValidateCommandTest.class.getClassLoader().getResource("invalidsTemplates/template.yml"); ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setErr(new PrintStream(out)); try (ApplicationContext ctx = ApplicationContext.r...
public static ReleaseInfo getReleaseInfo() { return LazyInit.INSTANCE; }
@Test public void getReleaseInfo() throws Exception { ReleaseInfo info = ReleaseInfo.getReleaseInfo(); // Validate name assertThat(info.getName(), containsString("Beam")); // Validate semantic version String version = info.getVersion(); String pattern = "\\d+\\.\\d+\\.\\d+.*"; assertTrue...
public boolean isReadOnly(final String topicName) { return readOnlyTopicsPattern.matcher(topicName).matches(); }
@Test public void shouldReturnFalseOnNonReadOnlyTopics() { // Given final List<String> topicNames = ImmutableList.of( "topic_prefix_", "_suffix_topic" ); // Given topicNames.forEach(topic -> { // When final boolean isReadOnly = internalTopics.isReadOnly(topic); // Then ...
public void write(D datum, Encoder out) throws IOException { Objects.requireNonNull(out, "Encoder cannot be null"); try { write(root, datum, out); } catch (TracingNullPointException | TracingClassCastException | TracingAvroTypeException e) { throw e.summarize(root); } }
@Test void allowWritingPrimitives() throws IOException { Schema doubleType = Schema.create(Schema.Type.DOUBLE); Schema.Field field = new Schema.Field("double", doubleType); List<Schema.Field> fields = Collections.singletonList(field); Schema schema = Schema.createRecord("test", "doc", "", false, field...
@Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); }
@SuppressWarnings("unchecked") @Test void testJavaException() { ExceptionFilter exceptionFilter = new ExceptionFilter(); RpcInvocation invocation = new RpcInvocation( "sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {"world"}); Ap...
@Deprecated public PassiveCompletableFuture<TaskExecutionState> deployLocalTask( @NonNull TaskGroup taskGroup) { return deployLocalTask( taskGroup, Thread.currentThread().getContextClassLoader(), emptyList()); }
@Test public void testFinish() { TaskExecutionService taskExecutionService = server.getTaskExecutionService(); long sleepTime = 300; AtomicBoolean stop = new AtomicBoolean(false); AtomicBoolean futureMark = new AtomicBoolean(false); TestTask testTask1 = new TestTask(stop, L...
@Override public InterpreterResult interpret(String st, InterpreterContext context) throws InterpreterException { LOGGER.info("Running SQL query: '{}' over Pandas DataFrame", st); return pythonInterpreter.interpret( "z.show(pysqldf('" + st.trim() + "'))", context); }
@Test public void badSqlSyntaxFails() throws InterpreterException { // when context = getInterpreterContext(); InterpreterResult ret = pandasSqlInterpreter.interpret("select wrong syntax", context); // then assertNotNull(ret, "Interpreter returned 'null'"); assertEquals(InterpreterResult.Code...
public <T> ProducerBuilder<T> createProducerBuilder(String topic, Schema<T> schema, String producerName) { ProducerBuilder<T> builder = client.newProducer(schema); if (defaultConfigurer != null) { defaultConfigurer.accept(builder); } builder.blockIfQueueFull(true) ...
@Test public void testCreateProducerBuilderWithDefaultConfigurer() { ProducerBuilderFactory builderFactory = new ProducerBuilderFactory(pulsarClient, null, null, builder -> builder.property("key", "value")); builderFactory.createProducerBuilder("topic", Schema.STRING, "producerName")...
CallIdSequence newCallIdSequence(ConcurrencyDetection concurrencyDetection) { return CallIdFactory.newCallIdSequence(maxConcurrentInvocations, backoffTimeoutMs, concurrencyDetection); }
@Test public void newCallIdSequence_whenBackPressureDisabled() { Config config = new Config(); config.setProperty(BACKPRESSURE_ENABLED.getName(), "false"); HazelcastProperties hazelcastProperties = new HazelcastProperties(config); BackpressureRegulator backpressureRegulator = new Bac...
@Override public byte[] fromConnectData(final String topic, final Schema schema, final Object value) { if (this.schema == null) { throw new UnsupportedOperationException("ProtobufNoSRConverter is an internal " + "converter to ksqldb. It should not be instantiated via reflection through a no-arg " ...
@Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionWhenUsedWithNoArgConstructor2() { // Given final ProtobufNoSRConverter protobufNoSRConverter = new ProtobufNoSRConverter(); // When protobufNoSRConverter.fromConnectData("topic", Schema.STRING_SCHEMA, "test"); }
@VisibleForTesting String validateMail(String mail) { if (StrUtil.isEmpty(mail)) { throw exception(MAIL_SEND_MAIL_NOT_EXISTS); } return mail; }
@Test public void testValidateMail_notExists() { // 准备参数 // mock 方法 // 调用,并断言异常 assertServiceException(() -> mailSendService.validateMail(null), MAIL_SEND_MAIL_NOT_EXISTS); }
public static TriRpcStatus getStatus(Throwable throwable) { return getStatus(throwable, null); }
@Test void getStatus() { StatusRpcException rpcException = new StatusRpcException(TriRpcStatus.INTERNAL); Assertions.assertEquals(TriRpcStatus.INTERNAL.code, TriRpcStatus.getStatus(rpcException).code); }
public synchronized void setLevel(Level newLevel) { if (level == newLevel) { // nothing to do; return; } if (newLevel == null && isRootLogger()) { throw new IllegalArgumentException("The level of the root logger cannot be set to null"); } leve...
@Test public void fluentAPIAtDisabledDebugLevelShouldReturnNOPLoggingEventBuilder() throws Exception { root.setLevel(Level.INFO); LoggingEventBuilder leb = loggerTest.atLevel(org.slf4j.event.Level.DEBUG); assertEquals(NOPLoggingEventBuilder.class, leb.getClass()); }
public static SortOrder buildSortOrder(Table table) { return buildSortOrder(table.schema(), table.spec(), table.sortOrder()); }
@Test public void testSortOrderClusteringSomePartitionFields() { PartitionSpec spec = PartitionSpec.builderFor(SCHEMA).identity("category").day("ts").build(); SortOrder order = SortOrder.builderFor(SCHEMA).withOrderId(1).asc("category").desc("id").build(); SortOrder expected = SortOrder.b...
public CompletableFuture<Void> reserveUsernameHash( final Account account, final byte[] reservedUsernameHash, final Duration ttl) { final Timer.Sample sample = Timer.start(); // if there is an existing old reservation it will be cleaned up via ttl. Save it so we can restore it to the local ...
@Test void switchBetweenReservedUsernameHashes() { final Account account = generateAccount("+18005551111", UUID.randomUUID(), UUID.randomUUID()); createAccount(account); accounts.reserveUsernameHash(account, USERNAME_HASH_1, Duration.ofDays(1)).join(); assertArrayEquals(account.getReservedUsernameHas...
public static List<Long> getLongListOrNull(String property, JsonNode node) { if (!node.has(property) || node.get(property).isNull()) { return null; } return ImmutableList.<Long>builder().addAll(new JsonLongArrayIterator(property, node)).build(); }
@Test public void getLongListOrNull() throws JsonProcessingException { assertThat(JsonUtil.getLongListOrNull("items", JsonUtil.mapper().readTree("{}"))).isNull(); assertThat(JsonUtil.getLongListOrNull("items", JsonUtil.mapper().readTree("{\"items\": null}"))) .isNull(); assertThatThrownBy( ...
@Override public String getNext() { if (alreadyUsed) { throw new KsqlServerException("QueryIdGenerator has not been updated with new offset"); } alreadyUsed = true; return String.valueOf(nextId); }
@Test public void shouldReturnZeroIdForFirstQuery() { assertThat(generator.getNext(), is("0")); }
@Override protected Future<ReconcileResult<Service>> internalUpdate(Reconciliation reconciliation, String namespace, String name, Service current, Service desired) { try { if (current.getSpec() != null && desired.getSpec() != null) { if (("NodePort".equals(current.getSpec().getTy...
@Test void testCattleAnnotationPatching() { KubernetesClient client = mock(KubernetesClient.class); Map<String, String> currentAnnotations = Map.of( "field.cattle.io~1publicEndpoints", "foo", "cattle.io/test", "bar", "some-other", "baz" ); ...
@Override public Iterator<T> iterator() { return new LinkedQueueIterator(Direction.ASCENDING); }
@Test public void testEarlyRemoveFails() { LinkedDeque<Integer> q = new LinkedDeque<>(Arrays.asList(1, 2, 3)); try { q.iterator().remove(); } catch (IllegalStateException e) { // Expected } }
public ClusterAclVersionInfo getBrokerClusterAclInfo(final String addr, final long timeoutMillis) throws RemotingCommandException, InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException { RemotingCommand request = RemotingCommand...
@Test public void assertGetBrokerClusterAclInfo() throws MQBrokerException, RemotingException, InterruptedException { mockInvokeSync(); GetBrokerAclConfigResponseHeader responseHeader = mock(GetBrokerAclConfigResponseHeader.class); when(responseHeader.getBrokerName()).thenReturn(brokerName);...
public String getQuery() throws Exception { return getQuery(weatherConfiguration.getLocation()); }
@Test public void testFindInCircleQuery() throws Exception { WeatherConfiguration weatherConfiguration = new WeatherConfiguration(); weatherConfiguration.setLat(LATITUDE); weatherConfiguration.setLon(LONGITUDE); weatherConfiguration.setCnt(25); weatherConfiguration.setMode(We...
@Override public String getName() { return "dijkstrabi|ch"; }
@Test public void testBaseGraph() { BaseGraph graph = createGHStorage(); RoutingAlgorithmTest.initDirectedAndDiffSpeed(graph, carSpeedEnc); // do CH preparation for car Weighting weighting = new SpeedWeighting(carSpeedEnc); prepareCH(graph, CHConfig.nodeBased(weighting.getNa...
@Override public void handle(TaskEvent event) { if (LOG.isDebugEnabled()) { LOG.debug("Processing " + event.getTaskID() + " of type " + event.getType()); } try { writeLock.lock(); TaskStateInternal oldState = getInternalState(); try { stateMachine.doTransition(eve...
@Test public void testSpeculativeMapFetchFailure() { // Setup a scenario where speculative task wins, first attempt killed mockTask = createMockTask(TaskType.MAP); runSpeculativeTaskAttemptSucceeds(TaskEventType.T_ATTEMPT_KILLED); assertEquals(2, taskAttempts.size()); // speculative attempt retro...
@Override public boolean checkPassword(CharSequence password) { Objects.requireNonNull(password); checkState(keyCrypter != null, () -> "key chain not encrypted"); return checkAESKey(keyCrypter.deriveKey(password)); }
@Test(expected = IllegalStateException.class) public void checkPasswordNoKeys() { chain.checkPassword("test"); }
public void unsetMeta(String key) { metadata.remove(key); }
@Test public void testUnsetMeta() { ZCert cert = new ZCert(); cert.setMeta("version", "1"); cert.unsetMeta("version"); assertThat(cert.getMeta("version"), nullValue()); }