focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public SchemaAndValue toConnectData(String topic, byte[] value) { try { return new SchemaAndValue(schema, deserializer.deserialize(topic, value)); } catch (SerializationException e) { throw new DataException("Failed to deserialize " + typeName + ": ", e); } ...
@Test public void testBytesNullToNumber() { SchemaAndValue data = converter.toConnectData(TOPIC, null); assertEquals(schema(), data.schema()); assertNull(data.value()); }
@Override public void blame(BlameInput input, BlameOutput output) { File basedir = input.fileSystem().baseDir(); try (Repository repo = JGitUtils.buildRepository(basedir.toPath())) { File gitBaseDir = repo.getWorkTree(); if (cloneIsInvalid(gitBaseDir)) { return; } Profiler pro...
@Test @UseDataProvider("blameAlgorithms") public void skip_files_not_committed(BlameAlgorithmEnum strategy) throws Exception { // skip if git not installed if (strategy == GIT_NATIVE_BLAME) { assumeTrue(nativeGitBlameCommand.checkIfEnabled()); } JGitBlameCommand jgit = mock(JGitBlameCommand.c...
public static String getRootLevelFieldName(String fieldName) { return fieldName.split("\\.")[0]; }
@Test public void testGetRootLevelFieldName() { assertEquals("a", HoodieAvroUtils.getRootLevelFieldName("a.b.c")); assertEquals("a", HoodieAvroUtils.getRootLevelFieldName("a")); assertEquals("", HoodieAvroUtils.getRootLevelFieldName("")); }
@Override public List<Namespace> listNamespaces(Namespace namespace) { SnowflakeIdentifier scope = NamespaceHelpers.toSnowflakeIdentifier(namespace); List<SnowflakeIdentifier> results; switch (scope.type()) { case ROOT: results = snowflakeClient.listDatabases(); break; case DAT...
@Test public void testListNamespaceWithinNonExistentDB() { // Existence check for nonexistent parent namespaces is optional in the SupportsNamespaces // interface. String dbName = "NONEXISTENT_DB"; assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> catalog.listNamespaces(Names...
public static int readUint16BE(ByteBuffer buf) throws BufferUnderflowException { return Short.toUnsignedInt(buf.order(ByteOrder.BIG_ENDIAN).getShort()); }
@Test(expected = ArrayIndexOutOfBoundsException.class) public void testReadUint16BEThrowsException3() { ByteUtils.readUint16BE(new byte[]{1, 2, 3}, -1); }
@Override public ClientPoolHandler addLast(String name, ChannelHandler handler) { super.addLast(name, handler); return this; }
@Test public void testAddLast() { ClientPoolHandler handler = new ClientPoolHandler(); Assert.assertTrue(handler.isEmpty()); handler.addLast(test, new TestHandler()); Assert.assertFalse(handler.isEmpty()); }
public static int nextCapacity(int current) { assert current > 0 && Long.bitCount(current) == 1 : "Capacity must be a power of two."; if (current < MIN_CAPACITY / 2) { current = MIN_CAPACITY / 2; } current <<= 1; if (current < 0) { throw new RuntimeExcep...
@Test public void testNextCapacity_withLong() { long capacity = 16; long nextCapacity = nextCapacity(capacity); assertEquals(32, nextCapacity); }
public PrepareResult prepare(HostValidator hostValidator, DeployLogger logger, PrepareParams params, Optional<ApplicationVersions> activeApplicationVersions, Instant now, File serverDbSessionDir, ApplicationPackage applicationPackage, SessionZooKeeperCli...
@Test public void require_that_cloud_account_is_written() throws Exception { TestModelFactory modelFactory = new TestModelFactory(version123); preparer = createPreparer(new ModelFactoryRegistry(List.of(modelFactory)), HostProvisionerProvider.empty()); ApplicationId applicationId = applicatio...
@Override public String encodeKey(String key) { return key; }
@Test public void testEncodeValidKeys() { assertEquals("foo", strategy.encodeKey("foo")); assertEquals("foo123bar", strategy.encodeKey("foo123bar")); assertEquals("CamelFileName", strategy.encodeKey("CamelFileName")); assertEquals("org.apache.camel.MyBean", strategy.encodeKey("org.ap...
public boolean isActive() { return active; }
@Test public void testMvAfterBaseTableRename() throws Exception { starRocksAssert.withDatabase("test").useDatabase("test") .withTable("CREATE TABLE test.tbl_to_rename\n" + "(\n" + " k1 date,\n" + " k2 int,\n" + ...
@Override public RemotingCommand processRequest(final ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { return this.processRequest(ctx.channel(), request, true); }
@Test public void testProcessRequest_NoPermission() throws RemotingCommandException { this.brokerController.getBrokerConfig().setBrokerPermission(PermName.PERM_WRITE); RemotingCommand request = createPeekMessageRequest("group","topic",0); RemotingCommand response = peekMessageProcessor.proce...
@Deprecated String getPassword(Configuration conf, String alias, String defaultPass) { String password = defaultPass; try { char[] passchars = conf.getPassword(alias); if (passchars != null) { password = new String(passchars); } } catch (IOException ioe) { LOG.warn("Excepti...
@Test public void testConfGetPassword() throws Exception { File testDir = GenericTestUtils.getTestDir(); Configuration conf = getBaseConf(); final Path jksPath = new Path(testDir.toString(), "test.jks"); final String ourUrl = JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri(); ...
@Deprecated public Statement createStatement(String sql) { return createStatement(sql, new ParsingOptions()); }
@Test public void testAllowIdentifierColon() { SqlParser sqlParser = new SqlParser(new SqlParserOptions().allowIdentifierSymbol(COLON)); sqlParser.createStatement("select * from foo:bar"); }
@Override public String getDataSource() { return DataSourceConstant.DERBY; }
@Test void testGetDataSource() { String dataSource = historyConfigInfoMapperByDerby.getDataSource(); assertEquals(DataSourceConstant.DERBY, dataSource); }
@Override public String toString() { return String.format("%s{configMapName='%s'}", getClass().getSimpleName(), configMapName); }
@Test void testToStringContainingConfigMap() throws Exception { new Context() { { runTest( () -> assertThat(leaderElectionDriver.toString()) .as( ...
@Override public int getGrace() { return grace; }
@Test public void testDifferingTypesForNumericalParameters() throws Exception { final AlertCondition alertConditionWithDouble = getDummyAlertCondition(ImmutableMap.of("grace", 3.0)); assertEquals(3, alertConditionWithDouble.getGrace()); final AlertCondition alertConditionWithInteger = getDum...
public Object clone() { BlockUntilStepsFinishMeta retval = (BlockUntilStepsFinishMeta) super.clone(); int nrfields = stepName.length; retval.allocate( nrfields ); System.arraycopy( stepName, 0, retval.stepName, 0, nrfields ); System.arraycopy( stepCopyNr, 0, retval.stepCopyNr, 0, nrfields ); r...
@Test public void cloneTest() throws Exception { BlockUntilStepsFinishMeta meta = new BlockUntilStepsFinishMeta(); meta.allocate( 2 ); meta.setStepName( new String[] { "step1", "step2" } ); meta.setStepCopyNr( new String[] { "copy1", "copy2" } ); BlockUntilStepsFinishMeta aClone = (BlockUntilSteps...
void put(@Nonnull String name, @Nonnull DataConnectionCatalogEntry dataConnectionCatalogEntry) { storage().put(wrapDataConnectionKey(name), dataConnectionCatalogEntry); }
@Test public void when_put_then_overridesPrevious() { String name = randomName(); DataConnectionCatalogEntry originalDL = dataConnection(name, "type1", false); DataConnectionCatalogEntry updatedDL = dataConnection(name, "type2", true); storage.put(name, originalDL); storage....
public static <K, V> Printed<K, V> toFile(final String filePath) { Objects.requireNonNull(filePath, "filePath can't be null"); if (Utils.isBlank(filePath)) { throw new TopologyException("filePath can't be an empty string"); } try { return new Printed<>(Files.newOu...
@Test public void shouldCreateProcessorThatPrintsToFile() throws IOException { final File file = TestUtils.tempFile(); final ProcessorSupplier<String, Integer, Void, Void> processorSupplier = new PrintedInternal<>( Printed.<String, Integer>toFile(file.getPath())) .bui...
@Override @SuppressWarnings("unchecked") public int run() throws IOException { Preconditions.checkArgument(targets != null && targets.size() >= 1, "A Parquet file is required."); Preconditions.checkArgument(targets.size() == 1, "Cannot process multiple Parquet files."); String source = targets.get(0); ...
@Test public void testShowDirectoryCommandForFixedLengthByteArray() throws IOException { File file = parquetFile(); ShowDictionaryCommand command = new ShowDictionaryCommand(createLogger()); command.targets = Arrays.asList(file.getAbsolutePath()); command.column = FIXED_LEN_BYTE_ARRAY_FIELD; comma...
@Override public String generate(TokenType tokenType) { String rawToken = generateRawToken(); return buildIdentifiablePartOfToken(tokenType) + rawToken; }
@Test public void generated_userToken_should_have_squ_prefix() { String token = underTest.generate(TokenType.USER_TOKEN); assertThat(token).matches("squ_.{40}"); }
public <T> List<T> getList(String path) { return get(path); }
@Test public void automatically_escapes_json_attributes_whose_name_equals_properties() { // Given String json = "{\n" + " \"features\":[\n" + " {\n" + " \"type\":\"Feature\",\n" + " \"geometry\":{\n" + ...
public List<T> query(double lat, double lon) { Envelope searchEnv = new Envelope(lon, lon, lat, lat); @SuppressWarnings("unchecked") List<IndexedCustomArea<T>> result = index.query(searchEnv); Point point = gf.createPoint(new Coordinate(lon, lat)); return result.stream() ...
@Test public void testCountries() { AreaIndex<CustomArea> countryIndex = createCountryIndex(); assertEquals("DE", countryIndex.query(52.52437, 13.41053).get(0).getProperties().get(State.ISO_3166_2)); assertEquals("FR", countryIndex.query(48.86471, 2.349014).get(0).getProperties().get(State.I...
boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); }
@Test void findCloserToShouldReturnNUmber2IfItCloserToGoalThanNumber1() { // given int number1 = 1002; int number2 = 999; // when boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2); // then assertThat(actual).isFalse(); }
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException{ PluginRiskConsent riskConsent = PluginRiskConsent.valueOf(config.get(PLUGINS_RISK_CONSENT).orElse(NOT_ACCEPTED.name())); if (userSession.hasSession() && userSession.isLoggedIn() && userSess...
@Test public void doFilter_givenNotLoggedIn_dontRedirect() throws Exception { PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession); when(userSession.hasSession()).thenReturn(true); when(userSession.isLoggedIn()).thenReturn(false); consentFilter.doFilter(r...
public void copyOnlyForQuery(OlapTable olapTable) { olapTable.id = this.id; olapTable.name = this.name; olapTable.type = this.type; olapTable.fullSchema = Lists.newArrayList(this.fullSchema); olapTable.nameToColumn = new CaseInsensitiveMap(this.nameToColumn); olapTable.id...
@Test public void testCopyOnlyForQuery() { OlapTable olapTable = new OlapTable(); olapTable.setHasDelete(); OlapTable copied = new OlapTable(); olapTable.copyOnlyForQuery(copied); Assert.assertEquals(olapTable.hasDelete(), copied.hasDelete()); Assert.assertEquals(ol...
public String decode(byte[] val) { return codecs[0].decode(val, 0, val.length); }
@Test public void testDecodeGermanPersonName() { assertEquals(GERMAN_PERSON_NAME, iso8859_1().decode(GERMAN_PERSON_NAME_BYTE)); }
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return true; } try { new SwiftAttributesFinderFeature(session).find(file, listener); return true; } catch(N...
@Test public void testFindRoot() throws Exception { assertTrue(new SwiftFindFeature(session).find(new Path("/", EnumSet.of(Path.Type.directory)))); }
public static boolean isFolderEmpty(File folder) { if (folder == null) { return true; } File[] files = folder.listFiles(); return files == null || files.length == 0; }
@Test void FolderIsNotEmptyWhenItHasContents() throws Exception { new File(folder, "subfolder").createNewFile(); assertThat(FileUtil.isFolderEmpty(folder)).isFalse(); }
@Override public SQLParserRuleConfiguration build() { return new SQLParserRuleConfiguration(PARSE_TREE_CACHE_OPTION, SQL_STATEMENT_CACHE_OPTION); }
@Test void assertBuild() { SQLParserRuleConfiguration actual = new DefaultSQLParserRuleConfigurationBuilder().build(); assertThat(actual.getParseTreeCache().getInitialCapacity(), is(128)); assertThat(actual.getParseTreeCache().getMaximumSize(), is(1024L)); assertThat(actual.getSqlSta...
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) { final Fetch<K, V> fetch = Fetch.empty(); final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>(); int recordsRemaining = fetchConfig.maxPollRecords; try { while (recordsRemaining > 0) { ...
@Test public void testCollectFetchInitializationWithUpdateLastStableOffsetOnNotAssignedPartition() { final TopicPartition topicPartition0 = new TopicPartition("topic", 0); final long fetchOffset = 42; final long highWatermark = 1000; final long logStartOffset = 10; final long...
public static String fromPersistenceNamingEncoding(String mlName) { // The managedLedgerName convention is: tenant/namespace/domain/topic // We want to transform to topic full name in the order: domain://tenant/namespace/topic if (mlName == null || mlName.length() == 0) { return mlNa...
@Test public void testFromPersistenceNamingEncoding() { // case1: V2 String mlName1 = "public_tenant/default_namespace/persistent/test_topic"; String expectedTopicName1 = "persistent://public_tenant/default_namespace/test_topic"; TopicName name1 = TopicName.get(expectedTopicName1); ...
@Override public String doLayout(ILoggingEvent event) { StringWriter output = new StringWriter(); try (JsonWriter json = new JsonWriter(output)) { json.beginObject(); if (!"".equals(nodeName)) { json.name("nodename").value(nodeName); } json.name("process").value(processKey); ...
@Test public void doLayout_whenMDC_shouldNotContainExcludedFields() { try { LogbackJsonLayout logbackJsonLayout = new LogbackJsonLayout("web", "", List.of("fromMdc")); LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the messag...
public static Set<String> findKeywordsFromCrashReport(String crashReport) { Matcher matcher = CRASH_REPORT_STACK_TRACE_PATTERN.matcher(crashReport); Set<String> result = new HashSet<>(); if (matcher.find()) { for (String line : matcher.group("stacktrace").split("\\n")) { ...
@Test public void bettersprinting() throws IOException { assertEquals( new HashSet<>(Arrays.asList("chylex", "bettersprinting")), CrashReportAnalyzer.findKeywordsFromCrashReport(loadLog("/crash-report/mod/bettersprinting.txt"))); }
public static Result parse(@NonNull String body, int mode) throws Exception { Result result = new Result(); Document d; try{ d = Jsoup.parse(body); }catch (Exception ignored){ return result; } try { Element ptt = d.getElementsByClass("p...
@Test public void testParse() throws Exception { InputStream resource = GalleryPageApiParserTest.class.getResourceAsStream(file); BufferedSource source = Okio.buffer(Okio.source(resource)); String body = source.readUtf8(); GalleryListParser.Result result = GalleryListParser.parse(body, MODE_NORMAL); ...
@Override public boolean apply(InputFile inputFile) { return originalPredicate.apply(inputFile) && InputFile.Status.SAME != inputFile.status(); }
@Test public void predicate_is_evaluated_before_file_status() { when(predicate.apply(inputFile)).thenReturn(false); Assertions.assertThat(underTest.apply(inputFile)).isFalse(); verify(inputFile, never()).status(); }
@ScalarOperator(INDETERMINATE) @SqlType(StandardTypes.BOOLEAN) public static boolean indeterminate(@SqlType(StandardTypes.SMALLINT) long value, @IsNull boolean isNull) { return isNull; }
@Test public void testIndeterminate() throws Exception { assertOperator(INDETERMINATE, "cast(null as smallint)", BOOLEAN, true); assertOperator(INDETERMINATE, "cast(12 as smallint)", BOOLEAN, false); assertOperator(INDETERMINATE, "cast(0 as smallint)", BOOLEAN, false); ...
@Override public Source getSource(PropertyKey key) { return mProperties.getSource(key); }
@Test public void source() throws Exception { Properties siteProps = new Properties(); File propsFile = mFolder.newFile(Constants.SITE_PROPERTIES); siteProps.setProperty(PropertyKey.MASTER_HOSTNAME.toString(), "host-1"); siteProps.setProperty(PropertyKey.MASTER_WEB_PORT.toString(), "1234"); sitePr...
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("sideInputIndex", sideInputIndex) .add("declaringStep", declaringOperationContext.nameContext()) .toString(); }
@Test public void testToStringReturnsWellFormedDescriptionString() { DataflowExecutionContext mockedExecutionContext = mock(DataflowExecutionContext.class); DataflowOperationContext mockedOperationContext = mock(DataflowOperationContext.class); final int siIndexId = 3; ExecutionStateTracker mockedExe...
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } ...
@Test public void optifineIsNotCompatibleWithForge4() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/optifine_is_not_compatible_with_forge5.txt")), CrashReportAnalyzer.Rule.OPTIFINE_IS_NOT_COMPATIBLE_WITH_...
public static Object convertValue(final Object value, final Class<?> convertType) throws SQLFeatureNotSupportedException { ShardingSpherePreconditions.checkNotNull(convertType, () -> new SQLFeatureNotSupportedException("Type can not be null")); if (null == value) { return convertNullValue(co...
@Test void assertConvertByteArrayValueSuccess() throws SQLException { byte[] bytesValue = {}; assertThat(ResultSetUtils.convertValue(bytesValue, byte.class), is(bytesValue)); assertThat(ResultSetUtils.convertValue(new byte[]{(byte) 1}, byte.class), is((byte) 1)); assertThat(ResultSet...
@Override public ExportedConfig pipelineExport(final String pluginId, final CRPipeline pipeline) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_PIPELINE_EXPORT, new DefaultPluginInteractionCallback<>() { @Override public String requestBody(String resolvedExtensionVersio...
@Test public void shouldTalkToPluginToGetPipelineExport() { CRPipeline pipeline = new CRPipeline(); String serialized = new GsonCodec().getGson().toJson(pipeline); when(jsonMessageHandler2.responseMessageForPipelineExport(responseBody, responseHeaders)).thenReturn(ExportedConfig.from(seriali...
@Override public void execute(ComputationStep.Context context) { new PathAwareCrawler<>( FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor( Iterables.concat(NewLinesAndConditionsCoverageFormula.from(newLinesRepository, reportReader), FORMULAS))) ...
@Test public void zero_measures_when_nothing_has_changed() { treeRootHolder.setRoot(FILE_COMPONENT); when(newLinesRepository.newLinesAvailable()).thenReturn(true); when(newLinesRepository.getNewLines(FILE_COMPONENT)).thenReturn(Optional.of(Collections.emptySet())); reportReader.putCoverage(FILE_COMPO...
public boolean similarTo(ClusterStateBundle other) { if (!baselineState.getClusterState().similarToIgnoringInitProgress(other.baselineState.getClusterState())) { return false; } if (clusterFeedIsBlocked() != other.clusterFeedIsBlocked()) { return false; } ...
@Test void same_bundle_instance_considered_similar() { ClusterStateBundle bundle = createTestBundle(); assertTrue(bundle.similarTo(bundle)); }
@Override public String toString() { return SelParserTreeConstants.jjtNodeName[id] + (value == null ? "" : ": " + value); }
@Test public void testToString() { assertEquals("Execute", root.toString()); }
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testPartialFetchWithPausedPartitions() { // this test sends creates a completed fetch with 3 records and a max poll of 2 records to assert // that a fetch that must be returned over at least 2 polls can be cached successfully when its partition is // paused, then returned s...
public DoubleValue increment(double increment) { this.value += increment; this.set = true; return this; }
@Test public void increment_DoubleVariationValue_increments_by_the_value_of_the_arg() { DoubleValue source = new DoubleValue().increment(10); DoubleValue target = new DoubleValue().increment(source); verifySetVariationValue(target, 10); }
@Override public void write(int b) throws IOException { throwIfClosed(); inputBuffer[inputPosition++] = (byte) b; flushIfFull(); }
@Test void compressed_size_is_less_than_uncompressed() throws IOException { StringBuilder builder = new StringBuilder(); for (int i = 0; i < 100; i++) { builder.append("The quick brown fox jumps over the lazy dog").append('\n'); } byte[] inputData = builder.toString().get...
@Override public void replyComment(ProductCommentReplyReqVO replyVO, Long userId) { // 校验评论是否存在 validateCommentExists(replyVO.getId()); // 回复评论 productCommentMapper.updateById(new ProductCommentDO().setId(replyVO.getId()) .setReplyTime(LocalDateTime.now()).setReplyUse...
@Test public void testCommentReply_success() { // mock 测试 ProductCommentDO productComment = randomPojo(ProductCommentDO.class); productCommentMapper.insert(productComment); Long productCommentId = productComment.getId(); ProductCommentReplyReqVO replyVO = new ProductComment...
public static ShardingTableReferenceRuleConfiguration convertToObject(final String referenceConfig) { return referenceConfig.contains(":") ? convertYamlConfigurationWithName(referenceConfig) : convertYamlConfigurationWithoutName(referenceConfig); }
@Test void assertConvertToObjectForYamlConfigurationWithoutName() { ShardingTableReferenceRuleConfiguration actual = YamlShardingTableReferenceRuleConfigurationConverter.convertToObject("LOGIC_TABLE,SUB_LOGIC_TABLE"); assertThat(actual.getReference(), is("LOGIC_TABLE,SUB_LOGIC_TABLE")); }
public static <InputT> ProjectedBuilder<InputT, InputT> of(PCollection<InputT> input) { return named(null).of(input); }
@Test public void testBuild_Windowing() { final PCollection<String> dataset = TestUtils.createMockDataset(TypeDescriptors.strings()); final PCollection<String> uniq = Distinct.of(dataset) .windowBy(FixedWindows.of(org.joda.time.Duration.standardHours(1))) .triggeredBy(DefaultTr...
public static HistoryConfigCleaner getHistoryConfigCleaner(String name) { return historyConfigCleanerMap.getOrDefault(name, historyConfigCleanerMap.get("nacos")); }
@Test public void testHistoryConfigCleanerManangerTest() { HistoryConfigCleaner cleaner = HistoryConfigCleanerManager.getHistoryConfigCleaner( HistoryConfigCleanerConfig.getInstance().getActiveHistoryConfigCleaner()); assertEquals(cleaner.getName(), "nacos"); }
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 testMissingKey() throws IOException { Event event = getTestEvent(); String path = "/full/%{do-not-exist}"; assertEquals("/full/%{do-not-exist}", StringInterpolation.evaluate(event, path)); }
protected final boolean isConnected() { return service != null; }
@Test void testIsConnected() { AbstractServiceConnectionManager<Object> connectionManager = new TestServiceConnectionManager(); assertThat(connectionManager.isConnected()).isFalse(); connectionManager.connect(new Object()); assertThat(connectionManager.isConnected()...
List<MethodSpec> buildFunctions(AbiDefinition functionDefinition) throws ClassNotFoundException { return buildFunctions(functionDefinition, true); }
@Test public void testBuildFunctionConstantInvalid() throws Exception { AbiDefinition functionDefinition = new AbiDefinition( true, Collections.singletonList(new NamedType("param", "uint8")), "functionName", ...
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) { checkArgument( OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp); return new AutoValue_UBinary(binaryOp, lhs, rhs); }
@Test public void mod() { assertUnifiesAndInlines( "4 % 17", UBinary.create(Kind.REMAINDER, ULiteral.intLit(4), ULiteral.intLit(17))); }
public static <T> Bounded<T> from(BoundedSource<T> source) { return new Bounded<>(null, source); }
@Test public void failsWhenCustomBoundedSourceIsNotSerializable() { thrown.expect(IllegalArgumentException.class); Read.from(new NotSerializableBoundedSource()); }
private boolean isNotEmptyConfig() { return header.isNotEmptyConfig() || parameter.isNotEmptyConfig() || cookie.isNotEmptyConfig(); }
@Test public void testShenyuRequestParameter() { RequestHandle handle = new RequestHandle(); RequestHandle.ShenyuRequestParameter parameter = handle.new ShenyuRequestParameter( ImmutableMap.of("addKey", "addValue"), ImmutableMap.of("replaceKey", "newKey"), ImmutableMa...
@Override public long read() { return gaugeSource.read(); }
@Test public void whenNoProbeSet() { LongGauge gauge = metricsRegistry.newLongGauge("foo"); long actual = gauge.read(); assertEquals(0, actual); }
public static <T> boolean isEmpty(List<T> list) { return list == null || list.isEmpty(); }
@Test void isEmpty() { assertThat(ListUtils.isEmpty(null), is(true)); assertThat(ListUtils.isEmpty(Collections.emptyList()), is(true)); assertThat(ListUtils.isEmpty(List.of("1")), is(false)); }
public static Builder custom() { return new Builder(); }
@Test(expected = IllegalArgumentException.class) public void testBuildWithIllegalQueueCapacity() { ThreadPoolBulkheadConfig.custom() .queueCapacity(-1) .build(); }
@Override public Map<Path, Path> normalize(final Map<Path, Path> files) { final Map<Path, Path> normalized = new HashMap<>(); Iterator<Path> sourcesIter = files.keySet().iterator(); Iterator<Path> destinationsIter = files.values().iterator(); while(sourcesIter.hasNext()) { ...
@Test public void testNormalize2() { CopyRootPathsNormalizer normalizer = new CopyRootPathsNormalizer(); final HashMap<Path, Path> files = new HashMap<>(); files.put(new Path("/p/child", EnumSet.of(Path.Type.directory)), new Path("/d/child", EnumSet.of(Path.Type.directory))); files.p...
@Override public ObjectNode encode(Meter meter, CodecContext context) { checkNotNull(meter, "Meter cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(ID, meter.meterCellId().toString()) .put(LIFE, meter.life()) .put(PACKETS,...
@Test public void testMeterEncode() { Band band1 = DefaultBand.builder() .ofType(Band.Type.DROP) .burstSize(10) .withRate(10).build(); Band band2 = DefaultBand.builder() .ofType(Band.Type.REMARK) ...
@VisibleForTesting static SortedMap<OffsetRange, Integer> computeOverlappingRanges(Iterable<OffsetRange> ranges) { ImmutableSortedMap.Builder<OffsetRange, Integer> rval = ImmutableSortedMap.orderedBy(OffsetRangeComparator.INSTANCE); List<OffsetRange> sortedRanges = Lists.newArrayList(ranges); if (...
@Test public void testRandomRanges() { Random random = new Random(123892154890L); // use an arbitrary seed to make this test deterministic for (int i = 0; i < 1000; ++i) { List<OffsetRange> ranges = new ArrayList<>(); for (int j = 0; j < 20; ++j) { long start = random.nextInt(10); ...
public Disjunction addOperand(Predicate operand) { operands.add(operand); return this; }
@Test void requireThatEqualsIsImplemented() { Disjunction lhs = new Disjunction(SimplePredicates.newString("foo"), SimplePredicates.newString("bar")); assertEquals(lhs, lhs); assertNotEquals(lhs, new Object()); Disjunction rhs = new Disjunction(); assertNotEq...
boolean matchesNonValueField(final Optional<SourceName> source, final ColumnName column) { if (!source.isPresent()) { return sourceSchemas.values().stream() .anyMatch(schema -> SystemColumns.isPseudoColumn(column) || schema.isKeyColumn(column)); } final SourceName sourceName =...
@Test(expected = IllegalArgumentException.class) public void shouldThrowOnUnknownSourceWhenMatchingNonValueFields() { sourceSchemas.matchesNonValueField(Optional.of(SourceName.of("unknown")), K0); }
@Override public LocalResourceId resolve(String other, ResolveOptions resolveOptions) { checkState(isDirectory(), "Expected the path is a directory, but had [%s].", pathString); checkArgument( resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE) || resolveOptions.equals(StandardResol...
@Test public void testResolveInUnix() { if (SystemUtils.IS_OS_WINDOWS) { // Skip tests return; } // Tests for local files without the scheme. assertEquals( toResourceIdentifier("/root/tmp/aa"), toResourceIdentifier("/root/tmp/").resolve("aa", StandardResolveOptions.RESOLVE_...
public static CacheScope create(String id) { Preconditions.checkArgument(id != null && id.length() > 0, "scope id can not be null or empty string"); if (GLOBAL_ID.equals(id)) { return GLOBAL; } else if (Level.SCHEMA.matches(id)) { return new CacheScope(id, id.length(), Level.SCHEMA); ...
@Test public void scopeEquals() { assertEquals(CacheScope.GLOBAL, CacheScope.create(".")); assertEquals(CacheScope.create("."), CacheScope.create(".")); assertEquals(CacheScope.create("schema"), CacheScope.create("schema")); assertEquals(CacheScope.create("schema.table"), CacheScope.create("schema.tab...
static void setStringProperty(Message message, String name, String value) { try { message.setStringProperty(name, value); } catch (Throwable t) { propagateIfFatal(t); log(t, "error setting property {0} on message {1}", name, message); } }
@Test void setStringProperty() throws Exception { MessageProperties.setStringProperty(message, "b3", "1"); assertThat(message.getObjectProperty("b3")) .isEqualTo("1"); }
static boolean isNewDatabase(String uppercaseProductName) { if (SUPPORTED_DATABASE_NAMES.contains(uppercaseProductName)) { return false; } return DETECTED_DATABASE_NAMES.add(uppercaseProductName); }
@Test public void testH2() { String dbName = "H2"; boolean newDB = SupportedDatabases.isNewDatabase(dbName); assertThat(newDB).isFalse(); }
@Override protected void run(Environment environment, Namespace namespace, T configuration) throws Exception { final Server server = configuration.getServerFactory().build(environment); try { server.addEventListener(new LifeCycleListener()); cleanupAsynchronously(); ...
@Test void stopsAServerIfThereIsAnErrorStartingIt() { this.throwException = true; server.addBean(new AbstractLifeCycle() { @Override protected void doStart() throws Exception { throw new IOException("oh crap"); } }); assertThatIOEx...
@Override public List<String> getServerList() { return serverList.isEmpty() ? serversFromEndpoint : serverList; }
@Test void testConstructEndpointContextPathIsEmpty() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, ""); clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "bbb"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CLUSTER_NAME, "ccc"); ...
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (iconIds == null) { return; } switch (chatMessage.getType()) { case PUBLICCHAT: case MODCHAT: case FRIENDSCHAT: case CLAN_CHAT: case CLAN_GUEST_CHAT: case CLAN_GIM_CHAT: case PRIVATECHAT: case PRIVATECHATOUT: c...
@Test public void testOnChatMessage() { MessageNode messageNode = mock(MessageNode.class); // With chat recolor, message may be wrapped in col tags when(messageNode.getValue()).thenReturn("<col=ff0000>:) :) :)</col>"); ChatMessage chatMessage = new ChatMessage(); chatMessage.setType(ChatMessageType.PUBLICC...
@Override public void executeUpdate(final AlterStorageUnitStatement sqlStatement, final ContextManager contextManager) { checkBefore(sqlStatement); Map<String, DataSourcePoolProperties> propsMap = DataSourceSegmentsConverter.convert(database.getProtocolType(), sqlStatement.getStorageUnits()); ...
@Test void assertExecuteUpdateWithAlterDatabase() { ResourceMetaData resourceMetaData = mock(ResourceMetaData.class, RETURNS_DEEP_STUBS); StorageUnit storageUnit = mock(StorageUnit.class, RETURNS_DEEP_STUBS); ConnectionProperties connectionProps = mockConnectionProperties("ds_1"); wh...
public String convert(ILoggingEvent le) { long timestamp = le.getTimeStamp(); return cachingDateFormatter.format(timestamp); }
@Test public void convertsDateWithEnglishLocaleByDefault() { Locale origLocale = Locale.getDefault(); Locale.setDefault(Locale.FRANCE); assertEquals(ENGLISH_TIME_UTC, convert(_timestamp, DATETIME_PATTERN, "UTC")); Locale.setDefault(origLocale); }
public Optional<LocalSession> getActiveLocalSession(Tenant tenant, ApplicationId applicationId) { TenantApplications applicationRepo = tenant.getApplicationRepo(); return applicationRepo.activeSessionOf(applicationId).map(aLong -> tenant.getSessionRepository().getLocalSession(aLong)); }
@Test public void redeploy() { long firstSessionId = deployApp(testApp).sessionId(); long secondSessionId = deployApp(testApp).sessionId(); assertNotEquals(firstSessionId, secondSessionId); Session session = applicationRepository.getActiveLocalSession(tenant(), applicationId()).get...
@Nullable protected String findWebJarResourcePath(String pathStr) { Path path = Paths.get(pathStr); if (path.getNameCount() < 2) return null; String version = swaggerUiConfigProperties.getVersion(); if (version == null) return null; Path first = path.getName(0); Path rest = path.subpath(1, path.getNameCoun...
@Test void findWebJarResourcePath() { String path = "swagger-ui/swagger-initializer.js"; String actual = abstractSwaggerResourceResolver.findWebJarResourcePath(path); assertEquals("swagger-ui" + File.separator + "4.18.2" + File.separator + "swagger-initializer.js", actual); }
@Override public SerializationServiceBuilder setInitialOutputBufferSize(int initialOutputBufferSize) { if (initialOutputBufferSize <= 0) { throw new IllegalArgumentException("Initial buffer size must be positive!"); } this.initialOutputBufferSize = initialOutputBufferSize; ...
@Test(expected = IllegalArgumentException.class) public void test_exceptionThrown_whenInitialOutputBufferSizeNegative() { getSerializationServiceBuilder().setInitialOutputBufferSize(-1); }
@Override public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException { Collection<TableMetaData> tableMetaDataList = new LinkedList<>(); Map<String, Collection<ColumnMetaData>> columnMetaDataMap = loadColumnMetaDataMap(material.getDataSource(), material.getActu...
@Test void assertLoadWithTablesWithLowVersion() throws SQLException { DataSource dataSource = mockDataSource(); ResultSet resultSet = mockTableMetaDataResultSet(); when(dataSource.getConnection().prepareStatement(LOAD_COLUMN_META_DATA_WITH_TABLES_LOW_VERSION).executeQuery()).thenReturn(resul...
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) { return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context); }
@Test public void testShowEmpty() throws AnalysisException, DdlException { ShowProcedureStmt stmt = new ShowProcedureStmt(); ShowResultSet resultSet = ShowExecutor.execute(stmt, ctx); Assert.assertFalse(resultSet.next()); }
public CustomFieldMappings mergeWith(final CustomFieldMapping changedMapping) { final Set<CustomFieldMapping> modifiedMappings = new HashSet<>(this); modifiedMappings.removeIf(m -> changedMapping.fieldName().equals(m.fieldName())); modifiedMappings.add(changedMapping); return new CustomF...
@Test void testReturnsOriginalMappingsIfMergedWithEmptyMappings() { CustomFieldMappings customFieldMappings = new CustomFieldMappings(List.of()); assertSame(customFieldMappings, customFieldMappings.mergeWith(new CustomFieldMappings())); }
@VisibleForTesting List<Page> getAllPages() { return requireNonNull(pages, "Pages haven't been initialized yet"); }
@Test public void fail_if_pages_called_before_server_startup() { assertThatThrownBy(() -> underTest.getAllPages()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Pages haven't been initialized yet"); }
@Override public void handleRequest(HttpServerExchange httpServerExchange) { if (!httpServerExchange.getRequestMethod().equals(HttpString.tryFromString("GET"))) { httpServerExchange.setStatusCode(HTTP_METHOD_NOT_ALLOWED); httpServerExchange.getResponseSender().send(""); } else { // For now i...
@Test void get() { var sut = new HealthEndpoint(); // when var httpServerExchange = mock(HttpServerExchange.class); var headers = mock(HeaderMap.class); var sender = mock(Sender.class); when(httpServerExchange.getResponseHeaders()).thenReturn(headers); when(httpServerExchange.getResponse...
public Capacity getCapacityWithDefault(String group, String tenant) { Capacity capacity; boolean isTenant = StringUtils.isNotBlank(tenant); if (isTenant) { capacity = getTenantCapacity(tenant); } else { capacity = getGroupCapacity(group); } if (cap...
@Test void testGetCapacityWithDefault() { TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setQuota(0); tenantCapacity.setMaxSize(0); tenantCapacity.setMaxAggrCount(0); tenantCapacity.setMaxAggrSize(0); when(tenantCapacityPersistService.getTenantCa...
public int size() { return pfbdata.length; }
@Test void testPfbPDFBox5713() throws IOException { Type1Font font; try (InputStream is = new FileInputStream("target/fonts/DejaVuSerifCondensed.pfb")) { font = Type1Font.createWithPFB(is); } Assertions.assertEquals("Version 2.33", font.getVersion()); ...
@Override public boolean supports(Class<?> authentication) { return (JWTBearerAssertionAuthenticationToken.class.isAssignableFrom(authentication)); }
@Test public void should_support_JWTBearerAssertionAuthenticationToken() { assertThat(jwtBearerAuthenticationProvider.supports(JWTBearerAssertionAuthenticationToken.class), is(true)); }
public Reader getReader(InputStream in, String declaredEncoding) { fDeclaredEncoding = declaredEncoding; try { setText(in); CharsetMatch match = detect(); if (match == null) { return null; } return match.getReader(); ...
@Test public void testEmptyOrNullDeclaredCharset() throws IOException { try (InputStream in = getResourceAsStream("/test-documents/resume.html")) { CharsetDetector detector = new CharsetDetector(); Reader reader = detector.getReader(in, null); assertTrue(reader.ready()); ...
@Override public void setSessionIntervalTime(int sessionIntervalTime) { }
@Test public void setSessionIntervalTime() { mSensorsAPI.setSessionIntervalTime(50 * 100); Assert.assertEquals(30 * 1000, mSensorsAPI.getSessionIntervalTime()); }
public static String escapeString(String identifier) { return "'" + identifier.replace("\\", "\\\\").replace("'", "\\'") + "'"; }
@Test public void testEscapeStringNoSpecialCharacters() { assertEquals("'asdasd asd ad'", SingleStoreUtil.escapeString("asdasd asd ad")); }
public static void preserve(FileSystem targetFS, Path path, CopyListingFileStatus srcFileStatus, EnumSet<FileAttribute> attributes, boolean preserveRawXattrs) throws IOException { // strip out those attributes we don't need a...
@Test public void testPreserveNothingOnDirectory() throws IOException { FileSystem fs = FileSystem.get(config); EnumSet<FileAttribute> attributes = EnumSet.noneOf(FileAttribute.class); Path dst = new Path("/tmp/abc"); Path src = new Path("/tmp/src"); createDirectory(fs, src); createDirectory...
File putIfAbsent(String userId, boolean saveToDisk) throws IOException { String idKey = getIdStrategy().keyFor(userId); String directoryName = idToDirectoryNameMap.get(idKey); File directory = null; if (directoryName == null) { synchronized (this) { directoryN...
@Test public void testDirectoryFormatMixed() throws IOException { UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE); String user1 = "a$b!c^d~e@f"; File directory1 = mapper.putIfAbsent(user1, true); assertThat(directory1.getName(), startsWith("abcdef_")); }
@Override public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception { // Retrieve the message body as input stream InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, graph); // and covert that to XML Docume...
@Test public void testPartialPayloadXMLElementEncryptionWithByteKeyAndAlgorithm() throws Exception { final byte[] bits192 = { (byte) 0x24, (byte) 0xf2, (byte) 0xd3, (byte) 0x45, (byte) 0xc0, (byte) 0x75, (byte) 0xb1, (byte) 0x00, (byte) 0x30, (byte) 0xd4, (byt...
@Override @Nullable public float[] readFloatArray(@Nonnull String fieldName) throws IOException { return readIncompatibleField(fieldName, FLOAT_ARRAY, super::readFloatArray); }
@Test public void testReadFloatArray() throws Exception { assertNull(reader.readFloatArray("NO SUCH FIELD")); }
public Editor edit(String key) throws IOException { return edit(key, ANY_SEQUENCE_NUMBER); }
@Test public void nullKeyThrows() throws Exception { try { cache.edit(null); Assert.fail(); } catch (NullPointerException expected) { } }
public static byte[] writeUtf8(final String in) { if (in == null) { return null; } if (UnsafeUtil.hasUnsafe()) { // Calculate the encoded length. final int len = UnsafeUtf8Util.encodedLength(in); final byte[] outBytes = new byte[len]; U...
@Test public void toUtf8BytesTest() { for (int i = 0; i < 100000; i++) { String in = UUID.randomUUID().toString(); assertArrayEquals(Utils.getBytes(in), BytesUtil.writeUtf8(in)); } }
public static <T> T toObj(byte[] json, Class<T> cls) { try { return mapper.readValue(json, cls); } catch (Exception e) { throw new NacosDeserializationException(cls, e); } }
@Test void testToObject10() { assertThrows(Exception.class, () -> { JacksonUtils.toObj("{not_A}Json:String}".getBytes(), new TypeReference<Object>() { }); }); }
@Override public void check(final EncryptRule encryptRule, final ShardingSphereSchema schema, final SelectStatementContext sqlStatementContext) { checkSelect(encryptRule, sqlStatementContext); for (SelectStatementContext each : sqlStatementContext.getSubqueryContexts().values()) { checkS...
@Test void assertCheckWhenCombineStatementContainsEncryptColumn() { SelectStatementContext sqlStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS); when(sqlStatementContext.isContainsCombine()).thenReturn(true); when(sqlStatementContext.getSqlStatement().getCombine().isP...
@Override public Optional<ExecuteResult> getSaneQueryResult(final SQLStatement sqlStatement, final SQLException ex) { if (ER_PARSE_ERROR == ex.getErrorCode()) { return Optional.empty(); } if (sqlStatement instanceof SelectStatement) { return createQueryResult((SelectS...
@Test void assertGetSaneQueryResultForSyntaxError() { SQLException ex = new SQLException("", "", 1064, null); assertThat(new MySQLDialectSaneQueryResultEngine().getSaneQueryResult(null, ex), is(Optional.empty())); }
public static int findName(String expectedLogName) { int count = 0; List<Log> logList = DubboAppender.logList; for (int i = 0; i < logList.size(); i++) { String logName = logList.get(i).getLogName(); if (logName.contains(expectedLogName)) { count++; ...
@Test void testFindName() { Log log = mock(Log.class); DubboAppender.logList.add(log); when(log.getLogName()).thenReturn("a"); assertThat(LogUtil.findName("a"), equalTo(1)); }
@Override public Statement createStatement() { return new CircuitBreakerStatement(); }
@Test void assertCreateStatement() { assertThat(connection.createStatement(), instanceOf(CircuitBreakerStatement.class)); assertThat(connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY), instanceOf(CircuitBreakerStatement.class)); assertThat(connection.createSt...