focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
protected static boolean isSingleQuoted(String input) { if (input == null || input.isBlank()) { return false; } return input.matches("(^" + QUOTE_CHAR + "{1}([^" + QUOTE_CHAR + "]+)" + QUOTE_CHAR + "{1})"); }
@Test public void testSingleQuotedNegative() { assertFalse(isSingleQuoted("arg 0")); }
public static GlobalConfig readConfig() throws IOException, InvalidGlobalConfigException { return readConfig(getConfigDir()); }
@Test public void testReadConfig_missingRegistry() throws IOException { String json = "{\"registryMirrors\":[{\"mirrors\":[\"mirror.gcr.io\"]}]}"; Files.write(configDir.resolve("config.json"), json.getBytes(StandardCharsets.UTF_8)); InvalidGlobalConfigException exception = assertThrows(InvalidGlob...
public void extractTablesFromInsert(final InsertStatement insertStatement) { if (null != insertStatement.getTable()) { extractTablesFromTableSegment(insertStatement.getTable()); } if (!insertStatement.getColumns().isEmpty()) { for (ColumnSegment each : insertStatement.get...
@Test void assertExtractTablesFromInsert() { InsertStatement insertStatement = mock(InsertStatement.class); when(insertStatement.getTable()).thenReturn(new SimpleTableSegment(new TableNameSegment(122, 128, new IdentifierValue("t_order")))); Collection<ColumnAssignmentSegment> assignmentSegme...
public Future<Void> migrateFromDeploymentToStrimziPodSets(Deployment deployment, StrimziPodSet podSet) { if (deployment == null) { // Deployment does not exist anymore => no migration needed return Future.succeededFuture(); } else { int depReplicas = deployment.get...
@Test public void testMigrationToPodSets(VertxTestContext context) { DeploymentOperator mockDepOps = mock(DeploymentOperator.class); StrimziPodSetOperator mockPodSetOps = mock(StrimziPodSetOperator.class); PodOperator mockPodOps = mock(PodOperator.class); LinkedList<String> events =...
@Override public void onProjectsRekeyed(Set<RekeyedProject> rekeyedProjects) { checkNotNull(rekeyedProjects, "rekeyedProjects can't be null"); if (rekeyedProjects.isEmpty()) { return; } Arrays.stream(listeners) .forEach(safelyCallListener(listener -> listener.onProjectsRekeyed(rekeyedProj...
@Test @UseDataProvider("oneOrManyRekeyedProjects") public void onProjectsRekeyed_calls_all_listeners_in_order_of_addition_to_constructor(Set<RekeyedProject> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); underTestWithListeners.onProjectsRekeyed(projects); inOrder.verif...
@Override public void publish(ScannerReportWriter writer) { Optional<String> targetBranch = getTargetBranch(); if (targetBranch.isPresent()) { Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG); int count = writeChangedLines(scmConfiguration.provider(), writer, targetBranch.get()); ...
@Test public void write_changed_file_with_GitScmProvider() { GitScmProvider provider = mock(GitScmProvider.class); when(scmConfiguration.provider()).thenReturn(provider); Set<Integer> lines = new HashSet<>(Arrays.asList(1, 10)); when(provider.branchChangedLines(eq(TARGET_BRANCH), eq(BASE_DIR), anySet(...
<K, V> ShareInFlightBatch<K, V> fetchRecords(final Deserializers<K, V> deserializers, final int maxRecords, final boolean checkCrcs) { // Creating an empty ShareInFlightBatch ShareInFlightBatch<K, V> inFlig...
@Test public void testUnaligned() { long firstMessageId = 5; long startingOffset = 10L; int numRecords = 10; ShareFetchResponseData.PartitionData partitionData = new ShareFetchResponseData.PartitionData() .setRecords(newRecords(startingOffset, numRecords + 500, firstM...
public double bearingTo(final IGeoPoint other) { final double lat1 = Math.toRadians(this.mLatitude); final double long1 = Math.toRadians(this.mLongitude); final double lat2 = Math.toRadians(other.getLatitude()); final double long2 = Math.toRadians(other.getLongitude()); final dou...
@Test public void test_bearingTo_west() { final GeoPoint target = new GeoPoint(0.0, 0.0); final GeoPoint other = new GeoPoint(0.0, -10.0); assertEquals("directly west", 270, Math.round(target.bearingTo(other))); }
public synchronized Stream updateStreamState(String streamId, Stream.State state) { LOG.info("Updating {}'s state to {} in project {}.", streamId, state.name(), projectId); try { Stream.Builder streamBuilder = Stream.newBuilder() .setName(StreamName.format(projectId, location, st...
@Test public void testUpdateStreamStateInterruptedExceptionShouldFail() throws ExecutionException, InterruptedException { when(datastreamClient.updateStreamAsync(any(UpdateStreamRequest.class)).get()) .thenThrow(InterruptedException.class); DatastreamResourceManagerException exception = ...
@Override public boolean dataDefinitionIgnoredInTransactions() { return false; }
@Test void assertDataDefinitionIgnoredInTransactions() { assertFalse(metaData.dataDefinitionIgnoredInTransactions()); }
public static InetSocketAddress parseAddress(String address, int defaultPort) { return parseAddress(address, defaultPort, false); }
@Test void shouldParseAddressForIPv6WithoutPort() { InetSocketAddress socketAddress = AddressUtils.parseAddress("[1abc:2abc:3abc::5ABC:6abc]:", 80); assertThat(socketAddress.isUnresolved()).isFalse(); assertThat(socketAddress.getAddress().getHostAddress()).isEqualTo("1abc:2abc:3abc:0:0:0:5abc:6abc"); assertTha...
protected boolean isVfsPath( String filePath ) { boolean ret = false; try { VFSFileProvider vfsFileProvider = (VFSFileProvider) providerService.get( VFSFileProvider.TYPE ); if ( vfsFileProvider == null ) { return false; } return vfsFileProvider.isSupported( filePath ); } catc...
@Test public void testIsVfsPath() throws Exception { // SETUP String vfsPath = "pvfs://someConnection/someFilePath"; ProviderService mockProviderService = mock( ProviderService.class ); VFSFileProvider mockVFSFileProvider = mock( VFSFileProvider.class ); when( mockProviderService.get( VFSFileProvi...
@Override public Sink.SinkWriter<WindowedValue<PubsubMessage>> writer() { return new PubsubDynamicSink.PubsubWriter(); }
@Test public void testWriteDynamicDestinations() throws Exception { Windmill.WorkItemCommitRequest.Builder outputBuilder = Windmill.WorkItemCommitRequest.newBuilder() .setKey(ByteString.copyFromUtf8("key")) .setWorkToken(0); when(mockContext.getOutputBuilder()).thenReturn(outp...
@GET @Path("/callback") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response callback( @CookieParam("session_id") String sessionId, @QueryParam("code") String code) { var redirect = authService.callback(new CallbackRequest(sessionId, code)); return Response.seeOther(redirect).build(); ...
@Test void callback_success() { var callbackRedirect = URI.create("https://app.example.com/success"); var authService = mock(AuthService.class); when(authService.callback(any())).thenReturn(callbackRedirect); var sut = new AuthEndpoint(authService); // when try (var res = sut.callback(null, ...
public List<PushConnection> getAll() { return new ArrayList<>(clientPushConnectionMap.values()); }
@Test void testGetAll() { pushConnectionRegistry.put("clientId1", pushConnection); pushConnectionRegistry.put("clientId2", pushConnection); List<PushConnection> connections = pushConnectionRegistry.getAll(); assertEquals(2, connections.size()); }
public LoggerContext apply(LogLevelConfig logLevelConfig, Props props) { if (!ROOT_LOGGER_NAME.equals(logLevelConfig.getRootLoggerName())) { throw new IllegalArgumentException("Value of LogLevelConfig#rootLoggerName must be \"" + ROOT_LOGGER_NAME + "\""); } LoggerContext rootContext = getRootContext(...
@Test public void apply_sets_domain_property_over_global_property_if_both_set() { LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", WEB_SERVER, LogDomain.ES).build(); props.set("sonar.log.level", "DEBUG"); props.set("sonar.log.level.web.es", "TRACE"); LoggerContext context = underTest....
public static Event[] fromJson(final String json) throws IOException { return fromJson(json, BasicEventFactory.INSTANCE); }
@Test(expected=ClassCastException.class) public void testFromJsonWithInvalidJsonArray2() throws Exception { Event.fromJson("[\"gabeutch\"]"); }
@Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { return createInputStream(() -> originalFs.open(f, bufferSize)); }
@Test void testSlowInputStreamNotClosed() throws Exception { final File file = File.createTempFile("junit", null, tempFolder); createRandomContents(file, new Random(), 50); final LimitedConnectionsFileSystem fs = new LimitedConnectionsFileSystem(LocalFileSystem.getSharedInst...
@Override public void updateProject(GoViewProjectUpdateReqVO updateReqVO) { // 校验存在 validateProjectExists(updateReqVO.getId()); // 更新 GoViewProjectDO updateObj = GoViewProjectConvert.INSTANCE.convert(updateReqVO); goViewProjectMapper.updateById(updateObj); }
@Test public void testUpdateProject_success() { // mock 数据 GoViewProjectDO dbGoViewProject = randomPojo(GoViewProjectDO.class); goViewProjectMapper.insert(dbGoViewProject);// @Sql: 先插入出一条存在的数据 // 准备参数 GoViewProjectUpdateReqVO reqVO = randomPojo(GoViewProjectUpdateReqVO.class,...
public <T extends AwsSyncClientBuilder> void applyHttpClientConfigurations(T builder) { if (Strings.isNullOrEmpty(httpClientType)) { httpClientType = CLIENT_TYPE_DEFAULT; } switch (httpClientType) { case CLIENT_TYPE_URLCONNECTION: UrlConnectionHttpClientConfigurations urlConnectionHttpC...
@Test public void testApacheHttpClientConfiguration() { Map<String, String> properties = Maps.newHashMap(); properties.put(HttpClientProperties.CLIENT_TYPE, "apache"); HttpClientProperties httpClientProperties = new HttpClientProperties(properties); S3ClientBuilder mockS3ClientBuilder = Mockito.mock(S...
@Override public boolean remove(Object value) { lock.lock(); try { checkComparator(); BinarySearchResult<V> res = binarySearch((V) value); if (res.getIndex() < 0) { return false; } remove((int) res.getIndex())...
@Test public void testRemove() { RPriorityQueue<Integer> set = redisson.getPriorityQueue("set"); set.add(5); set.add(3); set.add(1); set.add(2); set.add(4); set.add(1); Assertions.assertFalse(set.remove(0)); Assertions.assertTrue(set.remove(3)...
public static TextSingleFormField.Builder textSingleBuilder(String fieldName) { return new TextSingleFormField.Builder(fieldName, Type.text_single); }
@Test public void testThrowExceptionWhenNullLabel() { TextSingleFormField.Builder builder = FormField.textSingleBuilder("type"); assertThrows(IllegalArgumentException.class, () -> builder.setLabel(null)); }
@Nullable static String errorCode(Throwable error) { if (error instanceof RpcException) { return ERROR_CODE_NUMBER_TO_NAME.get(((RpcException) error).getCode()); } return null; }
@Test void errorCodes() { assertThat(DubboParser.errorCode(null)) .isEqualTo(DubboParser.errorCode(new IOException("timeout"))) .isNull(); assertThat(DubboParser.errorCode(new RpcException(0))) .isEqualTo("UNKNOWN_EXCEPTION"); assertThat(DubboParser.errorCode(new RpcException(1))) ...
protected Diff() {}
@Test(timeout=60000) public void testDiff() throws Exception { for(int startSize = 0; startSize <= 10000; startSize = nextStep(startSize)) { for(int m = 0; m <= 10000; m = nextStep(m)) { runDiffTest(startSize, m); } } }
@VisibleForTesting public int getListReservationsFailedRetrieved() { return numListReservationsFailedRetrieved.value(); }
@Test public void testListReservationsFailed() { long totalBadBefore = metrics.getListReservationsFailedRetrieved(); badSubCluster.getListReservations(); Assert.assertEquals(totalBadBefore + 1, metrics.getListReservationsFailedRetrieved()); }
public int[] predict(int[] o) { int N = a.nrow(); // The probability of the most probable path. double[][] trellis = new double[o.length][N]; // Backtrace. int[][] psy = new int[o.length][N]; // The most likely state sequence. int[] s = new int[o.length]; ...
@Test public void testPredict() { System.out.println("predict"); HMM hmm = new HMM(pi, Matrix.of(a), Matrix.of(b)); int[] o = {0, 0, 1, 1, 0, 1, 1, 0}; int[] s = {0, 0, 0, 0, 0, 0, 0, 0}; int[] result = hmm.predict(o); assertEquals(o.length, result.length); fo...
@Override @CheckForNull public EmailMessage format(Notification notification) { if (!"alerts".equals(notification.getType())) { return null; } // Retrieve useful values String projectId = notification.getFieldValue("projectId"); String projectKey = notification.getFieldValue("projectKey")...
@Test public void shouldFormatNewAlertWithOneMessageOnBranch() { Notification notification = createNotification("Failed", "violations > 4", "ERROR", "true") .setFieldValue("branch", "feature"); EmailMessage message = template.format(notification); assertThat(message.getMessageId(), is("alerts/45"))...
static ArgumentParser argParser() { ArgumentParser parser = ArgumentParsers .newArgumentParser("producer-performance") .defaultHelp(true) .description("This tool is used to verify the producer performance. To enable transactions, " + "you c...
@Test public void testEnableTransactionByProducerProps() throws IOException, ArgumentParserException { ArgumentParser parser = ProducerPerformance.argParser(); String[] args = new String[]{ "--topic", "Hello-Kafka", "--num-records", "5", "--throughput", "100", ...
public Operation parseMethod( Method method, List<Parameter> globalParameters, JsonView jsonViewAnnotation) { JavaType classType = TypeFactory.defaultInstance().constructType(method.getDeclaringClass()); return parseMethod( classType.getClass(), ...
@Test(description = "scan methods") public void testScanMethods() { Reader reader = new Reader(new OpenAPI()); Method[] methods = SimpleMethods.class.getMethods(); for (final Method method : methods) { if (isValidRestPath(method)) { Operation operation = reader.pa...
public String getTopicName(AsyncMockDefinition definition, EventMessage eventMessage) { // Produce service name part of topic name. String serviceName = definition.getOwnerService().getName().replace(" ", ""); serviceName = serviceName.replace("-", ""); // Produce version name part of topic nam...
@Test void testGetTopicName() { KafkaProducerManager producerManager = new KafkaProducerManager(); Service service = new Service(); service.setName("Streetlights API"); service.setVersion("0.1.0"); Operation operation = new Operation(); operation.setName("RECEIVE receiveLightMea...
public static <K, V> V computeIfAbsent(ConcurrentMap<K, V> map, K key, Function<? super K, ? extends V> func) { Objects.requireNonNull(func); if (isJdk8) { V v = map.get(key); if (null == v) { // this bug fix methods maybe cause `func.apply` multiple calls. ...
@Test public void computeIfAbsent() { ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(); map.put("123", "1111"); String value = ConcurrentHashMapUtils.computeIfAbsent(map, "123", k -> "234"); assertEquals("1111", value); String value1 = ConcurrentHashMapUtils....
public static <T> Partition<T> of( int numPartitions, PartitionWithSideInputsFn<? super T> partitionFn, Requirements requirements) { Contextful ctfFn = Contextful.fn( (T element, Contextful.Fn.Context c) -> partitionFn.partitionFor(element, numPartitions, c), ...
@Test @Category(NeedsRunner.class) public void testDroppedPartition() { // Compute the set of integers either 1 or 2 mod 3, the hard way. PCollectionList<Integer> outputs = pipeline .apply(Create.of(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) .apply(Partition.of(3, new ModFn())); ...
public static Builder builder() { return new Builder(); }
@Test public void testBuilder() { PiTableId piTableId = PiTableId.of("table10"); long cookie = 0xfff0323; int priority = 100; double timeout = 1000; PiMatchFieldId piMatchFieldId = PiMatchFieldId.of(IPV4_HEADER_NAME + DOT + DST_ADDR); PiFieldMatch piFieldMatch = new ...
public void createPipe(CreatePipeStmt stmt) throws DdlException { try { lock.writeLock().lock(); Pair<Long, String> dbIdAndName = resolvePipeNameUnlock(stmt.getPipeName()); boolean existed = nameToId.containsKey(dbIdAndName); if (existed) { if (!st...
@Test @Ignore("flaky test") public void testExecuteTaskSubmitFailed() throws Exception { mockRepoExecutor(); final String pipeName = "p3"; String sql = "create pipe p3 as insert into tbl1 select * from files('path'='fake://pipe', 'format'='parquet')"; createPipe(sql); //...
@Override public CucumberOptionsAnnotationParser.CucumberOptions getOptions(Class<?> clazz) { CucumberOptions annotation = clazz.getAnnotation(CucumberOptions.class); if (annotation != null) { return new JunitCucumberOptions(annotation); } warnWhenTestNGCucumberOptionsAre...
@Test void testUuidGeneratorWhenNotSpecified() { io.cucumber.core.options.CucumberOptionsAnnotationParser.CucumberOptions options = this.optionsProvider .getOptions(ClassWithDefault.class); assertNotNull(options); assertNull(options.uuidGenerator()); }
public SchemaMapping fromParquet(MessageType parquetSchema) { List<Type> fields = parquetSchema.getFields(); List<TypeMapping> mappings = fromParquet(fields); List<Field> arrowFields = fields(mappings); return new SchemaMapping(new Schema(arrowFields), parquetSchema, mappings); }
@Test public void testParquetMapToArrow() { GroupType mapType = Types.requiredMap().key(INT32).optionalValue(INT64).named("myMap"); MessageType parquet = Types.buildMessage().addField(mapType).named("root"); Schema expected = new Schema(asList(field( "myMap", new ArrowType.Map(false), ...
@Override public TopicRouteData examineTopicRouteInfo( String topic) throws RemotingException, MQClientException, InterruptedException { return defaultMQAdminExtImpl.examineTopicRouteInfo(topic); }
@Test public void testExamineTopicRouteInfo() throws RemotingException, MQClientException, InterruptedException { TopicRouteData topicRouteData = defaultMQAdminExt.examineTopicRouteInfo("UnitTest"); assertThat(topicRouteData.getBrokerDatas().get(0).getBrokerName()).isEqualTo("default-broker"); ...
public static long hashToLong(final String value) { return getHashString(value).asLong(); }
@Test void shouldReturnConsistentHashLong() { assertEquals(Hashing.hashToLong("random"), 8668895776616456786L); }
@Override public Failure parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { Failure.CompressFailureError compressFailureError = null; StanzaError stanzaError = null; XmlEnvironment failureXmlEnviron...
@Test public void simpleFailureTest() throws Exception { final String xml = "<failure xmlns='http://jabber.org/protocol/compress'><processing-failed/></failure>"; final XmlPullParser parser = PacketParserUtils.getParserFor(xml); final Failure failure = FailureProvider.INSTANCE.parse(parser);...
@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 assertWriteWithEightBytes() { MySQLTimeBinaryProtocolValue actual = new MySQLTimeBinaryProtocolValue(); actual.write(payload, Time.valueOf("01:30:10")); verify(payload).writeInt1(8); verify(payload).writeInt1(0); verify(payload).writeInt4(0); payload.writeI...
@Override public boolean isDetected() { return StringUtils.isNotBlank(system.envVariable("GITHUB_ACTION")); }
@Test public void isDetected() { setEnvVariable("GITHUB_ACTION", "build"); assertThat(underTest.isDetected()).isTrue(); setEnvVariable("GITHUB_ACTION", null); assertThat(underTest.isDetected()).isFalse(); }
@Override public long estimate() { final double raw = (1 / computeE()) * alpha() * m * m; return applyRangeCorrection(raw); }
@RequireAssertEnabled @Test(expected = AssertionError.class) public void testAlpha_withInvalidMemoryFootprint() { DenseHyperLogLogEncoder encoder = new DenseHyperLogLogEncoder(1); encoder.estimate(); }
@Nullable public static URI normalizeURI(@Nullable final URI uri, String scheme, int port, String path) { return Optional.ofNullable(uri) .map(u -> getUriWithScheme(u, scheme)) .map(u -> getUriWithPort(u, port)) .map(u -> getUriWithDefaultPath(u, path)) ...
@Test public void normalizeURIReturnsNormalizedURI() { final URI uri = URI.create("foobar://example.com//foo/////bar"); assertEquals(URI.create("quux://example.com:1234/foo/bar/"), Tools.normalizeURI(uri, "quux", 1234, "/baz")); }
@Override protected void runTask() { LOGGER.trace("Looking for deleted jobs that can be deleted permanently..."); int totalAmountOfPermanentlyDeletedJobs = storageProvider.deleteJobsPermanently(StateName.DELETED, now().minus(backgroundJobServerConfiguration().getPermanentlyDeleteDeletedJobsAfter()))...
@Test void testTask() { runTask(task); verify(storageProvider).deleteJobsPermanently(eq(DELETED), any()); }
public Set<PValue> getKeyedPValues() { checkState( finalized, "can't call getKeyedPValues before a Pipeline has been completely traversed"); return keyedValues; }
@Test public void unkeyedInputWithKeyPreserving() { PCollection<KV<String, Iterable<WindowedValue<KV<String, Integer>>>>> input = p.apply( Create.of( KV.of( "hello", (Iterable<WindowedValue<KV<String, Integer>>>) ...
public Statistics getTableStatistics(IcebergTable icebergTable, Map<ColumnRefOperator, Column> colRefToColumnMetaMap, OptimizerContext session, ScalarOperator predicate, ...
@Test public void testUnknownTableStatistics() { IcebergStatisticProvider statisticProvider = new IcebergStatisticProvider(); mockedNativeTableA.newFastAppend().appendFile(FILE_A).commit(); IcebergTable icebergTable = new IcebergTable(1, "srTableName", "iceberg_catalog", "resource_name", "db...
public static String evaluate(final co.elastic.logstash.api.Event event, final String template) throws JsonProcessingException { if (event instanceof Event) { return evaluate((Event) event, template); } else { throw new IllegalStateException("Unknown event concrete class:...
@Test public void TestMixDateAndFields() throws IOException { Event event = getTestEvent(); String path = "/full/%{+YYYY}/weeee/%{bar}"; assertEquals("/full/2015/weeee/foo", StringInterpolation.evaluate(event, path)); }
public static <T> byte[] write(Writer<T> writer, T value) { byte[] result = new byte[writer.sizeInBytes(value)]; WriteBuffer b = WriteBuffer.wrap(result); try { writer.write(value, b); } catch (RuntimeException e) { int lengthWritten = result.length; for (int i = 0; i < result.length; ...
@Test void doesntStackOverflowOnToBufferWriterBug_lessThanBytes() { class FooWriter implements WriteBuffer.Writer<Object> { @Override public int sizeInBytes(Object value) { return 2; } @Override public void write(Object value, WriteBuffer buffer) { buffer.writeByte('a'); t...
public static String normalizeParams(String paramPart, Charset charset) { if(StrUtil.isEmpty(paramPart)){ return paramPart; } final StrBuilder builder = StrBuilder.create(paramPart.length() + 16); final int len = paramPart.length(); String name = null; int pos = 0; // 未处理字符开始位置 char c; // 当前字符 int i;...
@Test public void normalizeBlankParamsTest() { final String encodeResult = HttpUtil.normalizeParams("", CharsetUtil.CHARSET_UTF_8); assertEquals("", encodeResult); }
@Override public Boolean authenticate(final Host bookmark, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { final Credentials credentials = bookmark.getCredentials(); if(credentials.isPublicKeyAuthentication()) { if(log.isDebugEnabled()) { ...
@Test(expected = LoginCanceledException.class) public void testAuthenticateOpenSSHKeyWithPassword() throws Exception { final Local key = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); try { new DefaultLocalTouchFeature().touch(key); IOUtils.cop...
public Task schedule(BackOff backOff, ThrowingFunction<Task, Boolean, Exception> function) { final BackOffTimerTask task = new BackOffTimerTask(backOff, scheduler, function); long delay = task.next(); if (delay != BackOff.NEVER) { scheduler.schedule(task, delay, TimeUnit.MILLISECOND...
@Test public void testBackOffTimerWithMaxElapsedTime() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger counter = new AtomicInteger(); final ScheduledExecutorService executor = Executors.newScheduledThreadPool(3); final BackOff backOff = Back...
public ValidationResult validateSecretsConfig(final String pluginId, final Map<String, String> configuration) { return getVersionedSecretsExtension(pluginId).validateSecretsConfig(pluginId, configuration); }
@Test void validateSecretsConfig_shouldDelegateToVersionedExtension() { SecretsExtensionV1 secretsExtensionV1 = mock(SecretsExtensionV1.class); Map<String, VersionedSecretsExtension> secretsExtensionMap = Map.of("1.0", secretsExtensionV1); extension = new SecretsExtension(pluginManager, exte...
@PublicEvolving public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes( MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) { return getMapReturnTypes(mapInterface, inType, null, false); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test void testValueSupertypeException() { RichMapFunction<?, ?> function = new RichMapFunction<StringValue, Value>() { private static final long serialVersionUID = 1L; @Override pub...
public ConsumptionRateLimiter createServerRateLimiter(PinotConfiguration serverConfig, ServerMetrics serverMetrics) { double serverRateLimit = serverConfig.getProperty(CommonConstants.Server.CONFIG_OF_SERVER_CONSUMPTION_RATE_LIMIT, CommonConstants.Server.DEFAULT_SERVER_CONSUMPTION_RATE_LIMIT); ...
@Test public void testCreateServerRateLimiter() { // Server config 1 ConsumptionRateLimiter rateLimiter = _consumptionRateManager.createServerRateLimiter(SERVER_CONFIG_1, null); assertEquals(5.0, ((RateLimiterImpl) rateLimiter).getRate(), DELTA); // Server config 2 rateLimiter = _consumptionRateM...
@Override public boolean tryClaim(Timestamp position) { if (position.equals(lastAttemptedPosition)) { return true; } return super.tryClaim(position, this.partition); }
@Test public void testTryClaim() { assertEquals(range, tracker.currentRestriction()); assertTrue(tracker.tryClaim(Timestamp.ofTimeMicroseconds(10L))); assertTrue(tracker.tryClaim(Timestamp.ofTimeMicroseconds(10L))); assertTrue(tracker.tryClaim(Timestamp.ofTimeMicroseconds(11L))); assertTrue(tracke...
public boolean isJavaFunction() { return type == Type.JAVA_FUNCTION; }
@Test void testJavaFunction() { Variable v = new Variable((Function<String, String>) this::simpleFunction); assertTrue(v.isJavaFunction()); v = new Variable((BiFunction<String, String, String>) this::simpleBiFunction); // maybe we are ok with this, karate "call" can be used only with...
public void processNullMessage(Null nullMessage, Afnemersbericht afnemersbericht){ if (afnemersbericht != null && afnemersbericht.getType() == Afnemersbericht.Type.Av01){ afnemersberichtRepository.delete(afnemersbericht); } logger.info("Received null message"); }
@Test public void testProcessNullMessageAv01(){ Null testNullMessage = TestDglMessagesUtil.createTestNullMessage(); when(afnemersbericht.getType()).thenReturn(Afnemersbericht.Type.Av01); classUnderTest.processNullMessage(testNullMessage, afnemersbericht); verify(afnemersberichtRep...
public static synchronized void configure(DataflowWorkerLoggingOptions options) { if (!initialized) { throw new RuntimeException("configure() called before initialize()"); } // For compatibility reason, we do not call SdkHarnessOptions.getConfiguredLoggerFromOptions // to config the logging for l...
@Test public void testWithSdkHarnessCustomLogLevels() { SdkHarnessOptions options = PipelineOptionsFactory.as(SdkHarnessOptions.class); options.setSdkHarnessLogLevelOverrides( new SdkHarnessLogLevelOverrides() .addOverrideForName("C", SdkHarnessOptions.LogLevel.DEBUG) .addOverr...
public JoinedRowData replace(RowData row1, RowData row2) { this.row1 = row1; this.row2 = row2; return this; }
@Test void testReplace() { final RowData row1 = GenericRowData.of(1L); final RowData row2 = GenericRowData.of(2L); final JoinedRowData joinedRow = new JoinedRowData(row1, row2); assertThat(joinedRow).hasArity(2); joinedRow.replace(GenericRowData.of(3L), GenericRowData.of(4L...
@Override public Path move(final Path file, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException { try { final EueApiClient client = new EueApiClient(session); if(status.isExists()) { ...
@Test public void testMoveFileToRoot() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final Path sourceFolder = new EueDirectoryFeature(session, fileid).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.d...
public int size() { return mWorkers.size(); }
@Test public void size() { WorkerIdentity worker1 = WorkerIdentityTestUtils.ofLegacyId(1); WorkerIdentity worker2 = WorkerIdentityTestUtils.ofLegacyId(2); List<WorkerInfo> workers = ImmutableList.of( new WorkerInfo().setIdentity(worker1), new WorkerInfo().setIdentity(worker2) ); Wo...
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 shouldFormatSelectWithReservedWordAlias() { final String statementString = "CREATE STREAM S AS SELECT address AS `STREAM` FROM address;"; final Statement statement = parseSingle(statementString); assertThat(SqlFormatter.formatSql(statement), equalTo("CREATE STREAM S AS SELECT" ...
public static KMeans fit(double[][] data, int k) { return fit(data, k, 100, 1E-4); }
@Test public void testUSPS() throws Exception { System.out.println("USPS"); MathEx.setSeed(19650218); // to get repeatable results. double[][] x = USPS.x; int[] y = USPS.y; double[][] testx = USPS.testx; int[] testy = USPS.testy; KMeans model = KMeans.fit(x,...
public static int compareVersion(final String versionA, final String versionB) { final String[] sA = versionA.split("\\."); final String[] sB = versionB.split("\\."); int expectSize = 3; if (sA.length != expectSize || sB.length != expectSize) { throw new IllegalArgumentExcept...
@Test void testVersionCompareEtWithChar() { assertEquals(0, VersionUtils.compareVersion("1.2.1", "1.2.1-beta")); }
@Override public String toString() { ToStringHelper helper = MoreObjects.toStringHelper("byte[]"); if (bytes != null) { helper.add("length", bytes.length) .add("hash", Arrays.hashCode(bytes)); } else { helper.addValue(bytes); } return...
@Test public void testToString() { final byte[] some = new byte[] {2, 5, 0, 1 }; final String expected = "byte[]{length=" + some.length + ", hash=" + Arrays.hashCode(some) + "}"; assertEquals(expected, String.valueOf(ByteArraySizeHashPrinter.of(some))); assertNotNull(ByteArraySizeHa...
@Override public boolean markSlotActive(AllocationID allocationId) throws SlotNotFoundException { checkRunning(); TaskSlot<T> taskSlot = getTaskSlot(allocationId); if (taskSlot != null) { return markExistingSlotActive(taskSlot); } else { throw new SlotNotFou...
@Test void testMarkSlotActiveDeactivatesSlotTimeout() throws Exception { runDeactivateSlotTimeoutTest( (taskSlotTable, jobId, allocationId) -> taskSlotTable.markSlotActive(allocationId)); }
@Operation(summary = "queryUnauthorizedProject", description = "QUERY_UNAUTHORIZED_PROJECT_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", schema = @Schema(implementation = int.class, example = "100")) }) @GetMapping(value = "/unauth-project") @ResponseStatus(HttpS...
@Test public void testQueryUnauthorizedProject() { Result result = new Result(); putMsg(result, Status.SUCCESS); Mockito.when(projectService.queryUnauthorizedProject(user, 2)).thenReturn(result); Result response = projectController.queryUnauthorizedProject(user, 2); Assertion...
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { String returnCommand = null; Throwable exception = (Throwable) Protocol.getObject(reader.readLine(), this.gateway); // EOQ reader.readLine(); String stackTrace = Protocol.ge...
@Test public void testException() { String id = null; try { throw new RuntimeException("Hello World"); } catch (Exception e) { id = "r" + gateway.putNewObject(e); } String inputCommand = id + "\ne\n"; try { command.execute("p", new BufferedReader(new StringReader(inputCommand)), writer); Syste...
public void updateEndTime(String eventName, long endTime) { synchronized (mTrackTimer) { EventTimer eventTimer = mTrackTimer.get(eventName); if (eventTimer != null) { eventTimer.setEndTime(endTime); } } }
@Test public void updateEndTime() { mInstance.addEventTimer("EventTimer", new EventTimer(TimeUnit.SECONDS, 10000L)); mInstance.updateEndTime("EventTimer", 20000); Assert.assertEquals(20000, mInstance.getEventTimer("EventTimer").getEndTime()); }
public static <T> Iterator<Class<T>> classIterator(Class<T> expectedType, String factoryId, ClassLoader classLoader) { Set<ServiceDefinition> serviceDefinitions = getServiceDefinitions(factoryId, classLoader); return new ClassIterator<>(serviceDefinitions, expectedType); }
@Test public void testClassIteratorInTomcat_whenClassesInBothLibs() throws Exception { ClassLoader launchClassLoader = this.getClass().getClassLoader(); ClassLoader webappClassLoader; // setup embedded tomcat Tomcat tomcat = new Tomcat(); tomcat.setPort(13256); //...
@PutMapping("/{id}") @RequiresPermissions("system:plugin:edit") public ShenyuAdminResult updatePlugin(@PathVariable("id") @Existed(message = "plugin is not existed", provider = PluginMapper.class) final String id, ...
@Test public void testUpdatePlugin() throws Exception { PluginDTO pluginDTO = new PluginDTO(); pluginDTO.setId("123"); pluginDTO.setName("test1"); pluginDTO.setEnabled(true); pluginDTO.setRole("1"); pluginDTO.setSort(100); when(SpringBeanUtils.getInstance().ge...
public static Criterion matchMplsTc(byte mplsTc) { return new MplsTcCriterion(mplsTc); }
@Test public void testMatchMplsTcMethod() { Criterion matchMplsTc = Criteria.matchMplsTc(mplsTc1); MplsTcCriterion mplsTcCriterion = checkAndConvert(matchMplsTc, Criterion.Type.MPLS_TC, MplsTcCriterion.class); as...
static Optional<ExecutorService> lookupExecutorServiceRef( CamelContext camelContext, String name, Object source, String executorServiceRef) { ExecutorServiceManager manager = camelContext.getExecutorServiceManager(); ObjectHelper.notNull(manager, ESM_NAME); ObjectHelper.notNull(exec...
@Test void testLookupExecutorServiceRefWithNewThreadPool() { String name = "ThreadPool"; Object source = new Object(); String executorServiceRef = "NewThreadPool"; when(camelContext.getExecutorServiceManager()).thenReturn(manager); when(manager.newThreadPool(source, name, exe...
public static List<String> getSupportedCipherSuites() throws NoSuchAlgorithmException, KeyManagementException { // TODO Might want to cache the result. It's unlikely to change at runtime. final SSLContext context = getUninitializedSSLContext(); context.init( null, null, null ); retur...
@Test public void testHasSupportedCipherSuites() throws Exception { // Setup fixture. // (not needed) // Execute system under test. final Collection<String> result = EncryptionArtifactFactory.getSupportedCipherSuites(); // Verify results. assertFalse( result.isE...
@Override public boolean isGenerateSQLToken(final SQLStatementContext sqlStatementContext) { if (!(sqlStatementContext instanceof InsertStatementContext)) { return false; } Optional<InsertColumnsSegment> insertColumnsSegment = ((InsertStatementContext) sqlStatementContext).getSql...
@Test void assertIsGenerateSQLTokenWithInsertStatementContext() { assertTrue(generator.isGenerateSQLToken(EncryptGeneratorFixtureBuilder.createInsertStatementContext(Collections.emptyList()))); }
public String toHtml(@Nullable RuleDto.Format descriptionFormat, RuleDescriptionSectionDto ruleDescriptionSectionDto) { if (MARKDOWN.equals(descriptionFormat)) { return Markdown.convertToHtml(ruleDescriptionSectionDto.getContent()); } return ruleDescriptionSectionDto.getContent(); }
@Test public void toHtmlWithHtmlFormat() { String result = ruleDescriptionFormatter.toHtml(HTML, HTML_SECTION); assertThat(result).isEqualTo(HTML_SECTION.getContent()); }
@Override public void updateIndices(SegmentDirectory.Writer segmentWriter) throws Exception { Map<String, List<Operation>> columnOperationsMap = computeOperations(segmentWriter); if (columnOperationsMap.isEmpty()) { return; } for (Map.Entry<String, List<Operation>> entry : columnOperation...
@Test public void testDisableForwardIndexForSingleDictColumn() throws Exception { Set<String> forwardIndexDisabledColumns = new HashSet<>(SV_FORWARD_INDEX_DISABLED_COLUMNS); forwardIndexDisabledColumns.addAll(MV_FORWARD_INDEX_DISABLED_COLUMNS); forwardIndexDisabledColumns.addAll(MV_FORWARD_INDEX_DIS...
public List<InterpreterResultMessage> message() { return msg; }
@Test void testSimpleMagicType() { InterpreterResult result = null; result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%table col1\tcol2\naaa\t123\n"); assertEquals(InterpreterResult.Type.TABLE, result.message().get(0).getType()); result = new InterpreterResult(InterpreterResult....
@Udf(description = "Returns the portion of str from pos to the end of str") public String substring( @UdfParameter(description = "The source string.") final String str, @UdfParameter(description = "The base-one position to start from.") final Integer pos ) { if (str == null || pos == null) { r...
@Test public void shouldTruncateOutOfBoundIndexesOnStrings() { assertThat(udf.substring("a test string", 0), is("a test string")); assertThat(udf.substring("a test string", 100), is("")); assertThat(udf.substring("a test string", -100), is("a test string")); assertThat(udf.substring("a test string", 3...
@Override public int maxCapacity() { return maxCapacity; }
@Test public void testCapacityNegative() { final ByteBuf buffer = newBuffer(3, 13); assertEquals(13, buffer.maxCapacity()); assertEquals(3, buffer.capacity()); try { assertThrows(IllegalArgumentException.class, new Executable() { @Override ...
public double d(int[] x, int[] y) { if (x.length != y.length) { throw new IllegalArgumentException(String.format("Arrays have different length: x[%d], y[%d]", x.length, y.length)); } double dist = 0.0; if (weight == null) { for (int i = 0; i < x.length; i++) { ...
@Test public void testDistance() { System.out.println("distance"); double[] x = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515}; double[] y = {-1.7781325, -0.6659839, 0.9526148, -0.9460919, -0.3925300}; MinkowskiDistance m3 = new MinkowskiDistance(3); MinkowskiD...
@Override public BuiltInScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, FunctionAndTypeManager functionAndTypeManager) { ImmutableList.Builder<ScalarFunctionImplementationChoice> implementationChoices = ImmutableList.builder(); for (PolymorphicScalarFunctionCho...
@Test public void testSelectsMethodBasedOnArgumentTypes() throws Throwable { SqlScalarFunction function = SqlScalarFunction.builder(TestMethods.class) .signature(SIGNATURE) .deterministic(true) .calledOnNullInput(false) .choice(...
public static String toJavaCode( final String argName, final Class<?> argType, final String lambdaBody ) { return toJavaCode(ImmutableList.of(new Pair<>(argName, argType)), lambdaBody); }
@Test public void shouldGenerateFunctionCode() { // Given: final String argName = "fred"; final Class<?> argType = Long.class; // When: final String javaCode = LambdaUtil .toJavaCode(argName, argType, argName + " + 1"); // Then: final Object result = CodeGenTestUtil.cookAndEval(j...
public static <K, V> Write<K, V> write() { return new AutoValue_CdapIO_Write.Builder<K, V>().build(); }
@Test public void testWindowedWriteCdapBatchSinkPlugin() throws IOException { List<KV<String, String>> data = new ArrayList<>(); for (int i = 0; i < EmployeeInputFormat.NUM_OF_TEST_EMPLOYEE_RECORDS; i++) { data.add(KV.of(String.valueOf(i), EmployeeInputFormat.EMPLOYEE_NAME_PREFIX + i)); } PColle...
public LocalReplicatedMapStats getLocalReplicatedMapStats(String name) { return statsProvider.getLocalReplicatedMapStats(name); }
@Test public void testGetLocalReplicatedMapStatsNoObjectGenerationIfDisabledStats() { String name = randomMapName(); ReplicatedMapConfig replicatedMapConfig = new ReplicatedMapConfig(); replicatedMapConfig.setName(name); replicatedMapConfig.setStatisticsEnabled(false); nodeEn...
@SuppressWarnings("unchecked") @Override public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) throws YarnException, IOException { NodeStatus remoteNodeStatus = request.getNodeStatus(); /** * Here is the node heartbeat sequence... * 1. Check if it's a valid (i.e. not excl...
@Test(timeout = 30000) public void testInitDecommMetricNoRegistration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); nm1.nodeHeartbeat(true); ...
@Udf public String concat(@UdfParameter( description = "The varchar fields to concatenate") final String... inputs) { if (inputs == null) { return null; } return Arrays.stream(inputs) .filter(Objects::nonNull) .collect(Collectors.joining()); }
@Test public void shouldConcatStrings() { assertThat(udf.concat("The", "Quick", "Brown", "Fox"), is("TheQuickBrownFox")); }
@ApiOperation(value = "Create Or Update Asset (saveAsset)", notes = "Creates or Updates the Asset. When creating asset, platform generates Asset Id as " + UUID_WIKI_LINK + "The newly created Asset id will be present in the response. " + "Specify existing Asset id to u...
@Test public void testSaveAsset() throws Exception { Asset asset = new Asset(); asset.setName("My asset"); asset.setType("default"); Mockito.reset(tbClusterService, auditLogService); Asset savedAsset = doPost("/api/asset", asset, Asset.class); testNotifyEntityAllOn...
@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 doesNotReportStringGaugeValues() throws Exception { reporter.report(map("gauge", gauge("value")), map(), map(), map(), map()); final InOrder inOrder = inOrder(graphite); inOrder.verify(graphite).connect(); inOrder.ver...
public void setHeaders(URLConnection connection, HTTPSamplerBase sampler) throws IOException { // Get the encoding to use for the request String contentEncoding = sampler.getContentEncoding(); long contentLength = 0L; HTTPFileArg[] files = sampler.getHTTPFiles(); // Check if we ...
@Test public void testSetHeaders_NoFilename() throws IOException { sampler.setMethod(HTTPConstants.POST); setupNoFilename(sampler); setupFormData(sampler); postWriter.setHeaders(connection, sampler); checkNoContentType(connection); checkContentLength(connection, "tit...
String extractVariablesFromAngularRegistry(String scriptBody, Map<String, Input> inputs, AngularObjectRegistry angularRegistry) { final String noteId = this.getNote().getId(); final String paragraphId = this.getId(); final Set<String> keys = new HashSet<>(inputs.keySet()); for (String varName :...
@Test void should_extract_variable_from_angular_object_registry() throws Exception { //Given final String noteId = "noteId"; final AngularObjectRegistry registry = mock(AngularObjectRegistry.class); final Note note = mock(Note.class); final Map<String, Input> inputs = new HashMap<>(); inputs....
public boolean validate(final CommandLine input) { for(Option o : input.getOptions()) { if(Option.UNINITIALIZED == o.getArgs()) { continue; } if(o.hasOptionalArg()) { continue; } if(o.getArgs() != o.getValuesList().size(...
@Test public void testListContainers() throws Exception { final Set<Protocol> list = new HashSet<>(Arrays.asList( new SwiftProtocol(), new ProfilePlistReader(new ProtocolFactory(Collections.singleton(new SwiftProtocol()))) .read(this.getClass().getResource...
@SuppressWarnings("unchecked") void openDB(final Map<String, Object> configs, final File stateDir) { // initialize the default rocksdb options final DBOptions dbOptions = new DBOptions(); final ColumnFamilyOptions columnFamilyOptions = new ColumnFamilyOptions(); userSpecifiedOptions...
@Test public void shouldSetStatisticsInValueProvidersWhenUserProvidesNoStatistics() throws Exception { rocksDBStore = getRocksDBStoreWithRocksDBMetricsRecorder(); context = getProcessorContext(RecordingLevel.DEBUG); rocksDBStore.openDB(context.appConfigs(), context.stateDir()); ver...
public static <K> Keys<K> create() { return new Keys<>(); }
@Test @Category(ValidatesRunner.class) public void testKeysEmpty() { PCollection<KV<String, Integer>> input = p.apply( Create.of(Arrays.asList(EMPTY_TABLE)) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); PCollection<String> output = input.appl...
public ZkService chooseService() { if (zkService != null) { return zkService; } synchronized (this) { if (zkService == null) { final String version = lbConfig.getZkServerVersion(); if (version.startsWith(VERSION_34_PREFIX)) { ...
@Test(expected = IllegalArgumentException.class) public void chooseService() { final ZkServiceManager zkServiceManager = new ZkServiceManager(); zkServiceManager.chooseService(); }
static PythonEnvironment preparePythonEnvironment( ReadableConfig config, String entryPointScript, String tmpDir) throws IOException { PythonEnvironment env = new PythonEnvironment(); // 1. set the path of python interpreter. String pythonExec = config.getOptional(PY...
@Test void testSetPythonExecutable() throws IOException { Configuration config = new Configuration(); File zipFile = new File(tmpDirPath + File.separator + "venv.zip"); try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(zipFile))) { ...
@Nonnull public static <K, V> Sink<Entry<K, V>> map(@Nonnull String mapName) { return map(mapName, Entry::getKey, Entry::getValue); }
@Test public void map_byRef() { // Given List<Integer> input = sequence(itemCount); putToBatchSrcMap(input); IMap<String, Integer> sinkMap = hz().getMap(sinkName); // When Sink<Entry<String, Integer>> sink = Sinks.map(sinkMap); // Then p.readFrom(Sou...
@Override public String getPrincipal() { Subject subject = org.apache.shiro.SecurityUtils.getSubject(); String principal; if (subject.isAuthenticated()) { principal = extractPrincipal(subject); if (zConf.isUsernameForceLowerCase()) { if (LOGGER.isDebugEnabled()) { LOGGER.deb...
@Test void canGetPrincipalName() { String expectedName = "java.security.Principal.getName()"; setupPrincipalName(expectedName); assertEquals(expectedName, shiroSecurityService.getPrincipal()); }
@Override public CacheOption swapToObject(final YamlSQLParserCacheOptionRuleConfiguration yamlConfig) { return new CacheOption(yamlConfig.getInitialCapacity(), yamlConfig.getMaximumSize()); }
@Test void assertSwapToObject() { YamlSQLParserCacheOptionRuleConfiguration cacheOptionRuleConfig = new YamlSQLParserCacheOptionRuleConfiguration(); cacheOptionRuleConfig.setInitialCapacity(2); cacheOptionRuleConfig.setMaximumSize(5L); CacheOption actual = new YamlSQLParserCacheOptio...
@Override public List<MenuDO> getMenuList() { return menuMapper.selectList(); }
@Test public void testGetMenuList_all() { // mock 数据 MenuDO menu100 = randomPojo(MenuDO.class); menuMapper.insert(menu100); MenuDO menu101 = randomPojo(MenuDO.class); menuMapper.insert(menu101); // 准备参数 // 调用 List<MenuDO> list = menuService.getMenuLis...