focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public Pet category(Category category) {
this.category = category;
return this;
} | @Test
public void categoryTest() {
// TODO: test category
} |
@Override
@SuppressWarnings("unchecked")
public HttpRestResult<T> convertResult(HttpClientResponse response, Type responseType) throws Exception {
final Header headers = response.getHeaders();
InputStream body = response.getBody();
T extractBody = JacksonUtils.toObj(body, responseType);
... | @Test
void testConvertResult() throws Exception {
RestResult<String> testCase = RestResult.<String>builder().withCode(200).withData("ok").withMsg("msg").build();
InputStream inputStream = new ByteArrayInputStream(JacksonUtils.toJsonBytes(testCase));
HttpClientResponse response = mock(HttpCli... |
@NotNull
public SocialUserDO authSocialUser(Integer socialType, Integer userType, String code, String state) {
// 优先从 DB 中获取,因为 code 有且可以使用一次。
// 在社交登录时,当未绑定 User 时,需要绑定登录,此时需要 code 使用两次
SocialUserDO socialUser = socialUserMapper.selectByTypeAndCodeAnState(socialType, code, state);
i... | @Test
public void testAuthSocialUser_exists() {
// 准备参数
Integer socialType = SocialTypeEnum.GITEE.getType();
Integer userType = randomEle(SocialTypeEnum.values()).getType();
String code = "tudou";
String state = "yuanma";
// mock 方法
SocialUserDO socialUser = r... |
public boolean isMatch(Map<String, Pattern> patterns) {
if (!patterns.isEmpty()) {
return matchPatterns(patterns);
}
// Empty pattern is still considered as a match.
return true;
} | @Test
public void testIsMatchValid() throws UnknownHostException {
Uuid uuid = Uuid.randomUuid();
ClientMetricsInstanceMetadata instanceMetadata = new ClientMetricsInstanceMetadata(uuid, ClientMetricsTestUtils.requestContext());
// We consider empty/missing client matching patterns as valid
... |
public static TimedCacheReloadTrigger fromConfig(ReadableConfig config) {
checkArgument(
config.get(CACHE_TYPE) == FULL,
"'%s' should be '%s' in order to build a Timed cache reload trigger.",
CACHE_TYPE.key(),
FULL);
checkArgument(
... | @Test
void testCreateFromConfig() {
assertThat(TimedCacheReloadTrigger.fromConfig(createValidConf())).isNotNull();
Configuration conf1 = createValidConf().set(CACHE_TYPE, PARTIAL);
assertThatThrownBy(() -> TimedCacheReloadTrigger.fromConfig(conf1))
.isInstanceOf(IllegalArgume... |
public static <T> PTransform<PCollection<T>, PCollection<T>> exceptAll(
PCollection<T> rightCollection) {
checkNotNull(rightCollection, "rightCollection argument is null");
return new SetImpl<>(rightCollection, exceptAll());
} | @Test
@Category(NeedsRunner.class)
public void testExceptAllCollectionList() {
PCollection<String> third = p.apply("third", Create.of(Arrays.asList("a", "b", "b", "g", "f")));
PCollection<Row> thirdRows = p.apply("thirdRows", Create.of(toRows("a", "b", "b", "g")));
PAssert.that(
PCollection... |
public MongoClientURI getMongoClientURI() {
final MongoClientOptions.Builder mongoClientOptionsBuilder = MongoClientOptions.builder()
.connectionsPerHost(getMaxConnections());
return new MongoClientURI(uri, mongoClientOptionsBuilder);
} | @Test
public void validateSucceedsWithIPv6Address() throws Exception {
MongoDbConfiguration configuration = new MongoDbConfiguration();
final Map<String, String> properties = singletonMap(
"mongodb_uri", "mongodb://[2001:DB8::DEAD:BEEF:CAFE:BABE]:1234,127.0.0.1:5678/TEST"
);
... |
@Override
public void setString( String string ) {
this.string = string;
} | @Test
public void testSetString() {
ValueString vs = new ValueString();
vs.setString( null );
assertNull( vs.getString() );
vs.setString( "" );
assertEquals( "", vs.getString() );
vs.setString( "Boden" );
assertEquals( "Boden", vs.getString() );
} |
public static <T> T newInstanceOrNull(Class<? extends T> clazz, Object... params) {
Constructor<T> constructor = selectMatchingConstructor(clazz, params);
if (constructor == null) {
return null;
}
try {
return constructor.newInstance(params);
} catch (Ill... | @Test
public void newInstanceOrNull_nullIsMatchingAllTypes() {
ClassWithTwoArgConstructorConstructor instance = InstantiationUtils.newInstanceOrNull(
ClassWithTwoArgConstructorConstructor.class,
"foo", null);
assertNotNull(instance);
} |
public String getFormattedMessage() {
if (formattedMessage != null) {
return formattedMessage;
}
if (argumentArray != null) {
formattedMessage = MessageFormatter.arrayFormat(message, argumentArray)
.getMessage();
} else {
formattedMessage = message;
}
return form... | @Test
public void testNoFormattingWithArgs() {
String message = "testNoFormatting";
Throwable throwable = null;
Object[] argArray = new Object[] {12, 13};
LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray);
assertNull(event.formattedMessage);
assertEqua... |
public ExternalIssueReport parse(Path reportPath) {
try (Reader reader = Files.newBufferedReader(reportPath, StandardCharsets.UTF_8)) {
ExternalIssueReport report = gson.fromJson(reader, ExternalIssueReport.class);
externalIssueReportValidator.validate(report, reportPath);
return report;
} cat... | @Test
public void parse_whenCorrectDeprecatedFormat_shouldParseCorrectly() {
reportPath = Paths.get(DEPRECATED_REPORTS_LOCATION + "report.json");
ExternalIssueReport report = externalIssueReportParser.parse(reportPath);
verify(validator).validate(report, reportPath);
assertDeprecatedReport(report);
... |
@Override
public void setUnixOwner(final Path file, final String owner) throws BackgroundException {
final FileAttributes attr = new FileAttributes.Builder()
.withUIDGID(new Integer(owner), 0)
.build();
try {
session.sftp().setAttributes(file.getAbsolute()... | @Test
@Ignore
public void testSetUnixOwner() throws Exception {
final Path home = new SFTPHomeDirectoryService(session).find();
final long modified = System.currentTimeMillis();
final Path test = new Path(home, "test", EnumSet.of(Path.Type.file));
new SFTPUnixPermissionFeature(se... |
public void notifyPluginAboutClusterProfileChanged(String pluginId, ClusterProfilesChangedStatus status, Map<String, String> oldClusterProfile, Map<String, String> newClusterProfile) {
try {
LOGGER.debug("Processing report cluster profile changed for plugin: {} with status: {} with old cluster: {} a... | @Test
public void shouldTalkToExtensionToNotifyClusterProfileHasChanged() {
final Map<String, String> newClusterProfileConfigurations = Map.of("Image", "alpine:latest");
elasticAgentPluginRegistry.notifyPluginAboutClusterProfileChanged(PLUGIN_ID, ClusterProfilesChangedStatus.CREATED, null, newCluste... |
public static Map<String, String[]> getQueryMap(String query) {
Map<String, String[]> map = new HashMap<>();
String[] params = query.split(PARAM_CONCATENATE);
for (String param : params) {
String[] paramSplit = param.split("=");
if (paramSplit.length == 0) {
... | @Test
void testGetQueryMapMultipleValues() {
String query = "param2=15¶m1=12¶m2=baulpismuth";
Map<String, String[]> params = RequestViewHTTP.getQueryMap(query);
Assertions.assertNotNull(params);
Assertions.assertEquals(2, params.size());
String[] param1 = params.get... |
long nextRecordingId()
{
return nextRecordingId;
} | @Test
void shouldNotThrowArchiveExceptionWhenNextRecordingIdIsInvalidIfCatalogIsReadOnly()
throws IOException
{
setNextRecordingId(recordingTwoId);
try (Catalog catalog = new Catalog(archiveDir, clock))
{
assertEquals(recordingTwoId, catalog.nextRecordingId());
... |
@Override
public Long time(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Long> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.TIME_LONG);
return syncFuture(f);
} | @Test
public void testTime() {
RedisClusterNode master = getFirstMaster();
Long time = connection.time(master);
assertThat(time).isGreaterThan(1000);
} |
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final HintShardingValue<Comparable<?>> shardingValue) {
return shardingValue.getValues().isEmpty() ? availableTargetNames : shardingValue.getValues().stream().map(this::doSharding).collect(Collectors.toList());
... | @Test
void assertDoShardingWithSingleValueOfDefault() {
List<String> availableTargetNames = Arrays.asList("t_order_0", "t_order_1", "t_order_2", "t_order_3");
HintShardingValue<Comparable<?>> shardingValue = new HintShardingValue<>("t_order", "order_id", Collections.singleton("t_order_0"));
... |
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> properties) throws Exception {
AS400ConnectionPool connectionPool;
if (properties.containsKey(CONNECTION_POOL)) {
LOG.trace("AS400ConnectionPool instance specified in the URI - will look it up."... | @Test
public void testCreatePgmEndpoint() throws Exception {
Endpoint endpoint = component
.createEndpoint("jt400://user:password@host/qsys.lib/library.lib/queue.pgm?connectionPool=#mockPool");
assertNotNull(endpoint);
assertTrue(endpoint instanceof Jt400Endpoint);
} |
public String sign(String msg) {
try {
RSAPrivateKey key = getPrivateKey();
Signature sig = Signature.getInstance(SIGNING_ALGORITHM + "with" + key.getAlgorithm());
sig.initSign(key);
sig.update(msg.getBytes(StandardCharsets.UTF_8));
return Base64.getEn... | @Test
public void dsigSignAndVerify() throws Exception {
String plainText = "Hello world";
String msg = key.sign(plainText);
System.out.println(msg);
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initVerify(key.getPublicKey());
sig.update(plainText.getB... |
public static List<PartitionSpec> getPartitionspecsGroupedByStorageDescriptor(Table table,
Collection<Partition> partitions) {
final String tablePath = table.getSd().getLocation();
ImmutableListMultimap<StorageDescriptorKey, Partit... | @Test
public void testGetPartitionspecsGroupedBySDOnePartitionInTable() throws MetaException {
// Create database and table
Table tbl = new TableBuilder()
.setDbName(DB_NAME)
.setTableName(TABLE_NAME)
.addCol("id", "int")
.setLocation("/foo")
.build(null);
Partition... |
public static RepositoryMetadataStore getInstance() {
return repositoryMetadataStore;
} | @Test
public void shouldBeAbleToCheckIfPluginExists() throws Exception {
RepositoryMetadataStore metadataStore = RepositoryMetadataStore.getInstance();
PackageConfigurations repositoryConfigurationPut = new PackageConfigurations();
metadataStore.addMetadataFor("plugin-id", repositoryConfigu... |
static KafkaAdminClient createInternal(AdminClientConfig config, TimeoutProcessorFactory timeoutProcessorFactory) {
return createInternal(config, timeoutProcessorFactory, null);
} | @Test
public void testDefaultApiTimeoutAndRequestTimeoutConflicts() {
final AdminClientConfig config = newConfMap(AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, "500");
KafkaException exception = assertThrows(KafkaException.class,
() -> KafkaAdminClient.createInternal(config, null));
... |
@Override
public UrlPattern doGetPattern() {
return UrlPattern.builder()
.includes(includeUrls)
.excludes(excludeUrls)
.build();
} | @Test
public void does_not_match_servlet_filter_that_prefix_a_ws() {
initWebServiceEngine(
newWsUrl("api/foo", "action").setHandler(ServletFilterHandler.INSTANCE),
newWsUrl("api/foo", "action_2"));
assertThat(underTest.doGetPattern().matches("/api/foo/action")).isFalse();
assertThat(underTest... |
@Override
public void validate(final SingleRule rule, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database) {
DropSchemaStatement dropSchemaStatement = (DropSchemaStatement) sqlStatementContext.getSqlStatement();
boolean containsCascade = dropSchemaStatement.isContain... | @Test
void assertValidate() {
new SingleDropSchemaMetaDataValidator().validate(mock(SingleRule.class, RETURNS_DEEP_STUBS), createSQLStatementContext("foo_schema", true), mockDatabase());
} |
@Override
public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic, Map<String, Subscription> subscriptions) {
Map<String, List<TopicPartition>> assignment = new HashMap();
Iterator subIter = subscriptions.keySet().iterator();
//initialize subscription mapping... | @Test
public void ConsumerEmptyWithoutTopic() {
String consumerId = "testConsumer";
Map<String, Integer> partitionsPerTopic = new HashMap<>();
Map<String, List<TopicPartition>> assignment = testAssignor.assign(
partitionsPerTopic,
Collections.singletonMap(consumerId, ... |
static AnnotatedClusterState generatedStateFrom(final Params params) {
final ContentCluster cluster = params.cluster;
final ClusterState workingState = ClusterState.emptyState();
final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>();
for (final NodeInfo nodeInfo : cluster.... | @Test
void cluster_down_if_less_than_min_count_of_distributors_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN)
.reportDistributorNodeState(2, State.DOWN);
... |
protected ValidationTaskResult loadHdfsConfig() {
Pair<String, String> clientConfFiles = getHdfsConfPaths();
String coreConfPath = clientConfFiles.getFirst();
String hdfsConfPath = clientConfFiles.getSecond();
mCoreConf = accessAndParseConf("core-site.xml", coreConfPath);
mHdfsConf = accessAndParse... | @Test
public void cannotParseCoreSiteXml() throws IOException {
String hdfsSite = Paths.get(sTestDir.toPath().toString(), "hdfs-site.xml").toString();
ValidationTestUtils.writeXML(hdfsSite, ImmutableMap.of("key2", "value2"));
RandomAccessFile hdfsFile = new RandomAccessFile(hdfsSite, "rw");
hdfsFile.s... |
public static void mergeMap(boolean decrypt, Map<String, Object> config) {
merge(decrypt, config);
} | @Test
public void testMap_allowNullOverwrite() {
Map<String, Object> testMap = new HashMap<>();
testMap.put("key", "${TEST.null: value}");
CentralizedManagement.mergeMap(true, testMap);
Assert.assertNull(testMap.get("key"));
} |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Test
public void testShowTableFromUnknownDatabase() throws SemanticException, DdlException {
ShowTableStmt stmt = new ShowTableStmt("emptyDb", false, null);
expectedEx.expect(SemanticException.class);
expectedEx.expectMessage("Unknown database 'emptyDb'");
ShowExecutor.execute(stmt... |
@Override
public byte[] encode(ILoggingEvent event) {
StringBuilder sb = new StringBuilder();
sb.append(OPEN_OBJ);
var level = event.getLevel();
if (level != null) {
appenderMember(sb, "level", level.levelStr);
sb.append(VALUE_SEPARATOR);
}
appenderMember(sb, "message", StringEsca... | @Test
void should_encode_when_no_level_and_no_stacktrace() {
var logEvent = mock(ILoggingEvent.class);
when(logEvent.getLevel()).thenReturn(null);
when(logEvent.getFormattedMessage()).thenReturn("message");
var bytes = underTest.encode(logEvent);
assertThat(new String(bytes, StandardCharsets.UTF... |
@PostMapping("create-review")
public Mono<String> createReview(@ModelAttribute("product") Mono<Product> productMono,
NewProductReviewPayload payload,
Model model,
ServerHttpResponse response) {
ret... | @Test
void createReview_RequestIsValid_RedirectsToProductPage() {
// given
var model = new ConcurrentModel();
var response = new MockServerHttpResponse();
doReturn(Mono.just(new ProductReview(UUID.fromString("86efa22c-cbae-11ee-ab01-679baf165fb7"), 1, 3, "Ну, на троечку...")))
... |
private static ByteBuf copiedBufferUtf8(CharSequence string) {
boolean release = true;
// Mimic the same behavior as other copiedBuffer implementations.
ByteBuf buffer = ALLOC.heapBuffer(ByteBufUtil.utf8Bytes(string));
try {
ByteBufUtil.writeUtf8(buffer, string);
... | @Test
public void testCopiedBufferUtf8() {
testCopiedBufferCharSequence("Some UTF_8 like äÄ∏ŒŒ", CharsetUtil.UTF_8);
} |
public static void addSizeAllMemTables(final StreamsMetricsImpl streamsMetrics,
final RocksDBMetricContext metricContext,
final Gauge<BigInteger> valueProvider) {
addMutableMetric(
streamsMetrics,
metri... | @Test
public void shouldAddSizeAllMemTablesMetric() {
final String name = "size-all-mem-tables";
final String description = "Approximate size of active, unflushed immutable, and pinned immutable memtables in bytes";
runAndVerifyMutableMetric(
name,
description,
... |
public List<ShenyuLoaderResult> loadExtendPlugins(final String path) throws IOException {
File[] jarFiles = ShenyuPluginPathBuilder.getPluginFile(path).listFiles(file -> file.getName().endsWith(".jar"));
if (Objects.isNull(jarFiles)) {
return Collections.emptyList();
}
List<S... | @Test
public void testGetPluginPathWithNoJar() throws IOException {
List<ShenyuLoaderResult> pluginList = shenyuPluginLoader.loadExtendPlugins("test");
assertThat(pluginList.size(), is(0));
} |
public static void validateValue(Schema schema, Object value) {
validateValue(null, schema, value);
} | @Test
public void testValidateValueMismatchTimestamp() {
assertThrows(DataException.class, () -> ConnectSchema.validateValue(Timestamp.SCHEMA, 1000L));
} |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testEqual() {
assertThat(equal("x", 5).literals().size()).isEqualTo(1);
Evaluator evaluator = new Evaluator(STRUCT, equal("x", 7));
assertThat(evaluator.eval(TestHelpers.Row.of(7, 8, null))).as("7 == 7 => true").isTrue();
assertThat(evaluator.eval(TestHelpers.Row.of(6, 8, null))).as... |
@Override
public String getUrl() {
return url != null ? url.originalArgument() : null;
} | @Test
void shouldReturnTheUrl() {
String url = "git@github.com/my/repo";
GitMaterialConfig config = git(url);
assertEquals(url, config.getUrl());
} |
public UUID initializeProcessId() {
if (!hasPersistentStores) {
final UUID processId = UUID.randomUUID();
log.info("Created new process id: {}", processId);
return processId;
}
if (!lockStateDirectory()) {
log.error("Unable to obtain lock as state... | @Test
public void shouldReadFutureProcessFileFormat() throws Exception {
final File processFile = new File(appDir, PROCESS_FILE_NAME);
final ObjectMapper mapper = new ObjectMapper();
final UUID processId = UUID.randomUUID();
mapper.writeValue(processFile, new FutureStateDirectoryProc... |
public synchronized void xaRollback(String xid, long branchId, String applicationData) throws XAException {
XAXid xaXid = XAXidBuilder.build(xid, branchId);
xaRollback(xaXid);
} | @Test
public void testXARollback() throws Throwable {
Connection connection = Mockito.mock(Connection.class);
Mockito.when(connection.getAutoCommit()).thenReturn(true);
XAResource xaResource = Mockito.mock(XAResource.class);
XAConnection xaConnection = Mockito.mock(XAConnection.cla... |
@Override
@Transactional(rollbackFor = Exception.class)
public Long createJob(JobSaveReqVO createReqVO) throws SchedulerException {
validateCronExpression(createReqVO.getCronExpression());
// 1.1 校验唯一性
if (jobMapper.selectByHandlerName(createReqVO.getHandlerName()) != null) {
... | @Test
public void testCreateJob_cronExpressionValid() {
// 准备参数。Cron 表达式为 String 类型,默认随机字符串。
JobSaveReqVO reqVO = randomPojo(JobSaveReqVO.class);
// 调用,并断言异常
assertServiceException(() -> jobService.createJob(reqVO), JOB_CRON_EXPRESSION_VALID);
} |
public void addTimeline(TimelineEvent event) {
if (timeline.add(event)) {
synced = false;
}
} | @Test
public void testAddDuplicateTimelineEvents() throws Exception {
StepRuntimeSummary summary =
loadObject(
"fixtures/execution/sample-step-runtime-summary-1.json", StepRuntimeSummary.class);
TimelineEvent event = TimelineLogEvent.info("hello world");
summary.addTimeline(event);
... |
public static void checkNotNullAndNotEmpty(@Nullable String value, String propertyName) {
Preconditions.checkNotNull(value, "Property '" + propertyName + "' cannot be null");
Preconditions.checkArgument(
!value.trim().isEmpty(), "Property '" + propertyName + "' cannot be an empty string");
} | @Test
public void testCheckNotNullAndNotEmpty_stringPass() {
Validator.checkNotNullAndNotEmpty("value", "ignored");
// pass
} |
@Override
public void setIntValue(String metricKey, int line, int value) {
checkNotNull(metricKey);
checkLineRange(line);
setValue(metricKey, line, value);
} | @Test
public void validateLineGreaterThanZero() {
assertThatThrownBy(() -> fileLineMeasures.setIntValue(HITS_METRIC_KEY, 0, 2))
.hasMessage("Line number should be positive for file src/foo.php.");
} |
@Override
public HttpResponseOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
return this.write(file, this.toHeaders(file, status, expect), status);
}
catch(ConflictException e) {
... | @Test(expected = AccessDeniedException.class)
@Ignore
public void testWriteAccessDenied() throws Exception {
final Path test = new Path(new DefaultHomeFinderService(session).find().getAbsolute() + "/nosuchdirectory/" + new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
... |
public MemoryLRUCacheBytesIterator range(final String namespace, final Bytes from, final Bytes to) {
return range(namespace, from, to, true);
} | @Test
public void shouldGetSameKeyAsPeekNext() {
final ThreadCache cache = setupThreadCache(0, 1, 10000L, false);
final Bytes theByte = Bytes.wrap(new byte[]{0});
final ThreadCache.MemoryLRUCacheBytesIterator iterator = cache.range(namespace, theByte, Bytes.wrap(new byte[]{1}));
asse... |
public static IRubyObject deep(final Ruby runtime, final Object input) {
if (input == null) {
return runtime.getNil();
}
final Class<?> cls = input.getClass();
final Rubyfier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return con... | @Test
public void testDeepMapWithFloat() throws Exception {
Map<String, Float> data = new HashMap<>();
data.put("foo", 1.0F);
RubyHash rubyHash = (RubyHash)Rubyfier.deep(RubyUtil.RUBY, data);
// Hack to be able to retrieve the original, unconverted Ruby object from Map
// it... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldExtractUnaliasedJoinDataSources() {
// Given:
final SingleStatementContext stmt = givenQuery("SELECT * FROM TEST1 JOIN TEST2"
+ " ON test1.col1 = test2.col1;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
assertThat(result.getF... |
@Override
public Batch toBatch() {
return new SparkBatch(
sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode());
} | @Test
public void testUnpartitionedMonths() throws Exception {
createUnpartitionedTable(spark, tableName);
SparkScanBuilder builder = scanBuilder();
MonthsFunction.TimestampToMonthsFunction function =
new MonthsFunction.TimestampToMonthsFunction();
UserDefinedScalarFunc udf = toUDF(function,... |
public ConvertedTime getConvertedTime(long duration) {
Set<Seconds> keys = RULES.keySet();
for (Seconds seconds : keys) {
if (duration <= seconds.getSeconds()) {
return RULES.get(seconds).getConvertedTime(duration);
}
}
return new TimeConverter.Ove... | @Test
public void testShouldReport2MonthsFor59Days23Hours59Minutes30Seconds() throws Exception {
assertEquals(TimeConverter.ABOUT_X_MONTHS_AGO.argument(2), timeConverter
.getConvertedTime(60 * TimeConverter.DAY_IN_SECONDS - 30));
} |
public static <T> T convert(Class<T> type, Object value) throws ConvertException {
return convert((Type) type, value);
} | @Test
public void toObjectTest() {
final Object result = Convert.convert(Object.class, "aaaa");
assertEquals("aaaa", result);
} |
@Override
public void verify(byte[] data, byte[] signature, MessageDigest digest) {
final byte[] decrypted = engine.processBlock(signature, 0, signature.length);
final int delta = checkSignature(decrypted, digest);
final int offset = decrypted.length - digest.getDigestLength() - delta;
... | @Test
public void shouldValidateSignatureSHA512() {
final byte[] challenge = CryptoUtils.random(40);
final byte[] signature = sign(0x54, challenge, ISOTrailers.TRAILER_SHA512, "SHA-512");
new DssRsaSignatureVerifier(PUBLIC).verify(challenge, signature, "SHA-512");
} |
public QueryParseResult parse(String sql, @Nonnull SqlSecurityContext ssc) {
try {
return parse0(sql, ssc);
} catch (QueryException e) {
throw e;
} catch (Exception e) {
String message;
// Check particular type of exception which causes typical lon... | @Test
public void unsupportedKeywordTest() {
assertThatThrownBy(() -> parser.parse("show tables"))
.isInstanceOf(QueryException.class)
.hasMessageContaining("Encountered \"show tables\" at line 1, column 1.");
} |
public PageListResponse<IndexSetFieldTypeSummary> getIndexSetFieldTypeSummary(final Set<String> streamIds,
final String fieldName,
final Predicate<String> i... | @Test
void testDoesNotReturnResultsForIndexSetsIfItDoesNotExist() {
Predicate<String> indexSetPermissionPredicateAlwaysReturningFalse = x -> false;
doReturn(Set.of("index_set_id")).when(streamService).indexSetIdsByIds(Set.of("stream_id"));
final PageListResponse<IndexSetFieldTypeSummary> sum... |
@CanIgnoreReturnValue
public Replacements add(Replacement replacement) {
return add(replacement, CoalescePolicy.REJECT);
} | @Test
public void overlap() {
Replacements replacements = new Replacements();
Replacement hello = Replacement.create(2, 4, "hello");
Replacement goodbye = Replacement.create(3, 5, "goodbye");
replacements.add(hello);
try {
replacements.add(goodbye);
fail();
} catch (IllegalArgument... |
public static CharSequence unescapeCsv(CharSequence value) {
int length = checkNotNull(value, "value").length();
if (length == 0) {
return value;
}
int last = length - 1;
boolean quoted = isDoubleQuote(value.charAt(0)) && isDoubleQuote(value.charAt(last)) && length !=... | @Test
public void testUnescapeCsv() {
assertEquals("", unescapeCsv(""));
assertEquals("\"", unescapeCsv("\"\"\"\""));
assertEquals("\"\"", unescapeCsv("\"\"\"\"\"\""));
assertEquals("\"\"\"", unescapeCsv("\"\"\"\"\"\"\"\""));
assertEquals("\"netty\"", unescapeCsv("\"\"\"netty... |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
try {
new DriveAttributesFinderFeature(session, fileid).find(file, listener);
return true;
}
catch(NotfoundException e) {
return false;
... | @Test
public void testFind() throws Exception {
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
final Path folder = new DriveDirectoryFeature(session, fileid).mkdir(
new Path(DriveHomeFinderService.MYDRIVE_FOLDER, UUID.randomUUID().toString(), EnumSet.of(Path.Typ... |
@ConstantFunction(name = "bitShiftRightLogical", argTypes = {BIGINT, BIGINT}, returnType = BIGINT)
public static ConstantOperator bitShiftRightLogicalBigint(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createBigint(first.getBigint() >>> second.getBigint());
} | @Test
public void bitShiftRightLogicalBigint() {
assertEquals(12, ScalarOperatorFunctions.bitShiftRightLogicalBigint(O_BI_100, O_BI_3).getBigint());
} |
public void handleSend(HttpServerResponse response, Span span) {
handleFinish(response, span);
} | @Test void handleSend_finishesSpanEvenIfUnwrappedNull() {
brave.Span span = mock(brave.Span.class);
when(span.context()).thenReturn(context);
when(span.customizer()).thenReturn(span);
handler.handleSend(response, span);
verify(span).isNoop();
verify(span).context();
verify(span).customizer... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
var tbMsg = ackIfNeeded(ctx, msg);
withCallback(publishMessageAsync(ctx, tbMsg),
m -> tellSuccess(ctx, m),
t -> tellFailure(ctx, processException(tbMsg, t), t));
} | @Test
void givenForceAckIsFalseAndErrorOccursDuringProcessingRequest_whenOnMsg_thenTellFailure() {
ReflectionTestUtils.setField(node, "forceAck", false);
ListeningExecutor listeningExecutor = mock(ListeningExecutor.class);
given(ctxMock.getExternalCallExecutor()).willReturn(listeningExecutor... |
@VisibleForTesting
S3Client getS3Client() {
return this.s3Client.get();
} | @Test
public void testGetPathStyleAccessEnabled() throws URISyntaxException {
S3FileSystem s3FileSystem = new S3FileSystem(s3ConfigWithPathStyleAccessEnabled("s3"));
URL s3Url =
s3FileSystem
.getS3Client()
.utilities()
.getUrl(GetUrlRequest.builder().bucket("bucket"... |
@Override
public Set<Permission> getRequestedPermissions(ApplicationId appId) {
Set<Permission> permissions = violations.get(appId);
return permissions != null ? permissions : ImmutableSet.of();
} | @Test
public void testGetRequestedPermissions() {
Set<Permission> permissions = violations.get(appId);
assertTrue(permissions.contains(testPermission));
} |
@Nonnull
public static <T> AggregateOperation1<T, LongLongAccumulator, Double> averagingLong(
@Nonnull ToLongFunctionEx<? super T> getLongValueFn
) {
checkSerializable(getLongValueFn, "getLongValueFn");
// count == accumulator.value1
// sum == accumulator.value2
retur... | @Test
public void when_averagingLong_sumTooLarge_then_exception() {
// Given
AggregateOperation1<Long, LongLongAccumulator, Double> aggrOp = averagingLong(Long::longValue);
LongLongAccumulator acc = aggrOp.createFn().get();
// When
BiConsumerEx<? super LongLongAccumulator, ?... |
@Override
public boolean addClass(final Class<?> stepClass) {
if (stepClasses.contains(stepClass)) {
return true;
}
checkNoComponentAnnotations(stepClass);
if (hasCucumberContextConfiguration(stepClass)) {
checkOnlyOneClassHasCucumberContextConfiguration(step... | @Test
void shouldBeStoppableWhenFacedWithFailedApplicationContext() {
final ObjectFactory factory = new SpringFactory();
factory.addClass(FailedTestInstanceCreation.class);
assertThrows(CucumberBackendException.class, factory::start);
assertDoesNotThrow(factory::stop);
} |
public static byte[] decode(String base32) {
return Base32Codec.INSTANCE.decode(base32);
} | @Test
public void decodeTest(){
String a = "伦家是一个非常长的字符串";
String decodeStr = Base32.decodeStr("4S6KNZNOW3TJRL7EXCAOJOFK5GOZ5ZNYXDUZLP7HTKCOLLMX46WKNZFYWI");
assertEquals(a, decodeStr);
} |
@VisibleForTesting
void setIsPartialBufferCleanupRequired() {
isPartialBufferCleanupRequired = true;
} | @TestTemplate
void testSkipPartialDataEndsInBufferWithNoMoreData() throws Exception {
final BufferWritingResultPartition writer = createResultPartition();
final PipelinedApproximateSubpartition subpartition =
getPipelinedApproximateSubpartition(writer);
writer.emitRecord(toB... |
public static boolean hasCauseOf(Throwable t, Class<? extends Throwable> causeType) {
return Throwables.getCausalChain(t)
.stream()
.anyMatch(c -> causeType.isAssignableFrom(c.getClass()));
} | @Test
public void hasCauseOf_returnsFalseIfNoCauseOfTheProvidedTypeFound() {
assertThat(ExceptionUtils.hasCauseOf(
new RuntimeException("parent", new RuntimeException("asdasd", new IllegalArgumentException())), IOException.class)).isFalse();
} |
public DoubleArrayAsIterable usingTolerance(double tolerance) {
return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject());
} | @Test
public void usingTolerance_contains_failureWithInfinity() {
expectFailureWhenTestingThat(array(1.1, POSITIVE_INFINITY, 3.3))
.usingTolerance(DEFAULT_TOLERANCE)
.contains(POSITIVE_INFINITY);
assertFailureKeys("value of", "expected to contain", "testing whether", "but was");
assertFail... |
public static String appendScheme(final String url, final String scheme) {
String schemeUrl = url;
if (!schemeUrl.startsWith("http://") && !schemeUrl.startsWith("https://")) {
schemeUrl = scheme + "://" + schemeUrl;
}
return schemeUrl;
} | @Test
void appendScheme() {
String uri = UriUtils.appendScheme("example.com", "http");
assertEquals("http://example.com", uri);
uri = UriUtils.appendScheme("example.com", "https");
assertEquals("https://example.com", uri);
uri = UriUtils.appendScheme("https://example.com", ... |
@Override
public void trace(String msg) {
logger.trace(msg);
} | @Test
public void testTrace() {
Log mockLog = mock(Log.class);
InternalLogger logger = new CommonsLogger(mockLog, "foo");
logger.trace("a");
verify(mockLog).trace("a");
} |
public static VersionedBytesStoreSupplier persistentVersionedKeyValueStore(final String name,
final Duration historyRetention) {
Objects.requireNonNull(name, "name cannot be null");
final String hrMsgPrefix = prepareMillisChe... | @Test
public void shouldThrowIfPersistentVersionedKeyValueStoreStoreNameIsNull() {
Exception e = assertThrows(NullPointerException.class, () -> Stores.persistentVersionedKeyValueStore(null, ZERO));
assertEquals("name cannot be null", e.getMessage());
e = assertThrows(NullPointerException.cl... |
@CanIgnoreReturnValue
public final Ordered containsAtLeastEntriesIn(Map<?, ?> expectedMap) {
if (expectedMap.isEmpty()) {
return IN_ORDER;
}
boolean containsAnyOrder = containsEntriesInAnyOrder(expectedMap, /* allowUnexpected= */ true);
if (containsAnyOrder) {
return new MapInOrder(expecte... | @Test
public void containsAtLeastEmpty() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("key", 1);
assertThat(actual).containsAtLeastEntriesIn(ImmutableMap.of());
assertThat(actual).containsAtLeastEntriesIn(ImmutableMap.of()).inOrder();
} |
@Override
public Collection<Block> getBySequenceHash(ByteArray sequenceHash) {
ensureSorted();
// prepare hash for binary search
int[] hash = sequenceHash.toIntArray();
if (hash.length != hashInts) {
throw new IllegalArgumentException("Expected " + hashInts + " ints in hash, but got " + hash.le... | @Test(expected = IllegalArgumentException.class)
public void attempt_to_find_hash_of_incorrect_size() {
CloneIndex index = new PackedMemoryCloneIndex(4, 1);
index.getBySequenceHash(new ByteArray(1L));
} |
public boolean isValid() {
return sizeInBytes() >= RECORD_BATCH_OVERHEAD && checksum() == computeChecksum();
} | @Test
public void testInvalidCrc() {
MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L,
Compression.NONE, TimestampType.CREATE_TIME,
new SimpleRecord(1L, "a".getBytes(), "1".getBytes()),
new SimpleRecord(2L, "b".getBytes(), "2".g... |
@Override
public void commit() throws SQLException {
for (TransactionHook each : transactionHooks) {
each.beforeCommit(connection.getCachedConnections().values(), getTransactionContext(), ProxyContext.getInstance().getContextManager().getComputeNodeInstanceContext().getLockContext());
}
... | @Test
void assertCommitForLocalTransaction() throws SQLException {
ContextManager contextManager = mockContextManager(TransactionType.LOCAL);
when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager);
newBackendTransactionManager(TransactionType.LOCAL, true);
ba... |
@Override
public String toString() {
int numColumns = getColumnCount();
TextTable table = new TextTable();
String[] columnNames = new String[numColumns];
for (int c = 0; c < getColumnCount(); c++) {
columnNames[c] = getColumnName(c);
}
table.addHeader(columnNames);
int numRows = ge... | @Test
public void testToString() {
// Run the test
final String result = _aggregationResultSetUnderTest.toString();
// Verify the results
assertNotEquals("", result);
} |
public void setContract(@Nullable Produce contract)
{
this.contract = contract;
setStoredContract(contract);
handleContractState();
} | @Test
public void cabbageContractCabbageGrowingAndCabbageDiseased()
{
final long unixNow = Instant.now().getEpochSecond();
final long expectedTime = unixNow + 60;
// Get the two allotment patches
final FarmingPatch patch1 = farmingGuildPatches.get(Varbits.FARMING_4773);
final FarmingPatch patch2 = farmingG... |
public static MutableURLClassLoader childFirst(
URL[] urls,
ClassLoader parent,
String[] alwaysParentFirstPatterns,
Consumer<Throwable> classLoadingExceptionHandler,
boolean checkClassLoaderLeak) {
FlinkUserCodeClassLoader classLoader =
... | @Test
void testRepeatedParentFirstPatternClass() throws Exception {
final String className = FlinkUserCodeClassLoadersTest.class.getName();
final String parentFirstPattern = className.substring(0, className.lastIndexOf('.'));
final ClassLoader parentClassLoader = getClass().getClassLoader()... |
public static Date parseDT(TimeZone tz, String s, DatePrecision precision) {
return parseDT(tz, s, false, precision);
} | @Test
public void testParseDT() {
DatePrecision precision = new DatePrecision();
assertEquals(0,
DateUtils.parseDT(tz, "19700101020000.000", precision).getTime());
assertEquals(Calendar.MILLISECOND, precision.lastField);
assertFalse(precision.includeTimezone);
} |
public void deleteBoardById(final Long boardId, final Long memberId) {
Board board = findBoard(boardId);
board.validateWriter(memberId);
boardRepository.deleteByBoardId(boardId);
imageUploader.delete(board.getImages());
Events.raise(new BoardDeletedEvent(boardId));
} | @Test
void 게시글을_삭제한다() {
// given
Board savedBoard = boardRepository.save(게시글_생성_사진없음());
// when & then
assertDoesNotThrow(() -> boardService.deleteBoardById(savedBoard.getId(), savedBoard.getWriterId()));
} |
@Override
public Iterator<CharSequence> valueIterator(CharSequence name) {
return new ReadOnlyValueIterator(name);
} | @Test
public void testEmptyValueIterator() {
Http2Headers headers = newServerHeaders();
final Iterator<CharSequence> itr = headers.valueIterator("foo");
assertFalse(itr.hasNext());
assertThrows(NoSuchElementException.class, new Executable() {
@Override
public ... |
@Override
public Collection<String> getEnhancedTableNames() {
return Collections.emptySet();
} | @Test
void assertGetEnhancedTableMapper() {
assertThat(new LinkedList<>(ruleAttribute.getEnhancedTableNames()), is(Collections.emptyList()));
} |
public static boolean isEmpty(final Object[] array) {
return array == null || array.length == 0;
} | @Test
void testisEmpty() {
Integer[] arr = new Integer[] {1, 2};
assertTrue(ArrayUtils.isEmpty(nullArr));
assertTrue(ArrayUtils.isEmpty(nothingArr));
assertFalse(ArrayUtils.isEmpty(arr));
} |
public static String normalize(String path) {
if (path == null) {
return null;
}
//兼容Windows下的共享目录路径(原始路径如果以\\开头,则保留这种路径)
if (path.startsWith("\\\\")) {
return path;
}
// 兼容Spring风格的ClassPath路径,去除前缀,不区分大小写
String pathToUse = StrUtil.removePrefixIgnoreCase(path, URLUtil.CLASSPATH_URL_PREFIX);
// ... | @Test
public void doubleNormalizeTest() {
final String normalize = FileUtil.normalize("/aa/b:/c");
final String normalize2 = FileUtil.normalize(normalize);
assertEquals("/aa/b:/c", normalize);
assertEquals(normalize, normalize2);
} |
public static InetSocketAddress[] netAddressToSocketAddress(List<NetAddress> request)
throws UnknownHostException {
InetSocketAddress[] addresses = new InetSocketAddress[request.size()];
for (int i = 0; i < addresses.length; i++) {
addresses[i] = new InetSocketAddress(
InetAddress.getByNam... | @Test
public void netAddressTest() throws Exception {
List<NetAddress> addressList = Collections.singletonList(
NetAddress.newBuilder().setHost("localhost").setRpcPort(1).build());
InetSocketAddress[] inetSocketAddressList = netAddressToSocketAddress(addressList);
Assert.assertEquals(1, inetSocket... |
public BackgroundException map(HttpResponse response) throws IOException {
final S3ServiceException failure;
if(null == response.getEntity()) {
failure = new S3ServiceException(response.getStatusLine().getReasonPhrase());
}
else {
EntityUtils.updateEntity(response... | @Test
public void testHandshakeFailure() {
final SSLHandshakeException f = new SSLHandshakeException("f");
f.initCause(new CertificateException("c"));
assertEquals(ConnectionCanceledException.class, new S3ExceptionMappingService().map(
new ServiceException(f)).getClass());
} |
@Override
public Mono<GetExternalServiceCredentialsResponse> getExternalServiceCredentials(final GetExternalServiceCredentialsRequest request) {
final ExternalServiceCredentialsGenerator credentialsGenerator = this.credentialsGeneratorByType
.get(request.getExternalService());
if (credentialsGenerator... | @Test
public void testUnauthenticatedCall() throws Exception {
assertStatusUnauthenticated(() -> unauthenticatedServiceStub().getExternalServiceCredentials(
GetExternalServiceCredentialsRequest.newBuilder()
.setExternalService(ExternalServiceType.EXTERNAL_SERVICE_TYPE_ART)
.build()... |
OperationNode createFlattenOperation(
Network<Node, Edge> network, ParallelInstructionNode node, OperationContext context) {
OutputReceiver[] receivers = getOutputReceivers(network, node);
return OperationNode.create(new FlattenOperation(receivers, context));
} | @Test
public void testCreateFlattenOperation() throws Exception {
int producerIndex1 = 1;
int producerOutputNum1 = 2;
int producerIndex2 = 0;
int producerOutputNum2 = 1;
ParallelInstructionNode instructionNode =
ParallelInstructionNode.create(
createFlattenInstruction(
... |
List<StepOption> retrieveOptions() {
return Arrays.asList(
new StepOption( KEEP_ALIVE_INTERVAL, getString( PKG, "MQTTDialog.Options.KEEP_ALIVE_INTERVAL" ),
keepAliveInterval ),
new StepOption( MAX_INFLIGHT, getString( PKG, "MQTTDialog.Options.MAX_INFLIGHT" ), maxInflight ),
new StepOption(... | @Test
public void testRetrieveOptions() {
List<String> keys = Arrays
.asList( KEEP_ALIVE_INTERVAL, MAX_INFLIGHT, CONNECTION_TIMEOUT, CLEAN_SESSION, STORAGE_LEVEL, SERVER_URIS,
MQTT_VERSION, AUTOMATIC_RECONNECT );
MQTTProducerMeta meta = new MQTTProducerMeta();
meta.setDefault();
List<St... |
public static UBlock create(List<UStatement> statements) {
return new AutoValue_UBlock(ImmutableList.copyOf(statements));
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(
UBlock.create(
UExpressionStatement.create(
UMethodInvocation.create(
UStaticIdent.create(
"java.lang.System",
"exit",
... |
@Override
@NonNull
public IndexEntry getIndexEntry(String name) {
readLock.lock();
try {
var indexDescriptor = findIndexByName(name);
if (indexDescriptor == null) {
throw new IllegalArgumentException(
"No index found for fieldPath [" + ... | @Test
void getIndexEntryTest() {
var spec = getNameIndexSpec();
var descriptor = new IndexDescriptor(spec);
descriptor.setReady(true);
var indexContainer = new IndexEntryContainer();
indexContainer.add(new IndexEntryImpl(descriptor));
var defaultIndexer = new Default... |
@Override
public void write(int datum)
{
if (this._bufferList.peekLast() == null || this._bufferList.getLast().length == this._index)
{
// If there's no buffer or its capacity is full, add a new one to the list.
addBuffer(1);
}
this._bufferList.getLast()[this._index++] = (byte) datum;
... | @Test
public void testWrite() throws Exception
{
FastByteArrayOutputStream testStream1 = new FastByteArrayOutputStream();
testStream1.write(1);
Assert.assertEquals(testStream1.size(), 1);
Assert.assertEquals(testStream1.toByteArray().length, 1);
Assert.assertEquals(testStream1.toByteArray()[0], ... |
public List<String> mergePartitions(
MergingStrategy mergingStrategy,
List<String> sourcePartitions,
List<String> derivedPartitions) {
if (!derivedPartitions.isEmpty()
&& !sourcePartitions.isEmpty()
&& mergingStrategy != MergingStrategy.EXCLUD... | @Test
void mergePartitionsFromDerivedTable() {
List<String> derivedPartitions = Arrays.asList("col1", "col2");
List<String> mergePartitions =
util.mergePartitions(
getDefaultMergingStrategies().get(FeatureOption.PARTITIONS),
Collections... |
@VisibleForTesting
void validateDictTypeUnique(Long id, String type) {
if (StrUtil.isEmpty(type)) {
return;
}
DictTypeDO dictType = dictTypeMapper.selectByType(type);
if (dictType == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典类型
if... | @Test
public void testValidateDictTypeUnique_success() {
// 调用,成功
dictTypeService.validateDictTypeUnique(randomLongId(), randomString());
} |
public static String generateFileName(String string) {
string = StringUtils.stripAccents(string);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (Character.isSpaceChar(c)
&& (buf.lengt... | @Test
public void testFeedTitleContainsAccents() {
String result = FileNameGenerator.generateFileName("Äàáâãå");
assertEquals("Aaaaaa", result);
} |
JspWrapper(String path, RequestDispatcher requestDispatcher) {
super();
assert path != null;
assert requestDispatcher != null;
// quand ce RequestDispatcher est utilisé, le compteur est affiché
// sauf si le paramètre displayed-counters dit le contraire
JSP_COUNTER.setDisplayed(!COUNTER_HIDDEN);
JSP_COUNT... | @Test
public void testJspWrapper() throws ServletException, IOException {
assertNotNull("getJspCounter", JspWrapper.getJspCounter());
final ServletContext servletContext = createNiceMock(ServletContext.class);
final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
final HttpServletRespon... |
public static Rect getTilesRect(final BoundingBox pBB,
final int pZoomLevel) {
final int mapTileUpperBound = 1 << pZoomLevel;
final int right = MapView.getTileSystem().getTileXFromLongitude(pBB.getLonEast(), pZoomLevel);
final int bottom = MapView.getTileSyste... | @Test
public void testGetTilesRectWholeWorld() {
final TileSystem tileSystem = MapView.getTileSystem();
final BoundingBox box = new BoundingBox( // whole world
tileSystem.getMaxLatitude(), tileSystem.getMaxLongitude(),
tileSystem.getMinLatitude(), tileSystem.getMinLon... |
@Override
public void start() {
if (isStarted()) return;
try {
ServerSocket socket = getServerSocketFactory().createServerSocket(
getPort(), getBacklog(), getInetAddress());
ServerListener<RemoteReceiverClient> listener = createServerListener(socket);
runner = createServerRunner(l... | @Test
public void testStartWhenAlreadyStarted() throws Exception {
appender.start();
appender.start();
assertEquals(1, runner.getStartCount());
} |
@VisibleForTesting
static Object convertAvroField(Object avroValue, Schema schema) {
if (avroValue == null) {
return null;
}
switch (schema.getType()) {
case NULL:
case INT:
case LONG:
case DOUBLE:
case FLOAT:
... | @Test
public void testConvertAvroInt() {
Object converted = BaseJdbcAutoSchemaSink.convertAvroField(Integer.MIN_VALUE, createFieldAndGetSchema((builder) ->
builder.name("field").type().intType().noDefault()));
Assert.assertEquals(converted, Integer.MIN_VALUE);
} |
@VisibleForTesting
static StreamExecutionEnvironment createStreamExecutionEnvironment(FlinkPipelineOptions options) {
return createStreamExecutionEnvironment(
options,
MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()),
options.getFlinkConfDir());
} | @Test
public void shouldAutoSetIdleSourcesFlagWithCheckpointing() {
// Checkpointing is enabled, never shut down sources
FlinkPipelineOptions options = getDefaultPipelineOptions();
options.setCheckpointingInterval(1000L);
FlinkExecutionEnvironments.createStreamExecutionEnvironment(options);
assert... |
public static double[] colMeans(double[][] matrix) {
double[] x = matrix[0].clone();
for (int i = 1; i < matrix.length; i++) {
for (int j = 0; j < x.length; j++) {
x[j] += matrix[i][j];
}
}
scale(1.0 / matrix.length, x);
return x;
} | @Test
public void testColMeans() {
System.out.println("colMeans");
double[][] A = {
{0.7220180, 0.07121225, 0.6881997},
{-0.2648886, -0.89044952, 0.3700456},
{-0.6391588, 0.44947578, 0.6240573}
};
double[] r = {-0.06067647, -0.12325383, 0.56076753}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.