focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public long getMaxOffset(final String addr, final MessageQueue messageQueue, final long timeoutMillis) throws RemotingException, MQBrokerException, InterruptedException { GetMaxOffsetRequestHeader requestHeader = new GetMaxOffsetRequestHeader(); requestHeader.setTopic(messageQueue.getTopic()); ...
@Test public void testGetMaxOffset() throws Exception { doAnswer((Answer<RemotingCommand>) mock -> { RemotingCommand request = mock.getArgument(1); final RemotingCommand response = RemotingCommand.createResponseCommand(GetMaxOffsetResponseHeader.class); final GetMaxOffse...
@Override public boolean tryAcquirePermission() { boolean callPermitted = tryEnterBulkhead(); publishBulkheadEvent( () -> callPermitted ? new BulkheadOnCallPermittedEvent(name) : new BulkheadOnCallRejectedEvent(name) ); return callPermitted; }
@Test public void testZeroMaxConcurrentCalls() { BulkheadConfig config = BulkheadConfig.custom() .maxConcurrentCalls(0) .maxWaitDuration(Duration.ofMillis(0)) .build(); SemaphoreBulkhead bulkhead = new SemaphoreBulkhead("test", config); boolean entered = ...
public static SecurityAdminService getSecurityService() { if (System.getSecurityManager() != null) { try { SecurityAdminService securityService = serviceDirectory.get(SecurityAdminService.class); if (securityService != null) { return securityServic...
@Test public void testGetSecurityService() { assertNull(System.getSecurityManager()); assertNotNull(service); }
public static StatementExecutorResponse execute( final ConfiguredStatement<AssertSchema> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { return AssertExecutor.execute( statement.getMaskedStat...
@Test public void shouldFailToAssertNotExistSchemaBySubject() { // Given final AssertSchema assertSchema = new AssertSchema(Optional.empty(), Optional.of("subjectName"), Optional.empty(), Optional.empty(), false); final ConfiguredStatement<AssertSchema> statement = ConfiguredStatement .of(KsqlPars...
public boolean isBackPressured() { if (invokable == null || partitionWriters.length == 0 || (executionState != ExecutionState.INITIALIZING && executionState != ExecutionState.RUNNING)) { return false; } for (int i = 0; i < parti...
@Test public void testNoBackPressureIfTaskNotStarted() throws Exception { final Task task = createTaskBuilder().build(Executors.directExecutor()); assertFalse(task.isBackPressured()); }
public ClientTelemetrySender telemetrySender() { return clientTelemetrySender; }
@Test public void testComputeStaggeredIntervalMs() { ClientTelemetryReporter.DefaultClientTelemetrySender telemetrySender = (ClientTelemetryReporter.DefaultClientTelemetrySender) clientTelemetryReporter.telemetrySender(); assertEquals(0, telemetrySender.computeStaggeredIntervalMs(0, 0.5, 1.5)); ...
static CommandLineOptions parse(Iterable<String> options) { CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder(); List<String> expandedOptions = new ArrayList<>(); expandParamsFiles(options, expandedOptions); Iterator<String> it = expandedOptions.iterator(); while (it.hasNext()) ...
@Test public void aosp() { assertThat(CommandLineOptionsParser.parse(Arrays.asList("-aosp")).aosp()).isTrue(); }
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) { return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context); }
@Test public void testShowCreateExternalCatalog() throws AnalysisException, DdlException { new MockUp<CatalogMgr>() { @Mock public Catalog getCatalogByName(String name) { Map<String, String> properties = new HashMap<>(); properties.put("hive.metastore....
@ExecuteOn(TaskExecutors.IO) @Post(consumes = MediaType.APPLICATION_YAML) @Operation(tags = {"Flows"}, summary = "Create a flow from yaml source") public HttpResponse<FlowWithSource> create( @Parameter(description = "The flow") @Body String flow ) throws ConstraintViolationException { Fl...
@Test void updateFlow() { String flowId = IdUtils.create(); Flow flow = generateFlow(flowId, "io.kestra.unittest", "a"); Flow result = client.toBlocking().retrieve(POST("/api/v1/flows", flow), Flow.class); assertThat(result.getId(), is(flow.getId())); assertThat(result.get...
@Override public final byte readByte() throws EOFException { final int ch = read(); if (ch < 0) { throw new EOFException(); } return (byte) (ch); }
@Test public void testReadByte() throws Exception { int read = in.readByte(); assertEquals(0, read); }
public static InternalLogger getInstance(Class<?> clazz) { return getInstance(clazz.getName()); }
@Test public void testIsDebugEnabled() { when(mockLogger.isDebugEnabled()).thenReturn(true); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); assertTrue(logger.isDebugEnabled()); verify(mockLogger).isDebugEnabled(); }
@Override public WindowStore<K, V> build() { if (storeSupplier.retainDuplicates() && enableCaching) { log.warn("Disabling caching for {} since store was configured to retain duplicates", storeSupplier.name()); enableCaching = false; } return new MeteredWindowStore<>(...
@Test public void shouldHaveChangeLoggingStoreWhenLoggingEnabled() { setUp(); final WindowStore<String, String> store = builder .withLoggingEnabled(Collections.emptyMap()) .build(); final StateStore wrapped = ((WrappedStateStore) store).wrapped(); asse...
@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)) { ...
@SuppressWarnings("unchecked") @Test void assertGenerateNullConditionValue() { BinaryOperationExpression rightValue = new BinaryOperationExpression(0, 0, mock(ColumnSegment.class), new LiteralExpressionSegment(0, 0, null), "=", null); Optional<ShardingConditionValue> shardingConditionValue = gen...
public static String now() { return formatDateTime(new DateTime()); }
@Test public void nowTest() { // 当前时间 final Date date = DateUtil.date(); assertNotNull(date); // 当前时间 final Date date2 = DateUtil.date(Calendar.getInstance()); assertNotNull(date2); // 当前时间 final Date date3 = DateUtil.date(System.currentTimeMillis()); assertNotNull(date3); // 当前日期字符串,格式:yyyy-MM-dd...
public static String findJavaHomeFromJavaExecutable(String javaExecutable) { String[] cmd = {javaExecutable, "-XshowSettings:properties", "-version"}; final List<String> output = new ArrayList<>(); exec(cmd, output); return output.stream() .filter(l -> l.contains(" java.h...
@Test void findJavaHomeFromPath() { final String expectedJavaHome = System.getProperty("java.home"); Assertions.assertEquals( expectedJavaHome, OsUtils.findJavaHomeFromJavaExecutable(expectedJavaHome + "/bin/java")); }
@Override public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException { if (1 == queryResults.size() && !isNeedAggregateRewri...
@Test void assertBuildIteratorStreamMergedResultWithLimit() throws SQLException { final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "MySQL")); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS)...
@Override public Predicate<FileInfo> get() { long currentTimeMS = System.currentTimeMillis(); Interval interval = Interval.between(currentTimeMS, currentTimeMS + 1); return FileInfo -> { try { return interval.intersect(mInterval.add(mGetter.apply(FileInfo))).isValid(); } catch (Runtime...
@Test public void testDateFromFileNameOlderThan() { FileFilter filter = FileFilter.newBuilder().setName("dateFromFileNameOlderThan").setValue("2d") .setPattern("YYYYMMDD").build(); FileInfo info = new FileInfo(); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd"); LocalDateTime no...
@VisibleForTesting void parseWorkflowParameter( Map<String, Parameter> workflowParams, Parameter param, String workflowId) { parseWorkflowParameter(workflowParams, param, workflowId, new HashSet<>()); }
@Test public void testParseWorkflowParameterWithImplicitToBoolean() { BooleanParameter bar = BooleanParameter.builder().name("bar").expression("foo + 'e';").build(); paramEvaluator.parseWorkflowParameter( Collections.singletonMap("foo", StringParameter.builder().expression("'trU'").build()), b...
public static long parse(String value, String format) { try { DateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.parse(value).getTime(); } catch (Exception e) { return -1; } }
@Test void TestParse () { String stringDateStart = "1970-01-01T00:00:00Z"; TbDate d = new TbDate(stringDateStart); long actualMillis = TbDate.parse("1970-01-01 T00:00:00"); Assertions.assertEquals(-d.getLocaleZoneOffset().getTotalSeconds() * 1000, actualMillis); String patter...
@Override public Result execute( Result previousResult, int nr ) throws KettleJobException { previousResult.setResult( false ); previousResult.setNrErrors( previousResult.getNrErrors() + 1 ); getLogChannel().logError( BaseMessages.getString( MissingEntry.class, "MissingEntry.Log.CannotRunJob" ) ); ret...
@Test public void testExecute() throws KettleJobException { MissingEntry entry = spy( new MissingEntry() ); when( entry.getLogChannel() ).thenReturn( mock( LogChannel.class ) ); entry.setName( "MissingTest" ); Result result = new Result(); result.setNrErrors( 0 ); result.setResult( true ); ...
@Override public ThreadPoolPluginSupport cancelManagement(String threadPoolId) { return managedThreadPoolPluginSupports.remove(threadPoolId); }
@Test public void testCancelManagement() { GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager(); manager.enableThreadPoolPlugin(new TestPlugin("1")); TestSupport support = new TestSupport("1"); manager.registerThreadPoolPluginSupport(support); A...
@Override public Map<String, String> getLabels(Properties properties) { LOGGER.info("DefaultLabelsCollectorManager get labels....."); Map<String, String> labels = getLabels(labelsCollectorsList, properties); LOGGER.info("DefaultLabelsCollectorManager get labels finished,labels :{}", labels);...
@Test void tagV2LabelsCollectorOrderTest() { Properties properties = new Properties(); DefaultLabelsCollectorManager defaultLabelsCollectorManager = new DefaultLabelsCollectorManager(); Map<String, String> labels = defaultLabelsCollectorManager.getLabels(properties); String test = la...
public static String decode(InputStream qrCodeInputStream) { BufferedImage image = null; try{ image = ImgUtil.read(qrCodeInputStream); return decode(image); } finally { ImgUtil.flush(image); } }
@Test @Disabled public void decodeTest3() { final String decode = QrCodeUtil.decode(ImgUtil.read("d:/test/qr_a.png"), false, true); //Console.log(decode); }
@DELETE @Path("{nodeId}") @ApiOperation("Remove node from cluster") @AuditEvent(type = DATANODE_REMOVE) @RequiresPermissions(RestPermissions.DATANODE_REMOVE) public DataNodeDto removeNode(@ApiParam(name = "nodeId", required = true) @PathParam("nodeId") String nodeId, ...
@Test public void removeUnavailableNode_throwsNotFoundException() throws NodeNotFoundException { doThrow(NodeNotFoundException.class).when(dataNodeCommandService).removeNode(NODEID); Exception e = assertThrows(NotFoundException.class, () -> classUnderTest.removeNode(NODEID, userContext)); as...
public static boolean overrideExecutorTemplateEnabled(ApplicationSpec applicationSpec) { return applicationSpec != null && applicationSpec.getExecutorSpec() != null && applicationSpec.getExecutorSpec().getPodTemplateSpec() != null; }
@Test void testOverrideExecutorTemplateEnabled() { ApplicationSpec applicationSpec = new ApplicationSpec(); assertFalse(ModelUtils.overrideDriverTemplateEnabled(applicationSpec)); BaseApplicationTemplateSpec executorSpec = new BaseApplicationTemplateSpec(); applicationSpec.setExecutorSpec(executorSpe...
@Override public void process(Exchange exchange) throws Exception { JsonElement json = getBodyAsJsonElement(exchange); String operation = exchange.getIn().getHeader(CouchDbConstants.HEADER_METHOD, String.class); if (ObjectHelper.isEmpty(operation)) { Response<DocumentResult> save...
@Test void testNullSaveResponseThrowsError() throws Exception { when(exchange.getIn().getMandatoryBody()).thenThrow(InvalidPayloadException.class); assertThrows(InvalidPayloadException.class, () -> { producer.process(exchange); }); }
@JsonProperty("lookup_regions") public abstract String lookupRegions();
@Test public void lookupRegions() throws Exception { final AWSPluginConfiguration config = createDefault() .toBuilder() .lookupRegions("us-west-1,eu-west-1 , us-east-1 ") .build(); assertThat(config.getLookupRegions()).containsExactly(Regions.US_WEST...
static boolean shouldUseRecordReaderFromInputFormat(Configuration configuration, Storage storage, Map<String, String> customSplitInfo) { if (customSplitInfo == null || !customSplitInfo.containsKey(CUSTOM_FILE_SPLIT_CLASS_KEY)) { return false; } InputFormat<?, ?> inputFormat = Hi...
@Test public void testShouldUseRecordReaderFromInputFormat() { StorageFormat hudiStorageFormat = StorageFormat.create("parquet.hive.serde.ParquetHiveSerDe", "org.apache.hudi.hadoop.HoodieParquetInputFormat", ""); assertFalse(shouldUseRecordReaderFromInputFormat(new Configuration(), new Storage(h...
@GET @Path("job/{noteId}/{paragraphId}") @ZeppelinApi public Response getNoteParagraphJobStatus(@PathParam("noteId") String noteId, @PathParam("paragraphId") String paragraphId) throws IOException, IllegalArgumentException { LOGGER.info("Get note paragraph jo...
@Test void testGetNoteParagraphJobStatus() throws IOException { LOG.info("Running testGetNoteParagraphJobStatus"); String note1Id = null; try { note1Id = notebook.createNote("note1", anonymous); String paragraphId = notebook.processNote(note1Id, note1 -> { return note1.addNew...
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testFetchDisconnectedShouldNotClearPreferredReadReplicaIfUnassigned() { buildFetcher(new MetricConfig(), OffsetResetStrategy.EARLIEST, new BytesDeserializer(), new BytesDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED, Duration.ofMinutes(5).toMillis()); ...
@Override public List<SocialUserDO> getSocialUserList(Long userId, Integer userType) { // 获得绑定 List<SocialUserBindDO> socialUserBinds = socialUserBindMapper.selectListByUserIdAndUserType(userId, userType); if (CollUtil.isEmpty(socialUserBinds)) { return Collections.emptyList(); ...
@Test public void testGetSocialUserList() { Long userId = 1L; Integer userType = UserTypeEnum.ADMIN.getValue(); // mock 获得社交用户 SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(SocialTypeEnum.GITEE.getType()); socialUserMapper.insert(socialUser); // 可被查到 ...
public static PCollection<String> coGroupByKeyTuple( TupleTag<String> emailsTag, TupleTag<String> phonesTag, PCollection<KV<String, String>> emails, PCollection<KV<String, String>> phones) { // [START CoGroupByKeyTuple] PCollection<KV<String, CoGbkResult>> results = KeyedPCollec...
@Test public void testCoGroupByKeyTuple() throws IOException { // [START CoGroupByKeyTupleInputs] final List<KV<String, String>> emailsList = Arrays.asList( KV.of("amy", "amy@example.com"), KV.of("carl", "carl@example.com"), KV.of("julia", "julia@example.com"), ...
public static long noHeapMemoryFree() { return Math.subtractExact(noHeapMemoryMax(), noHeapMemoryUsed()); }
@Test public void noHeapMemoryFree() { long memoryUsed = MemoryUtil.noHeapMemoryFree(); Assert.assertNotEquals(0, memoryUsed); }
@Override public Object decode(Response response, Type type) throws IOException { JsonAdapter<Object> jsonAdapter = moshi.adapter(type); if (response.status() == 404 || response.status() == 204) return Util.emptyValueOf(type); if (response.body() == null) return null; try (BufferedSource...
@Test void emptyBodyDecodesToNull() throws Exception { Response response = Response.builder() .status(204) .reason("OK") .headers(Collections.emptyMap()) .request(Request.create(Request.HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8)) .body(new...
public Optional<String> addStreamThread() { if (isRunningOrRebalancing()) { final StreamThread streamThread; synchronized (changeThreadCount) { final int threadIdx = nextThreadIndex(); final int numLiveThreads = numLiveStreamThreads(); fina...
@Test public void shouldNotAddThreadWhenCreated() { prepareStreams(); prepareStreamThread(streamThreadOne, 1); prepareStreamThread(streamThreadTwo, 2); try (final KafkaStreams streams = new KafkaStreams(getBuilderWithSource().build(), props, supplier, time)) { final int o...
public static DispositionNotificationOptions parseDispositionNotificationOptions( final String value, DispositionNotificationOptionsParser parser) throws ParseException { if (value == null) { return new DispositionNotificationOptions(null, null); } ...
@Test public void parseDispositionNotificationOptionsTest() throws ParseException { DispositionNotificationOptions dispositionNotificationOptions = DispositionNotificationOptionsParser.parseDispositionNotificationOptions(TEST_NAME_VALUES, null); Parameter signedReceiptProtocol = dis...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .nullable(typeDefine.isNullable()) .defaultValue(typeDefin...
@Test public void testConvertDouble() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("double") .dataType("double") .build(); Column column = Dmd...
protected TransactionReceipt executeTransaction(Function function) throws IOException, TransactionException { return executeTransaction(function, BigInteger.ZERO); }
@Test public void testJsonRpcError() throws IOException { EthSendTransaction ethSendTransaction = new EthSendTransaction(); Response.Error error = new Response.Error(1, "Invalid Transaction"); error.setData("Additional data"); ethSendTransaction.setError(error); TransactionM...
public static long readUIntBE(InputStream stream) throws IOException, BufferUnderrunException { int ch1 = stream.read(); int ch2 = stream.read(); int ch3 = stream.read(); int ch4 = stream.read(); if ((ch1 | ch2 | ch3 | ch4) < 0) { throw new BufferUnderrunException(); ...
@Test public void testReadUIntBE() throws Exception { byte[] data = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x08}; assertEquals(8, EndianUtils.readUIntBE(new ByteArrayInputStream(data))); data = new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xF0}; assertE...
public static <T> T[] createCopy(T[] src) { return Arrays.copyOf(src, src.length); }
@Test public void createCopy_whenZeroLengthArray_thenReturnDifferentZeroLengthArray() { Object[] original = new Object[0]; Object[] result = ArrayUtils.createCopy(original); assertThat(result).isNotSameAs(original); assertThat(result).isEmpty(); }
@Override public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, final Void options, final PasswordCallback callback) throws BackgroundException { final Acl permission = acl.getPermission(file); final Acl.GroupUser everyone = new Acl.GroupUser(Acl.GroupUser.EVERYONE); fina...
@Test public void toDownloadUrl() throws Exception { final Path bucket = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new S3TouchFeat...
public static Schema convertToSchema(LogicalType schema) { return convertToSchema(schema, true); }
@Test void testInvalidTimestampTypeAvroSchemaConversion() { RowType rowType = (RowType) ResolvedSchema.of( Column.physical("a", DataTypes.STRING()), Column.physical("b", DataTypes.TIMESTAM...
@Override public String toString() { boolean traceHi = traceIdHigh != 0; char[] result = new char[traceHi ? 32 : 16]; int pos = 0; if (traceHi) { writeHexLong(result, pos, traceIdHigh); pos += 16; } writeHexLong(result, pos, traceId); return new String(result); }
@Test void testToString_lo() { assertThat(base.toString()) .isEqualTo("000000000000014d"); }
@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_update() { // 准备参数 Integer socialType = SocialTypeEnum.GITEE.getType(); Integer userType = randomEle(SocialTypeEnum.values()).getType(); String code = "tudou"; String state = "yuanma"; // mock 数据 socialUserMapper.insert(ran...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof PiActionProfileMember)) { return false; } PiActionProfileMember that = (PiActionProfileMember) o; return Objects.equal(actionProfileId, that.actionPr...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(piActionProfileMember1, sameAsPiActionProfileMember1) .addEqualityGroup(piActionProfileMember2) .addEqualityGroup(piActionProfileMember3) .testEquals(); }
@Override public void run() { final Instant now = time.get(); try { final Collection<PersistentQueryMetadata> queries = engine.getPersistentQueries(); final Optional<Double> saturation = queries.stream() .collect(Collectors.groupingBy(PersistentQueryMetadata::getQueryApplicationId)) ...
@Test public void shouldComputeSaturationForThread() { // Given: final Instant start = Instant.now(); when(clock.get()).thenReturn(start); givenMetrics(kafkaStreams1) .withThreadStartTime("t1", start.minus(WINDOW.multipliedBy(2))) .withBlockedTime("t1", Duration.ofMinutes(1)); coll...
public void writeRow( RowMetaInterface rowMeta, Object[] r ) throws KettleStepException { try { if ( Utils.isEmpty( meta.getOutputFields() ) ) { /* * Write all values in stream to text file. */ for ( int i = 0; i < rowMeta.size(); i++ ) { if ( i > 0 && data.binarySe...
@Test public void testFastDumpDisableStreamEncodeTest() throws Exception { textFileOutput = new TextFileOutputTestHandler( stepMockHelper.stepMeta, stepMockHelper.stepDataInterface, 0, stepMockHelper.transMeta, stepMockHelper.trans ); textFileOutput.meta = stepMockHelper.processRowsStep...
@Override public <VR> KTable<K, VR> aggregate(final Initializer<VR> initializer, final Aggregator<? super K, ? super V, VR> aggregator, final Materialized<K, VR, KeyValueStore<Bytes, byte[]>> materialized) { return aggregate(ini...
@Test public void shouldNotHaveNullAdderOnAggregate() { assertThrows(NullPointerException.class, () -> groupedStream.aggregate(MockInitializer.STRING_INIT, null, Materialized.as("store"))); }
@Override public int read() throws IOException { if (mPosition == mLength) { // at end of file return -1; } updateStreamIfNeeded(); int res = mUfsInStream.get().read(); if (res == -1) { return -1; } mPosition++; Metrics.BYTES_READ_FROM_UFS.inc(1); return res; }
@Test public void readNullBuffer() throws IOException, AlluxioException { AlluxioURI ufsPath = getUfsPath(); createFile(ufsPath, CHUNK_SIZE); try (FileInStream inStream = getStream(ufsPath)) { assertThrows(NullPointerException.class, () -> inStream.read((ByteBuffer) null, 0, CHUNK_SIZE)); ...
@Override public void put(final Windowed<Bytes> sessionKey, final byte[] aggregate) { wrapped().put(sessionKey, aggregate); context.logChange(name(), SessionKeySchema.toBinary(sessionKey), aggregate, context.timestamp(), wrapped().getPosition()); }
@Test public void shouldLogPuts() { final Bytes binaryKey = SessionKeySchema.toBinary(key1); when(inner.getPosition()).thenReturn(Position.emptyPosition()); store.put(key1, value1); verify(inner).put(key1, value1); verify(context).logChange(store.name(), binaryKey, value1, ...
public static int nextCapacity(int current) { assert current > 0 && Long.bitCount(current) == 1 : "Capacity must be a power of two."; if (current < MIN_CAPACITY / 2) { current = MIN_CAPACITY / 2; } current <<= 1; if (current < 0) { throw new RuntimeExcep...
@Test public void testNextCapacity_withInt_shouldIncreaseToHalfOfMinCapacity() { int capacity = 1; int nextCapacity = nextCapacity(capacity); assertEquals(4, nextCapacity); }
@VisibleForTesting static void setupAndModifyConfiguration( Configuration configuration, String currDir, Map<String, String> variables) throws Exception { final String localDirs = variables.get(Environment.LOCAL_DIRS.key()); LOG.info("Current working/local Directory: {}", loc...
@Test public void testDefaultKerberosKeytabConfiguration() throws Exception { final String resourceDirPath = Paths.get("src", "test", "resources").toAbsolutePath().toString(); final Map<String, String> envs = new HashMap<>(2); envs.put(YarnConfigKeys.KEYTAB_PRINCIPAL, "testu...
public static <T> List<T> page(int pageNo, int pageSize, List<T> list) { if (CollUtil.isEmpty(list)) { return new ArrayList<>(0); } int resultSize = list.size(); // 每页条目数大于总数直接返回所有 if (resultSize <= pageSize) { if (pageNo < (PageUtil.getFirstPageNo() + 1)) { return unmodifiable(list); } else { ...
@Test public void pageTest() { final List<Integer> a = ListUtil.toLinkedList(1, 2, 3, 4, 5); PageUtil.setFirstPageNo(1); final int[] a_1 = ListUtil.page(1, 2, a).stream().mapToInt(Integer::valueOf).toArray(); final int[] a1 = ListUtil.page(1, 2, a).stream().mapToInt(Integer::valueOf).toArray(); final int[] ...
public static byte[] parseHex(String string) { return hexFormat.parseHex(string); }
@Test @Parameters(method = "bytesToHexStringVectors") public void parseHexValid(byte[] expectedBytes, String hexString) { byte[] actual = ByteUtils.parseHex(hexString); assertArrayEquals("incorrect hex formatted string", expectedBytes, actual); }
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { try { final EueApiClient client = new EueApiClient(session); // Move to trash first as precondition of delete this.dele...
@Test(expected = NotfoundException.class) public void testNotfound() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); new EueDeleteFeature(session, fileid).delete(Collections.singletonList( new Path(new AlphanumericRandomStringService().rand...
@Override public ModelMBean assemble(Object obj, ObjectName name) throws JMException { ModelMBeanInfo mbi = null; // use the default provided mbean which has been annotated with JMX annotations LOGGER.trace("Assembling MBeanInfo for: {} from @ManagedResource object: {}", name, obj); ...
@Test public void testNotificationAware() throws MalformedObjectNameException, JMException { NotificationSenderAware mockedNotificationAwareMbean = mock(NotificationSenderAware.class); ModelMBean modelBean = defaultManagementMBeanAssembler.assemble(mockedNotificationAwareMbean, new ObjectName("org.f...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test public void testParameterMaximumValue() { Reader reader = new Reader(new SwaggerConfiguration().openAPI(new OpenAPI()).openAPI31(true)); OpenAPI openAPI = reader.read(ParameterMaximumValueResource.class); String yaml = "openapi: 3.1.0\n" + "paths:\n" + ...
@Override public int compare(Path o1, Path o2) { final String c1 = PathNormalizer.name(o1.getAbsolute()); final boolean c2 = PathNormalizer.name(o2.getAbsolute()).matches(pattern); if(c1.matches(pattern) && c2) { return 0; } if(c1.matches(pattern)) { r...
@Test public void testCompare() { assertEquals(-1, new DownloadRegexPriorityComparator(".*\\.html").compare( new Path("f.html", EnumSet.of(Path.Type.file)), new Path("g.t", EnumSet.of(Path.Type.file)))); assertEquals(1, new DownloadRegexPriorityComparator(".*\\.html").compare( ...
@Override public HttpServletRequest readRequest(AwsProxyRequest request, SecurityContext securityContext, Context lambdaContext, ContainerConfig config) throws InvalidRequestEventException { // Expect the HTTP method and context to be populated. If they are not, we are handling an // uns...
@Test void readRequest_validEventEmptyPath_expectException() { try { AwsProxyRequest req = new AwsProxyRequestBuilder(null, "GET").build(); HttpServletRequest servletReq = reader.readRequest(req, null, null, ContainerConfig.defaultConfig()); assertNotNull(servletReq); ...
@VisibleForTesting public Supplier<PageProjection> compileProjection( SqlFunctionProperties sqlFunctionProperties, RowExpression projection, Optional<String> classNameSuffix) { return compileProjection(sqlFunctionProperties, emptyMap(), projection, classNameSuffix); ...
@Test public void testGeneratedClassName() { PageFunctionCompiler functionCompiler = new PageFunctionCompiler(createTestMetadataManager(), 0); String planNodeId = "7"; String stageId = "20170707_223500_67496_zguwn.2"; String classSuffix = stageId + "_" + planNodeId; Supp...
public boolean rollbackClusterState(UUID txnId) { clusterServiceLock.lock(); try { final LockGuard currentLock = getStateLock(); if (!currentLock.allowsUnlock(txnId)) { return false; } logger.fine("Rolling back cluster state transaction: "...
@Test public void test_unlockClusterState_fail_whenNotLocked() { assertFalse(clusterStateManager.rollbackClusterState(TXN)); }
@Override public void run() throws Exception { // Get list of files to process. List<String> filteredFiles = SegmentGenerationUtils.listMatchedFilesWithRecursiveOption(_inputDirFS, _inputDirURI, _spec.getIncludeFileNamePattern(), _spec.getExcludeFileNamePattern(), _spec.isSearchRecursively()); ...
@Test public void testSegmentGeneration() throws Exception { // TODO use common resource definitions & code shared with Hadoop unit test. // So probably need a pinot-batch-ingestion-common tests jar that we depend on. File testDir = makeTestDir(); File inputDir = new File(testDir, "input"); input...
public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf, QueuePath childQueuePath) { setTemplateEntriesForChild(conf, childQueuePath, false); }
@Test public void testQueueSpecificTemplates() { conf.set(getTemplateKey(ROOT, "capacity"), "2w"); conf.set(getLeafTemplateKey(ROOT, "default-node-label-expression"), "test"); conf.set(getLeafTemplateKey(ROOT, "capacity"), "10w"); conf.setBoolean(getParentTemplateKey( ROOT, AUTO_CR...
@Override public void validateSmsCode(SmsCodeValidateReqDTO reqDTO) { validateSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene()); }
@Test public void validateSmsCode_success() { // 准备参数 SmsCodeValidateReqDTO reqDTO = randomPojo(SmsCodeValidateReqDTO.class, o -> { o.setMobile("15601691300"); o.setScene(randomEle(SmsSceneEnum.values()).getScene()); }); // mock 数据 SqlConstants.init(Db...
public Node deserializeObject(JsonReader reader) { Log.info("Deserializing JSON to Node."); JsonObject jsonObject = reader.readObject(); return deserializeObject(jsonObject); }
@Test void simpleTest() { CompilationUnit cu = parse("public class X{} class Z{}"); String serialized = serialize(cu, false); Node deserialized = deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); assertEqualsStringIgnoringEol("public class X {\n}\n\nc...
@Override public int intersection(String... names) { return get(intersectionAsync(names)); }
@Test public void testIntersection() { RScoredSortedSet<String> set1 = redisson.getScoredSortedSet("simple1"); set1.add(1, "one"); set1.add(2, "two"); RScoredSortedSet<String> set2 = redisson.getScoredSortedSet("simple2"); set2.add(1, "one"); set2.add(2, "two"); ...
public double vincentyDistance(LatLong other) { return LatLongUtils.vincentyDistance(this, other); }
@Test public void vincentyDistance_originToNorthPole_returnDistanceFromPoleToEquator() { // This is the origin of the WGS-84 reference system LatLong zeroZero = new LatLong(0d, 0d); // Calculating the distance between the north pole and the equator LatLong northPole = new LatLong(90d...
public static Comparator<InstanceInfo> comparatorByAppNameAndId() { return INSTANCE_APP_ID_COMPARATOR; }
@Test public void testComparatorByAppNameAndIdIfNotNullReturnInt() { InstanceInfo instanceInfo1 = Mockito.mock(InstanceInfo.class); InstanceInfo instanceInfo2 = Mockito.mock(InstanceInfo.class); InstanceInfo instanceInfo3 = createSingleInstanceApp("foo", "foo", InstanceInfo.A...
@Override public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) { for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) { Map<String, ?> sourceOffset = offsetEntry.getValue(); if (sourceOffset == null)...
@Test public void testAlterOffsetsTombstones() { MirrorCheckpointConnector connector = new MirrorCheckpointConnector(); Function<Map<String, ?>, Boolean> alterOffsets = partition -> connector.alterOffsets( null, Collections.singletonMap(partition, null) ); ...
public static String decodeBase64ZippedString( String loggingString64 ) throws IOException { if ( loggingString64 == null || loggingString64.isEmpty() ) { return ""; } StringWriter writer = new StringWriter(); // base 64 decode byte[] bytes64 = Base64.decodeBase64( loggingString64.getBytes() )...
@Test public final void testDecodeBase64ZippedString() throws IOException, NoSuchAlgorithmException { String enc64 = this.canonicalBase64Encode( STANDART ); // decode string String decoded = HttpUtil.decodeBase64ZippedString( enc64 ); Assert.assertEquals( "Strings are the same after transformation", ...
public static ClassLoader findClassLoader(final ClassLoader proposed) { ClassLoader classLoader = proposed; if (classLoader == null) { classLoader = ReflectHelpers.class.getClassLoader(); } if (classLoader == null) { classLoader = ClassLoader.getSystemClassLoader(); } return classLoa...
@Test public void testFindProperClassLoaderIfContextClassLoaderIsAvailable() throws InterruptedException { final ClassLoader[] classLoader = new ClassLoader[1]; Thread thread = new Thread(() -> classLoader[0] = ReflectHelpers.findClassLoader()); ClassLoader cl = new ClassLoader() {}; thread.setC...
public void persistInstanceWorkerId(final String instanceId, final int workerId) { repository.persistEphemeral(ComputeNode.getInstanceWorkerIdNodePath(instanceId), String.valueOf(workerId)); }
@Test void assertPersistInstanceWorkerId() { InstanceMetaData instanceMetaData = new ProxyInstanceMetaData("foo_instance_id", 3307); final String instanceId = instanceMetaData.getId(); new ComputeNodePersistService(repository).persistInstanceWorkerId(instanceId, 100); verify(reposito...
public CompletableFuture<ChangeInvisibleDurationResponse> changeInvisibleDuration(ProxyContext ctx, ChangeInvisibleDurationRequest request) { CompletableFuture<ChangeInvisibleDurationResponse> future = new CompletableFuture<>(); try { validateTopicAndConsumerGroup(request.getTopic()...
@Test public void testChangeInvisibleDurationInvisibleTimeTooSmall() throws Throwable { try { this.changeInvisibleDurationActivity.changeInvisibleDuration( createContext(), ChangeInvisibleDurationRequest.newBuilder() .setInvisibleDuration(Durat...
@Override public void onPartitionsDeleted( List<TopicPartition> topicPartitions, BufferSupplier bufferSupplier ) throws ExecutionException, InterruptedException { throwIfNotActive(); CompletableFuture.allOf( FutureUtils.mapExceptionally( runtime.sched...
@Test public void testOnPartitionsDeletedWhenServiceIsNotStarted() { CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime(); GroupCoordinatorService service = new GroupCoordinatorService( new LogContext(), createConfig(), runtime, ...
public void setPageSegMode(String pageSegMode) { if (!pageSegMode.matches("[0-9]|10|11|12|13")) { throw new IllegalArgumentException("Invalid page segmentation mode"); } this.pageSegMode = pageSegMode; userConfigured.add("pageSegMode"); }
@Test public void testValidatePageSegMode() { TesseractOCRConfig config = new TesseractOCRConfig(); config.setPageSegMode("0"); config.setPageSegMode("10"); assertTrue(true, "Couldn't set valid values"); assertThrows(IllegalArgumentException.class, () -> { config....
@SuppressWarnings("deprecation") public static <K> KStreamHolder<K> build( final KStreamHolder<K> left, final KStreamHolder<K> right, final StreamStreamJoin<K> join, final RuntimeBuildContext buildContext, final StreamJoinedFactory streamJoinedFactory) { final QueryContext queryConte...
@Test public void shouldDoOuterJoinWithGrace() { // Given: givenOuterJoin(Optional.of(GRACE)); // When: final KStreamHolder<Struct> result = join.build(planBuilder, planInfo); // Then: verify(leftKStream).outerJoin( same(rightKStream), eq(new KsqlValueJoiner(LEFT_SCHEMA.value...
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testIncrementalFromSnapshotId() throws Exception { appendTwoSnapshots(); ScanContext scanContext = ScanContext.builder() .startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_SNAPSHOT_ID) .startSnapshotId(snapshot2.snapshotId()) .build(); ...
@Override public String getConfig(String key, String group, long timeout) throws IllegalStateException { try { long nacosTimeout = timeout < 0 ? getDefaultTimeout() : timeout; if (StringUtils.isEmpty(group)) { group = DEFAULT_GROUP; } return co...
@Test void testGetConfig() throws Exception { put("org.apache.dubbo.nacos.testService.configurators", "hello"); Thread.sleep(200); put("dubbo.properties", "test", "aaa=bbb"); Thread.sleep(200); put("org.apache.dubbo.demo.DemoService:1.0.0.test:xxxx.configurators", "helloworld...
List<Token> tokenize() throws ScanException { List<Token> tokenList = new ArrayList<Token>(); StringBuffer buf = new StringBuffer(); while (pointer < patternLength) { char c = pattern.charAt(pointer); pointer++; switch (state) { case LITERAL_STAT...
@Test public void testOptions() throws ScanException { { List<Token> tl = new TokenStream("%x{t}").tokenize(); List<Token> witness = new ArrayList<Token>(); witness.add(Token.PERCENT_TOKEN); witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); List<S...
public static String trimEnd( final String source, char c ) { if ( source == null ) { return null; } int index = source.length(); while ( index > 0 && source.charAt( index - 1 ) == c ) { index--; } return source.substring( 0, index ); }
@Test public void testTrimEnd_Many() { assertEquals( "/file/path", StringUtil.trimEnd( "/file/path///", '/' ) ); }
@Override public boolean hasPrivileges(final String database) { return databases.contains(AuthorityConstants.PRIVILEGE_WILDCARD) || databases.contains(database); }
@Test void assertHasNotPrivileges() { assertFalse(new DatabasePermittedPrivileges(Collections.singleton("foo_db")).hasPrivileges("bar_db")); }
public static int[] generateRandomNumber(int begin, int end, int size) { // 种子你可以随意生成,但不能重复 final int[] seed = ArrayUtil.range(begin, end); return generateRandomNumber(begin, end, size, seed); }
@Test public void generateRandomNumberTest2(){ // 检查边界 final int[] ints = NumberUtil.generateRandomNumber(1, 8, 7); assertEquals(7, ints.length); final Set<?> set = Convert.convert(Set.class, ints); assertEquals(7, set.size()); }
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testOnlyCPU() throws Exception { String value = "1024vcores"; expectUnparsableResource(value); parseResourceConfigValue(value); }
@Override public void deleteFiles(Iterable<String> pathsToDelete) throws BulkDeletionFailureException { AtomicInteger failureCount = new AtomicInteger(0); Tasks.foreach(pathsToDelete) .executeWith(executorService()) .retry(DELETE_RETRY_ATTEMPTS) .stopRetryOn(FileNotFoundException.class...
@Test public void testDeleteFiles() { Path parent = new Path(tempDir.toURI()); List<Path> filesCreated = createRandomFiles(parent, 10); hadoopFileIO.deleteFiles( filesCreated.stream().map(Path::toString).collect(Collectors.toList())); filesCreated.forEach( file -> assertThat(hadoopFile...
@Override public void processElement(final StreamRecord<T> element) throws Exception { final T event = element.getValue(); final long previousTimestamp = element.hasTimestamp() ? element.getTimestamp() : Long.MIN_VALUE; final long newTimestamp = timestampAssigner.extractTimes...
@Test void periodicWatermarksOnlyEmitOnPeriodicEmitStreamMode() throws Exception { OneInputStreamOperatorTestHarness<Long, Long> testHarness = createTestHarness( WatermarkStrategy.forGenerator((ctx) -> new PeriodicWatermarkGenerator()) ...
public void validatePositionsIfNeeded() { Map<TopicPartition, SubscriptionState.FetchPosition> partitionsToValidate = offsetFetcherUtils.getPartitionsToValidate(); validatePositionsAsync(partitionsToValidate); }
@Test public void testOffsetValidationHandlesSeekWithInflightOffsetForLeaderRequest() { buildFetcher(); assignFromUser(singleton(tp0)); Map<String, Integer> partitionCounts = new HashMap<>(); partitionCounts.put(tp0.topic(), 4); final int epochOne = 1; final Optiona...
public static long convertVersion(String version) throws IncompatibleVersionException { if (StringUtils.isBlank(version)) { throw new IllegalArgumentException("The version must not be blank."); } String[] parts = StringUtils.split(version, '.'); int size = parts.length; ...
@Test public void testConvertVersion() { // case: success Assertions.assertDoesNotThrow(() -> { long v = Version.convertVersion(Version.getCurrent()); Assertions.assertTrue(v > 0); }); Assertions.assertDoesNotThrow(() -> { long v = Version.convertV...
public static int modPowerOfTwo(int a, int b) { return a & (b - 1); }
@Test public void testModPowerOfTwo() { int[] aParams = new int[]{ 0, 1, Integer.MAX_VALUE / 2, Integer.MAX_VALUE, }; int[] bParams = new int[]{ 1, 2, 1024, powerOf...
static Map<Integer, Schema.Field> mapFieldPositions(CSVFormat format, Schema schema) { List<String> header = Arrays.asList(format.getHeader()); Map<Integer, Schema.Field> indexToFieldMap = new HashMap<>(); for (Schema.Field field : schema.getFields()) { int index = getIndex(header, field); if (i...
@Test public void givenNonNullableHeaderAndSchemaFieldMismatch_throws() { Schema schema = Schema.builder() .addStringField("another_string") .addInt32Field("an_integer") .addStringField("a_string") .build(); IllegalArgumentException e = assertThr...
public boolean initWithCommittedOffsetsIfNeeded(Timer timer) { final Set<TopicPartition> initializingPartitions = subscriptions.initializingPartitions(); final Map<TopicPartition, OffsetAndMetadata> offsets = fetchCommittedOffsets(initializingPartitions, timer); // "offsets" will be null if the...
@Test public void testRefreshOffset() { client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE)); subscriptions.assignFromUser(singleton(t1p)); client.prepareResponse(offsetFetchResponse(t1p, Errors.NONE, "",...
@Override public CompletableFuture<ConsumeMessageDirectlyResult> consumeMessageDirectly(String address, ConsumeMessageDirectlyResultRequestHeader requestHeader, long timeoutMillis) { CompletableFuture<ConsumeMessageDirectlyResult> future = new CompletableFuture<>(); RemotingCommand request =...
@Test public void assertConsumeMessageDirectlyWithSuccess() throws Exception { ConsumeMessageDirectlyResult responseBody = new ConsumeMessageDirectlyResult(); setResponseSuccess(RemotingSerializable.encode(responseBody)); ConsumeMessageDirectlyResultRequestHeader requestHeader = mock(Consume...
@Override @SuppressWarnings("rawtypes") public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String,...
@Test public void reportsHistogramValues() throws Exception { final Histogram histogram = mock(Histogram.class); when(histogram.getCount()).thenReturn(1L); final Snapshot snapshot = mock(Snapshot.class); when(snapshot.getMax()).thenReturn(2L); when(snapshot.getMean()).thenRe...
@Override public ConfigErrors errors() { return errors; }
@Test public void shouldValidatePipelineLabelWithBrokenTruncationSyntax2() { String labelFormat = "pipeline-${COUNT}-${git[7]}-alpha"; PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat); String expectedLabelTemplate = "Invalid label 'pipeline-${COUNT}-${git[7]}-alpha...
@Override public String toString() { return major + "." + minor; }
@Test public void toStringTest() { assertEquals("3.8", Version.of(3, 8).toString()); }
@Override public PageData<WidgetsBundle> findAllTenantWidgetsBundlesByTenantId(WidgetsBundleFilter widgetsBundleFilter, PageLink pageLink) { return findTenantWidgetsBundlesByTenantIds(Arrays.asList(widgetsBundleFilter.getTenantId().getId(), NULL_UUID), widgetsBundleFilter, pageLink); }
@Test public void testOrderInFindAllWidgetsBundlesByTenantIdFullSearch() { UUID tenantId1 = Uuids.timeBased(); for (int i = 0; i < 10; i++) { createWidgetsBundle(TenantId.fromUUID(tenantId1), "WB1_" + i, "WB1_" + (10-i), i % 2 == 1 ? null : (int)(Math.random() * 1000)); creat...
public static NotificationDispatcherMetadata newMetadata() { return METADATA; }
@Test public void qgChange_notification_is_enable_at_project_level() { NotificationDispatcherMetadata metadata = QGChangeNotificationHandler.newMetadata(); assertThat(metadata.getProperty(PER_PROJECT_NOTIFICATION)).isEqualTo("true"); }
@Override public boolean apply(Collection<Member> members) { if (members.size() < minimumClusterSize) { return false; } int count = 0; long now = currentTimeMillis(); for (Member member : members) { if (!isAlivePerIcmp(member)) { conti...
@Test public void testRecentlyActiveSplitBrainProtectionFunction_splitBrainProtectionPresent_allMembersRecentlyActive() { splitBrainProtectionFunction = new RecentlyActiveSplitBrainProtectionFunction(splitBrainProtectionSize, 10000); // heartbeat each second for all members for 5 seconds hea...
public static URL parseURL(String address, Map<String, String> defaults) { if (StringUtils.isEmpty(address)) { throw new IllegalArgumentException("Address is not allowed to be empty, please re-enter."); } String url; if (address.contains("://") || address.contains(URL_PARAM_S...
@Test void testParseUrl() { String address = "remote://root:alibaba@127.0.0.1:9090/dubbo.test.api"; URL url = UrlUtils.parseURL(address, null); assertEquals(localAddress + ":9090", url.getAddress()); assertEquals("root", url.getUsername()); assertEquals("alibaba", url.getPass...
public void collectRequestStats(HttpRequestInfo req) { // ipv4/ipv6 tracking String clientIp; final String xForwardedFor = req.getHeaders().getFirst(X_FORWARDED_FOR_HEADER); if (xForwardedFor == null) { clientIp = req.getClientIp(); } else { clientIp = ext...
@Test void testCollectRequestStats() { final String host = "api.netflix.com"; final String proto = "https"; final HttpRequestInfo req = Mockito.mock(HttpRequestInfo.class); Headers headers = new Headers(); when(req.getHeaders()).thenReturn(headers); headers.set(Stats...
@Override @Transactional(rollbackFor = Exception.class) public void deleteCodegen(Long tableId) { // 校验是否已经存在 if (codegenTableMapper.selectById(tableId) == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } // 删除 table 表定义 codegenTableMapper.deleteById(tabl...
@Test public void testDeleteCodegen_notExists() { assertServiceException(() -> codegenService.deleteCodegen(randomLongId()), CODEGEN_TABLE_NOT_EXISTS); }