focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public boolean containsAll(Collection c) {
for (Object o : c) {
if (!contains(o)) return false;
}
return true;
} | @Test
public void testContainsAll() {
Uuid fooUuid = Uuid.randomUuid();
Uuid barUuid = Uuid.randomUuid();
Uuid bazUuid = Uuid.randomUuid();
Uuid quxUuid = Uuid.randomUuid();
TopicsImage topicsImage = new MetadataImageBuilder()
.addTopic(fooUuid, "foo", 3)
... |
@Transactional
@PostMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases")
public ReleaseDTO publish(@PathVariable("appId") String appId,
@PathVariable("clusterName") String clusterName,
@PathVariable("namespaceName") String namesp... | @Test
public void testMessageSendAfterBuildRelease() throws Exception {
String someAppId = "someAppId";
String someNamespaceName = "someNamespace";
String someCluster = "someCluster";
String someName = "someName";
String someComment = "someComment";
NamespaceService someNamespaceService = moc... |
public Object[] parseParameterFor(String resource, T request, Predicate<GatewayFlowRule> rulePredicate) {
if (StringUtil.isEmpty(resource) || request == null || rulePredicate == null) {
return new Object[0];
}
Set<GatewayFlowRule> gatewayRules = new HashSet<>();
Set<Boolean> ... | @Test
public void testParseParametersWithEmptyItemPattern() {
RequestItemParser<Object> itemParser = mock(RequestItemParser.class);
GatewayParamParser<Object> paramParser = new GatewayParamParser<>(itemParser);
// Create a fake request.
Object request = new Object();
// Prepa... |
@Override
public BackgroundData addData(int index) {
if (index < 0 || index > scesimData.size()) {
throw new IndexOutOfBoundsException(new StringBuilder().append("Index out of range ").append(index).toString());
}
BackgroundData backgroundData = new BackgroundData();
sces... | @Test
public void addData() {
background.addData(1);
assertThatThrownBy(() -> background.addData(-1)).isInstanceOf(IndexOutOfBoundsException.class);
assertThatThrownBy(() -> background.addData(3)).isInstanceOf(IndexOutOfBoundsException.class);
} |
@Override
public boolean accept(final Path file) {
if(!super.accept(file)) {
return false;
}
if(pattern.matcher(file.getName()).matches()) {
if(log.isDebugEnabled()) {
log.debug(String.format("Skip %s excluded with regex", file.getAbsolute()));
... | @Test
public void testAccept() {
final Pattern pattern = Pattern.compile(".*~\\..*|\\.DS_Store|\\.svn|CVS|RCS|SCCS|\\.git|\\.bzr|\\.bzrignore|\\.bzrtags|\\.hg|\\.hgignore|\\.hgtags|_darcs|\\.file-segments");
assertFalse(new DownloadRegexFilter(pattern).accept(new Path(".DS_Store", EnumSet.of(Path.Ty... |
public static Date toDate(Object value, Date defaultValue) {
return convertQuietly(Date.class, value, defaultValue);
} | @Test
public void toDateTest2() {
final Date date = Convert.toDate("2021-01");
assertNull(date);
} |
@Override
public String getServerStatus() {
if (worker.isHealthServer()) {
return UP;
} else {
return DOWN;
}
} | @Test
void testGetServerStatus() {
Mockito.when(mockWoker.isHealthServer()).thenReturn(true);
assertEquals("UP", nacosConfigService.getServerStatus());
Mockito.verify(mockWoker, Mockito.times(1)).isHealthServer();
Mockito.when(mockWoker.isHealthServer()).thenReturn(false);
... |
public void updateTableStatistics(String dbName, String tableName, Function<HivePartitionStats, HivePartitionStats> update) {
try {
metastore.updateTableStatistics(dbName, tableName, update);
} finally {
if (!(metastore instanceof CachingHiveMetastore)) {
refreshT... | @Test
public void testUpdateTableStats() {
CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore(
metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false);
HivePartitionStats partitionStats = HivePartitionStats.empty();
cachingHiveMetastore.... |
public int remap(int var, int size) {
if ((var & REMAP_FLAG) != 0) {
return unmask(var);
}
int offset = var - argsSize;
if (offset < 0) {
// self projection for method arguments
return var;
}
if (offset >= mapping.length) {
mapping = Arrays.copyOf(mapping, Math.max(mappi... | @Test
void testRemapDoublesAndSingles() {
assertEquals(0, instance.remap(0, 1));
assertEquals(1, instance.remap(1, 2));
assertEquals(3, instance.remap(3, 2));
assertEquals(5, instance.remap(5, 1));
assertEquals(6, instance.remap(6, 1));
assertEquals(1, instance.remap(1, 1)); // change slot 1 ... |
@Override
public void close() throws IOException {
boolean triedToClose = false, success = false;
try {
flush();
((FileOutputStream)out).getChannel().force(true);
triedToClose = true;
super.close();
success = true;
} finally {
if (success) {
boolean renamed = t... | @Test
public void testFailToFlush() throws IOException {
// Create a file at destination
FileOutputStream fos = new FileOutputStream(DST_FILE);
fos.write(TEST_STRING_2.getBytes());
fos.close();
OutputStream failingStream = createFailingStream();
failingStream.write(TEST_STRING.getBytes())... |
@Override
public void connectionEstablished(
TieredStorageSubpartitionId subpartitionId,
NettyConnectionWriter nettyConnectionWriter) {
subpartitionProducerAgents[subpartitionId.getSubpartitionId()].connectionEstablished(
nettyConnectionWriter);
nettyConnectio... | @Test
void testRelease() {
TieredStorageResourceRegistry resourceRegistry = new TieredStorageResourceRegistry();
MemoryTierProducerAgent memoryTierProducerAgent =
createMemoryTierProducerAgent(false, SEGMENT_SIZE_BYTES, resourceRegistry);
AtomicBoolean isClosed = new AtomicB... |
@Override
public FieldValueProvider decode(JsonNode value)
{
return new ISO8601JsonValueProvider(value, columnHandle);
} | @Test
public void testDecode()
{
tester.assertDecodedAs("\"2018-02-19T09:20:11\"", TIMESTAMP, 1519032011000L);
tester.assertDecodedAs("\"2018-02-19T09:20:11Z\"", TIMESTAMP, 1519032011000L);
tester.assertDecodedAs("\"2018-02-19T09:20:11+10:00\"", TIMESTAMP, 1519032011000L);
tester... |
protected static KeyPair signWithEcdsa() {
KeyPair keyPair = null;
try {
ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
KeyPairGenerator g = KeyPairGenerator.getInstance("EC");
g.initialize(ecSpec, new SecureRandom());
java.security.KeyPa... | @Test
void testSignWithEcdsa() {
DubboCertManager.KeyPair keyPair = DubboCertManager.signWithEcdsa();
Assertions.assertNotNull(keyPair);
Assertions.assertNotNull(keyPair.getPrivateKey());
Assertions.assertNotNull(keyPair.getPublicKey());
Assertions.assertNotNull(keyPair.getSi... |
public static boolean isIPv4Address(final String input) {
return IPV4_PATTERN.matcher(input).matches();
} | @Test
void isIPv4Address() {
assertTrue(InetAddressValidator.isIPv4Address("192.168.1.2"));
} |
@Override
public int size() {
return actualToMetaFieldMapping.length;
} | @Test
public void size() {
assertEquals( 2, fieldsMapping.size() );
} |
public static Builder newBuilder() {
return new Builder();
} | @Test
public void build_fails_with_NPE_if_source_is_null() {
AuthenticationException.Builder builder = AuthenticationException.newBuilder()
.setLogin("login")
.setMessage("message");
assertThatThrownBy(builder::build)
.isInstanceOf(NullPointerException.class)
.hasMessage("source c... |
void precheckMaxResultLimitOnLocalPartitions(String mapName) {
// check if feature is enabled
if (!isPreCheckEnabled) {
return;
}
// limit number of local partitions to check to keep runtime constant
PartitionIdSet localPartitions = mapServiceContext.getCachedOwnedPa... | @Test
public void testLocalPreCheckEnabledWithEmptyPartition() {
int[] partitionsSizes = {0};
populatePartitions(partitionsSizes);
initMocksWithConfiguration(200000, 1);
limiter.precheckMaxResultLimitOnLocalPartitions(ANY_MAP_NAME);
} |
public Set<Long> calculateUsers(DelegateExecution execution, int level) {
Assert.isTrue(level > 0, "level 必须大于 0");
// 获得发起人
ProcessInstance processInstance = processInstanceService.getProcessInstance(execution.getProcessInstanceId());
Long startUserId = NumberUtils.parseLong(processInst... | @Test
public void testCalculateUsers_existParentDept() {
// 准备参数
DelegateExecution execution = mockDelegateExecution(1L);
// mock 方法(startUser)
AdminUserRespDTO startUser = randomPojo(AdminUserRespDTO.class, o -> o.setDeptId(10L));
when(adminUserApi.getUser(eq(1L))).thenRetur... |
@Override
public void failed(Exception ex) {
httpAsyncRequestProducer.failed(ex);
} | @Test
public void failed() {
final HttpAsyncRequestProducer delegate = Mockito.mock(HttpAsyncRequestProducer.class);
final HttpAsyncRequestProducerDecorator decorator = new HttpAsyncRequestProducerDecorator(
delegate, null, null);
decorator.failed(null);
Mockito.verif... |
static <RequestT, ResponseT> Call<RequestT, ResponseT> of(
Caller<RequestT, ResponseT> caller, Coder<ResponseT> responseTCoder) {
caller = SerializableUtils.ensureSerializable(caller);
return new Call<>(
Configuration.<RequestT, ResponseT>builder()
.setCaller(caller)
.setRe... | @Test
public void givenCallerNotSerializable_throwsError() {
assertThrows(
IllegalArgumentException.class,
() -> Call.of(new UnSerializableCaller(), NON_DETERMINISTIC_RESPONSE_CODER));
} |
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) {
final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps());
map.put(
MetricCollectors.RESOURCE_LABEL_PREFIX
+ StreamsConfig.APPLICATION_ID_CONFIG,
applicationId
);
// Streams cli... | @Test
public void shouldSetPrefixedStreamsConfigProperties() {
final KsqlConfig ksqlConfig = new KsqlConfig(Collections.singletonMap(
KsqlConfig.KSQL_STREAMS_PREFIX + StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, "128"));
assertThat(ksqlConfig.getKsqlStreamConfigProps().
get(StreamsConfig.C... |
public SearchSourceBuilder create(SearchesConfig config) {
return create(SearchCommand.from(config));
} | @Test
void searchIncludesSearchFilters() {
final SearchSourceBuilder search = this.searchRequestFactory.create(ChunkCommand.builder()
.filters(Collections.singletonList(InlineQueryStringSearchFilter.builder()
.title("filter 1")
.queryString("te... |
@Override public boolean replace(long key, long oldValue, long newValue) {
assert oldValue != nullValue : "replace() called with null-sentinel oldValue " + nullValue;
assert newValue != nullValue : "replace() called with null-sentinel newValue " + nullValue;
final long valueAddr = hsa.get(key);
... | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void test_replace_invalidValue() {
map.replace(newKey(), MISSING_VALUE);
} |
public void performSortOperation(int option, List<File> pdf) {
switch (option) {
case DATE_INDEX:
sortFilesByDateNewestToOldest(pdf);
break;
case NAME_INDEX:
sortByNameAlphabetical(pdf);
break;
case SIZE_INCREASI... | @Test
public void shouldReturnArraySortedByAscendingSize() {
// given
long[] sizes = {10000, 1000, 100, 50, 2000, 2500};
for (int i = 0; i < sizes.length; i++)
when(mFiles.get(i).length()).thenReturn(sizes[i]);
File[] expected = new File[]{mFiles.get(3), mFiles.get(2), m... |
static void commonPopulateGetCreatedKiePMMLOutputFieldsMethod(final MethodDeclaration methodDeclaration,
final List<org.dmg.pmml.OutputField> outputFields) {
BlockStmt body = new BlockStmt();
NodeList<Expression> arguments = new NodeList<... | @Test
void commonPopulateGetCreatedKiePMMLOutputFieldsMethod() throws IOException {
final CompilationDTO compilationDTO = CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME,
pmmlModel,
... |
public static <T> T fillBean(String className, Map<List<String>, Object> params, ClassLoader classLoader) {
return fillBean(errorEmptyMessage(), className, params, classLoader);
} | @Test(expected = ScenarioException.class)
public void fillBeanFailNullClassTest() {
Map<List<String>, Object> paramsToSet = new HashMap<>();
paramsToSet.put(List.of("fakeField"), null);
ScenarioBeanUtil.fillBean(errorEmptyMessage(), null, paramsToSet, classLoader);
} |
@VisibleForTesting
Map<ExecutionVertexID, Collection<ExecutionAttemptID>> findSlowTasks(
final ExecutionGraph executionGraph) {
final long currentTimeMillis = System.currentTimeMillis();
final Map<ExecutionVertexID, Collection<ExecutionAttemptID>> slowTasks = new HashMap<>();
f... | @Test
void testFinishedTaskExceedRatioInDynamicGraph() throws Exception {
final int parallelism = 3;
final JobVertex jobVertex1 = createNoOpVertex(parallelism);
// create jobVertex2 and leave its parallelism unset
final JobVertex jobVertex2 = new JobVertex("vertex2");
jobVert... |
public static String getHttpMethod(Exchange exchange, Endpoint endpoint) {
// 1. Use method provided in header.
Object method = exchange.getIn().getHeader(Exchange.HTTP_METHOD);
if (method instanceof String) {
return (String) method;
} else if (method instanceof Enum) {
... | @Test
public void testGetMethodDefault() {
Endpoint endpoint = Mockito.mock(Endpoint.class);
Exchange exchange = Mockito.mock(Exchange.class);
Message message = Mockito.mock(Message.class);
Mockito.when(endpoint.getEndpointUri()).thenReturn(TEST_URI);
Mockito.when(exchange.g... |
public static FileIO loadFileIO(String impl, Map<String, String> properties, Object hadoopConf) {
LOG.info("Loading custom FileIO implementation: {}", impl);
DynConstructors.Ctor<FileIO> ctor;
try {
ctor =
DynConstructors.builder(FileIO.class)
.loader(CatalogUtil.class.getClass... | @Test
public void loadCustomFileIO_badClass() {
assertThatThrownBy(
() ->
CatalogUtil.loadFileIO(TestFileIONotImpl.class.getName(), Maps.newHashMap(), null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageStartingWith("Cannot initialize FileIO")
.hasMe... |
@Override
public void createDb(String dbName, Map<String, String> properties) throws AlreadyExistsException {
if (dbExists(dbName)) {
throw new AlreadyExistsException("Database Already Exists");
}
icebergCatalog.createDb(dbName, properties);
} | @Test
public void testCreateDbInvalidateLocation() {
IcebergHiveCatalog icebergHiveCatalog = new IcebergHiveCatalog(CATALOG_NAME, new Configuration(), DEFAULT_CONFIG);
IcebergMetadata metadata = new IcebergMetadata(CATALOG_NAME, HDFS_ENVIRONMENT, icebergHiveCatalog,
Executors.newSing... |
public void setFilePath(PropertyType filePath) {
this.filePath = filePath;
} | @Test
@SuppressWarnings("squid:S2699")
public void testSetFilePath() {
//already tested, this is just left so the IDE doesn't recreate it.
} |
public boolean delete(ApplicationId applicationId) {
Tenant tenant = getTenant(applicationId);
TenantApplications tenantApplications = tenant.getApplicationRepo();
NestedTransaction transaction = new NestedTransaction();
Optional<ApplicationTransaction> applicationTransaction = hostProv... | @Test
public void delete() {
SessionRepository sessionRepository = tenant().getSessionRepository();
{
PrepareResult result = deployApp(testApp);
long sessionId = result.sessionId();
Session applicationData = sessionRepository.getLocalSession(sessionId);
... |
@Override
public AMFeedback statusUpdate(TaskAttemptID taskAttemptID,
TaskStatus taskStatus) throws IOException, InterruptedException {
org.apache.hadoop.mapreduce.v2.api.records.TaskAttemptId yarnAttemptID =
TypeConverter.toYarn(taskAttemptID);
AMFeedback feedback = new AMFeedback();
feed... | @Test
public void testStatusUpdateProgress()
throws IOException, InterruptedException {
configureMocks();
startListener(true);
verify(hbHandler).register(attemptId);
// make sure a ping doesn't report progress
AMFeedback feedback = listener.statusUpdate(attemptID, null);
assertTrue(feed... |
@Override
public MapTileArea computeFromSource(final MapTileArea pSource, final MapTileArea pReuse) {
final MapTileArea out = pReuse != null ? pReuse : new MapTileArea();
if (pSource.size() == 0) {
out.reset();
return out;
}
final int left = pSource.getLeft() ... | @Test
public void testOnePointModulo() {
final MapTileArea source = new MapTileArea();
final MapTileArea dest = new MapTileArea();
final Set<Long> set = new HashSet<>();
final int border = 2;
final MapTileAreaBorderComputer computer = new MapTileAreaBorderComputer(border);
... |
static long parseLong(String key, @Nullable String value) {
requireArgument((value != null) && !value.isEmpty(), "value of key %s was omitted", key);
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(String.format(US,
"key %s val... | @Test
public void parseLong_exception() {
assertThrows(IllegalArgumentException.class, () -> CaffeineSpec.parseLong("key", "value"));
} |
@Override
public Coder<T> getCoder(CoderRegistry coderRegistry) {
return (Coder<T>) AvroCoder.of(getAvroSchema());
} | @Test
public void testGetCoder() {
String schemaRegistryUrl = "mock://my-scope-name";
String subject = "mytopic";
SchemaRegistryClient mockRegistryClient = mockSchemaRegistryClient(schemaRegistryUrl, subject);
CoderRegistry coderRegistry = CoderRegistry.createDefault();
AvroCoder<Object> coderV0 ... |
public Expression rewrite(final Expression expression) {
return new ExpressionTreeRewriter<>(new OperatorPlugin()::process)
.rewrite(expression, null);
} | @Test
public void shouldPassRowTimeStringsToTheParser() {
// Given:
final Expression predicate = getPredicate(
"SELECT * FROM orders where ROWTIME = '2017-01-01T00:44:00.000';");
// When:
rewriter.rewrite(predicate);
// Then:
verify(parser).parse("2017-01-01T00:44:00.000");
} |
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) {
return new DateTime(dateStr, dateFormat);
} | @Test
public void parseUTCTest3() {
// issue#I5M6DP
final String dateStr = "2022-08-13T09:30";
final DateTime dateTime = DateUtil.parse(dateStr);
assertNotNull(dateTime);
assertEquals("2022-08-13 09:30:00", dateTime.toString());
} |
@SuppressWarnings("JdkObsolete")
void runNonGui(String testFile, String logFile, boolean remoteStart, String remoteHostsString, boolean generateReportDashboard)
throws ConfigurationException {
try {
File f = new File(testFile);
if (!f.exists() || !f.isFile()) {
... | @Test
void testFailureWithMissingPlugin() throws IOException {
File temp = File.createTempFile("testPlan", ".jmx");
String testPlan = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<jmeterTestPlan version=\"1.2\" properties=\"5.0\" jmeter=\"5.2-SNAPSHOT.20190506\">\n"
... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void setChatPermissions() {
for (boolean bool : new boolean[]{false, true}) {
ChatPermissions setPerms = new ChatPermissions();
setPerms.canSendMessages(bool);
setPerms.canSendAudios(bool);
setPerms.canSendDocuments(bool);
setPerms.can... |
public static String name(String name, String... names) {
final StringBuilder builder = new StringBuilder();
append(builder, name);
if (names != null) {
for (String s : names) {
append(builder, s);
}
}
return builder.toString();
} | @Test
public void elidesNullValuesFromNamesWhenManyNullsPassedIn() {
assertThat(name("one", null, null))
.isEqualTo("one");
} |
public static DataMap processProjections(DataMap dataMap, Map<String, List<String>> result)
{
//We send this through the pipeline and migrate from the dataMap into the result
for (final String parameterName : RestConstants.PROJECTION_PARAMETERS)
{
if (dataMap.containsKey(parameterName))
{
... | @Test
public void testProcessProjections()
{
//Construct a MaskTree from a series of PathSpecs. Extract the subsequent Datamap representation.
final MaskTree rootObjectsMask = MaskCreator
.createPositiveMask(new PathSpec("foo", PathSpec.WILDCARD, "bar"));
final MaskTree metadataMask = MaskCreat... |
@Override
public void populateContainer(TaskContainer container) {
ComputationSteps steps = new ReportComputationSteps(container);
container.add(SettingsLoader.class);
container.add(task);
container.add(steps);
container.add(componentClasses());
for (ReportAnalysisComponentProvider componentPr... | @Test
public void all_computation_steps_are_added_in_order_to_the_container() {
ListTaskContainer container = new ListTaskContainer();
underTest.populateContainer(container);
Set<String> computationStepClassNames = container.getAddedComponents().stream()
.map(s -> {
if (s instanceof Class) ... |
public static SourceConfig validateUpdate(SourceConfig existingConfig, SourceConfig newConfig) {
SourceConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!ex... | @Test
public void testMergeDifferentBatchSourceConfig() {
SourceConfig sourceConfig = createSourceConfigWithBatch();
BatchSourceConfig batchSourceConfig = createBatchSourceConfig();
Map<String, Object> newConfig = new HashMap<>();
newConfig.put("something", "different");
batc... |
@NonNull
public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) {
Comparator<FeedItem> comparator = null;
Permutor<FeedItem> permutor = null;
switch (sortOrder) {
case EPISODE_TITLE_A_Z:
comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTi... | @Test
public void testPermutorForRule_size_desc() {
Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.SIZE_LARGE_SMALL);
List<FeedItem> itemList = getTestList();
assertTrue(checkIdOrder(itemList, 1, 3, 2)); // before sorting
permutor.reorder(itemList);
as... |
CodeEmitter<T> emit(final Parameter parameter) {
emitter.emit("param");
emit("name", parameter.getName());
final String parameterType = parameter.getIn();
if (ObjectHelper.isNotEmpty(parameterType)) {
emit("type", RestParamType.valueOf(parameterType));
}
if (... | @Test
public void shouldEmitCodeForOas3ParameterWithType() {
final Builder method = MethodSpec.methodBuilder("configure");
final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method);
final OperationVisitor<?> visitor = new OperationVisitor<>(emitter, null, null, null... |
@SuppressWarnings("unchecked")
public <T> RefererConfig<T> get(final String path) {
try {
return (RefererConfig<T>) cache.get(path);
} catch (ExecutionException e) {
throw new ShenyuException(e);
}
} | @Test
public void testMethodInfo() {
List<Pair<String, String>> params = new ArrayList<>();
Pair<String, String> pair = Pair.of("left", "right");
params.add(pair);
ApplicationConfigCache.MethodInfo methodInfo = new ApplicationConfigCache.MethodInfo();
methodInfo.setParams(par... |
public void setName(String name) throws IllegalStateException {
if (name != null && name.equals(this.name)) {
return; // idempotent naming
}
if (this.name == null || CoreConstants.DEFAULT_CONTEXT_NAME.equals(this.name)) {
this.name = name;
} else {
thr... | @Test
public void idempotentNameTest() {
context.setName("hello");
context.setName("hello");
} |
@Override
public Num calculate(BarSeries series, Position position) {
return numberOfPositionsCriterion.calculate(series, position);
} | @Test
public void calculateWithOnePosition() {
BarSeries series = new MockBarSeries(numFunction, 100d, 95d, 102d, 105d, 97d, 113d);
Position position = new Position(Trade.buyAt(0, series), Trade.sellAt(1, series));
// 0 winning position
AnalysisCriterion winningPositionsRatio = getC... |
public static Optional<SentinelVersion> parseVersion(String verStr) {
if (StringUtil.isBlank(verStr)) {
return Optional.empty();
}
try {
String versionFull = verStr;
SentinelVersion version = new SentinelVersion();
// postfix
... | @Test
public void test() {
Optional<SentinelVersion> version = VersionUtils.parseVersion("1.2.3");
assertTrue(version.isPresent());
assertEquals(1, version.get().getMajorVersion());
assertEquals(2, version.get().getMinorVersion());
assertEquals(3, version.get().getFixVersion(... |
@JsonProperty
public DateTime getTimestamp() {
return message.getTimestamp();
} | @Test
public void testGetTimestamp() throws Exception {
assertEquals(message.getTimestamp(), messageSummary.getTimestamp());
} |
public static Method getter(Class<?> o, String propertiesName) {
if (o == null) {
return null;
}
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertiesName, o);
return descriptor.getReadMethod();
} catch (IntrospectionException e) {
... | @Test
public void testGetter() {
Method name = BeanUtil.getter(Customer.class, "name");
Assert.assertEquals("getName", name.getName());
} |
public static Configuration loadConfiguration(String[] args) throws FlinkException {
return ConfigurationParserUtils.loadCommonConfiguration(
filterCmdArgs(args, ClusterConfigurationParserFactory.options()),
BashJavaUtils.class.getSimpleName());
} | @TestTemplate
void testLoadConfigurationDynamicPropertyWithoutSpace() throws Exception {
String[] args = {"--configDir", confDir.toFile().getAbsolutePath(), "-Dkey=value"};
Configuration configuration = FlinkConfigLoader.loadConfiguration(args);
verifyConfiguration(configuration, "key", "val... |
public void transitionTo(ClassicGroupState groupState) {
assertValidTransition(groupState);
previousState = state;
state = groupState;
currentStateTimestamp = Optional.of(time.milliseconds());
metrics.onClassicGroupStateTransition(previousState, state);
} | @Test
public void testDeadToAwaitingRebalanceIllegalTransition() {
group.transitionTo(PREPARING_REBALANCE);
group.transitionTo(DEAD);
assertThrows(IllegalStateException.class, () -> group.transitionTo(COMPLETING_REBALANCE));
} |
public void run() {
runner = newJsonRunnerWithSetting(
globalSettings.stream()
.filter(byEnv(this.env))
.map(toRunnerSetting())
.collect(toList()), startArgs);
runner.run();
} | @Test
public void should_run_with_setting() throws IOException {
stream = getResourceAsStream("settings/settings.json");
runner = new SettingRunner(stream, createStartArgs(12306));
runner.run();
assertThat(helper.get(remoteUrl("/foo")), is("foo"));
assertThat(helper.get(remo... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(!session.getClient().setFileType(FTP.BINARY_FILE_TYPE)) {
throw new FTPException(session.getClient().getReplyCode(), session.ge... | @Test
public void testAbortNoRead() throws Exception {
final TransferStatus status = new TransferStatus();
status.setLength(5L);
final Path workdir = new FTPWorkdirService(session).find();
final Path file = new Path(workdir, new AlphanumericRandomStringService().random(), EnumSet.of(... |
public Type getType(final String name)
{
return containedTypeByNameMap.get(name);
} | @Test
void shouldHandleCompositeHasNullableType() throws Exception
{
final String nullValStr = "9223372036854775807";
final String testXmlString =
"<types>" +
"<composite name=\"PRICENULL\" description=\"Price NULL\" semanticType=\"Price\">" +
" <type name=... |
public ShenyuServiceInstanceLists get(final String contextPath) {
try {
return cache.get(contextPath);
} catch (ExecutionException e) {
throw new ShenyuException(e.getCause());
}
} | @Test
public void testGet() {
assertNotNull(this.applicationConfigCache.get("/test"));
} |
static String buildAcceptEncodingHeader(EncodingType[] acceptedEncodings)
{
//Essentially, we want to assign nonzero quality values to all those specified;
float delta = 1.0f/(acceptedEncodings.length + 1);
float currentQuality = 1.0f;
//Special case so we don't end with an unnecessary delimiter
... | @Test(dataProvider = "contentEncodingGeneratorDataProvider")
public void testEncodingGeneration(EncodingType[] encoding, String acceptEncoding)
{
Assert.assertEquals(ClientCompressionFilter.buildAcceptEncodingHeader(encoding), acceptEncoding);
} |
public static <T> List<LocalProperty<T>> grouped(Collection<T> columns)
{
return ImmutableList.of(new GroupingProperty<>(columns));
} | @Test
public void testMatchedGroupHierarchy()
{
List<LocalProperty<String>> actual = builder()
.grouped("a")
.grouped("b")
.grouped("c")
.build();
assertMatch(
actual,
builder().grouped("a", "b", "c"... |
@VisibleForTesting
@Nullable
static Map<String, Map<String, String>> volumesSetToMap(@Nullable Set<AbsoluteUnixPath> volumes) {
return setToMap(volumes, AbsoluteUnixPath::toString);
} | @Test
public void testVolumeListToMap() {
ImmutableSet<AbsoluteUnixPath> input =
ImmutableSet.of(
AbsoluteUnixPath.get("/var/job-result-data"),
AbsoluteUnixPath.get("/var/log/my-app-logs"));
ImmutableSortedMap<String, Map<?, ?>> expected =
ImmutableSortedMap.of(
... |
@Override
public String pluginNamed() {
return PluginEnum.WAF.getName();
} | @Test
public void testPluginNamed() {
final String result = wafPluginDataHandlerUnderTest.pluginNamed();
assertEquals(PluginEnum.WAF.getName(), result);
} |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testBloodEssenceExtract()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", EXTRACT_BLOOD_ESSENCE, "", 0);
when(configManager.getConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_BLOOD_ESSENCE, Integer.class)).thenReturn(1000);
itemChargePlugin.onChatM... |
@Override
public Optional<String> getContentHash() {
return Optional.ofNullable(mContentHash);
} | @Test
public void writeByteArrayForLargeFile() throws Exception {
int partSize = (int) FormatUtils.parseSpaceSize(PARTITION_SIZE);
byte[] b = new byte[partSize + 1];
mStream.write(b, 0, b.length);
Mockito.verify(mMockOssClient)
.initiateMultipartUpload(any(InitiateMultipartUploadRequest.class... |
public boolean isNewerOrEqualTo(VersionNumber versionNumber) {
return equals(versionNumber) || isNewerThan(versionNumber);
} | @Test
void testIsNewerOrEqualTo() {
assertThat(v("6.0.0").isNewerOrEqualTo(v("6.0.0"))).isTrue();
assertThat(v("6.0.0").isNewerOrEqualTo(v("5.0.0"))).isTrue();
assertThat(v("10.0.0").isNewerOrEqualTo(v("9.0.0"))).isTrue();
assertThat(v("10.0.0").isNewerOrEqualTo(v("1.0.0"))).isTrue()... |
public String getLanguage() {
return language;
} | @Test
void gettersAndSetters() {
LanguageMetric metric = new LanguageMetric("ncloc", 100, "java", TelemetryDataType.INTEGER, Granularity.MONTHLY);
assertThat(metric.getLanguage()).isEqualTo("java");
assertThat(metric.getValue()).isEqualTo(100);
assertThat(metric.getKey()).isEqualTo("ncloc");
asse... |
public Partition getPartition(String dbName, String tableName, List<String> partitionValues) {
return metastore.getPartition(dbName, tableName, partitionValues);
} | @Test
public void testGetPartition() {
Partition partition = hmsOps.getPartition(
"db1", "tbl1", Lists.newArrayList("par1"));
Assert.assertEquals(ORC, partition.getFileFormat());
Assert.assertEquals("100", partition.getParameters().get(TOTAL_SIZE));
partition = hmsOp... |
public static URI buildURI(String schema, String hostPort, String path, Map<String, String> params) {
StringTokenizer tokenizer = new StringTokenizer(hostPort, ":");
String host = tokenizer.nextToken();
String port = null;
if (tokenizer.hasMoreTokens()) {
port = tokenizer.nextToken();
}
UR... | @Test
public void testBuildURI() {
URI uri = URIUtils.buildURI("http", "foo", "bar", Collections.emptyMap());
Assert.assertEquals(uri.toString(), "http://foo/bar");
uri = URIUtils.buildURI("http", "foo:8080", "bar/moo", Collections.emptyMap());
Assert.assertEquals(uri.toString(), "http://foo:8080/bar... |
static int parseMajorJavaVersion(String javaVersion) {
int version = parseDotted(javaVersion);
if (version == -1) {
version = extractBeginningInt(javaVersion);
}
if (version == -1) {
return 6; // Choose minimum supported JDK version as default
}
return version;
} | @Test
public void testJava6() {
// http://www.oracle.com/technetwork/java/javase/version-6-141920.html
assertThat(JavaVersion.parseMajorJavaVersion("1.6.0")).isEqualTo(6);
} |
@Nullable
public Supplier<? extends SocketAddress> bindAddressSupplier() {
return bindAddressSupplier;
} | @Test
void bindAddressSupplierBadValues() {
assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> builder.bindAddressSupplier(null));
} |
@ThriftField(1)
public List<PrestoThriftRange> getRanges()
{
return ranges;
} | @Test
public void testFromValueSetOf()
{
PrestoThriftValueSet thriftValueSet = fromValueSet(ValueSet.of(BIGINT, 1L, 2L, 3L));
assertNotNull(thriftValueSet.getRangeValueSet());
assertEquals(thriftValueSet.getRangeValueSet().getRanges(), ImmutableList.of(
new PrestoThriftRa... |
@NonNull
public GifHeader parseHeader() {
if (rawData == null) {
throw new IllegalStateException("You must call setData() before parseHeader()");
}
if (err()) {
return header;
}
readHeader();
if (!err()) {
readContents();
if (header.frameCount < 0) {
header.sta... | @Test(expected = IllegalStateException.class)
public void testThrowsIfParseHeaderCalledBeforeSetData() {
GifHeaderParser parser = new GifHeaderParser();
parser.parseHeader();
} |
public synchronized GpuDeviceInformation parseXml(String xmlContent)
throws YarnException {
InputSource inputSource = new InputSource(new StringReader(xmlContent));
SAXSource source = new SAXSource(xmlReader, inputSource);
try {
return (GpuDeviceInformation) unmarshaller.unmarshal(source);
}... | @Test
public void testParseInvalidRootElement() throws YarnException {
expected.expect(YarnException.class);
GpuDeviceInformationParser parser = new GpuDeviceInformationParser();
parser.parseXml("<nvidia_smiiiii></nvidia_smiiiii");
} |
@Override
public void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) {
int payloadLength = in.markReaderIndex().readUnsignedMediumLE();
int remainPayloadLength = SEQUENCE_LENGTH + payloadLength;
if (in.readableBytes() < remainPayloadLength) {
... | @Test
void assertDecodeWithStickyPacket() {
when(byteBuf.markReaderIndex()).thenReturn(byteBuf);
when(byteBuf.readUnsignedMediumLE()).thenReturn(50);
List<Object> out = new LinkedList<>();
new MySQLPacketCodecEngine().decode(context, byteBuf, out);
assertTrue(out.isEmpty());
... |
public static Read<String> readStrings() {
return Read.newBuilder(
(PubsubMessage message) -> new String(message.getPayload(), StandardCharsets.UTF_8))
.setCoder(StringUtf8Coder.of())
.build();
} | @Test
public void testFailedParseWithErrorHandlerConfigured() throws Exception {
ByteString data = ByteString.copyFrom("Hello, World!".getBytes(StandardCharsets.UTF_8));
RuntimeException exception = new RuntimeException("Some error message");
ImmutableList<IncomingMessage> expectedReads =
Immutabl... |
@Override
protected boolean hasLeadership(String componentId, UUID leaderSessionId) {
synchronized (lock) {
if (leaderElectionDriver != null) {
if (leaderContenderRegistry.containsKey(componentId)) {
return leaderElectionDriver.hasLeadership()
... | @Test
void testHasLeadershipWithLeadershipButNoGrantEventProcessed() throws Exception {
new Context() {
{
runTestWithManuallyTriggeredEvents(
executorService -> {
final UUID expectedSessionID = UUID.randomUUID();
... |
void doSyntaxCheck(NamespaceTextModel model) {
if (StringUtils.isBlank(model.getConfigText())) {
return;
}
// only support yaml syntax check
if (model.getFormat() != ConfigFileFormat.YAML && model.getFormat() != ConfigFileFormat.YML) {
return;
}
// use YamlPropertiesFactoryBean to ... | @Test(expected = BadRequestException.class)
public void yamlSyntaxCheckWithDuplicatedValue() throws Exception {
String yaml = loadYaml("case2.yaml");
itemController.doSyntaxCheck(assemble(ConfigFileFormat.YAML.getValue(), yaml));
} |
@Override
public <R> R create(final Class<R> resourceClass)
{
return _containerAdaptor.getBean(resourceClass);
} | @Test
public void testMockInjectionSubClass()
{
InjectMockResourceFactory factory =
new InjectMockResourceFactory(new SimpleBeanProvider()
.add("counterBean", new CounterBean())
.add("mySpecialBean", ... |
@Override
public V put(K key, V value) {
Objects.requireNonNull(key);
Objects.requireNonNull(value);
TimelineHashMapEntry<K, V> entry = new TimelineHashMapEntry<>(key, value);
TimelineHashMapEntry<K, V> prev = snapshottableAddOrReplace(entry);
if (prev == null) {
... | @Test
public void testNullsForbidden() {
SnapshotRegistry registry = new SnapshotRegistry(new LogContext());
TimelineHashMap<String, Boolean> map = new TimelineHashMap<>(registry, 1);
assertThrows(NullPointerException.class, () -> map.put(null, true));
assertThrows(NullPointerExcepti... |
@Override
public ValueType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
if (p.currentTokenId() == JsonTokenId.ID_STRING) {
final String str = StringUtils.upperCase(p.getText(), Locale.ROOT);
try {
return ValueType.valueOf(str);
... | @Test
public void deserialize() throws IOException {
assertThat(objectMapper.readValue("\"boolean\"", ValueType.class)).isEqualTo(ValueType.BOOLEAN);
assertThat(objectMapper.readValue("\"double\"", ValueType.class)).isEqualTo(ValueType.DOUBLE);
assertThat(objectMapper.readValue("\"float\"", ... |
public static Getter newMethodGetter(Object object, Getter parent, Method method, String modifier) throws Exception {
return newGetter(object, parent, modifier, method.getReturnType(), method::invoke,
(t, et) -> new MethodGetter(parent, method, modifier, t, et));
} | @Test
public void newMethodGetter_whenExtractingFromNonEmpty_Collection_nullFirst_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType()
throws Exception {
OuterObject object = new OuterObject("name", null, new InnerObject("inner", 0, 1, 2, 3));
Getter parentGetter = GetterFactory.ne... |
public ExitStatus(Options options) {
this.options = options;
} | @Test
void with_failed_scenarios() {
createRuntime();
bus.send(testCaseFinishedWithStatus(Status.FAILED));
assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x1)));
} |
static DynamicState stateMachineStep(DynamicState dynamicState, StaticState staticState) throws Exception {
LOG.debug("STATE {}", dynamicState.state);
switch (dynamicState.state) {
case EMPTY:
return handleEmpty(dynamicState, staticState);
case RUNNING:
... | @Test
public void testReschedule() throws Exception {
try (SimulatedTime ignored = new SimulatedTime(1010)) {
int port = 8080;
String cTopoId = "CURRENT";
List<ExecutorInfo> cExecList = mkExecutorInfoList(1, 2, 3, 4, 5);
LocalAssignment cAssignment =
... |
@Override
public void updateUserPassword(String username, String password) {
try {
EmbeddedStorageContextHolder
.addSqlContext("UPDATE users SET password = ? WHERE username=?", password, username);
databaseOperate.blockUpdate();
} finally {
Emb... | @Test
void testUpdateUserPassword() {
embeddedUserPersistService.updateUserPassword("username", "password");
Mockito.verify(databaseOperate).blockUpdate();
} |
@Description("arc cosine")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double acos(@SqlType(StandardTypes.DOUBLE) double num)
{
return Math.acos(num);
} | @Test
public void testAcos()
{
for (double doubleValue : DOUBLE_VALUES) {
assertFunction("acos(" + doubleValue + ")", DOUBLE, Math.acos(doubleValue));
assertFunction("acos(REAL '" + (float) doubleValue + "')", DOUBLE, Math.acos((float) doubleValue));
}
assertFunct... |
@Override
public void processElement(StreamRecord<FlinkInputSplit> element) {
splits.add(element.getValue());
enqueueProcessSplits();
} | @TestTemplate
public void testProcessAllRecords() throws Exception {
List<List<Record>> expectedRecords = generateRecordsAndCommitTxn(10);
List<FlinkInputSplit> splits = generateSplits();
assertThat(splits).hasSize(10);
try (OneInputStreamOperatorTestHarness<FlinkInputSplit, RowData> harness = creat... |
static PreferredAddressTypeComparator comparator(InternetProtocolFamily family) {
switch (family) {
case IPv4:
return IPv4;
case IPv6:
return IPv6;
default:
throw new IllegalArgumentException();
}
} | @Test
public void testIpv6() throws UnknownHostException {
InetAddress ipv4Address1 = InetAddress.getByName("10.0.0.1");
InetAddress ipv4Address2 = InetAddress.getByName("10.0.0.2");
InetAddress ipv4Address3 = InetAddress.getByName("10.0.0.3");
InetAddress ipv6Address1 = InetAddress.... |
@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, final ShareCreationRequestModel options, final PasswordCallback callback) throws BackgroundException {
return this.toGuestUrl(file, options, callback);
} | @Test
public void testDownloadUrlForFile() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path sourceFolder = new EueDirectoryFeature(session, fileid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), n... |
public void submitEtlJob(long loadJobId, String loadLabel, EtlJobConfig etlJobConfig, SparkResource resource,
BrokerDesc brokerDesc, SparkLoadAppHandle handle, SparkPendingTaskAttachment attachment,
Long sparkLoadSubmitTimeout)
throws LoadException {... | @Test
public void testSubmitEtlJob(@Mocked BrokerUtil brokerUtil, @Mocked SparkLauncher launcher,
@Injectable Process process,
@Mocked SparkLoadAppHandle handle) throws IOException, LoadException {
new Expectations() {
{
... |
public static <K, V> Reshuffle<K, V> of() {
return new Reshuffle<>();
} | @Test
public void testNoOldTransformByDefault() {
pipeline.enableAbandonedNodeEnforcement(false);
pipeline.apply(Create.of(KV.of("arbitrary", "kv"))).apply(Reshuffle.of());
OldTransformSeeker seeker = new OldTransformSeeker();
pipeline.traverseTopologically(seeker);
assertFalse(seeker.isOldTransf... |
public static Optional<String> getRuleName(final String rulePath) {
Pattern pattern = Pattern.compile(getRuleNameNode() + "/(\\w+)" + ACTIVE_VERSION_SUFFIX, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(rulePath);
return matcher.find() ? Optional.of(matcher.group(1)) : Optional.em... | @Test
void assertGetRuleName() {
Optional<String> actual = GlobalNodePath.getRuleName("/rules/transaction/active_version");
assertTrue(actual.isPresent());
assertThat(actual.get(), is("transaction"));
} |
public static void copyBytes(InputStream in, OutputStream out,
int buffSize, boolean close)
throws IOException {
try {
copyBytes(in, out, buffSize);
if(close) {
out.close();
out = null;
in.close();
in = null;
}
} finally {
... | @Test
public void testCopyBytesShouldNotCloseStreamsWhenCloseIsFalse()
throws Exception {
InputStream inputStream = Mockito.mock(InputStream.class);
OutputStream outputStream = Mockito.mock(OutputStream.class);
Mockito.doReturn(-1).when(inputStream).read(new byte[1]);
IOUtils.copyBytes(inputStre... |
public static void getSemanticPropsSingleFromString(
SingleInputSemanticProperties result,
String[] forwarded,
String[] nonForwarded,
String[] readSet,
TypeInformation<?> inType,
TypeInformation<?> outType) {
getSemanticPropsSingleFromStrin... | @Test
void testForwardedInvalidTargetFieldType5() {
String[] forwardedFields = {"f0.*->*"};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
assertThatThrownBy(
() ->
SemanticPropUtil.getSemanticPropsSingleFromStr... |
@Override
public Optional<ReadableRegion> getReadableRegion(
int subpartitionId, int bufferIndex, int consumingOffset) {
synchronized (lock) {
return getInternalRegion(subpartitionId, bufferIndex)
.map(
internalRegion ->
... | @Test
void testGetReadableRegion() {
final int subpartitionId = 0;
hsDataIndex.addBuffers(createSpilledBuffers(subpartitionId, Arrays.asList(0, 1, 3, 4, 5)));
hsDataIndex.markBufferReleased(subpartitionId, 1);
hsDataIndex.markBufferReleased(subpartitionId, 3);
hsDataIndex.ma... |
public static int[] rainbow(int pageNo, int totalPage, int displayCount) {
// displayCount % 2
boolean isEven = (displayCount & 1) == 0;
int left = displayCount >> 1;
int right = displayCount >> 1;
int length = displayCount;
if (isEven) {
right++;
}
if (totalPage < displayCount) {
length = totalP... | @Test
public void rainbowTest() {
final int[] rainbow = PageUtil.rainbow(5, 20, 6);
assertArrayEquals(new int[]{3, 4, 5, 6, 7, 8}, rainbow);
} |
@Override
public void onProjectsRekeyed(Set<RekeyedProject> rekeyedProjects) {
checkNotNull(rekeyedProjects, "rekeyedProjects can't be null");
if (rekeyedProjects.isEmpty()) {
return;
}
Arrays.stream(listeners)
.forEach(safelyCallListener(listener -> listener.onProjectsRekeyed(rekeyedProj... | @Test
@UseDataProvider("oneOrManyRekeyedProjects")
public void onProjectsRekeyed_calls_all_listeners_even_if_one_throws_an_Error(Set<RekeyedProject> projects) {
InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3);
doThrow(new Error("Faking listener2 throwing an Error"))
.when(listener2)... |
public static boolean isCoastedPoint(NopHit starsPoint) {
StarsRadarHit srh = (StarsRadarHit) starsPoint.rawMessage();
return isCoastedRadarHit(srh);
} | @Test
public void testIsCoastedPoint() {
NopHit active = new NopHit(ACTIVE_STARS);
NopHit coasted = new NopHit(COASTED_STARS);
NopHit dropped = new NopHit(DROPPED_STARS);
assertFalse(StarsSmoothing.isCoastedPoint(active));
assertTrue(StarsSmoothing.isCoastedPoint(coasted));
... |
public Summation[] partition(final int nParts) {
final Summation[] parts = new Summation[nParts];
final long steps = (E.limit - E.value)/E.delta + 1;
long prevN = N.value;
long prevE = E.value;
for(int i = 1; i < parts.length; i++) {
final long k = (i * steps)/parts.length;
final long... | @Test
void testSubtract() {
final Summation sigma = newSummation(3, 10000, 20);
final int size = 10;
final List<Summation> parts = Arrays.asList(sigma.partition(size));
Collections.sort(parts);
runTestSubtract(sigma, new ArrayList<Summation>());
runTestSubtract(sigma, parts);
for (int n ... |
public static HttpRequestMessage getRequestFromChannel(Channel ch) {
return ch.attr(ATTR_ZUUL_REQ).get();
} | @Test
void multipleHostHeaders_setBadRequestStatus() {
ClientRequestReceiver receiver = new ClientRequestReceiver(null);
EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestEncoder());
PassportLoggingHandler loggingHandler = new PassportLoggingHandler(new DefaultRegistry());
... |
@Override
public int read() throws IOException {
if (advanceStream()) {
final int value = buffer[bufferStart];
incrementRead();
return value;
}
return -1;
} | @Test()
public void testRead_3args() throws Exception {
byte[] input = new byte[2048];
Arrays.fill(input, (byte) ' ');
input[0] = '{';
input[2047] = '}';
byte[] results = new byte[2050];
byte[] expected = new byte[2050];
Arrays.fill(expected, (byte) ' ');
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.