focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Collection<RedisServer> masters() { List<Map<String, String>> masters = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_MASTERS); return toRedisServersList(masters); }
@Test public void testMasters() { Collection<RedisServer> masters = connection.masters(); assertThat(masters).hasSize(1); }
@Nullable public Integer getIntValue(@IntFormat final int formatType, @IntRange(from = 0) final int offset) { if ((offset + getTypeLen(formatType)) > size()) return null; return switch (formatType) { case FORMAT_UINT8 -> unsignedByteToInt(mValue[offset]); case FORMAT_UINT16_LE -> unsignedBytesToIn...
@Test public void getValue_SINT32() { final Data data = new Data(new byte[] { (byte) 0x00, (byte) 0xFD, (byte) 0xFD, (byte) 0xFE }); final int value = data.getIntValue(Data.FORMAT_UINT32_LE, 0); assertEquals(0xfefdfd00, value); }
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filte...
@Test(description = "it should filter with null definitions") public void filterWithNullDefinitions() throws IOException { final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH); openAPI.getComponents().setSchemas(null); final InternalModelPropertiesRemoverFilter filter = new InternalModelProper...
@Override public void register(Component component) { checkComponent(component); checkArgument(component.getType() == Component.Type.FILE, "component must be a file"); checkState(analysisMetadataHolder.isPullRequest() || !analysisMetadataHolder.isFirstAnalysis(), "No file can be registered on first branch...
@Test public void register_fails_with_NPE_if_component_is_null() { assertThatThrownBy(() -> underTest.register(null)) .isInstanceOf(NullPointerException.class) .hasMessage("component can't be null"); }
public static MkdirsOptions defaults(AlluxioConfiguration conf) { return new MkdirsOptions(conf.getString(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK)); }
@Test public void defaults() throws IOException { MkdirsOptions options = MkdirsOptions.defaults(mConfiguration); // Verify the default createParent is true. assertTrue(options.getCreateParent()); // Verify that the owner and group are not set. assertNull(options.getOwner()); assertNull(optio...
@Override public void writeData(ObjectDataOutput out) throws IOException { throw new UnsupportedOperationException(); }
@Test(expected = UnsupportedOperationException.class) public void testWriteData() throws Exception { localCacheWideEventData.writeData(null); }
@Override public ResultSetMetaData getMetaData() throws SQLException { checkClosed(); return resultSetMetaData; }
@Test void assertGetMetaData() throws SQLException { assertThat(databaseMetaDataResultSet.getMetaData(), is(resultSetMetaData)); }
public RegistryBuilder isDynamic(Boolean dynamic) { this.dynamic = dynamic; return getThis(); }
@Test void isDynamic() { RegistryBuilder builder = new RegistryBuilder(); builder.isDynamic(true); Assertions.assertTrue(builder.build().isDynamic()); }
Flux<Account> getAll(final int segments, final Scheduler scheduler) { if (segments < 1) { throw new IllegalArgumentException("Total number of segments must be positive"); } return Flux.range(0, segments) .parallel() .runOn(scheduler) .flatMap(segment -> asyncClient.scanPaginat...
@Test void testGetAll() { final List<Account> expectedAccounts = new ArrayList<>(); for (int i = 1; i <= 100; i++) { final Account account = generateAccount("+1" + String.format("%03d", i), UUID.randomUUID(), UUID.randomUUID()); expectedAccounts.add(account); createAccount(account); } ...
public static <U> Task<U> withRetryPolicy(String name, RetryPolicy policy, Function1<Integer, Task<U>> taskFunction) { RetriableTask<U> retriableTask = new RetriableTask<>(name, policy, taskFunction); Task<U> retryTaskWrapper = Task.async(name + " retriableTask", retriableTask::run); retryTaskWrapper.getSha...
@Test public void testSimpleRetryPolicy() { Task<Void> task = withRetryPolicy("testSimpleRetryPolicy", RetryPolicy.attempts(3, 0), attempt -> Task.failure(new RuntimeException("current attempt: " + attempt))); runAndWaitException(task, RuntimeException.class); assertTrue(task.isDone()); asse...
public Optional<ContentPack> findByIdAndRevision(ModelId id, int revision) { final DBQuery.Query query = DBQuery.is(Identified.FIELD_META_ID, id).is(Revisioned.FIELD_META_REVISION, revision); return Optional.ofNullable(dbCollection.findOne(query)); }
@Test @MongoDBFixtures("ContentPackPersistenceServiceTest.json") public void findByIdAndRevisionWithInvalidRevision() { final Optional<ContentPack> contentPack = contentPackPersistenceService.findByIdAndRevision(ModelId.of("dcd74ede-6832-4ef7-9f69-deadbeef0000"), 42); assertThat(contentPack).is...
public static Optional<NoticeContents> parseNoticeFile(Path noticeFile) throws IOException { // 1st line contains module name final List<String> noticeContents = Files.readAllLines(noticeFile); return parseNoticeFile(noticeContents); }
@Test void testParseNoticeFileBundlesPath() { final String module = "some-module"; final Dependency dependency = Dependency.create("groupId", "artifactId", "version", "classifier"); final List<String> noticeContents = Arrays.asList( mod...
public MethodBuilder isReturn(Boolean isReturn) { this.isReturn = isReturn; return getThis(); }
@Test void isReturn() { MethodBuilder builder = MethodBuilder.newBuilder(); builder.isReturn(true); Assertions.assertTrue(builder.build().isReturn()); }
@Override public long checksum() { long c = checksum(this.type.getNumber(), this.id.checksum()); c = checksum(this.peers, c); c = checksum(this.oldPeers, c); c = checksum(this.learners, c); c = checksum(this.oldLearners, c); if (this.data != null && this.data.hasRemai...
@Test public void testChecksum() { ByteBuffer buf = ByteBuffer.wrap("hello".getBytes()); LogEntry entry = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_NO_OP); entry.setId(new LogId(100, 3)); entry.setData(buf); entry.setPeers(Arrays.asList(new PeerId("localhost", 99, 1), new ...
private long replayStartPosition(final RecordingLog.Entry lastTerm) { return replayStartPosition(lastTerm, snapshotsRetrieved, ctx.initialReplayStart(), backupArchive); }
@Test void shouldReturnNullPositionIfLastTermIsNullAndSnapshotsIsEmpty() { assertEquals(NULL_POSITION, replayStartPosition(null, emptyList(), ReplayStart.BEGINNING, mockAeronArchive)); }
void handleStatement(final QueuedCommand queuedCommand) { throwIfNotConfigured(); handleStatementWithTerminatedQueries( queuedCommand.getAndDeserializeCommand(commandDeserializer), queuedCommand.getAndDeserializeCommandId(), queuedCommand.getStatus(), Mode.EXECUTE, queue...
@Test public void shouldSetCorrectFinalStatusOnCompletedPlannedDDLCommand() { // Given: when(mockEngine.execute(any(), any(ConfiguredKsqlPlan.class), any(Boolean.class))) .thenReturn(ExecuteResult.of("result")); // When: handleStatement( statementExecutorWithMocks, plannedComm...
@Override public void write(final MySQLPacketPayload payload, final Object value) { LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(((Time) value).getTime()), ZoneId.systemDefault()); int hours = localDateTime.getHour(); int minutes = localDateTime.getMinute(); ...
@Test void assertWriteWithZeroByte() { MySQLTimeBinaryProtocolValue actual = new MySQLTimeBinaryProtocolValue(); actual.write(payload, Time.valueOf("00:00:00")); verify(payload).writeInt1(0); }
@Operation(summary = "update", description = "Update a host") @PutMapping("/{id}") public ResponseEntity<HostVO> update( @PathVariable Long clusterId, @PathVariable Long id, @RequestBody @Validated HostReq hostReq) { HostDTO hostDTO = HostConverter.INSTANCE.fromReq2DTO(hostReq); retu...
@Test void updateReturnsNullForInvalidHostId() { Long clusterId = 1L; Long hostId = 999L; HostReq hostReq = new HostReq(); when(hostService.update(anyLong(), any(HostDTO.class))).thenReturn(null); ResponseEntity<HostVO> response = hostController.update(clusterId, hostId, hos...
@Override public OpenstackVtapNetwork updateVtapNetwork(OpenstackVtapNetwork description) { checkNotNull(description, VTAP_DESC_NULL, "vtapNetwork"); return store.updateVtapNetwork(VTAP_NETWORK_KEY, description); }
@Test(expected = NullPointerException.class) public void testUpdateNullVtapNetwork() { target.updateVtapNetwork(null); }
@Override public void importData(JsonReader reader) throws IOException { logger.info("Reading configuration for 1.2"); // this *HAS* to start as an object reader.beginObject(); while (reader.hasNext()) { JsonToken tok = reader.peek(); switch (tok) { case NAME: String name = reader.nextName();...
@Test public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException { String expiration1 = "2014-09-10T22:49:44.090+00:00"; Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); when(mockedCl...
@Override public T master() { List<ChildData<T>> children = getActiveChildren(); children.sort(sequenceComparator); if (children.isEmpty()) { return null; } return children.get(0).getNode(); }
@Test public void testMaster() throws Exception { putChildData(group, PATH + "/001", "container1"); putChildData(group, PATH + "/002", "container2"); putChildData(group, PATH + "/003", "container3"); NodeState master = group.master(); assertThat(master, notNullValue()); ...
@Override public Response toResponse(Throwable e) { if (log.isDebugEnabled()) { log.debug("Uncaught exception in REST call: ", e); } else if (log.isInfoEnabled()) { log.info("Uncaught exception in REST call: {}", e.getMessage()); } if (e instanceof NotFoundExc...
@Test public void testToResponseInvalidRequestException() { RestExceptionMapper mapper = new RestExceptionMapper(); Response resp = mapper.toResponse(new InvalidRequestException("invalid request")); assertEquals(resp.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); }
public static WorkerIdentity fromProto(alluxio.grpc.WorkerIdentity proto) throws ProtoParsingException { return Parsers.fromProto(proto); }
@Test public void parserInvalidVersion() throws Exception { alluxio.grpc.WorkerIdentity proto = alluxio.grpc.WorkerIdentity.newBuilder() .setVersion(-1) .setIdentifier(ByteString.copyFrom(Longs.toByteArray(1L))) .build(); assertThrows(InvalidVersionParsingException.class, () ->...
@Override public void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException { // Charset is a global setting on Oracle, it can't be set on a specified schema with a // different value. To not block users who already have a SonarQube schema, charset // is verified only on fr...
@Test public void does_nothing_if_regular_startup() throws Exception { underTest.handle(connection, DatabaseCharsetChecker.State.STARTUP); verifyNoInteractions(sqlExecutor); }
@Override public AnalysisPhase getAnalysisPhase() { return AnalysisPhase.INFORMATION_COLLECTION; }
@Test public void testGetAnalysisPhase() { PerlCpanfileAnalyzer instance = new PerlCpanfileAnalyzer(); AnalysisPhase expResult = AnalysisPhase.INFORMATION_COLLECTION; AnalysisPhase result = instance.getAnalysisPhase(); assertEquals(expResult, result); }
@Deprecated public static <T> Task<T> withSideEffect(final Task<T> parent, final Task<?> sideEffect) { return parent.withSideEffect(t -> sideEffect); }
@Test public void testSideEffectFullCompletion() throws InterruptedException { // ensure that the individual side effect task will be run Task<String> taskOne = new BaseTask<String>() { @Override protected Promise<? extends String> run(Context context) throws Exception { return Promises.va...
@Override public String convert(final EncryptRuleConfiguration ruleConfig) { if (ruleConfig.getTables().isEmpty()) { return ""; } StringBuilder result = new StringBuilder(EncryptDistSQLConstants.CREATE_ENCRYPT); Iterator<EncryptTableRuleConfiguration> iterator = ruleConfi...
@Test void assertConvertWithEmptyTables() { EncryptRuleConfiguration encryptRuleConfig = mock(EncryptRuleConfiguration.class); when(encryptRuleConfig.getTables()).thenReturn(Collections.emptyList()); EncryptRuleConfigurationToDistSQLConverter encryptRuleConfigurationToDistSQLConverter = new ...
@GET @Path("{path:.*}") @Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8}) public Response get(@PathParam("path") String path, @Context UriInfo uriInfo, @QueryParam(OperationParam.NAME) O...
@Test @TestDir @TestJetty @TestHdfs public void testStoragePolicySatisfier() throws Exception { createHttpFSServer(false, false); final String dir = "/parent"; Path path1 = new Path(dir); String file = "/parent/file"; Path filePath = new Path(file); DistributedFileSystem dfs = (Distribut...
public static Slime jsonToSlimeOrThrow(String json) { return jsonToSlimeOrThrow(json.getBytes(StandardCharsets.UTF_8)); }
@Test public void test_invalid_json() { try { SlimeUtils.jsonToSlimeOrThrow("foo"); fail(); } catch (RuntimeException e) { assertEquals("Unexpected character 'o'", e.getMessage()); } }
public Map<String, String> parse(String body) { final ImmutableMap.Builder<String, String> newLookupBuilder = ImmutableMap.builder(); final String[] lines = body.split(lineSeparator); for (String line : lines) { if (line.startsWith(this.ignorechar)) { continue; ...
@Test public void parseKeyOnlyFileWithNonexistingKeyColumn() throws Exception { final String input = "# Sample file for testing\n" + "1;foo\n" + "2;bar\n" + "3;baz"; final DSVParser dsvParser = new DSVParser("#", "\n", ";", "", true, false, 2, Optional...
public void formatSource(CharSource input, CharSink output) throws FormatterException, IOException { // TODO(cushon): proper support for streaming input/output. Input may // not be feasible (parsing) but output should be easier. output.write(formatSource(input.read())); }
@Test public void badConstructor() throws FormatterException { String input = "class X { Y() {} }"; String output = new Formatter().formatSource(input); String expect = "class X {\n Y() {}\n}\n"; assertThat(output).isEqualTo(expect); }
@Override public Collection<LocalDataQueryResultRow> getRows(final ShowSQLFederationRuleStatement sqlStatement, final ContextManager contextManager) { SQLFederationRuleConfiguration ruleConfig = rule.getConfiguration(); boolean sqlFederationEnabled = ruleConfig.isSqlFederationEnabled(); bool...
@Test void assertGetRows() throws SQLException { engine.executeQuery(); Collection<LocalDataQueryResultRow> actual = engine.getRows(); assertThat(actual.size(), is(1)); Iterator<LocalDataQueryResultRow> iterator = actual.iterator(); LocalDataQueryResultRow row = iterator.next...
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldFormatUndefineStatement() { final String statementString = "UNDEFINE _topic;"; final Statement statement = parseSingle(statementString); final String result = SqlFormatter.formatSql(statement); assertThat(result, is("UNDEFINE _topic")); }
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_contains_successWithNaN() { assertThat(array(1.0f, NaN, 3.0f)).usingExactEquality().contains(NaN); }
public static CronPattern of(String pattern) { return new CronPattern(pattern); }
@Test public void patternNegativeTest() { // -4表示倒数的数字,此处在小时上,-4表示 23 - 4,为19 CronPattern pattern = CronPattern.of("* 0 -4 * * ?"); assertMatch(pattern, "2017-02-09 19:00:00"); assertMatch(pattern, "2017-02-19 19:00:33"); }
public void registerCommand(String commandName, CommandHandler handler) { if (StringUtil.isEmpty(commandName) || handler == null) { return; } if (handlerMap.containsKey(commandName)) { CommandCenterLog.warn("[NettyHttpCommandCenter] Register failed (duplicate command): "...
@Test public void testRegisterCommand() { String commandName; CommandHandler handler; // If commandName is null, no handler added in handlerMap commandName = null; handler = new VersionCommandHandler(); httpServer.registerCommand(commandName, handler); assert...
public HivePartitionStats getTableStatistics(String dbName, String tblName) { org.apache.hadoop.hive.metastore.api.Table table = client.getTable(dbName, tblName); HiveCommonStats commonStats = toHiveCommonStats(table.getParameters()); long totalRowNums = commonStats.getRowNums(); if (tot...
@Test public void testGetTableStatistics() { HiveMetaClient client = new MockedHiveMetaClient(); HiveMetastore metastore = new HiveMetastore(client, "hive_catalog", MetastoreType.HMS); HivePartitionStats statistics = metastore.getTableStatistics("db1", "table1"); HiveCommonStats comm...
@Override public Future<?> shutdownGracefully() { return group.shutdownGracefully(); }
@Test public void testInvalidGroup() { final EventExecutorGroup group = new DefaultEventExecutorGroup(1); try { assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() { new NonStickyEventExecutor...
public String getMessage() { return getFieldAs(String.class, FIELD_MESSAGE); }
@Test public void testGetMessage() throws Exception { assertEquals("foo", message.getMessage()); }
public String getEcosystem(DefCveItem cve) { final int[] ecosystemMap = new int[ECOSYSTEMS.length]; cve.getCve().getDescriptions().stream() .filter((langString) -> (langString.getLang().equals("en"))) .forEachOrdered((langString) -> search(langString.getValue(), ecosystem...
@Test public void testJspLinksDoNotCountScoring() throws IOException { DescriptionEcosystemMapper mapper = new DescriptionEcosystemMapper(); String value = "Read more at https://domain/help.jsp."; assertNull(mapper.getEcosystem(asCve(value))); }
public void close() { close(Long.MAX_VALUE, false); }
@Test public void testCloseIsIdempotent() { prepareStreams(); prepareStreamThread(streamThreadOne, 1); prepareStreamThread(streamThreadTwo, 2); try (final KafkaStreams streams = new KafkaStreams(getBuilderWithSource().build(), props, supplier, time)) { streams.close(); ...
@Override final void requestSubpartitions() { throw new UnsupportedOperationException( "RecoveredInputChannel should never request partition."); }
@Test void testRequestPartitionsImpossible() { assertThatThrownBy(() -> buildChannel().requestSubpartitions()) .isInstanceOf(UnsupportedOperationException.class); }
public TxnCoordinator getCoordinator() { return txnCoordinator; }
@Test public void testSerDe() { UUID uuid = UUID.randomUUID(); TransactionState transactionState = new TransactionState(1000L, Lists.newArrayList(20000L, 20001L), 3000, "label123", new TUniqueId(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()), LoadJobSo...
public static int getVersionNumber(String version) { if (version == null) { return -1; } String[] vs = version.split("\\."); int sum = 0; for (int i = 0; i < vs.length; i++) { try { sum = sum * 10 + Integer.parseInt(vs[i]); } ca...
@Test void testGetVersionNumber() { assertEquals(-1, Protocol.getVersionNumber(null)); assertEquals(0, Protocol.getVersionNumber("")); assertEquals(120, Protocol.getVersionNumber("1.2.0")); assertEquals(10, Protocol.getVersionNumber("1.A.0")); }
@Override public void checkpointStarted(CheckpointBarrier barrier) throws CheckpointException { throw new CheckpointException(CHECKPOINT_DECLINED_TASK_NOT_READY); }
@Test void testCheckpointStartImpossible() { assertThatThrownBy( () -> buildChannel() .checkpointStarted( new CheckpointBarrier( ...
public static <T> void forEachWithIndex(Iterable<T> iterable, ObjectIntProcedure<? super T> procedure) { FJIterate.forEachWithIndex(iterable, procedure, FJIterate.FORK_JOIN_POOL); }
@Test public void testForEachWithIndexToArrayUsingArrayList() { Integer[] array = new Integer[200]; MutableList<Integer> list = FastList.newList(Interval.oneTo(200)); assertTrue(ArrayIterate.allSatisfy(array, Predicates.isNull())); FJIterate.forEachWithIndex(list, (each, index) -...
@Override public List<String> getServerList() { return serverList.isEmpty() ? serversFromEndpoint : serverList; }
@Test void testConstructWithAddr() { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848,127.0.0.1:8849"); serverListManager = new ServerListManager(properties); final List<String> serverList = serverListManager.getServerList(); ...
@Override public Object remove(String key) { throw new UnsupportedOperationException(); }
@Test public void testRemove() { assertThrowsUnsupportedOperation( () -> unmodifiables.remove("some.key")); }
@Override public void write(int b) throws IOException { checkClosed(); if (chunkSize - currentBufferPointer <= 0) { expandBuffer(); } currentBuffer.put((byte) b); currentBufferPointer++; pointer++; if (pointer > size) { ...
@Test void testRandomAccessRead() throws IOException { try (RandomAccess randomAccessReadWrite = new RandomAccessReadWriteBuffer()) { randomAccessReadWrite.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }); assertEquals(11, randomAccessReadWrite.length()); ...
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testTableScanThenIncrementalWithEmptyTable() throws Exception { ScanContext scanContext = ScanContext.builder() .startingStrategy(StreamingStartingStrategy.TABLE_SCAN_THEN_INCREMENTAL) .build(); ContinuousSplitPlannerImpl splitPlanner = new ContinuousS...
@Override public OAuth2AccessTokenDO getAccessToken(String accessToken) { // 优先从 Redis 中获取 OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenRedisDAO.get(accessToken); if (accessTokenDO != null) { return accessTokenDO; } // 获取不到,从 MySQL 中获取 accessToken...
@Test public void testCheckAccessToken_success() { // mock 数据(访问令牌) OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class) .setExpiresTime(LocalDateTime.now().plusDays(1)); oauth2AccessTokenMapper.insert(accessTokenDO); // 准备参数 String access...
public static ProxyConfig getProxyConfig() { return configuration.getProxyConfig(); }
@Test public void testGetProxyConfig() { assertThat(ConfigurationManager.getProxyConfig()).isNotNull(); }
@Override public boolean add(V value) { lock.lock(); try { checkComparator(); BinarySearchResult<V> res = binarySearch(value, codec); if (res.getIndex() < 0) { int index = -(res.getIndex() + 1); ByteBu...
@Test public void testIteratorSequence() { Set<Integer> set = redisson.getSortedSet("set"); for (int i = 0; i < 1000; i++) { set.add(Integer.valueOf(i)); } Set<Integer> setCopy = new HashSet<Integer>(); for (int i = 0; i < 1000; i++) { setCopy.add(Int...
public String transform() throws ScanException { StringBuilder stringBuilder = new StringBuilder(); compileNode(node, stringBuilder, new Stack<Node>()); return stringBuilder.toString(); }
@Test public void LOGBACK729() throws ScanException { String input = "${${k0}.jdbc.url}"; Node node = makeNode(input); NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); Assertions.assertEquals("http://..", nodeToStringTransformer...
public static Profiler create(Logger logger) { return new DefaultProfiler(logger); }
@Test public void create() { Profiler profiler = Profiler.create(LoggerFactory.getLogger("foo")); assertThat(profiler).isInstanceOf(DefaultProfiler.class); }
@Override public void open() { super.open(); for (String propertyKey : properties.stringPropertyNames()) { LOGGER.debug("propertyKey: {}", propertyKey); String[] keyValue = propertyKey.split("\\.", 2); if (2 == keyValue.length) { LOGGER.debug("key: {}, value: {}", keyValue[0], keyVal...
@Test void testSelectQueryMaxResult() throws IOException, InterpreterException { Properties properties = new Properties(); properties.setProperty("common.max_count", "1"); properties.setProperty("common.max_retry", "3"); properties.setProperty("default.driver", "org.h2.Driver"); properties.setProp...
@Description("Euler's number") @ScalarFunction @SqlType(StandardTypes.DOUBLE) public static double e() { return Math.E; }
@Test public void testE() { assertFunction("e()", DOUBLE, Math.E); }
public static Row toBeamRow(GenericRecord record, Schema schema, ConversionOptions options) { List<Object> valuesInOrder = schema.getFields().stream() .map( field -> { try { org.apache.avro.Schema.Field avroField = rec...
@Test public void testToBeamRow_avro_array_row() { Row flatRowExpected = Row.withSchema(AVRO_FLAT_TYPE).addValues(123L, 123.456, "test", false).build(); Row expected = Row.withSchema(AVRO_ARRAY_TYPE).addValues((Object) Arrays.asList(flatRowExpected)).build(); GenericData.Record record = ne...
public WorkflowInstance.Status getWorkflowInstanceStatus( String workflowId, long workflowInstanceId, long workflowRunId) { String status = getWorkflowInstanceRawStatus(workflowId, workflowInstanceId, workflowRunId); return withMetricLogError( () -> { if (status == null) { re...
@Test public void testGetWorkflowInstanceStatus() { WorkflowInstance.Status status = instanceDao.getWorkflowInstanceStatus( wfi.getWorkflowId(), wfi.getWorkflowInstanceId(), wfi.getWorkflowRunId()); assertEquals(WorkflowInstance.Status.CREATED, status); boolean res = instanceDa...
public static KiePMMLDroolsAST getKiePMMLDroolsAST(final List<Field<?>> fields, final Scorecard model, final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap, ...
@Test void getKiePMMLDroolsAST() { final DataDictionary dataDictionary = pmml.getDataDictionary(); final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap = getFieldTypeMap(dataDictionary, pmml.getTransformationDictionary(), scorecardModel.getLocalTransformat...
public final void isLessThan(int other) { asDouble.isLessThan(other); }
@Test public void isLessThan_int_strictly() { expectFailureWhenTestingThat(2.0f).isLessThan(1); }
public final TraceContext decorate(TraceContext context) { long traceId = context.traceId(), spanId = context.spanId(); E claimed = null; int existingIndex = -1, extraLength = context.extra().size(); for (int i = 0; i < extraLength; i++) { Object next = context.extra().get(i); if (next inst...
@Test void decorate_makesNewExtra() { List<TraceContext> contexts = asList( context.toBuilder().build(), context.toBuilder().addExtra(1L).build(), context.toBuilder().addExtra(1L).addExtra(2L).build() ); for (TraceContext context : contexts) { // adds a new extra container and...
@Override void toHtml() throws IOException { final List<CounterError> errors = counter.getErrors(); if (errors.isEmpty()) { writeln("#Aucune_erreur#"); } else { writeErrors(errors); } }
@Test public void testCounterError() throws IOException { final Counter errorCounter = new Counter(Counter.ERROR_COUNTER_NAME, null); final StringWriter writer = new StringWriter(); final HtmlCounterErrorReport report = new HtmlCounterErrorReport(errorCounter, writer); report.toHtml(); assertNotEmptyAndClear...
@Bean public ShenyuPlugin loggingKafkaPlugin() { return new LoggingKafkaPlugin(); }
@Test public void testLoggingKafkaPlugin() { applicationContextRunner .withPropertyValues( "debug=true", "shenyu.logging.kafka.enabled=true" ) .run(context -> { PluginDataHandler pluginDataHan...
public Set<SubscriberRedoData> findSubscriberRedoData() { Set<SubscriberRedoData> result = new HashSet<>(); synchronized (subscribes) { for (SubscriberRedoData each : subscribes.values()) { if (each.isNeedRedo()) { result.add(each); } ...
@Test void testFindSubscriberRedoData() { redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); assertFalse(redoService.findSubscriberRedoData().isEmpty()); redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER); assertTrue(redoService.findSubscriberRedoData().isEmpty()); ...
@NotNull public SocialUserDO authSocialUser(Integer socialType, Integer userType, String code, String state) { // 优先从 DB 中获取,因为 code 有且可以使用一次。 // 在社交登录时,当未绑定 User 时,需要绑定登录,此时需要 code 使用两次 SocialUserDO socialUser = socialUserMapper.selectByTypeAndCodeAnState(socialType, code, state); i...
@Test public void testAuthSocialUser_insert() { // 准备参数 Integer socialType = SocialTypeEnum.GITEE.getType(); Integer userType = randomEle(SocialTypeEnum.values()).getType(); String code = "tudou"; String state = "yuanma"; // mock 方法 AuthUser authUser = randomP...
public static boolean isEcCoordBase64Valid(String s) { return s.matches("(?:[A-Za-z0-9-_]{4})*(?:[A-Za-z0-9-_]{2}|[A-Za-z0-9-_]{3})"); }
@Test public void testIsEcCoordBase64Valid() { BigInteger example = new BigInteger( "3229926951468396372745881109827389213802338353528900010374647556550771243437"); String message = Base64.getEncoder().encodeToString(example.toByteArray()); // Format ...
@Operation(summary = "getUserInfo", description = "GET_USER_INFO_NOTES") @GetMapping(value = "/get-user-info") @ResponseStatus(HttpStatus.OK) @ApiException(GET_USER_INFO_ERROR) public Result getUserInfo(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser) { ...
@Test public void testGetUserInfo() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/users/get-user-info") .header(SESSION_ID, sessionId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) ....
@VisibleForTesting List<DeletionMeta> perWorkerDirCleanup(long size) { return workerLogs.getAllWorkerDirs().stream() .map(dir -> { try { return directoryCleaner.deleteOldestWhileTooLarge(Collections.singletonList(dir), size, true, null); ...
@Test public void testPerWorkerDirectoryCleanup() throws IOException { long nowMillis = Time.currentTimeMillis(); try (TmpPath testDir = new TmpPath()) { Files.createDirectories(testDir.getFile().toPath()); Path rootDir = createDir(testDir.getFile().toPath(), "workers-artifa...
@VisibleForTesting void handleResponse(DiscoveryResponseData response) { ResourceType resourceType = response.getResourceType(); switch (resourceType) { case NODE: handleD2NodeResponse(response); break; case D2_URI_MAP: handleD2URIMapResponse(response); break;...
@Test public void testHandleD2URICollectionResponseWithData() { DiscoveryResponseData createUri1 = new DiscoveryResponseData(D2_URI, Collections.singletonList( Resource.newBuilder() .setVersion(VERSION1) .setName(URI_URN1) .setResource(Any.pack(D2URI_1)) ....
public static synchronized AbstractAbilityControlManager getInstance() { if (null == abstractAbilityControlManager) { initAbilityControlManager(); } return abstractAbilityControlManager; }
@Test void testGetInstanceByWrongType() { assertThrows(ClassCastException.class, () -> { assertNotNull(NacosAbilityManagerHolder.getInstance(LowerMockAbilityManager.class)); }); }
public List<String> collectErrorsFromAllNodes() { List<String> errors = new ArrayList<>(); for (T node : mNodeResults.values()) { // add all the errors for this node, with the node appended to prefix for (String err : node.getErrors()) { errors.add(String.format("%s :%s", node.getBaseParamet...
@Test public void collectErrorFromAllNodesWithEmptyResults() { // test summary with empty nodes TestMultipleNodeSummary summary = new TestMultipleNodeSummary(); List<String> emptyList = summary.collectErrorsFromAllNodes(); assertTrue(emptyList.isEmpty()); }
static void logTerminatingException( ConsoleLogger consoleLogger, Exception exception, boolean logStackTrace) { if (logStackTrace) { StringWriter writer = new StringWriter(); exception.printStackTrace(new PrintWriter(writer)); consoleLogger.log(LogEvent.Level.ERROR, writer.toString()); }...
@Test public void testLogTerminatingException() { JibCli.logTerminatingException(logger, new IOException("test error message"), false); verify(logger) .log(LogEvent.Level.ERROR, "\u001B[31;1mjava.io.IOException: test error message\u001B[0m"); verifyNoMoreInteractions(logger); }
@Override public void onCreating(AbstractJob job) { JobDetails jobDetails = job.getJobDetails(); Optional<Job> jobAnnotation = getJobAnnotation(jobDetails); setJobName(job, jobAnnotation); setAmountOfRetries(job, jobAnnotation); setLabels(job, jobAnnotation); }
@Test void testDisplayNameFilterAlsoWorksWithJobContext() { Job job = anEnqueuedJob() .withoutName() .withJobDetails(jobDetails() .withClassName(TestService.class) .withMethodName("doWorkWithAnnotationAndJobContext") ...
@Override public void markEvent() { meter.mark(); }
@Test void testMarkEvent() { com.codahale.metrics.Meter dropwizardMeter = mock(com.codahale.metrics.Meter.class); DropwizardMeterWrapper wrapper = new DropwizardMeterWrapper(dropwizardMeter); wrapper.markEvent(); verify(dropwizardMeter).mark(); }
@Override public void onEnd(CeTask ceTask) { // nothing to do }
@Test public void onEnd_has_no_effect() { CeTask ceTask = mock(CeTask.class); underTest.onEnd(ceTask); verifyNoInteractions(ceTask); }
public FEELFnResult<Object> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern, @ParameterName( "replacement" ) String replacement ) { return invoke(input, pattern, replacement, null); }
@Test void invokeWithFlagCaseInsensitive() { FunctionTestUtil.assertResult(replaceFunction.invoke("foobar", "^fOO", "ttt", "i"), "tttbar"); }
public static TieredStorageTopicId convertId(IntermediateDataSetID intermediateDataSetID) { return new TieredStorageTopicId(intermediateDataSetID.getBytes()); }
@Test void testConvertResultPartitionId() { ResultPartitionID resultPartitionID = new ResultPartitionID(); TieredStoragePartitionId tieredStoragePartitionId = TieredStorageIdMappingUtils.convertId(resultPartitionID); ResultPartitionID convertedResultPartitionID = ...
@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 transformShouldReturnInputStringWhenMarkersContainCRLFSafeMarker() { ILoggingEvent event = mock(ILoggingEvent.class); Marker marker = MarkerFactory.getMarker("CRLF_SAFE"); List<Marker> markers = Collections.singletonList(marker); when(event.getMarkerList()).thenReturn(mark...
@Override public Map<String, Set<String>> getAllIndexAliases() { final Map<String, Set<String>> indexNamesAndAliases = indices.getIndexNamesAndAliases(getIndexWildcard()); // filter out the restored archives from the result set return indexNamesAndAliases.entrySet().stream() ...
@Test public void getAllGraylogDeflectorIndices() { final Map<String, Set<String>> indexNameAliases = ImmutableMap.of( "graylog_1", Collections.emptySet(), "graylog_2", Collections.emptySet(), "graylog_3", Collections.emptySet(), "graylog_4_res...
public final void setStrictness(Strictness strictness) { Objects.requireNonNull(strictness); this.strictness = strictness; }
@Test public void testCapitalizedFalseFailWhenStrict() { JsonReader reader = new JsonReader(reader("FALSE")); reader.setStrictness(Strictness.STRICT); IOException expected = assertThrows(IOException.class, reader::nextBoolean); assertThat(expected) .hasMessageThat() .startsWith( ...
public static char getFirstLetter(char c) { return getEngine().getFirstLetter(c); }
@Test public void getFirstLetterTest(){ final String result = PinyinUtil.getFirstLetter("H是第一个", ", "); assertEquals("h, s, d, y, g", result); }
@SuppressWarnings("DataFlowIssue") public static CommandExecutor newInstance(final MySQLCommandPacketType commandPacketType, final CommandPacket commandPacket, final ConnectionSession connectionSession) throws SQLException { if (commandPacket instanceof SQLReceivedPacket) { log.debug("Execute pa...
@Test void assertNewInstanceWithComStmtPrepare() throws SQLException { assertThat(MySQLCommandExecutorFactory.newInstance( MySQLCommandPacketType.COM_STMT_PREPARE, mock(MySQLComStmtPreparePacket.class), connectionSession), instanceOf(MySQLComStmtPrepareExecutor.class)); }
public ConnectionFactory connectionFactory(ConnectionFactory connectionFactory) { // It is common to implement both interfaces if (connectionFactory instanceof XAConnectionFactory) { return (ConnectionFactory) xaConnectionFactory((XAConnectionFactory) connectionFactory); } return TracingConnection...
@Test void connectionFactory_doesntDoubleWrap() { ConnectionFactory wrapped = jmsTracing.connectionFactory(mock(ConnectionFactory.class)); assertThat(jmsTracing.connectionFactory(wrapped)) .isSameAs(wrapped); }
@OnError public void onError(final Session session, final Throwable error) { clearSession(session); LOG.error("websocket collection on client[{}] error: ", getClientIp(session), error); }
@Test public void testOnError() { websocketCollector.onOpen(session); assertEquals(1L, getSessionSetSize()); doNothing().when(loggerSpy).error(anyString(), anyString(), isA(Throwable.class)); Throwable throwable = new Throwable(); websocketCollector.onError(session, throwable...
@JsonIgnore public List<String> getAllStepIds() { List<String> allStepIds = new ArrayList<>(steps.size()); getAllStepIds(steps, allStepIds); return allStepIds; }
@Test public void testGetAllStepIdsInNestedForeach() { TypedStep step = new TypedStep(); step.setId("foo"); ForeachStep foreachStep = new ForeachStep(); foreachStep.setId("foreach-step"); foreachStep.setSteps(Collections.nCopies(Constants.STEP_LIST_SIZE_LIMIT - 1, step)); Workflow workflow = ...
protected T executeAutoCommitFalse(Object[] args) throws Exception { try { TableRecords beforeImage = beforeImage(); T result = statementCallback.execute(statementProxy.getTargetStatement(), args); TableRecords afterImage = afterImage(beforeImage); prepareUndoLog(...
@Test @Disabled public void testOnlySupportMysqlWhenUseMultiPk() throws Exception { Mockito.when(connectionProxy.getContext()) .thenReturn(new ConnectionContext()); PreparedStatementProxy statementProxy = Mockito.mock(PreparedStatementProxy.class); Mockito.when(statementP...
@Override protected double maintain() { if ( ! nodeRepository().nodes().isWorking()) return 0.0; if (nodeRepository().zone().environment().isTest()) return 1.0; int attempts = 0; int failures = 0; outer: for (var applicationNodes : activeNodesByApplication().entrySet...
@Test public void test_autoscaling_ignores_measurements_during_warmup() { ApplicationId app1 = AutoscalingMaintainerTester.makeApplicationId("app1"); ClusterSpec cluster1 = AutoscalingMaintainerTester.containerClusterSpec(); NodeResources resources = new NodeResources(4, 4, 10, 1); C...
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") @GetMapping("/api/images") public PageData<TbResourceInfo> getImages(@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, ...
@Test public void testGetImages() throws Exception { loginSysAdmin(); String systemImageName = "my_system_png_image.png"; TbResourceInfo systemImage = uploadImage(HttpMethod.POST, "/api/image", systemImageName, "image/png", PNG_IMAGE); String systemScadaSymbolName = "my_system_scad...
public void setConnectionSubjectFactory(ConnectionSubjectFactory connectionSubjectFactory) { if (connectionSubjectFactory == null) { throw new IllegalArgumentException("ConnectionSubjectFactory argument cannot be null."); } this.connectionSubjectFactory = connectionSubjectFactory; ...
@Test(expected = IllegalArgumentException.class) public void setNullSubjectConnectionFactory() { filter.setConnectionSubjectFactory(null); }
protected abstract void validatePaths(DistCpContext distCpContext) throws IOException, InvalidInputException;
@Test(timeout=10000) public void testMultipleSrcToFile() { FileSystem fs = null; try { fs = FileSystem.get(getConf()); List<Path> srcPaths = new ArrayList<Path>(); srcPaths.add(new Path("/tmp/in/1")); srcPaths.add(new Path("/tmp/in/2")); final Path target = new Path("/tmp/out/1")...
@Override public ByteBuf setMedium(int index, int value) { throw new ReadOnlyBufferException(); }
@Test public void testSetMedium() { final ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); try { assertThrows(ReadOnlyBufferException.class, new Executable() { @Override public void execute() { buf.setMedium(0, 1); }...
public static AmountRequest fromString(String amountRequestAsString) { if (isNullOrEmpty(amountRequestAsString)) return null; return new AmountRequest( lenientSubstringBetween(amountRequestAsString, "order=", "&"), Integer.parseInt(lenientSubstringBetween(amountRequestAs...
@Test void testOffsetBasedPageRequestWithEmptyString() { OffsetBasedPageRequest offsetBasedPageRequest = OffsetBasedPageRequest.fromString(""); assertThat(offsetBasedPageRequest).isNull(); }
public static AbstractHealthChecker deserialize(String jsonString) { try { return MAPPER.readValue(jsonString, AbstractHealthChecker.class); } catch (IOException e) { throw new NacosDeserializationException(AbstractHealthChecker.class, e); } }
@Test void testDeserializeExtend() { String tcpString = "{\"type\":\"TEST\",\"testValue\":null}"; AbstractHealthChecker actual = HealthCheckerFactory.deserialize(tcpString); assertEquals(TestChecker.class, actual.getClass()); }
@Override public RelDataType deriveSumType(RelDataTypeFactory typeFactory, RelDataType argumentType) { if (argumentType instanceof BasicSqlType) { SqlTypeName type = deriveSumType(argumentType.getSqlTypeName()); if (type == BIGINT) { // special-case for BIGINT - we u...
@Test public void deriveSumTypeTest() { final HazelcastIntegerType bigint_64 = HazelcastIntegerType.create(64, false); assertEquals(type(VARCHAR), HazelcastTypeSystem.INSTANCE.deriveSumType(TYPE_FACTORY, type(VARCHAR))); assertEquals(type(BOOLEAN), HazelcastTypeSystem.INSTANCE.deriveSumType...
static TimeUnit parseTimeUnit(String key, @Nullable String value) { requireArgument((value != null) && !value.isEmpty(), "value of key %s omitted", key); @SuppressWarnings("NullAway") char lastChar = Character.toLowerCase(value.charAt(value.length() - 1)); switch (lastChar) { case 'd': ret...
@Test public void parseTimeUnit_exception() { assertThrows(IllegalArgumentException.class, () -> CaffeineSpec.parseTimeUnit("key", "value")); }
@Override public String getMessage() { if (!logPhi) { return super.getMessage(); } String answer; if (hasHl7MessageBytes() || hasHl7AcknowledgementBytes()) { String parentMessage = super.getMessage(); StringBuilder messageBuilder = new StringBuil...
@Test public void testEmptyHl7Message() { instance = new MllpException(EXCEPTION_MESSAGE, EMPTY_BYTE_ARRAY, HL7_ACKNOWLEDGEMENT_BYTES, LOG_PHI_TRUE); assertEquals(expectedMessage(null, HL7_ACKNOWLEDGEMENT), instance.getMessage()); }
public void setLoadDataRetryDelayMillis(long loadDataRetryDelayMillis) { this.loadDataRetryDelayMillis = loadDataRetryDelayMillis; }
@Test void testSetLoadDataRetryDelayMillis() { distroConfig.setLoadDataRetryDelayMillis(loadDataRetryDelayMillis); assertEquals(loadDataRetryDelayMillis, distroConfig.getLoadDataRetryDelayMillis()); }
@Override public double getStdDev() { // two-pass algorithm for variance, avoids numeric overflow if (values.length <= 1) { return 0; } final double mean = getMean(); double variance = 0; for (int i = 0; i < values.length; i++) { final doubl...
@Test public void calculatesAStdDevOfZeroForASingletonSnapshot() { final Snapshot singleItemSnapshot = new WeightedSnapshot( weightedArray(new long[]{1}, new double[]{1.0})); assertThat(singleItemSnapshot.getStdDev()) .isZero(); }
@Override public void remove() { if (currentIterator == null) { throw new IllegalStateException("next() has not yet been called"); } currentIterator.remove(); }
@Test public void testRemoveWithEmpty() { Assertions.assertThrows(IllegalStateException.class, () -> { List<Integer> emptyList = new ArrayList<>(); CompositeIterable<Integer> compositeIterable = new CompositeIterable<Integer>( emptyList); compositeIterable.iterator().remove(); }); }