focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void begin() throws SQLException { ConnectionTransaction connectionTransaction = getConnectionTransaction(); if (TransactionType.isDistributedTransaction(connectionTransaction.getTransactionType())) { close(); connectionTransaction.begin(); } connectionCont...
@Test void assertBeginTransaction() throws SQLException { databaseConnectionManager.begin(); assertTrue(databaseConnectionManager.getConnectionContext().getTransactionContext().isInTransaction()); }
public static PrivateKey readPemPrivateKey(InputStream pemStream) { return (PrivateKey) readPemKey(pemStream); }
@Test public void readECPrivateKeyTest() { final PrivateKey privateKey = PemUtil.readPemPrivateKey(ResourceUtil.getStream("test_ec_sec1_private_key.pem")); final SM2 sm2 = new SM2(privateKey, null); sm2.usePlainEncoding(); //需要签名的明文,得到明文对应的字节数组 final byte[] dataBytes = "我是一段测试aaaa".getBytes(StandardCharsets...
public static Collection<SubquerySegment> getSubquerySegments(final SelectStatement selectStatement) { List<SubquerySegment> result = new LinkedList<>(); extractSubquerySegments(result, selectStatement); return result; }
@Test void assertGetSubquerySegmentsInFrom1() { SelectStatement subquery = mock(SelectStatement.class); ColumnSegment left = new ColumnSegment(59, 66, new IdentifierValue("order_id")); LiteralExpressionSegment right = new LiteralExpressionSegment(70, 70, 1); when(subquery.getWhere())...
public static String substVars(String val, PropertyContainer pc1) throws ScanException { return substVars(val, pc1, null); }
@Disabled @Test public void defaultExpansionForEmptyVariables() throws JoranException, ScanException { String varName = "var"+diff; context.putProperty(varName, ""); String r = OptionHelper.substVars("x ${"+varName+":-def} b", context); assertEquals("x def b", r); }
@VisibleForTesting void validateDictTypeUnique(Long id, String type) { if (StrUtil.isEmpty(type)) { return; } DictTypeDO dictType = dictTypeMapper.selectByType(type); if (dictType == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的字典类型 if...
@Test public void testValidateDictTypeUnique_valueDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String type = randomString(); // mock 数据 dictTypeMapper.insert(randomDictTypeDO(o -> o.setType(type))); // 调用,校验异常 assertServiceException(() -> dictType...
public T get(final int index) { if (index < 0 || index >= values.size()) { throw new IndexOutOfBoundsException( String.format( "Attempted to access variadic argument at index %s when only %s " + "arguments are available", index, ...
@Test public void shouldThrowWhenIndexTooLarge() { final VariadicArgs<Integer> varArgs = new VariadicArgs<>(ImmutableList.of(1, 2, 3)); final Exception e = assertThrows( IndexOutOfBoundsException.class, () -> varArgs.get(3) ); assertThat(e.getMessage(), is("Attempted to acces...
@Override public Optional<ShardingConditionValue> generate(final BinaryOperationExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) { String operator = predicate.getOperator().toUpperCase(); if (!isSupportedOperator(operator)) { ...
@Test void assertGenerateConditionValueWithoutNowExpression() { BinaryOperationExpression rightValue = new BinaryOperationExpression(0, 0, mock(ColumnSegment.class), new CommonExpressionSegment(0, 0, "value"), "=", null); assertFalse(generator.generate(rightValue, column, new LinkedList<>(), mock(Ti...
@VisibleForTesting long getDelayMs() { return delayMs; }
@Test public void create_instance_with_default_delay() { AbstractStopRequestWatcher underTest = new AbstractStopRequestWatcher(threadName, booleanSupplier, stopAction) { }; assertThat(underTest.getDelayMs()).isEqualTo(500L); }
static void readFullyHeapBuffer(InputStream f, ByteBuffer buf) throws IOException { readFully(f, buf.array(), buf.arrayOffset() + buf.position(), buf.remaining()); buf.position(buf.limit()); }
@Test public void testHeapReadFullySmallBuffer() throws Exception { ByteBuffer readBuffer = ByteBuffer.allocate(8); MockInputStream stream = new MockInputStream(); DelegatingSeekableInputStream.readFullyHeapBuffer(stream, readBuffer); Assert.assertEquals(8, readBuffer.position()); Assert.assertE...
static Map<String, Object> of(final Task task) { return Map.of( "id", task.getId(), "type", task.getType() ); }
@Test void shouldGetVariablesGivenFlowWithNoTenant() { Map<String, Object> variables = new RunVariables.DefaultBuilder() .withFlow(Flow .builder() .id("id-value") .namespace("namespace-value") .revision(42) .build() ...
public static Map<AbilityKey, Boolean> getStaticAbilities() { return INSTANCE.getSupportedAbilities(); }
@Test void testSupportPersistentInstanceByGrpcAbilities() { assertTrue(ServerAbilities.getStaticAbilities().get(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); }
public Iterator<Entry<String, Optional<MetaProperties>>> nonFailedDirectoryProps() { return new Iterator<Entry<String, Optional<MetaProperties>>>() { private final Iterator<String> emptyLogDirsIterator = emptyLogDirs.iterator(); private final Iterator<Entry<String, MetaProperties>> logDi...
@Test public void testNonFailedDirectoryPropsForEmpty() { assertFalse(EMPTY.nonFailedDirectoryProps().hasNext()); }
@Override public List<RemoteFileInfo> getRemoteFiles(Table table, GetRemoteFilesParams params) { List<Partition> partitions = buildGetRemoteFilesPartitions(table, params); boolean useCache = true; if (table instanceof HiveTable) { useCache = ((HiveTable) table).isUseMetadataCach...
@Test public void testGetRemoteFiles( @Mocked HiveTable table, @Mocked HiveMetastoreOperations hmsOps) { List<String> partitionNames = Lists.newArrayList("dt=20200101", "dt=20200102", "dt=20200103"); Map<String, Partition> partitionMap = Maps.newHashMap(); for (String...
public static void main(String[] args) { // Getting the bar series BarSeries series = CsvTradesLoader.loadBitstampSeries(); // Building the trading strategy Strategy strategy = buildStrategy(series); // Running the strategy BarSeriesManager seriesManager = new BarSerie...
@Test public void test() { MovingMomentumStrategy.main(null); }
static boolean unprotectedSetOwner( FSDirectory fsd, INodesInPath iip, String username, String groupname) throws FileNotFoundException, UnresolvedLinkException, QuotaExceededException, SnapshotAccessControlException { assert fsd.hasWriteLock(); final INode inode = FSDirectory.resolveLastINode(...
@Test public void testUnprotectedSetOwner() throws Exception { assertTrue("SetOwner should return true for a new user", unprotectedSetAttributes((short) 0777, (short) 0777, "user1", "user2", true)); assertFalse("SetOwner should return false for same user", unprotectedSetAttributes(...
public static String detectWithCustomConfig(String name) throws Exception { String config = "/org/apache/tika/mime/tika-mimetypes.xml"; Tika tika = new Tika(MimeTypesFactory.create(config)); return tika.detect(name); }
@Test public void testDetectWithCustomConfig() throws Exception { assertEquals("application/xml", AdvancedTypeDetector.detectWithCustomConfig("pom.xml")); }
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldFixScaleWhenDeserializingDecimalsWithTooSmallAScale() { // Given: final KsqlJsonDeserializer<BigDecimal> deserializer = givenDeserializerForSchema(DecimalUtil.builder(4, 3).build(), BigDecimal.class); final byte[] bytes = addMagic("1.1".getBytes(UTF_8)); // When: ...
@Description("test if value is finite") @ScalarFunction @SqlType(StandardTypes.BOOLEAN) public static boolean isFinite(@SqlType(StandardTypes.DOUBLE) double num) { return Doubles.isFinite(num); }
@Test public void testIsFinite() { assertFunction("is_finite(100000)", BOOLEAN, true); assertFunction("is_finite(rand() / 0.0E0)", BOOLEAN, false); assertFunction("is_finite(REAL '754.2008E0')", BOOLEAN, true); assertFunction("is_finite(rand() / REAL '0.0E0')", BOOLEAN, false); ...
@Override public Connection getConnection() { return new CircuitBreakerConnection(); }
@Test void assertGetConnection() { assertThat(dataSource.getConnection(), instanceOf(CircuitBreakerConnection.class)); assertThat(dataSource.getConnection("", ""), instanceOf(CircuitBreakerConnection.class)); }
@Override public void authenticate( final JsonObject authInfo, final Handler<AsyncResult<User>> resultHandler ) { final String username = authInfo.getString("username"); if (username == null) { resultHandler.handle(Future.failedFuture("authInfo missing 'username' field")); return; ...
@Test public void shouldFailToAuthenticateWithNonAllowedRole() throws Exception { // Given: givenAllowedRoles("user"); givenUserRoles("other"); // When: authProvider.authenticate(authInfo, userHandler); // Then: verifyUnauthorizedSuccessfulLogin(); }
@Override public byte[] encode(ILoggingEvent event) { var baos = new ByteArrayOutputStream(); try (var generator = jsonFactory.createGenerator(baos)) { generator.writeStartObject(); // https://cloud.google.com/logging/docs/structured-logging#structured_logging_special_fields // https://gith...
@Test void encode_fallback() { var e = mockEvent(); doThrow(NullPointerException.class).when(e).getKeyValuePairs(); var msg = encoder.encode(e); assertMatchesJson( """ {"message":"error serializing log record: null","serviceContext":{"service":"","version":""},"severity":"ERRO...
public static Element getUniqueDirectChild(Element parent, String namespace, String tag) throws MalformedXmlException { NodeList children = parent.getElementsByTagNameNS(namespace, tag); if (children.getLength() == 0) { throw new MalformedXmlException("Element " + tag + " is missing under ...
@Test void getUniqueDirectChild() { assertThrows(MalformedXmlException.class, () -> { XmlUtil.getUniqueDirectChild(parent, "http://example.com", "child1"); }); Element uniqueChild = document.createElementNS("http://example.com", "uniqueChild"); parent.appendChild(uniqueChild); ...
public static Timer getRaftApplyLogTimer() { return RAFT_APPLY_LOG_TIMER; }
@Test void testRaftApplyLogTimer() { Timer raftApplyTimerLog = MetricsMonitor.getRaftApplyLogTimer(); raftApplyTimerLog.record(10, TimeUnit.SECONDS); raftApplyTimerLog.record(20, TimeUnit.SECONDS); assertEquals(0.5D, raftApplyTimerLog.totalTime(TimeUnit.MINUTES), 0.01); ...
public String readStringEOF() { byte[] result = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(result); return new String(result, charset); }
@Test void assertReadStringEOF() { when(byteBuf.readableBytes()).thenReturn(0); assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readStringEOF(), is("")); }
public static String decimalFormat(String pattern, double value) { Assert.isTrue(isValid(value), "value is NaN or Infinite!"); return new DecimalFormat(pattern).format(value); }
@Test public void decimalFormatDoubleTest() { final Double c = 467.8101; final String format = NumberUtil.decimalFormat("0.00", c); assertEquals("467.81", format); }
@Override public String save(AccessToken accessToken) throws ValidationException { return super.save(encrypt(accessToken)); }
@Test public void testSave() throws Exception { final String username = "admin"; final String tokenname = "web"; final String tokenString = "foobar"; assertNull(accessTokenService.load(tokenString)); assertEquals(0, accessTokenService.loadAll(username).size()); fina...
@Override public void notify(Metrics metrics) { WithMetadata withMetadata = (WithMetadata) metrics; MetricsMetaInfo meta = withMetadata.getMeta(); int scope = meta.getScope(); if (!DefaultScopeDefine.inServiceCatalog(scope) && !DefaultScopeDefine.inServiceInstanceCatalog(scope) ...
@Test public void testNotifyWithServiceCatalog() { String metricsName = "service-metrics"; when(metadata.getMetricsName()).thenReturn(metricsName); when(DefaultScopeDefine.inServiceCatalog(0)).thenReturn(true); final String serviceId = IDManager.ServiceID.buildId("service", true); ...
public void removeData(Service service) { serviceDataIndexes.remove(service); serviceClusterIndex.remove(service); }
@Test void testRemoveData() throws NoSuchFieldException, IllegalAccessException { serviceStorage.removeData(SERVICE); Field serviceClusterIndex = ServiceStorage.class.getDeclaredField("serviceClusterIndex"); serviceClusterIndex.setAccessible(true); ConcurrentMap<Service, Set...
public boolean supportsFileAttributeView(Class<? extends FileAttributeView> type) { return providersByViewType.containsKey(type); }
@Test public void testSupportsFileAttributeView() { assertThat(service.supportsFileAttributeView(BasicFileAttributeView.class)).isTrue(); assertThat(service.supportsFileAttributeView(TestAttributeView.class)).isTrue(); assertThat(service.supportsFileAttributeView(PosixFileAttributeView.class)).isFalse(); ...
@Override public AdminUserDO authenticate(String username, String password) { final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME; // 校验账号是否存在 AdminUserDO user = userService.getUserByUsername(username); if (user == null) { createLoginLog(null, username, l...
@Test public void testAuthenticate_success() { // 准备参数 String username = randomString(); String password = randomString(); // mock user 数据 AdminUserDO user = randomPojo(AdminUserDO.class, o -> o.setUsername(username) .setPassword(password).setStatus(CommonStat...
public void completeTx(SendRequest req) throws InsufficientMoneyException, CompletionException { lock.lock(); try { checkArgument(!req.completed, () -> "given SendRequest has already been completed"); log.info("Completing send tx with {} outputs totalling {} ...
@Test(expected = Wallet.ExceededMaxTransactionSize.class) public void respectMaxStandardSize() throws Exception { // Check that we won't create txns > 100kb. Average tx size is ~220 bytes so this would have to be enormous. sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(100, 0)...
@UdafFactory(description = "Build a value-to-count histogram of input Strings") public static TableUdaf<String, Map<String, Long>, Map<String, Long>> histogramString() { return histogram(); }
@Test public void shouldUndoCountedValues() { final TableUdaf<String, Map<String, Long>, Map<String, Long>> udaf = HistogramUdaf.histogramString(); Map<String, Long> agg = udaf.initialize(); final Boolean[] values = new Boolean[] {true, true, false, null, true}; for (final Boolean thisValue : values) ...
public static Color colorLerp(final Color a, final Color b, final double t) { final double r1 = a.getRed(); final double r2 = b.getRed(); final double g1 = a.getGreen(); final double g2 = b.getGreen(); final double b1 = a.getBlue(); final double b2 = b.getBlue(); final double a1 = a.getAlpha(); final d...
@Test public void colorLerp() { assertEquals(Color.WHITE, ColorUtil.colorLerp(Color.WHITE, Color.WHITE, 0.9)); assertEquals(new Color(128, 128, 128), ColorUtil.colorLerp(Color.BLACK, Color.WHITE, 0.5)); assertEquals(Color.BLACK, ColorUtil.colorLerp(Color.BLACK, Color.CYAN, 0)); assertEquals(Color.CYAN, ColorU...
public static String buildURIFromPattern(String pattern, List<Parameter> parameters) { if (parameters != null) { // Browse parameters and choose between template or query one. for (Parameter parameter : parameters) { String wadlTemplate = "{" + parameter.getName() + "}"; ...
@Test void testBuildURIFromPatternWithMap() { // Prepare a bunch of parameters. Map<String, String> parameters = new HashMap<>(); parameters.put("year", "2018"); parameters.put("month", "05"); parameters.put("status", "published"); parameters.put("page", "0"); // Test with ...
public static DataSourceProvider tryGetDataSourceProviderOrNull(Configuration hdpConfig) { final String configuredPoolingType = MetastoreConf.getVar(hdpConfig, MetastoreConf.ConfVars.CONNECTION_POOLING_TYPE); return Iterables.tryFind(FACTORIES, factory -> { String poolingType = factory.getPoolingT...
@Test public void testSetHikariCpLeakDetectionThresholdProperty() throws SQLException { MetastoreConf.setVar(conf, ConfVars.CONNECTION_POOLING_TYPE, HikariCPDataSourceProvider.HIKARI); conf.set(HikariCPDataSourceProvider.HIKARI + ".leakDetectionThreshold", "3600"); conf.set(HikariCPDataSourceProvider.HIK...
DataTableType lookupTableTypeByType(Type type) { return lookupTableTypeByType(type, Function.identity()); }
@Test void null_long_transformed_to_null() { DataTableTypeRegistry registry = new DataTableTypeRegistry(Locale.ENGLISH); DataTableType dataTableType = registry.lookupTableTypeByType(LIST_OF_LIST_OF_LONG); assertEquals( singletonList(singletonList(null)), dataTableType...
@GetMapping( path = "/api/{namespace}/{extension}", produces = MediaType.APPLICATION_JSON_VALUE ) @CrossOrigin @Operation(summary = "Provides metadata of the latest version of an extension") @ApiResponses({ @ApiResponse( responseCode = "200", description =...
@Test public void testPreReleaseExtensionVersionWebTarget() throws Exception { var extVersion = mockExtension("web"); extVersion.setPreRelease(true); extVersion.setDisplayName("Foo Bar (web)"); Mockito.when(repositories.findExtensionVersion("foo", "bar", "web", VersionAlias.PRE_RELEA...
@Override public Boolean run(final Session<?> session) throws BackgroundException { final Metadata feature = session.getFeature(Metadata.class); if(log.isDebugEnabled()) { log.debug(String.format("Run with feature %s", feature)); } for(Path file : files) { if(...
@Test public void testRunEmpty() throws Exception { final List<Path> files = new ArrayList<>(); WriteMetadataWorker worker = new WriteMetadataWorker(files, Collections.emptyMap(), false, new DisabledProgressListener()) { @Override public void cleanup(final Boolean result) { ...
@Override public Map<String, Object> toElasticSearchObject(ObjectMapper objectMapper, @Nonnull final Meter invalidTimestampMeter) { final Map<String, Object> obj = Maps.newHashMapWithExpectedSize(REQUIRED_FIELDS.size() + fields.size()); for (Map.Entry<String, Object> entry : fields.entrySet()) { ...
@Test public void testToElasticsearchObjectAddsAccountedMessageSize() { final Message message = new Message("message", "source", Tools.nowUTC()); assertThat(message.toElasticSearchObject(objectMapper, invalidTimestampMeter).get("gl2_accounted_message_size")) .isEqualTo(43L); }
public static ElasticAgentRuntimeInfo fromAgent(AgentIdentifier identifier, AgentRuntimeStatus runtimeStatus, String workingDir, String elasticAgentId, String pluginId, String agentBootstrapperVersion, String agentVe...
@Test public void shouldRefreshOperatingSystemOfAgent() { AgentIdentifier identifier = new AgentIdentifier("local.in", "127.0.0.1", "uuid-1"); AgentRuntimeInfo runtimeInfo = ElasticAgentRuntimeInfo.fromAgent(identifier, AgentRuntimeStatus.Idle, "/tmp/foo", "20.3.0-1234", "20.5.0-2345", TEST_OS_SUPPL...
public void executeInNonInteractiveMode(String content) { try { terminal = terminalFactory.get(); executeFile(content, terminal.output(), ExecutionMode.NON_INTERACTIVE_EXECUTION); } finally { closeTerminal(); } }
@Test void testCancelExecutionInNonInteractiveMode() throws Exception { // add "\n" with quit to trigger commit the line final List<String> statements = Arrays.asList( "HELP;", "CREATE TABLE tbl( -- comment\n" ...
@Deprecated public DomainNameMapping<V> add(String hostname, V output) { map.put(normalizeHostname(checkNotNull(hostname, "hostname")), checkNotNull(output, "output")); return this; }
@Test public void testNullValuesAreForbiddenInDeprecatedApi() { assertThrows(NullPointerException.class, new Executable() { @Override public void execute() { new DomainNameMapping<String>("NotFound").add("Some key", null); } }); }
@Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); }
@Test public void testGetParentLogger() throws SQLFeatureNotSupportedException { assertNotNull("getParentLogger", driver.getParentLogger()); }
public static RelativeUnixPath get(String relativePath) { if (relativePath.startsWith("/")) { throw new IllegalArgumentException("Path starts with forward slash (/): " + relativePath); } return new RelativeUnixPath(UnixPathParser.parse(relativePath)); }
@Test public void testGet_absolute() { try { RelativeUnixPath.get("/absolute"); Assert.fail(); } catch (IllegalArgumentException ex) { Assert.assertEquals("Path starts with forward slash (/): /absolute", ex.getMessage()); } }
@PUT @Path("{noteId}/revision/{revisionId}") @ZeppelinApi public Response setNoteRevision(@PathParam("noteId") String noteId, @PathParam("revisionId") String revisionId) throws IOException { LOGGER.info("Revert note {} to the revision {}", noteId, revisionId); notebookSer...
@Test void testSetNoteRevision() throws IOException { LOG.info("Running testSetNoteRevision"); String note1Id = null; try { String notePath = "note1"; note1Id = notebook.createNote(notePath, anonymous); //Add a paragraph and commit NotebookRepoWithVersionControl.Revision first_com...
public String transform() throws ScanException { StringBuilder stringBuilder = new StringBuilder(); compileNode(node, stringBuilder, new Stack<Node>()); return stringBuilder.toString(); }
@Test public void loneColonShouldReadLikeAnyOtherCharacter() throws ScanException { String input = "java:comp/env/jdbc/datasource"; Node node = makeNode(input); NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); assertEquals(input, nodeToStringTran...
public static <T> NavigableSet<Point<T>> slowKNearestPoints(Collection<? extends Point<T>> points, Instant time, int k) { checkNotNull(points, "The input collection of Points cannot be null"); checkNotNull(time, "The input time cannot be null"); checkArgument(k >= 0, "k (" + k + ") must be non-n...
@Test public void testKNearestPointsWithGenericInputs() { /* * This test confirms that the signature of kNearestPoints will accept any Collection<T> * where T is some arbitrary class that implements Point */ List<Point<NopHit>> listOfPoints = newArrayList(); Navig...
void start(Iterable<ShardCheckpoint> checkpoints) { LOG.info( "Pool {} - starting for stream {} consumer {}. Checkpoints = {}", poolId, read.getStreamName(), consumerArn, checkpoints); for (ShardCheckpoint shardCheckpoint : checkpoints) { checkState( !stat...
@Test public void poolReSubscribesAndReadsRecordsAfterCheckPointWithPositiveSubSeqNumber() throws Exception { kinesis = new EFOStubbedKinesisAsyncClient(10); kinesis.stubSubscribeToShard("shard-000", eventWithRecords(3)); kinesis.stubSubscribeToShard("shard-001", eventWithRecords(11, 3)); Kines...
public ApolloAuditTracer tracer() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes != null) { Object tracer = requestAttributes.getAttribute(ApolloAuditConstants.TRACER, RequestAttributes.SCOPE_REQUEST); if (tracer != null) { ...
@Test public void testGetTracerNotInRequestThread() { ApolloAuditTracer get = traceContext.tracer(); assertNull(get); }
@Override public void route(final RouteContext routeContext, final SingleRule singleRule) { if (routeContext.getRouteUnits().isEmpty() || sqlStatement instanceof SelectStatement) { routeStatement(routeContext, singleRule); } else { RouteContext newRouteContext = new RouteCont...
@Test void assertRouteIfNotExistsDuplicateSingleTable() { SingleStandardRouteEngine engine = new SingleStandardRouteEngine(Collections.singleton(new QualifiedTable(DefaultDatabase.LOGIC_NAME, "t_order")), mockStatement(true)); assertDoesNotThrow(() -> engine.route(new RouteContext(), mockSingleRule(...
public static FromMatchesFilter createFull(Jid address) { return new FromMatchesFilter(address, false); }
@Test public void fullCompareMatchingEntityFullJid() { FromMatchesFilter filter = FromMatchesFilter.createFull(FULL_JID1_R1); Stanza packet = StanzaBuilder.buildMessage().build(); packet.setFrom(FULL_JID1_R1); assertTrue(filter.accept(packet)); packet.setFrom(BASE_JID1); ...
public LoggerContextListener enableJulChangePropagation(LoggerContext loggerContext) { LogManager.getLogManager().reset(); SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); LevelChangePropagator propagator = new LevelChangePropagator(); propagator.setContext(loggerCont...
@Test public void enableJulChangePropagation() { LoggerContext ctx = underTest.getRootContext(); int countListeners = ctx.getCopyOfListenerList().size(); LoggerContextListener propagator = underTest.enableJulChangePropagation(ctx); assertThat(ctx.getCopyOfListenerList()).hasSize(countListeners + 1); ...
static String[] getListFromProperty(Map<String, String> properties, String key) { String propValue = properties.get(key); if (propValue != null) { return parseAsCsv(key, propValue); } return new String[0]; }
@Test public void shouldGetEmptyList() { Map<String, String> props = new HashMap<>(); props.put("prop", ""); assertThat(ProjectReactorBuilder.getListFromProperty(props, "prop")).isEmpty(); }
@Override public boolean supportsMinimumSQLGrammar() { return false; }
@Test void assertSupportsMinimumSQLGrammar() { assertFalse(metaData.supportsMinimumSQLGrammar()); }
protected String decrypt(String encryptedStr) throws Exception { String[] split = encryptedStr.split(":"); checkTrue(split.length == 3, "Wrong format of the encrypted variable (" + encryptedStr + ")"); byte[] salt = Base64.getDecoder().decode(split[0].getBytes(StandardCharsets.UTF_8)); c...
@Test(expected = IllegalArgumentException.class) public void testDecryptionFailWithEmptyPassword() throws Exception { assumeDefaultAlgorithmsSupported(); AbstractPbeReplacer replacer = createAndInitReplacer("", new Properties()); replacer.decrypt("aSalt1xx:1:test"); }
@Override public State getState() { return State.DONE; }
@Test public void testPipelineResultReturnsDone() { FlinkRunnerResult result = new FlinkRunnerResult(Collections.emptyMap(), 100); assertThat(result.getState(), is(PipelineResult.State.DONE)); }
@Override public ByteBuf writeMedium(int value) { ensureWritable0(3); _setMedium(writerIndex, value); writerIndex += 3; return this; }
@Test public void testWriteMediumAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().writeMedium(1); } }); }
public static Date getDateNowPlusDays(int days) throws ParseException { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, days); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String dateStr = dateFormat.format(calendar.getTime()); return ...
@Test public void testGetDateNowPlusDays() throws ParseException { Assertions.assertNotNull(DateUtil.getDateNowPlusDays(2)); }
public MappedFile createFile(final long physicalOffset) throws IOException { // cache max offset return mappedFileQueue.tryCreateMappedFile(physicalOffset); }
@Test public void testCreateFile() throws IOException { scq = new SparseConsumeQueue(topic, queueId, path, BatchConsumeQueue.CQ_STORE_UNIT_SIZE, defaultMessageStore); long physicalOffset = Math.abs(ThreadLocalRandom.current().nextLong()); String formatName = UtilAll.offset2FileName(physicalO...
public static void main(String[] args) { // Getting a bar series (from any provider: CSV, web service, etc.) BarSeries series = CsvTradesLoader.loadBitstampSeries(); // Getting the close price of the bars Num firstClosePrice = series.getBar(0).getClosePrice(); System.out.printl...
@Test public void test() { Quickstart.main(null); }
public static Schema schemaFromPojoClass( TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) { return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier); }
@Test public void testNestedCollection() { Schema schema = POJOUtils.schemaFromPojoClass( new TypeDescriptor<NestedCollectionPOJO>() {}, JavaFieldTypeSupplier.INSTANCE); SchemaTestUtils.assertSchemaEquivalent(NESTED_COLLECTION_POJO_SCHEMA, schema); }
@Override public <T extends ComponentRoot> T get(Class<T> providerId) { try { return providerId.getConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException(e); } }
@Test void getPrivateConstructorImplementation() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> appRoot.get(ComponentRootPrivateConstructor.class), "Expected constructor to throw, but it didn't" ); Strin...
public static WebService.NewParam createQualifiersParameter(WebService.NewAction action, QualifierParameterContext context) { return createQualifiersParameter(action, context, getAllQualifiers(context.getResourceTypes())); }
@Test public void createQualifiersParameter_whenIgnoreIsSetToTrue_shouldNotReturnQualifier(){ when(resourceTypes.getAll()).thenReturn(asList(Q1, Q2,ResourceType.builder("Q3").setProperty("ignored", true).build())); when(newAction.createParam(PARAM_QUALIFIERS)).thenReturn(newParam); when(newParam.setPossib...
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldThrowIfColumnDoesNotExistInSchema() { // Given: givenSourceStreamWithSchema(SINGLE_VALUE_COLUMN_SCHEMA, SerdeFeatures.of(), SerdeFeatures.of()); final ConfiguredStatement<InsertValues> statement = givenInsertValues( ImmutableList.of( K0, ColumnName....
public void contains(@Nullable CharSequence string) { checkNotNull(string); if (actual == null) { failWithActual("expected a string that contains", string); } else if (!actual.contains(string)) { failWithActual("expected to contain", string); } }
@Test public void stringContainsCharSeq() { CharSequence charSeq = new StringBuilder("c"); assertThat("abc").contains(charSeq); }
@Override public @Nullable V replace(K key, V value) { requireNonNull(key); requireNonNull(value); int[] oldWeight = new int[1]; @SuppressWarnings("unchecked") K[] nodeKey = (K[]) new Object[1]; @SuppressWarnings("unchecked") V[] oldValue = (V[]) new Object[1]; long[] now = new long[1...
@CheckMaxLogLevel(ERROR) @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, keys = ReferenceType.STRONG) public void brokenEquality_replace( BoundedLocalCache<MutableInt, Int> cache, CacheContext context) { testForBrokenEquality(cache, context, key -> { var value = cache.repl...
public <T> Future<Iterable<TimestampedValue<T>>> orderedListFuture( Range<Long> range, ByteString encodedTag, String stateFamily, Coder<T> elemCoder) { // First request has no continuation position. StateTag<ByteString> stateTag = StateTag.<ByteString>of(StateTag.Kind.ORDERED_LIST, encodedTag, sta...
@Test public void testReadSortedList() throws Exception { long beginning = SortedListRange.getDefaultInstance().getStart(); long end = SortedListRange.getDefaultInstance().getLimit(); Future<Iterable<TimestampedValue<Integer>>> future = underTest.orderedListFuture( Range.closedOpen(beg...
@SuppressWarnings("MethodLength") public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header) { messageHeaderDecoder.wrap(buffer, offset); final int templateId = messageHeaderDecoder.templateId(); final int schemaId = messageHeaderDecoder.s...
@Test void onFragmentShouldInvokeOnNewLeaderCallbackIfSessionIdMatches() { final int offset = 0; final long clusterSessionId = 0; final long leadershipTermId = 6; final int leaderMemberId = 9999; final String ingressEndpoints = "ingress endpoints ..."; newLeaderEv...
public static List<Method> getAllMethods(Class clazz) { List<Method> all = new ArrayList<Method>(); for (Class<?> c = clazz; c != Object.class && c != null; c = c.getSuperclass()) { Method[] methods = c.getDeclaredMethods(); // 所有方法,不包含父类 for (Method method : methods) { ...
@Test public void getAllMethods() throws Exception { List<Method> methods = ClassUtils.getAllMethods(TestBean.class); Assert.assertTrue(methods.size() >= 8); }
void writeLogs(OutputStream out, Instant from, Instant to, long maxLines, Optional<String> hostname) { double fromSeconds = from.getEpochSecond() + from.getNano() / 1e9; double toSeconds = to.getEpochSecond() + to.getNano() / 1e9; long linesWritten = 0; BufferedWriter writer = new Buffer...
@EnabledIf("hasZstdcat") @Test void testThatLogsOutsideRangeAreExcluded() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*")); logReader.writeLogs(baos, Instant.ofEpochMilli(150), Instant.ofEpochMilli(360105...
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test @SuppressWarnings("unchecked") public void testDecodeStaticStructDynamicArray() { String rawInput = "0x0000000000000000000000000000000000000000000000000000000000000020" + "0000000000000000000000000000000000000000000000000000000000000002" ...
@Override public ProxyInvocationHandler parserInterfaceToProxy(Object target, String objectName) throws Exception { Class<?> serviceInterface = DefaultTargetClassParser.get().findTargetClass(target); Class<?>[] interfacesIfJdk = DefaultTargetClassParser.get().findInterfaces(target); if (exi...
@Test void parserInterfaceToProxy() throws Exception { //given BusinessImpl business = new BusinessImpl(); GlobalTransactionalInterceptorParser globalTransactionalInterceptorParser = new GlobalTransactionalInterceptorParser(); //when ProxyInvocationHandler proxyInvocationH...
@Override public PageResult<ProductSpuDO> getSpuPage(ProductSpuPageReqVO pageReqVO) { return productSpuMapper.selectPage(pageReqVO); }
@Test void getSpuPage_alarmStock_empty() { // 准备参数 ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{ o.setCategoryId(generateId()); o.setBrandId(generateId()); o.setDeliveryTemplateId(generateId()); o.setSort(...
@Override public void doRun() { if (versionOverride.isPresent()) { LOG.debug("Elasticsearch version is set manually. Not running check."); return; } final Optional<SearchVersion> probedVersion = this.versionProbe.probe(this.elasticsearchHosts); probedVersion...
@Test void fixesNotificationIfCurrentVersionIsIncompatibleWithInitialOne() { returnProbedVersion(Version.of(8, 2, 3)); createPeriodical(SearchVersion.elasticsearch(8, 1, 2)).doRun(); assertNotificationWasFixed(); }
@Nonnull public HazelcastInstance getClient() { if (getConfig().isShared()) { retain(); return proxy.get(); } else { return HazelcastClient.newHazelcastClient(clientConfig); } }
@Test public void shared_client_from_file_should_return_same_instance() { DataConnectionConfig dataConnectionConfig = sharedDataConnectionConfigFromFile(clusterName); hazelcastDataConnection = new HazelcastDataConnection(dataConnectionConfig); HazelcastInstance c1 = hazelcastDataConnection.g...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AlluxioWorkerInfo)) { return false; } AlluxioWorkerInfo that = (AlluxioWorkerInfo) o; return Objects.equal(mCapacity, that.mCapacity) && Objects.equal(mConfiguration, that.mConfig...
@Test public void equals() { alluxio.test.util.CommonUtils.testEquals(AlluxioMasterInfo.class); }
@Override public void unlinkNode(K parentKey, K childKey) { final TreeEntryNode<K, V> childNode = nodes.get(childKey); if (ObjectUtil.isNull(childNode)) { return; } if (childNode.hasParent()) { childNode.getDeclaredParent().removeDeclaredChild(childNode.getKey()); } }
@Test public void unlinkNodeTest() { final ForestMap<String, String> map = new LinkedForestMap<>(false); map.linkNodes("a", "b"); final TreeEntry<String, String> parent = map.get("a"); final TreeEntry<String, String> child = map.get("b"); map.unlinkNode("a", "b"); assertFalse(child.hasParent()); assertFa...
public static ValidateTopicResult validateTopic(String topic) { if (UtilAll.isBlank(topic)) { return new ValidateTopicResult(false, "The specified topic is blank."); } if (isTopicOrGroupIllegal(topic)) { return new ValidateTopicResult(false, "The specified topic contain...
@Test public void testTopicValidator_NotPass() { TopicValidator.ValidateTopicResult res = TopicValidator.validateTopic(""); assertThat(res.isValid()).isFalse(); assertThat(res.getRemark()).contains("The specified topic is blank"); res = TopicValidator.validateTopic("../TopicTest"); ...
int getDictionaryId(String word) throws LongWordException { requireNonNull(word); if (word.length() > MAX_WORD_LENGTH) { throw new LongWordException("Too long value in the metric descriptor found, maximum is " + MAX_WORD_LENGTH + ": " + word); } int nextW...
@Test public void when_tooLongWord_then_fails() { String longWord = Stream.generate(() -> "a") .limit(MetricsDictionary.MAX_WORD_LENGTH + 1) .collect(Collectors.joining()); assertThrows(LongWordException.class, () -> dictionary.getDicti...
public static FuryBuilder builder() { return new FuryBuilder(); }
@Test public void testPrintReadObjectsWhenFailed() { Fury fury = Fury.builder() .withRefTracking(true) .withCodegen(false) .requireClassRegistration(false) .build(); PrintReadObject o = new PrintReadObject(true); try { serDe(fury, ImmutableList...
@VisibleForTesting public static <OUT> RecordWriterDelegate<SerializationDelegate<StreamRecord<OUT>>> createRecordWriterDelegate( StreamConfig configuration, Environment environment) { List<RecordWriter<SerializationDelegate<StreamRecord<OUT>>>> re...
@Test void testForwardPartitionerIsConvertedToRebalanceOnParallelismChanges() throws Exception { StreamTaskMailboxTestHarnessBuilder<Integer> builder = new StreamTaskMailboxTestHarnessBuilder<>( OneInputStreamTask::new, BasicTypeInfo.INT_TYPE_INFO) ...
@Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { return inject(statement, new TopicProperties.Builder()); }
@SuppressWarnings("unchecked") @Test public void shouldBuildWithClauseWithTopicProperties() { // Given: givenStatement("CREATE STREAM x WITH (kafka_topic='topic') AS SELECT * FROM SOURCE;"); when(builder.build()).thenReturn(new TopicProperties("expectedName", 10, (short) 10, (long) 5000)); // When...
public static Comparator<BaseOptionModel> createGroupAndLabelComparator() { return new EndpointOptionGroupAndLabelComparator(); }
@Test public void testSort2() throws IOException { final String json = PackageHelper.loadText(new File( Objects.requireNonNull(getClass().getClassLoader().getResource("json/test_component4.json")).getFile())); final ComponentModel componentModel = JsonMapper.generateComponentModel(js...
@ExecuteOn(TaskExecutors.IO) @Post(uri = "validate", consumes = MediaType.APPLICATION_YAML) @Operation(tags = {"Flows"}, summary = "Validate a list of flows") public List<ValidateConstraintViolation> validateFlows( @Parameter(description = "A list of flows") @Body String flows ) { Atomic...
@Test void validateFlows() throws IOException { URL resource = TestsUtils.class.getClassLoader().getResource("flows/validateMultipleValidFlows.yaml"); String flow = Files.readString(Path.of(Objects.requireNonNull(resource).getPath()), Charset.defaultCharset()); String firstFlowSource = flow...
public void recordSendOffsets(long duration) { sendOffsetsSensor.record(duration); }
@Test public void shouldRecordSendOffsetsTime() { // When: producerMetrics.recordSendOffsets(METRIC_VALUE); // Then: assertMetricValue(TXN_SEND_OFFSETS_TIME_TOTAL); }
public static CoordinatorRecord newConsumerGroupMemberSubscriptionRecord( String groupId, ConsumerGroupMember member ) { List<String> topicNames = new ArrayList<>(member.subscribedTopicNames()); Collections.sort(topicNames); return new CoordinatorRecord( new ApiMe...
@Test public void testNewConsumerGroupMemberSubscriptionRecord() { List<ConsumerGroupMemberMetadataValue.ClassicProtocol> protocols = new ArrayList<>(); protocols.add(new ConsumerGroupMemberMetadataValue.ClassicProtocol() .setName("range") .setMetadata(new byte[0])); ...
@Operation(summary = "start new activation session with other app", tags = { SwaggerConfig.ACTIVATE_WITH_APP }, operationId = "app_activate_start", parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter(ref = "OS-V"), @Parameter(ref = "REL-T")}) @GetMapping(...
@Test void validateIfCorrectProcessesAreCalledWithOtherApp() throws FlowNotDefinedException, NoSuchAlgorithmException, FlowStateNotDefinedException, IOException, SharedServiceClientException { activationController.startActivateWithOtherApp(); verify(flowService, times(1)).startFlow(ActivateAppWithO...
public static <T> RemoteIterator<T> remoteIteratorFromSingleton( @Nullable T singleton) { return new SingletonIterator<>(singleton); }
@Test public void testSingleton() throws Throwable { StringBuilder result = new StringBuilder(); String name = "singleton"; RemoteIterator<String> it = remoteIteratorFromSingleton(name); assertStringValueContains(it, "SingletonIterator"); assertStringValueContains(it, name); verifyInvoked( ...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { final PathContainerService service = new DefaultPathContainerService(); if(service.isContainer(file)) { for(RootFolder r : session.roots()) { ...
@Test public void testDefaultPaths() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); for(Path container : new StoregateListService(session, nodeid).list(Home.ROOT, new DisabledListProgressListener())) { assertEquals(container.attributes(), new Stor...
public static UUnary create(Kind unaryOp, UExpression expression) { checkArgument( UNARY_OP_CODES.containsKey(unaryOp), "%s is not a recognized unary operation", unaryOp); return new AutoValue_UUnary(unaryOp, expression); }
@Test public void preIncrement() { assertUnifiesAndInlines("++foo", UUnary.create(Kind.PREFIX_INCREMENT, fooIdent)); }
public static boolean checkPermission(byte neededPerm, byte ownedPerm) { if ((ownedPerm & DENY) > 0) { return false; } if ((neededPerm & ANY) > 0) { return (ownedPerm & PUB) > 0 || (ownedPerm & SUB) > 0; } return (neededPerm & ownedPerm) > 0; }
@Test public void checkPermissionTest() { boolean boo = Permission.checkPermission(Permission.DENY, Permission.DENY); Assert.assertFalse(boo); boo = Permission.checkPermission(Permission.PUB, Permission.PUB); Assert.assertTrue(boo); boo = Permission.checkPermission(Permissi...
public Set<Analysis.AliasedDataSource> extractDataSources(final AstNode node) { new Visitor().process(node, null); return getAllSources(); }
@Test public void shouldHandleAliasedJoinDataSources() { // Given: final AstNode stmt = givenQuery("SELECT * FROM TEST1 t1 JOIN TEST2 t2" + " ON test1.col1 = test2.col1;"); // When: extractor.extractDataSources(stmt); // Then: assertContainsAlias(T1, T2); }
@Override @Nullable public String errorCode() { if (status.isOk()) return null; return status.getCode().name(); }
@Test void errorCode() { assertThat(response.errorCode()).isEqualTo("CANCELLED"); }
ClassicGroup getOrMaybeCreateClassicGroup( String groupId, boolean createIfNotExists ) throws GroupIdNotFoundException { Group group = groups.get(groupId); if (group == null && !createIfNotExists) { throw new GroupIdNotFoundException(String.format("Classic group %s not f...
@Test public void testStaticMemberFenceDuplicateRejoiningFollowerAfterMemberIdChanged() throws Exception { GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .build(); GroupMetadataManagerTestContext.RebalanceResult rebalanceResult = context.staticMe...
public boolean appliesTo(Component project, @Nullable MetricEvaluationResult metricEvaluationResult) { return metricEvaluationResult != null && metricEvaluationResult.evaluationResult.level() != Measure.Level.OK && METRICS_TO_IGNORE_ON_SMALL_CHANGESETS.contains(metricEvaluationResult.condition.getMetric...
@Test public void should_not_change_issue_related_metrics() { QualityGateMeasuresStep.MetricEvaluationResult metricEvaluationResult = generateEvaluationResult(NEW_BUGS_KEY, ERROR); Component project = generateNewRootProject(); measureRepository.addRawMeasure(PROJECT_REF, CoreMetrics.NEW_LINES_KEY, newMeas...
public static Iterable<String> expandAtNFilepattern(String filepattern) { ImmutableList.Builder<String> builder = ImmutableList.builder(); Matcher match = AT_N_SPEC.matcher(filepattern); if (!match.find()) { builder.add(filepattern); } else { int numShards = Integer.parseInt(match.group("N")...
@Test public void testExpandAtNFilepatternLarge() throws Exception { Iterable<String> iterable = Filepatterns.expandAtNFilepattern("gs://bucket/file@200000.ism"); assertThat(iterable, Matchers.<String>iterableWithSize(200000)); assertThat( iterable, hasItems("gs://bucket/file-003232-of-200...
@JsonIgnore public RunPolicy getRestartRunPolicyWithUpstreamRestartMode() { if (upstreamRestartMode == UpstreamRestartMode.RESTART_FROM_INLINE_ROOT) { return RunPolicy.valueOf(restartPolicy.name()); } else { return RunPolicy.RESTART_FROM_SPECIFIC; } }
@Test public void testGetRestartRunPolicyWithUpstreamRestartMode() { StepInstanceRestartRequest request = new StepInstanceRestartRequest(); request.setRestartPolicy(RestartPolicy.RESTART_FROM_BEGINNING); assertEquals( RunPolicy.RESTART_FROM_SPECIFIC, request.getRestartRunPolicyWithUpstreamRestartM...
public ClientSession toClientSession() { return new ClientSession( parseServer(server), user, source, Optional.empty(), parseClientTags(clientTags), clientInfo, catalog, schema, ...
@Test public void testServerHostOnly() { ClientOptions options = new ClientOptions(); options.server = "localhost"; ClientSession session = options.toClientSession(); assertEquals(session.getServer().toString(), "http://localhost:80"); }
public List<SchemaChangeEvent> applySchemaChange(SchemaChangeEvent schemaChangeEvent) { List<SchemaChangeEvent> events = new ArrayList<>(); TableId originalTable = schemaChangeEvent.tableId(); boolean noRouteMatched = true; for (Tuple3<Selectors, String, String> route : routes) { ...
@Test void testMergingTablesWithExactSameSchema() { SchemaManager schemaManager = new SchemaManager(); SchemaDerivation schemaDerivation = new SchemaDerivation(schemaManager, ROUTES, new HashMap<>()); // Create table 1 List<SchemaChangeEvent> derivedChangesAfterCreat...
public static <K, V> Reshuffle<K, V> of() { return new Reshuffle<>(); }
@Test @Category(ValidatesRunner.class) public void testReshuffleAfterSlidingWindows() { PCollection<KV<String, Integer>> input = pipeline .apply( Create.of(ARBITRARY_KVS) .withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()))) .apply(W...