focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public String toString() { return "RangeSet(from=" + from + " (inclusive), to=" + to + " (exclusive))"; }
@Test void testToString() { RangeSet rangeSet = new RangeSet(5, 8); assertEquals("RangeSet(from=5 (inclusive), to=8 (exclusive))", rangeSet.toString()); }
public int getResourceProfileFailedRetrieved() { return numGetResourceProfileFailedRetrieved.value(); }
@Test public void testGetResourceProfileRetrievedFailed() { long totalBadBefore = metrics.getResourceProfileFailedRetrieved(); badSubCluster.getResourceProfileFailed(); Assert.assertEquals(totalBadBefore + 1, metrics.getResourceProfileFailedRetrieved()); }
@Override public boolean isUserConsentRequiredAfterUpgrade() { return configuration.getBoolean(GITLAB_USER_CONSENT_FOR_PERMISSION_PROVISIONING_REQUIRED).isPresent(); }
@Test public void isUserConsentRequiredForPermissionProvisioning_returnsTrueWhenPropertyPresent() { settings.setProperty(GITLAB_USER_CONSENT_FOR_PERMISSION_PROVISIONING_REQUIRED, ""); assertThat(config.isUserConsentRequiredAfterUpgrade()).isTrue(); }
@Override public Object getObject(final int columnIndex) throws SQLException { return mergeResultSet.getValue(columnIndex, Object.class); }
@Test void assertGetObjectWithTimestamp() throws SQLException { Timestamp result = mock(Timestamp.class); when(mergeResultSet.getValue(1, Timestamp.class)).thenReturn(result); assertThat(shardingSphereResultSet.getObject(1, Timestamp.class), is(result)); }
@Override public String toString() { return "ResourceConfig{" + "url=" + url + ", id='" + id + '\'' + ", resourceType=" + resourceType + '}'; }
@Test public void when_addDuplicateZipOfJarWithPath_then_throwsException() throws Exception { // Given String resourceId = "zipFile"; String path1 = createFile("path/to/" + resourceId).toString(); String path2 = createFile("path/to/another/" + resourceId).toString(); config.a...
static int inferParallelism( ReadableConfig readableConfig, long limitCount, Supplier<Integer> splitCountProvider) { int parallelism = readableConfig.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_DEFAULT_PARALLELISM); if (readableConfig.get(FlinkConfigOptions.TABLE_EXEC_ICEBERG_INFER_SOURCE_PARAL...
@Test public void testInferedParallelism() throws IOException { Configuration configuration = new Configuration(); // Empty table, infer parallelism should be at least 1 int parallelism = SourceUtil.inferParallelism(configuration, -1L, () -> 0); assertThat(parallelism).isEqualTo(1); // 2 splits (...
@Override public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { if(containerService.isContainer(source)) { if(new SimplePathPredicate(sourc...
@Test public void testMoveEncryptedDataRoom() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final String roomName = new AlphanumericRandomStringService().random(); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(roomName, EnumSe...
@Override public final void calculate() { }
@Test public void testCalculate() { function.accept(MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_1); function.accept(MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_2); function.calculate(); assertThat(function.getValue()).isEqualTo(H...
public static boolean test(byte[] bloomBytes, byte[]... topics) { Bloom bloom = new Bloom(bloomBytes); if (topics == null) { throw new IllegalArgumentException("topics can not be null"); } for (byte[] topic : topics) { if (!bloom.test(topic)) { ret...
@Test public void testStaticMethodTestWhenAllTopicsIsInBloomForBytesInput() { boolean result = Bloom.test( Numeric.hexStringToByteArray(ethereumSampleLogsBloom), Numeric.hexStringToByteArray(ethereumSampleLogs.get(0)), N...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { long datetime = payload.readInt8(); return 0L == datetime ? MySQLTimeValueUtils.DATETIME_OF_ZERO : readDateTime(datetime); }
@Test void assertReadNullTime() { when(payload.readInt8()).thenReturn(0L); assertThat(new MySQLDatetimeBinlogProtocolValue().read(columnDef, payload), is(MySQLTimeValueUtils.DATETIME_OF_ZERO)); }
public static void addListPopulationByObjectCreationExpr(final List<ObjectCreationExpr> toAdd, final BlockStmt body, final String listName) { toAdd.forEach(objectCreationExpr -> { ...
@Test void addListPopulation() { final List<ObjectCreationExpr> toAdd = IntStream.range(0, 5) .mapToObj(i -> { ObjectCreationExpr toReturn = new ObjectCreationExpr(); toReturn.setType(String.class); Expression value = new StringLite...
public static String computeQueryHash(String query) { requireNonNull(query, "query is null"); if (query.isEmpty()) { return ""; } byte[] queryBytes = query.getBytes(UTF_8); long queryHash = new XxHash64().update(queryBytes).hash(); return toHexString(que...
@Test public void testComputeQueryHashEquivalentStrings() { String query1 = "SELECT * FROM REPORTS WHERE YEAR >= 2000 AND ID = 293"; String query2 = "SELECT * FROM REPORTS WHERE YEAR >= 2000 AND ID = 293"; assertEquals(computeQueryHash(query1), computeQueryHash(query2)); }
public static String getDigitsOnly( String input ) { if ( Utils.isEmpty( input ) ) { return null; } StringBuilder digitsOnly = new StringBuilder(); char c; for ( int i = 0; i < input.length(); i++ ) { c = input.charAt( i ); if ( Character.isDigit( c ) ) { digitsOnly.append(...
@Test public void testGetDigitsOnly() { assertNull( Const.removeDigits( null ) ); assertEquals( "123456789", Const.getDigitsOnly( "123foo456bar789" ) ); }
@Override public boolean isSingleton() { return true; }
@Test public final void isSingletonShouldAlwaysReturnTrue() { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); assertTrue( "isSingleton() should always return true since each SpringRemoteCacheManagerFactoryBean will always produce " + "the same SpringRemoteCache...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testEthNewPendingTransactionFilter() throws Exception { web3j.ethNewPendingTransactionFilter().send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"eth_newPendingTransactionFilter\"," + "\"params\":[],\"id\":1}"); }
@Override public void deleteCouponTemplate(Long id) { // 校验存在 validateCouponTemplateExists(id); // 删除 couponTemplateMapper.deleteById(id); }
@Test public void testDeleteCouponTemplate_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> couponTemplateService.deleteCouponTemplate(id), COUPON_TEMPLATE_NOT_EXISTS); }
public static void convertReadBasedSplittableDoFnsToPrimitiveReadsIfNecessary(Pipeline pipeline) { if (!(ExperimentalOptions.hasExperiment(pipeline.getOptions(), "use_sdf_read") || ExperimentalOptions.hasExperiment( pipeline.getOptions(), "use_unbounded_sdf_wrapper")) || Experime...
@Test public void testConvertIsSkippedWhenUsingUseUnboundedSDFWrapper() { PipelineOptions pipelineOptions = PipelineOptionsFactory.create(); pipelineOptions.setRunner(CrashingRunner.class); ExperimentalOptions.addExperiment( pipelineOptions.as(ExperimentalOptions.class), "use_unbounded_sdf_wrapper...
@Override public Iterator<Text> search(String term) { if (invertedFile.containsKey(term)) { ArrayList<Text> hits = new ArrayList<>(invertedFile.get(term)); return hits.iterator(); } else { return Collections.emptyIterator(); } }
@Test public void testSearchNoHits() { System.out.println("search 'no hits'"); String[] terms = {"thisisnotaword"}; Iterator<Relevance> hits = corpus.search(new BM25(), terms); assertFalse(hits.hasNext()); }
@Override public MapperResult getCapacityList4CorrectUsage(MapperContext context) { String sql = "SELECT id, tenant_id FROM tenant_capacity WHERE id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"; return new MapperResult(sql, CollectionUtils.list(context.getWhereParameter(FieldConstant.ID), ...
@Test void testGetCapacityList4CorrectUsage() { Object id = 1; Object limit = 10; context.putWhereParameter(FieldConstant.ID, id); context.putWhereParameter(FieldConstant.LIMIT_SIZE, limit); MapperResult mapperResult = tenantCapacityMapperByDerby.getCapacityList4CorrectUsage(...
@Around(CLIENT_INTERFACE_REMOVE_CONFIG_RPC) Object removeConfigAroundRpc(ProceedingJoinPoint pjp, ConfigRemoveRequest request, RequestMeta meta) throws Throwable { final ConfigChangePointCutTypes configChangePointCutType = ConfigChangePointCutTypes.REMOVE_BY_RPC; final List<ConfigChangeP...
@Test void testRemoveConfigAroundRpc() throws Throwable { Mockito.when(configChangePluginService.executeType()).thenReturn(ConfigChangeExecuteTypes.EXECUTE_BEFORE_TYPE); ProceedingJoinPoint proceedingJoinPoint = Mockito.mock(ProceedingJoinPoint.class); ConfigRemoveRequest request = new Confi...
public int indexOf(final String str) { return indexOf(str, 0); }
@Test public void testIndexOf2() { final UnicodeHelper lh = new UnicodeHelper("a", Method.GRAPHEME); assertEquals(-1, lh.indexOf("b")); final UnicodeHelper lh2 = new UnicodeHelper( "a" + new String(Character.toChars(0x1f600)) + "a" + UCSTR + "A" + "k\u035fh" + "z" ...
public static boolean isNotEmpty(String str) { return !isEmpty(str); }
@Test void testIsNotEmpty() throws Exception { assertFalse(StringUtils.isNotEmpty(null)); assertFalse(StringUtils.isNotEmpty("")); assertTrue(StringUtils.isNotEmpty("abc")); }
public static Map<String, String> parseCondaCommonStdout(String out) throws IOException, InterruptedException { Map<String, String> kv = new LinkedHashMap<String, String>(); String[] lines = out.split("\n"); for (String s : lines) { if (s == null || s.isEmpty() || s.startsWith("#")) { c...
@Test void testParseCondaCommonStdout() throws IOException, InterruptedException { StringBuilder sb = new StringBuilder() .append("# comment1\n") .append("# comment2\n") .append("env1 /location1\n") .append("env2 /location2\n"); Map<String, String> locationPerEn...
public static long findAndVerifyWindowGrace(final GraphNode graphNode) { return findAndVerifyWindowGrace(graphNode, ""); }
@Test public void shouldExtractGraceFromSessionAncestorThroughStatefulParent() { final SessionWindows windows = SessionWindows.ofInactivityGapAndGrace(ofMillis(10L), ofMillis(1234L)); final StatefulProcessorNode<String, Long> graceGrandparent = new StatefulProcessorNode<>( "asdf", ...
public Filter parseSingleExpression(final String filterExpression, final List<EntityAttribute> attributes) { if (!filterExpression.contains(FIELD_AND_VALUE_SEPARATOR)) { throw new IllegalArgumentException(WRONG_FILTER_EXPR_FORMAT_ERROR_MSG); } final String[] split = filterExpression....
@Test void parsesFilterExpressionCorrectlyForOpenDateRanges() { final String dateString = "2012-12-12 12:12:12"; final DateTime dateObject = new DateTime(2012, 12, 12, 12, 12, 12, DateTimeZone.UTC); final List<EntityAttribute> entityAttributes = List.of(EntityAttribute.builder() ...
public static boolean isCompositeURI(URI uri) { String ssp = stripPrefix(uri.getRawSchemeSpecificPart().trim(), "//").trim(); if (ssp.indexOf('(') == 0 && checkParenthesis(ssp)) { return true; } return false; }
@Test public void testIsCompositeURIWithQueryNoSlashes() throws URISyntaxException { URI[] compositeURIs = new URI[] { new URI("test:(part1://host?part1=true)?outside=true"), new URI("broker:(tcp://localhost:61616)?name=foo") }; for (URI uri : compositeURIs) { assertTrue(uri + " must be ...
@Override public List<String> getServerList() { return serverList.isEmpty() ? serversFromEndpoint : serverList; }
@Test void testConstructWithEndpointAndRefreshEmpty() throws Exception { Properties properties = new Properties(); properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1"); serverListManager = new ServerListManager(properties); List<String> serverList = serverListManager.getServerList(...
@Override public void acknowledge(List<? extends Acknowledgeable> messages) { @SuppressWarnings("ConstantConditions") final Optional<Long> max = messages.stream() .map(Acknowledgeable::getMessageQueueId) .filter(this::isValidMessageQueu...
@Test void acknowledgeMessageWithWrongTypeOfMessageQueueId(MessageFactory messageFactory) { final Message message = messageFactory.createMessage("message", "source", DateTime.now(UTC)); message.setMessageQueueId("foo"); acknowledger.acknowledge(message); verifyNoMoreInteractions(kafk...
public void setName(String name) { this.name = name; }
@Test public void testSetName() { String name = "name"; Model instance = new Model(); instance.setName(name); assertEquals("name", instance.getName()); }
public DataSchemaParser.ParseResult parseSources(String[] rawSources) throws IOException { Set<String> fileExtensions = _parserByFileExtension.keySet(); Map<String, List<String>> byExtension = new HashMap<>(fileExtensions.size()); for (String fileExtension : fileExtensions) { byExtension.put(fil...
@Test(dataProvider = "inputFiles") public void testCustomSourceSchemaDirectory(String pegasusFilename, String[] expectedSchemas) throws Exception { String tempDirectoryPath = _tempDir.getAbsolutePath(); String jarFile = tempDirectoryPath + FS + "test.jar"; SchemaDirectory customSchemaDirectory = () -> "...
public void incQueueGetNums(final String group, final String topic, final Integer queueId, final int incValue) { if (enableQueueStat) { final String statsKey = buildStatsKey(topic, queueId, group); this.statsTable.get(Stats.QUEUE_GET_NUMS).addValue(statsKey, incValue, 1); } }
@Test public void testIncQueueGetNums() { brokerStatsManager.incQueueGetNums(GROUP_NAME, TOPIC, QUEUE_ID, 1); final String statsKey = brokerStatsManager.buildStatsKey(brokerStatsManager.buildStatsKey(TOPIC, String.valueOf(QUEUE_ID)), GROUP_NAME); assertThat(brokerStatsManager.getStatsItem(QU...
public static int toInt(String str) { return toInt(str, 0); }
@Test void testToInt() { assertEquals(0, NumberUtils.toInt(null)); assertEquals(0, NumberUtils.toInt(StringUtils.EMPTY)); assertEquals(1, NumberUtils.toInt("1")); }
@Override public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final SelectionParameters other = (SelectionParamet...
@Test public void testEqualsQualifiersOneNull() { List<String> qualifyingNames = Arrays.asList( "language", "german" ); TypeMirror resultType = new TestTypeMirror( "resultType" ); List<TypeMirror> qualifiers = new ArrayList<>(); qualifiers.add( new TestTypeMirror( "org.mapstruct.test...
@Description("Returns the type of the geometry") @ScalarFunction("ST_GeometryType") @SqlType(VARCHAR) public static Slice stGeometryType(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { return EsriGeometrySerde.getGeometryType(input).standardName(); }
@Test public void testSTGeometryType() { assertFunction("ST_GeometryType(ST_Point(1, 4))", VARCHAR, "ST_Point"); assertFunction("ST_GeometryType(ST_GeometryFromText('LINESTRING (1 1, 2 2)'))", VARCHAR, "ST_LineString"); assertFunction("ST_GeometryType(ST_GeometryFromText('POLYGON ((1 1, ...
@Override public String toString(final RouteUnit routeUnit) { StringBuilder result = new StringBuilder(); appendInsertValue(routeUnit, result); result.delete(result.length() - 2, result.length()); return result.toString(); }
@Test void assertToStringWithoutRouteUnit() { assertThat(shardingInsertValuesToken.toString(), is("('shardingsphere', 'test')")); }
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException { try { if(status.isExists()) { if(log.isWarnEnabled()) { log.warn(String.f...
@Test(expected = NotfoundException.class) public void testMoveNotFound() throws Exception { final BoxFileidProvider fileid = new BoxFileidProvider(session); final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.f...
public static boolean deactivate(Operation op) { return op.deactivate(); }
@Test public void testDeactivate() { Operation operation = new DummyOperation(); setCallId(operation, 10); assertTrue(deactivate(operation)); assertFalse(operation.isActive()); }
@Override public void write(final PostgreSQLPacketPayload payload, final Object value) { payload.writeBytes((byte[]) value); }
@Test void assertWrite() { byte[] bytes = new byte[5]; ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes).writerIndex(0); PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(byteBuf, StandardCharsets.UTF_8); byte[] expected = "value".getBytes(StandardCharsets.UTF_8); n...
public static String substVars(String val, PropertyContainer pc1) throws ScanException { return substVars(val, pc1, null); }
@Test public void leftAccoladeFollowedByDefaultStateWithNoLiteral() throws ScanException { Exception e = assertThrows(ScanException.class, () -> { OptionHelper.substVars("x{:-a}", context); }); String expectedMessage = EXPECTING_DATA_AFTER_LEFT_ACCOLADE; assertEquals(expe...
public CompletableFuture<QueryAssignmentResponse> queryAssignment(ProxyContext ctx, QueryAssignmentRequest request) { CompletableFuture<QueryAssignmentResponse> future = new CompletableFuture<>(); try { validateTopicAndConsumerGroup(request.getTopic(), request.getGroup()); ...
@Test public void testQueryAssignmentWithNoReadQueue() throws Throwable { when(this.messagingProcessor.getTopicRouteDataForProxy(any(), any(), anyString())) .thenReturn(createProxyTopicRouteData(0, 2, 6)); QueryAssignmentResponse response = this.routeActivity.queryAssignment( ...
public static Result parse(String body) throws ParseException { Matcher m; Result result = new Result(); m = PATTERN_IMAGE_URL.matcher(body); if (m.find()) { result.imageUrl = StringUtils.unescapeXml(StringUtils.trim(m.group(1))); } m = PATTERN_SKIP_HATH_KEY.m...
@Test public void testParse() throws IOException, ParseException { InputStream resource = GalleryPageParserTest.class.getResourceAsStream("GalleryPageParserTest.GalleryTopListEX.html"); BufferedSource source = Okio.buffer(Okio.source(resource)); String body = source.readUtf8(); GalleryPageParser.Resu...
@Override public Buffer allocate() { return allocate(this.pageSize); }
@Test public void testDefault() throws Exception { final PooledBufferAllocatorImpl allocator = new PooledBufferAllocatorImpl(4096); final Buffer buffer = allocator.allocate(); assertEquals(0, buffer.offset()); assertEquals(0, buffer.limit()); assertEquals(4096, buffer.capacit...
Future<Boolean> canRoll(int podId) { LOGGER.debugCr(reconciliation, "Determining whether broker {} can be rolled", podId); return canRollBroker(descriptions, podId); }
@Test public void testMinIsrMoreThanReplicas(VertxTestContext context) { KSB ksb = new KSB() .addNewTopic("A", false) .addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "2") .addNewPartition(0) .replicaOn(0) ...
@Override public void removeDevicePorts(DeviceId deviceId) { checkNotNull(deviceId, DEVICE_ID_NULL); if (isAvailable(deviceId)) { log.debug("Cannot remove ports of device {} while it is available.", deviceId); return; } List<PortDescription> portDescriptions ...
@Test public void removeDevicePorts() { connectDevice(DID1, SW1); List<PortDescription> pds = new ArrayList<>(); pds.add(DefaultPortDescription.builder().withPortNumber(P1).isEnabled(true).build()); pds.add(DefaultPortDescription.builder().withPortNumber(P2).isEnabled(true).build());...
@Override public boolean supportsStoredFunctionsUsingCallSyntax() { return false; }
@Test void assertSupportsStoredFunctionsUsingCallSyntax() { assertFalse(metaData.supportsStoredFunctionsUsingCallSyntax()); }
protected boolean clearMetricsHeaders(Message in) { return in.removeHeaders(HEADER_PATTERN); }
@Test public void testClearRealHeaders() { Message msg = new DefaultMessage(new DefaultCamelContext()); Object val = new Object(); msg.setHeader(HEADER_HISTOGRAM_VALUE, 109L); msg.setHeader(HEADER_METRIC_NAME, "the metric"); msg.setHeader("notRemoved", val); assertTha...
@SuppressWarnings("unchecked") public QueryMetadataHolder handleStatement( final ServiceContext serviceContext, final Map<String, Object> configOverrides, final Map<String, Object> requestProperties, final PreparedStatement<?> statement, final Optional<Boolean> isInternalRequest, f...
@Test public void queryLoggerShouldNotReceiveStatementsWhenHandlePullQuery() { when(mockDataSource.getDataSourceType()).thenReturn(DataSourceType.KTABLE); when(ksqlEngine.executeTablePullQuery(any(), any(), any(), any(), any(), any(), any(), anyBoolean(), any())) .thenReturn(pullQueryResult); ...
public RuleRestResponse toRuleRestResponse(RuleInformation ruleInformation) { RuleRestResponse.Builder builder = RuleRestResponse.Builder.builder(); RuleDto ruleDto = ruleInformation.ruleDto(); builder .setId(ruleDto.getUuid()) .setKey(ruleDto.getKey().toString()) .setRepositoryKey(ruleDt...
@Test public void toRuleRestResponse_shouldReturnNullFields_whenRuleIsEmpty() { RuleDto dto = new RuleDto().setRuleKey("key").setRepositoryKey("repoKey").setStatus(RuleStatus.READY).setType(RuleType.BUG.getDbConstant()); RuleRestResponse ruleRestResponse = ruleRestResponseGenerator.toRuleRestResponse(new Rule...
public JobId enqueue(JobLambda job) { return enqueue(null, job); }
@Test void onSaveJobCreatingAndCreatedAreCalled() { when(storageProvider.save(any(Job.class))).thenAnswer(invocation -> invocation.getArgument(0)); jobScheduler.enqueue(() -> testService.doWork()); assertThat(jobClientLogFilter.onCreating).isTrue(); assertThat(jobClientLogFilter.on...
public static List<String> splitOnCharacterAsList(String value, char needle, int count) { // skip leading and trailing needles int end = value.length() - 1; boolean skipStart = value.charAt(0) == needle; boolean skipEnd = value.charAt(end) == needle; if (skipStart && skipEnd) { ...
@Test public void testSplitOnCharacterAsList() { List<String> list = splitOnCharacterAsList("foo", ',', 1); assertEquals(1, list.size()); assertEquals("foo", list.get(0)); list = splitOnCharacterAsList("foo,bar", ',', 2); assertEquals(2, list.size()); assertEquals("f...
@VisibleForTesting protected String buildShortMessage(Map<String, Object> fields) { final StringBuilder shortMessage = new StringBuilder(); shortMessage.append("JSON API poll result: "); if (!flatten) { shortMessage.append(jsonPath.getPath()); } shortMessage.appen...
@Test public void testBuildShortMessageThatGetsCut() throws Exception { Map<String, Object> fields = Maps.newLinkedHashMap(); fields.put("baz", 9001); fields.put("foo", "bargggdzrtdfgfdgldfsjgkfdlgjdflkjglfdjgljslfperitperoujglkdnfkndsbafdofhasdpfoöadjsFOO"); JsonPathCodec selector ...
public static String getNamespaceFromResource(String resource) { if (StringUtils.isEmpty(resource) || isSystemResource(resource)) { return STRING_BLANK; } String resourceWithoutRetryAndDLQ = withOutRetryAndDLQ(resource); int index = resourceWithoutRetryAndDLQ.indexOf(NAMESPAC...
@Test public void testGetNamespaceFromResource() { String namespaceExpectBlank = NamespaceUtil.getNamespaceFromResource(TOPIC); Assert.assertEquals(namespaceExpectBlank, NamespaceUtil.STRING_BLANK); String namespace = NamespaceUtil.getNamespaceFromResource(TOPIC_WITH_NAMESPACE); Ass...
@Override public void deleteArticleCategory(Long id) { // 校验存在 validateArticleCategoryExists(id); // 校验是不是存在关联文章 Long count = articleService.getArticleCountByCategoryId(id); if (count > 0) { throw exception(ARTICLE_CATEGORY_DELETE_FAIL_HAVE_ARTICLES); } ...
@Test public void testDeleteArticleCategory_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> articleCategoryService.deleteArticleCategory(id), ARTICLE_CATEGORY_NOT_EXISTS); }
@Override public <T> @NonNull Schema schemaFor(TypeDescriptor<T> typeDescriptor) { return schemaFor(typeDescriptor.getRawType()); }
@Test public void testUnionSchema() { final Schema schema = defaultSchemaProvider.schemaFor(TypeDescriptor.of(TestThriftUnion.class)); assertNotNull(schema); assertEquals(TypeName.LOGICAL_TYPE, schema.getField("camelCaseEnum").getType().getTypeName()); assertEquals( EnumerationType.IDENTIFIER,...
public void project() { srcPotentialIndex = 0; trgPotentialIndex = 0; recurse(0, 0); BayesAbsorption.normalize(trgPotentials); }
@Test public void testProjection4() { // Projects from node1 into sep. A, B and C are in node1. B and C are in the sep. // this tests a non separator var, is before the vars BayesVariable a = new BayesVariable<String>( "A", 0, new String[] {"A1", "A2"}, new double[][] {{0.1, 0.2}}); ...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DefaultQueueDescription) { final DefaultQueueDescription other = (DefaultQueueDescription) obj; return Objects.equals(this.queueId, other.queueId) && ...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(queueDescription1, sameAsQueueDescription1) .addEqualityGroup(queueDescription2) .testEquals(); }
@Override public void onHeartbeatSuccess(ShareGroupHeartbeatResponseData response) { if (response.errorCode() != Errors.NONE.code()) { String errorMessage = String.format( "Unexpected error in Heartbeat response. Expected no error, but received: %s", Error...
@Test public void testMemberKeepsUnresolvedAssignmentWaitingForMetadataUntilResolved() { // Assignment with 2 topics, only 1 found in metadata Uuid topic1 = Uuid.randomUuid(); String topic1Name = "topic1"; Uuid topic2 = Uuid.randomUuid(); ShareGroupHeartbeatResponseData.Assig...
public static String getMediaType(String fileName) { if (fileName == null) return null; int idx = fileName.lastIndexOf("."); if (idx == -1 || idx == fileName.length()) return null; return FILE_MAP.get(fileName.toLowerCase().substring(idx + 1)); }
@Test public void testResolver() { assertNull(MediaTypeResolver.getMediaType(null)); assertNull(MediaTypeResolver.getMediaType("noextension")); assertNull(MediaTypeResolver.getMediaType("124.")); assertEquals("application/javascript", MediaTypeResolver.getMediaType("file.js")); assertEq...
public void setEnabled(boolean enabled) { this.enabled = enabled; }
@Test public void setEnabled() { properties.setEnabled(false); assertThat(properties.isEnabled()).isEqualTo(false); }
@Override public String rpcType() { return RpcTypeEnum.DUBBO.getName(); }
@Test public void testBuildDivideUpstreamList() { List<URIRegisterDTO> list = new ArrayList<>(); list.add(URIRegisterDTO.builder().appName("test1") .rpcType(RpcTypeEnum.DUBBO.getName()) .host(LOCALHOST).port(8090).build()); list.add(URIRegisterDTO.builder().ap...
@Override public OutputStream create(String path, CreateOptions options) throws IOException { if (!options.isEnsureAtomic()) { return createDirect(path, options); } return new AtomicFileOutputStream(path, this, options); }
@Test public void create() throws IOException { String filepath = PathUtils.concatPath(mLocalUfsRoot, getUniqueFileName()); OutputStream os = mLocalUfs.create(filepath); os.close(); assertTrue(mLocalUfs.isFile(filepath)); File file = new File(filepath); assertTrue(file.exists()); }
public ClusterStateBundle cloneWithMapper(Function<ClusterState, ClusterState> mapper) { AnnotatedClusterState clonedBaseline = baselineState.cloneWithClusterState( mapper.apply(baselineState.getClusterState().clone())); Map<String, AnnotatedClusterState> clonedDerived = derivedBucketSpa...
@Test void cloning_preserves_feed_block_state() { var bundle = createTestBundleWithFeedBlock("foo"); var derived = bundle.cloneWithMapper(Function.identity()); assertEquals(bundle, derived); }
@GetMapping("/image-path") public String getImagePath() { LOGGER.info("Successfully found image path"); return "/product-image.png"; }
@Test void testGetImagePath() { var imageController = new ImageController(); var imagePath = imageController.getImagePath(); assertEquals("/product-image.png", imagePath); }
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 shouldFormatReplaceSelectQueryCorrectly() { final String statementString = "CREATE OR REPLACE STREAM S AS SELECT a.address->city FROM address a;"; final Statement statement = parseSingle(statementString); assertThat(SqlFormatter.formatSql(statement), equalTo("CREATE OR REPLACE ST...
public static List<WeightedHostAddress> prioritize(WeightedHostAddress[] records) { final List<WeightedHostAddress> result = new LinkedList<>(); // sort by priority (ascending) SortedMap<Integer, Set<WeightedHostAddress>> byPriority = new TreeMap<>(); for(final WeightedHostAddress recor...
@Test public void testZeroWeights() throws Exception { // setup final DNSUtil.WeightedHostAddress hostA = new DNSUtil.WeightedHostAddress("hostA", 5222, false, 1, 0); final DNSUtil.WeightedHostAddress hostB = new DNSUtil.WeightedHostAddress("hostB", 5222, false, 1, 0); final DNSUtil....
public static Set<String> validateScopes(String scopeClaimName, Collection<String> scopes) throws ValidateException { if (scopes == null) throw new ValidateException(String.format("%s value must be non-null", scopeClaimName)); Set<String> copy = new HashSet<>(); for (String scope :...
@Test public void testValidateScopesDisallowsDuplicates() { assertThrows(ValidateException.class, () -> ClaimValidationUtils.validateScopes("scope", Arrays.asList("a", "b", "a"))); assertThrows(ValidateException.class, () -> ClaimValidationUtils.validateScopes("scope", Arrays.asList("a", "b", " a ...
public static <T> T getMapper(Class<T> clazz) { try { List<ClassLoader> classLoaders = collectClassLoaders( clazz.getClassLoader() ); return getMapper( clazz, classLoaders ); } catch ( ClassNotFoundException | NoSuchMethodException e ) { throw new RuntimeExce...
@Test public void findsNestedMapperImpl() { assertThat( Mappers.getMapper( SomeClass.Foo.class ) ).isNotNull(); assertThat( Mappers.getMapper( SomeClass.NestedClass.Foo.class ) ).isNotNull(); }
public void deletePolicy(String policyName) { policies.remove(policyName); }
@Test public void testDeletePolicy() throws Exception { NamespaceIsolationPolicies policies = this.getDefaultTestPolicies(); policies.deletePolicy("non-existing-policy"); assertFalse(policies.getPolicies().isEmpty()); policies.deletePolicy("policy1"); assertTrue(policies.get...
@CheckForNull @Override public CeTaskResult process(CeTask task) { try (TaskContainer container = new TaskContainerImpl(ceEngineContainer, newContainerPopulator(task))) { container.bootup(); container.getComponentByType(ComputationStepExecutor.class).execute(); } return null; }
@Test public void processThrowsNPEIfCeTaskIsNull() { assertThatThrownBy(() -> underTest.process(null)) .isInstanceOf(NullPointerException.class); }
@Override public boolean apply(InputFile inputFile) { return extension.equals(getExtension(inputFile)); }
@Test public void should_match_correct_extension_case_insensitively() throws IOException { FileExtensionPredicate predicate = new FileExtensionPredicate("jAVa"); assertThat(predicate.apply(mockWithName("Program.java"))).isTrue(); assertThat(predicate.apply(mockWithName("Program.JAVA"))).isTrue(); asse...
public boolean isNewer(Timestamped<T> other) { return isNewerThan(checkNotNull(other).timestamp()); }
@Test public final void testIsNewer() { Timestamped<String> a = new Timestamped<>("a", TS_1_2); Timestamped<String> b = new Timestamped<>("b", TS_1_1); assertTrue(a.isNewer(b)); assertFalse(b.isNewer(a)); }
public static Collection<Object> accumulateValues(DataIterator it, Collection<Object> accumulator) { for(DataElement element = it.next(); element !=null; element = it.next()) { accumulator.add(element.getValue()); } return accumulator; }
@Test public void testAccumulateByPath() throws Exception { SimpleTestData data = IteratorTestData.createSimpleTestData(); List<Object> ids = new LinkedList<>(); Builder.create(data.getDataElement(), IterationOrder.PRE_ORDER) .filterBy(Predicates.and(Predicates.pathMatchesPattern("foo", Wildcard...
@Description("cube root") @ScalarFunction @SqlType(StandardTypes.DOUBLE) public static double cbrt(@SqlType(StandardTypes.DOUBLE) double num) { return Math.cbrt(num); }
@Test public void testCbrt() { for (double doubleValue : DOUBLE_VALUES) { assertFunction("cbrt(" + doubleValue + ")", DOUBLE, Math.cbrt(doubleValue)); assertFunction("cbrt(REAL '" + (float) doubleValue + "')", DOUBLE, Math.cbrt((float) doubleValue)); } assertFunct...
@Override public void write(Cache.Entry<? extends K, ? extends V> entry) throws CacheWriterException { long startNanos = Timer.nanos(); try { delegate.get().write(entry); } finally { writeProbe.recordValue(Timer.nanosElapsed(startNanos)); } }
@Test public void write() { Cache.Entry<Integer, String> entry = new CacheEntry<>(1, "peter"); cacheWriter.write(entry); verify(delegate).write(entry); assertProbeCalledOnce("write"); }
@Override public MastershipRole getRole(DeviceId deviceId) { checkNotNull(deviceId, DEVICE_NULL); // TODO hard coded to master for now. return MastershipRole.MASTER; }
@Test public void testGetRole() { manager.registerTenantId(TenantId.tenantId(tenantIdValue1)); VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1)); DeviceService deviceService = manager.get(virtualNetwork.id(), DeviceService.class); // tes...
@Override public void requestInitialized(final ServletRequestEvent sre) { try { HttpServletRequest request = (HttpServletRequest) sre.getServletRequest(); if (Objects.nonNull(request) && Objects.nonNull(request.getSession())) { HttpSession session = request.getSession...
@Test public void testRequestInitialized() { ServletRequestEvent sre = mock(ServletRequestEvent.class); HttpServletRequest request = mock(HttpServletRequest.class); HttpSession session = mock(HttpSession.class); when(sre.getServletRequest()).thenReturn(request); when(request....
public static String concatUfsPath(String base, String path) { Pattern basePattern = Pattern.compile("(...)\\/\\/"); // use conCatPath to join path if base is not starting with // if (!basePattern.matcher(base).matches()) { return concatPath(base, path); } else { Preconditions.checkArgument(...
@Test public void concatUfsPath() { assertEquals("s3://", PathUtils.concatUfsPath("s3://", "")); assertEquals("s3://bar", PathUtils.concatUfsPath("s3://", "bar")); assertEquals("hdfs://localhost:9010", PathUtils.concatUfsPath("hdfs://localhost:9010/", "")); assertEquals("hdfs://localhost:9010...
public static Validator parses(final Function<String, ?> parser) { return (name, val) -> { if (val != null && !(val instanceof String)) { throw new IllegalArgumentException("validator should only be used with STRING defs"); } try { parser.apply((String)val); } catch (final Ex...
@Test public void shouldThrowIfParserThrows() { // Given: final Validator validator = ConfigValidators.parses(parser); when(parser.apply(any())).thenThrow(new IllegalArgumentException("some error")); // When: final Exception e = assertThrows( ConfigException.class, () -> validator...
Object[] findValues(int ordinal) { return getAllValues(ordinal, type, 0); }
@Test public void testMapObjectValueReference() throws Exception { MapValue val1 = new MapValue(); val1.val = "one"; MapValue val2 = new MapValue(); val2.val = "two"; Map<Integer, MapValue> map = new HashMap<>(); map.put(1, val1); map.put(2, val2); M...
public static int[] getCutIndices(String s, String splitChar, int index) { int found = 0; char target = splitChar.charAt(0); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == target) { found++; } if (found == index) { ...
@Test public void testCutIndicesWithFirstToken() throws Exception { String s = "<10> 07 Aug 2013 somesubsystem"; int[] result = SplitAndIndexExtractor.getCutIndices(s, " ", 0); assertEquals(0, result[0]); assertEquals(4, result[1]); }
@SuppressWarnings("unchecked") private SpscChannelConsumer<E> newConsumer(Object... args) { return mapper.newFlyweight(SpscChannelConsumer.class, "ChannelConsumerTemplate.java", Template.fromFile(Channel.class, "ChannelConsumerTemplate.java"), args); }
@Test public void shouldReadAnObject() { ChannelConsumer consumer = newConsumer(); shouldWriteAnObject(); assertTrue(consumer.read()); assertEmpty(); }
@Override public void run() { try (DbSession dbSession = dbClient.openSession(false)) { List<CeActivityDto> recentSuccessfulTasks = getRecentSuccessfulTasks(dbSession); Collection<String> entityUuids = recentSuccessfulTasks.stream() .map(CeActivityDto::getEntityUuid) .toList(); ...
@Test public void run_givenNullExecutionTime_dontReportMetricData() { RecentTasksDurationTask task = new RecentTasksDurationTask(dbClient, metrics, config, system); List<CeActivityDto> recentTasks = createTasks(1, 0); recentTasks.get(0).setExecutionTimeMs(null); when(entityDao.selectByUuids(any(), an...
public ZookeeperPrefixChildFilter(ZookeeperEphemeralPrefixGenerator prefixGenerator) { _prefixGenerator = prefixGenerator; }
@Test(dataProvider = "prefixFilterDataProvider") public void testZookeeperPrefixChildFilter(String hostName, List<String> children, List<String> expectedFilteredChildren) { ZookeeperPrefixChildFilter filter = new ZookeeperPrefixChildFilter(new AnnouncerHostPrefixGenerator(hostName)); List<String> actualFilt...
public static final FluentKieModuleDeploymentHelper newFluentInstance() { return new KieModuleDeploymentHelperImpl(); }
@Test public void testFluentDeploymentHelper() throws Exception { int numFiles = 0; int numDirs = 0; FluentKieModuleDeploymentHelper deploymentHelper = KieModuleDeploymentHelper.newFluentInstance(); String groupId = "org.kie.api.builder.fluent"; String artifactId = ...
public static ThrowableType getThrowableType(Throwable cause) { final ThrowableAnnotation annotation = cause.getClass().getAnnotation(ThrowableAnnotation.class); return annotation == null ? ThrowableType.RecoverableError : annotation.value(); }
@Test void testThrowableType_Recoverable() { assertThat(ThrowableClassifier.getThrowableType(new Exception(""))) .isEqualTo(ThrowableType.RecoverableError); assertThat(ThrowableClassifier.getThrowableType(new TestRecoverableErrorException())) .isEqualTo(ThrowableType....
public static void setInvocationTime(Operation op, long invocationTime) { op.setInvocationTime(invocationTime); }
@Test public void testSetInvocationTime() { Operation operation = new DummyOperation(); setInvocationTime(operation, 10); assertEquals(10, operation.getInvocationTime()); }
@Nonnull public static <T> BatchSource<T> batchFromProcessor( @Nonnull String sourceName, @Nonnull ProcessorMetaSupplier metaSupplier ) { checkSerializable(metaSupplier, "metaSupplier"); return new BatchSourceTransform<>(sourceName, metaSupplier); }
@Test public void fromProcessor() { // Given List<Integer> input = sequence(itemCount); putToBatchSrcMap(input); // When BatchSource<Integer> source = Sources.batchFromProcessor("test", readMapP(srcName, truePredicate(), Entry::getValue)); // Then ...
@Override public void updateNetwork(Network osNet) { checkNotNull(osNet, ERR_NULL_NETWORK); checkArgument(!Strings.isNullOrEmpty(osNet.getId()), ERR_NULL_NETWORK_ID); osNetworkStore.updateNetwork(osNet); OpenstackNetwork finalAugmentedNetwork = buildAugmentedNetworkFromType(osNet);...
@Test(expected = IllegalArgumentException.class) public void testUpdateNetworkWithNullName() { final Network updated = NeutronNetwork.builder() .name(null) .build(); updated.setId(NETWORK_ID); target.updateNetwork(updated); }
public static String getValidFilePath(String inputPath) { return getValidFilePath(inputPath, false); }
@Test public void getValidFilePath_nullOrEmpty_returnsNull() { assertNull(SecurityUtils.getValidFilePath("")); assertNull(SecurityUtils.getValidFilePath(null)); }
@PostMapping @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE) public Boolean createNamespace(@RequestParam("customNamespaceId") String namespaceId, @RequestParam("namespaceName") String namespaceName, @RequestParam(value = "namesp...
@Test void testCreateNamespaceWithIllegalName() { assertFalse(namespaceController.createNamespace(null, "test@Name", "testDesc")); assertFalse(namespaceController.createNamespace(null, "test#Name", "testDesc")); assertFalse(namespaceController.createNamespace(null, "test$Name", "testDesc"));...
protected InstrumentedHttpClientConnectionManager createConnectionManager(Registry<ConnectionSocketFactory> registry, String name) { final Duration ttl = configuration.getTimeToLive(); final InstrumentedHttpClientConnectionMan...
@Test void usesASystemDnsResolverByDefault() { final InstrumentedHttpClientConnectionManager manager = builder.createConnectionManager(registry, "test"); assertThat(manager) .extracting("connectionOperator") .extracting("dnsResolver") .isInstanceOf(Sy...
public static Map<TopicPartition, Long> parseSinkConnectorOffsets(Map<Map<String, ?>, Map<String, ?>> partitionOffsets) { Map<TopicPartition, Long> parsedOffsetMap = new HashMap<>(); for (Map.Entry<Map<String, ?>, Map<String, ?>> partitionOffset : partitionOffsets.entrySet()) { Map<String, ...
@Test public void testNullOffset() { Map<String, Object> partitionMap = new HashMap<>(); partitionMap.put(SinkUtils.KAFKA_TOPIC_KEY, "topic"); partitionMap.put(SinkUtils.KAFKA_PARTITION_KEY, 10); Map<Map<String, ?>, Map<String, ?>> partitionOffsets = new HashMap<>(); partitio...
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) { Object span = request.getAttribute(SpanCustomizer.class.getName()); if (span instanceof SpanCustomizer) { setHttpRouteAttribute(request); handlerParser.preHandle(request, o, (SpanCustomizer) sp...
@Test void preHandle_parsesAndAddsHttpRouteAttribute_coercesNullToEmpty() { when(request.getAttribute("brave.SpanCustomizer")).thenReturn(span); interceptor.preHandle(request, response, controller); verify(request).getAttribute("brave.SpanCustomizer"); verify(request).getAttribute(BEST_MATCHING_PATTER...
public final void isEmpty() { if (!Iterables.isEmpty(checkNotNull(actual))) { failWithActual(simpleFact("expected to be empty")); } }
@Test public void iterableIsEmpty() { assertThat(asList()).isEmpty(); }
@VisibleForTesting void validateNameUnique(List<MemberLevelDO> list, Long id, String name) { for (MemberLevelDO levelDO : list) { if (ObjUtil.notEqual(levelDO.getName(), name)) { continue; } if (id == null || !id.equals(levelDO.getId())) { ...
@Test public void testUpdateLevel_nameUnique() { // 准备参数 Long id = randomLongId(); String name = randomString(); // mock 数据 memberlevelMapper.insert(randomLevelDO(o -> o.setName(name))); // 调用,校验异常 List<MemberLevelDO> list = memberlevelMapper.selectList(); ...
@Override protected void route(List<SendingMailbox> sendingMailboxes, TransferableBlock block) throws Exception { sendBlock(sendingMailboxes.get(0), block); }
@Test(expectedExceptions = IllegalArgumentException.class) public void shouldThrowWhenSingletonWithNonLocalMailbox() throws Exception { // Given: ImmutableList<SendingMailbox> destinations = ImmutableList.of(_mailbox2); // When: new SingletonExchange(destinations, TransferableBlockUtils::splitB...
@Override public final void getSize(@NonNull SizeReadyCallback cb) { sizeDeterminer.getSize(cb); }
@Test public void testDecreasesDimensionsByViewPadding() { activity.visible(); view.setLayoutParams(new FrameLayout.LayoutParams(100, 100)); view.setPadding(25, 25, 25, 25); view.requestLayout(); target.getSize(cb); verify(cb).onSizeReady(50, 50); }
public static ColumnName parse(final String text) { final SqlBaseLexer lexer = new SqlBaseLexer( new CaseInsensitiveStream(CharStreams.fromString(text)) ); final CommonTokenStream tokStream = new CommonTokenStream(lexer); final SqlBaseParser parser = new SqlBaseParser(tokStream); final Prim...
@Test public void shouldParseUnquotedIdentifier() { // When: final ColumnName result = ColumnReferenceParser.parse("foo"); // Then: assertThat(result, is(ColumnName.of("FOO"))); }
@Override public void trash(final Local file) throws LocalAccessDeniedException { if(log.isDebugEnabled()) { log.debug(String.format("Move %s to Trash", file)); } final ObjCObjectByReference error = new ObjCObjectByReference(); if(!NSFileManager.defaultManager().trashItem...
@Test public void testTrashOpenDirectoryEnumeration() throws Exception { final Trash trash = new FileManagerTrashFeature(); final SupportDirectoryFinder finder = new TemporarySupportDirectoryFinder(); final Local temp = finder.find(); final Local directory = LocalFactory.get(temp, U...
static Result coerceUserList( final Collection<Expression> expressions, final ExpressionTypeManager typeManager ) { return coerceUserList(expressions, typeManager, Collections.emptyMap()); }
@Test public void shouldCoerceArrayOfCompatibleLiterals() { // Given: final ImmutableList<Expression> expressions = ImmutableList.of( new CreateArrayExpression( ImmutableList.of( new IntegerLiteral(10), new IntegerLiteral(289476) ) ), ...