focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public void editOptions( int index ) {
if ( index + 1 == optionsParameterTree.getRows() ) {
// editing last row add a new one below
Object[][] values = optionsParameterTree.getValues();
Object[] row = values[ values.length - 1 ];
if ( row != null && ( !StringUtils.isEmpty( (String) row[ 0 ]... | @Test
public void testEditOptions() throws Exception {
} |
public final StringSubject hasMessageThat() {
StandardSubjectBuilder check = check("getMessage()");
if (actual instanceof ErrorWithFacts && ((ErrorWithFacts) actual).facts().size() > 1) {
check =
check.withMessage(
"(Note from Truth: When possible, instead of asserting on the full ... | @Test
public void hasMessageThat_NullMessageHasMessage_failure() {
NullPointerException npe = new NullPointerException(null);
expectFailureWhenTestingThat(npe).hasMessageThat().isEqualTo("message");
} |
public static Map<String, String> parseMap(String str) {
if (str != null) {
StringTokenizer tok = new StringTokenizer(str, ", \t\n\r");
HashMap<String, String> map = new HashMap<>();
while (tok.hasMoreTokens()) {
String record = tok.nextToken();
... | @Test
public void testParseMapEmptyValue() {
String stringMap = "key1=value1\n" +
"key2=";
Map<String, String> m = parseMap(stringMap);
assertThat(m, aMapWithSize(2));
assertThat(m, hasEntry("key1", "value1"));
assertThat(m, hasEntry("key2", ""));
} |
@Override
public int getResultSetHoldability() {
return 0;
} | @Test
void assertGetResultSetHoldability() {
assertThat(metaData.getResultSetHoldability(), is(0));
} |
@Override
public IClonableStepAnalyzer newInstance() {
return new JsonInputAnalyzer();
} | @Test
public void testNewInstance(){
JsonInputAnalyzer analyzer = new JsonInputAnalyzer();
assertTrue( analyzer.newInstance().getClass().equals(JsonInputAnalyzer.class));
} |
public static boolean isRuncContainerRequested(Configuration daemonConf,
Map<String, String> env) {
String type = (env == null)
? null : env.get(ContainerRuntimeConstants.ENV_CONTAINER_TYPE);
if (type == null) {
type = daemonConf.get(YarnConfiguration.LINUX_CONTAINER_RUNTIME_TYPE);
}
... | @Test
public void testSelectRuncContainerTypeWithDefaultSet() {
Map<String, String> envRuncType = new HashMap<>();
Map<String, String> envOtherType = new HashMap<>();
conf.set(YarnConfiguration.LINUX_CONTAINER_RUNTIME_TYPE, "default");
envRuncType.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE,
... |
public void lockClusterState(ClusterStateChange stateChange, Address initiator, UUID txnId, long leaseTime,
int memberListVersion, long partitionStateStamp) {
Preconditions.checkNotNull(stateChange);
clusterServiceLock.lock();
try {
if (!node.getNodeE... | @Test(expected = IllegalStateException.class)
public void test_lockClusterState_forFrozenState_whenHasOnGoingMigration() throws Exception {
when(partitionService.hasOnGoingMigrationLocal()).thenReturn(true);
Address initiator = newAddress();
clusterStateManager.lockClusterState(ClusterState... |
@Override
public synchronized FunctionSource getFunction(final List<SqlType> argTypeList) {
final List<SqlArgument> args = argTypeList.stream()
.map((type) -> type == null ? null : SqlArgument.of(type))
.collect(Collectors.toList());
final UdafFactoryInvoker creator = udfIndex.getFun... | @Test
public void shouldHandleNullLiteralParams() {
// When:
AggregateFunctionFactory.FunctionSource result = functionFactory.getFunction(
Arrays.asList(SqlTypes.STRING, null, SqlTypes.INTEGER,
SqlTypes.BIGINT, SqlTypes.DOUBLE, SqlTypes.STRING)
);
int initArgs = result... |
@Override
public void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
final List<ClassNameInformation> classNames = collectClassNames(dependency);
final String fileName = dependency.getFileName().toLowerCase();
if ((classNames.isEmpty()
&& (... | @Test
public void testAnalyseDependency_SkipsNonZipFile() throws Exception {
JarAnalyzer instance = new JarAnalyzer();
Dependency textFileWithJarExtension = new Dependency();
textFileWithJarExtension
.setActualFilePath(BaseTest.getResourceAsFile(this, "test.properties").getAb... |
@Override
public String localize(final String key, final String table) {
final Key lookup = new Key(table, key);
if(!cache.contains(lookup)) {
if(!tables.contains(table)) {
try {
this.load(table);
}
catch(IOException e) ... | @Test
public void testLocalize() {
final RegexLocale locale = new RegexLocale(new Local(new WorkdirPrefixer().normalize("../i18n/src/main/resources")));
assertEquals("Download failed", locale.localize("Download failed", "Status"));
locale.setDefault("fr");
assertEquals("Échec du télé... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void functionInvocationWithKeyword() {
String inputExpression = "date and time( \"2016-07-29T19:47:53\" )";
BaseNode functionBase = parse( inputExpression );
assertThat( functionBase).isInstanceOf(FunctionInvocationNode.class);
assertThat( functionBase.getText()).isEqualTo(inp... |
@Udf(description = "Converts a number of milliseconds since 1970-01-01 00:00:00 UTC/GMT into the"
+ " string representation of the timestamp in the given format. Single quotes in the"
+ " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'."
+ " The system default time zon... | @Test
public void testReturnNullForNullFormat() {
// When:
final String result = udf.timestampToString(1534353043000L,
null);
// Then:
assertThat(result, is(nullValue()));
} |
@Override
public boolean evaluate(Map<String, Object> values) {
boolean toReturn = false;
if (values.containsKey(name)) {
logger.debug("found matching parameter, evaluating... ");
toReturn = evaluation(values.get(name));
}
return toReturn;
} | @Test
void evaluateIntIn() {
ARRAY_TYPE arrayType = ARRAY_TYPE.INT;
List<Object> values = getObjects(arrayType, 4);
KiePMMLSimpleSetPredicate kiePMMLSimpleSetPredicate = getKiePMMLSimpleSetPredicate(values, arrayType,
... |
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) {
// Set of Visited Schemas
IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>();
// Stack that contains the Schemas to process and afterVisitNonTerminal
// functions.
// Deque<Either<Schema, Supplier<SchemaVi... | @Test
public void testVisit5() {
String s5 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"c2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}";
Assert... |
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
// Do not allow framing; OF-997
... | @Test
public void nonExcludedUrlWillNotErrorWhenOnAllowlist() throws Exception {
AuthCheckFilter.SERVLET_REQUEST_AUTHENTICATOR.setValue(AdminUserServletAuthenticatorClass.class);
final AuthCheckFilter filter = new AuthCheckFilter(adminManager, loginLimitManager);
AuthCheckFilter.IP_ACCESS_A... |
@Override
public MapSettings setProperty(String key, String value) {
return (MapSettings) super.setProperty(key, value);
} | @Test
public void setStringArrayWithEmptyValues() {
Settings settings = new MapSettings(definitions);
settings.setProperty("multi_values", new String[]{"A,B", "", "C,D"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A,B", "", "C,D"});
} |
public abstract MySqlSplit toMySqlSplit(); | @Test
public void testFromToSplit() {
final MySqlSnapshotSplit split =
new MySqlSnapshotSplit(
TableId.parse("test_db.test_table"),
"test_db.test_table-1",
new RowType(
Collections.singlet... |
@Override
public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception {
OptionParser optParser = new OptionParser();
OptionSpec<Long> offsetOpt = optParser.accepts("offset", "offset for reading input").withRequiredArg()
.ofType(Long.class).defaultsTo(Long.value... | @Test
void offSetAccuracy() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData("input1.avro", Type.INT, metadata, DEFLATE);
File output = new File(DIR, name.getMethodName() + ".avro");
output.deleteOnExit();
... |
public List<String> getPlugins() {
return Collections.unmodifiableList(plugins);
} | @Test
void getPluginsShouldReturnEmptyListWhenNotSet() {
ExtensionInfo info = new ExtensionInfo("org.pf4j.asm.ExtensionInfo");
assertTrue(info.getPlugins().isEmpty());
} |
public static Multimap<String, SourceDescription> fetchSourceDescriptions(
final RemoteHostExecutor remoteHostExecutor
) {
final List<SourceDescription> sourceDescriptions = Maps
.transformValues(
remoteHostExecutor.fetchAllRemoteResults().getLeft(),
SourceDescriptionList.cla... | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void itShouldReturnEmptyIfNoRemoteResults() {
// Given
when(augmenter.fetchAllRemoteResults()).thenReturn(new Pair(ImmutableMap.of(), response.keySet()));
Multimap<String, SourceDescription> res = RemoteSourceDescriptionExecutor.fetchSourceDescr... |
public static String[] getStringArrayBySeparator(String value, String separator) {
String[] strings = StringUtils.splitByWholeSeparator(value, separator);
String[] result = new String[strings.length];
for (int index = 0; index < strings.length; index++) {
result[index] = trim(strings[index]);
}
... | @Test
public void test_getStringArrayBySeparator_on_input_without_separator() {
String[] result = SettingFormatter.getStringArrayBySeparator(" abc, DeF , ghi", ";");
assertThat(result).containsExactly("abc, DeF , ghi");
} |
public static void mergeParams(
Map<String, ParamDefinition> params,
Map<String, ParamDefinition> paramsToMerge,
MergeContext context) {
if (paramsToMerge == null) {
return;
}
Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream())
.forEach(
name ... | @Test
public void testMergeDisallowInvalidStartChanged() {
for (ParamMode mode : Arrays.asList(ParamMode.CONSTANT, ParamMode.IMMUTABLE)) {
AssertHelper.assertThrows(
String.format("Should not allow modifying reserved modes, mode [%s]", mode),
MaestroValidationException.class,
S... |
public void start() {
if (running.get()) {
throw new IllegalStateException(
"Attempting to start a MetricsSystem that is already running");
}
running.set(true);
registerDefaultSources();
registerSinks();
sinks.forEach(Sink::start);
} | @Test
void testMetricsSystemWithTwoSinkConfigurations() {
Properties properties = new Properties();
properties.put("sink.mocksink.class", "org.apache.spark.k8s.operator.metrics.sink.MockSink");
properties.put("sink.mocksink.period", "10");
properties.put("sink.console.class", "org.apache.spark.metrics... |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException{
PluginRiskConsent riskConsent = PluginRiskConsent.valueOf(config.get(PLUGINS_RISK_CONSENT).orElse(NOT_ACCEPTED.name()));
if (userSession.hasSession() && userSession.isLoggedIn()
&& userSess... | @Test
public void doFilter_givenNotLoggedInAndConsentAccepted_dontRedirect() throws Exception {
PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession);
when(userSession.hasSession()).thenReturn(true);
when(userSession.isLoggedIn()).thenReturn(false);
when(co... |
public static Optional<Object[]> coerceParams(Class<?> currentIdxActualParameterType, Class<?> expectedParameterType, Object[] actualParams, int i) {
Object actualObject = actualParams[i];
Optional<Object> coercedObject = coerceParam(currentIdxActualParameterType, expectedParameterType,
... | @Test
void coerceParamsNotConverted() {
Object item = "TESTED_OBJECT";
Object value = Collections.singleton(item);
Object[] actualParams1 = {value, "NOT_DATE"};
Optional<Object[]> retrieved = CoerceUtil.coerceParams(Set.class, BigDecimal.class, actualParams1, 0);
assertNotNul... |
static void assertNoCucumberAnnotatedMethods(Class<?> clazz) {
for (Method method : clazz.getDeclaredMethods()) {
for (Annotation annotation : method.getAnnotations()) {
if (annotation.annotationType().getName().startsWith("io.cucumber")) {
throw new CucumberExcep... | @Test
void should_throw_cucumber_exception_when_annotated() {
Executable testMethod = () -> Assertions.assertNoCucumberAnnotatedMethods(WithCucumberMethod.class);
CucumberException expectedThrown = assertThrows(CucumberException.class, testMethod);
assertThat(expectedThrown.getMessage(), is(... |
public SmppConfiguration getConfiguration() {
return configuration;
} | @Test
public void constructorSmppConfigurationShouldSetTheConfiguration() {
SmppConfiguration configuration = new SmppConfiguration();
component = new SmppComponent(configuration);
assertSame(configuration, component.getConfiguration());
} |
public float getProtectThreshold() {
return protectThreshold;
} | @Test
void testProtectThresholdDefault() {
final ProtectMode protectMode = new ProtectMode();
assertEquals(0.8f, protectMode.getProtectThreshold(), 0.01f);
} |
public static HeightLock ofBlockHeight(int blockHeight) {
if (blockHeight < 0)
throw new IllegalArgumentException("illegal negative block height: " + blockHeight);
if (blockHeight >= THRESHOLD)
throw new IllegalArgumentException("block height too high: " + blockHeight);
r... | @Test
public void ofBlockHeight() {
assertEquals(1, LockTime.ofBlockHeight(1).blockHeight());
assertEquals(499_999_999, LockTime.ofBlockHeight((int) LockTime.THRESHOLD - 1).blockHeight());
} |
@Override
public int hashCode() {
int hash = _hash;
if (hash == 1 && _bytes.length > 0) {
int i = 0;
for (; i + 7 < _bytes.length; i += 8) {
hash = -1807454463 * hash
+ 1742810335 * _bytes[i]
+ 887503681 * _bytes[i + 1]
+ 28629151 * _bytes[i + 2]
... | @Test(description = "hash code may have been used for partitioning so must be stable")
public void testHashCodeWithInterning() {
// ensure to test below 8
byte[] bytes = new byte[ThreadLocalRandom.current().nextInt(8)];
ThreadLocalRandom.current().nextBytes(bytes);
assertEquals(Arrays.hashCode(bytes),... |
public static InetSocketAddress getConnectAddress(ServiceAttributeProvider service,
AlluxioConfiguration conf) {
return InetSocketAddress.createUnresolved(getConnectHost(service, conf),
getPort(service, conf));
} | @Test
public void testGetConnectAddress() throws Exception {
for (ServiceType service : ServiceType.values()) {
if (service == ServiceType.JOB_MASTER_RAFT || service == ServiceType.MASTER_RAFT) {
// Skip the raft services, which don't support separate bind and connect ports.
continue;
... |
@Override
public V load(K key) {
awaitSuccessfulInit();
try (SqlResult queryResult = sqlService.execute(queries.load(), key)) {
Iterator<SqlRow> it = queryResult.iterator();
V value = null;
if (it.hasNext()) {
SqlRow sqlRow = it.next();
... | @Test
public void givenRowDoesNotExist_whenLoad_thenReturnNull() {
objectProvider.createObject(mapName, false);
mapLoader = createMapLoader();
GenericRecord genericRecord = mapLoader.load(0);
assertThat(genericRecord).isNull();
} |
public static String buildSplitScanQuery(
Table table, SeaTunnelRowType rowType, boolean isFirstSplit, boolean isLastSplit) {
return buildSplitQuery(table, rowType, isFirstSplit, isLastSplit, -1, true);
} | @Test
public void testSplitScanQuery() {
Table table =
Table.editor()
.tableId(TableId.parse("db1.schema1.table1"))
.addColumn(Column.editor().name("id").type("int8").create())
.create();
String splitScanSQL =
... |
@Override
public void ignoreView(View view) {
} | @Test
public void ignoreView() {
View view = new View(mApplication);
mSensorsAPI.ignoreView(view);
Object tag = view.getTag(R.id.sensors_analytics_tag_view_ignored);
Assert.assertNull(tag);
} |
@Override
public ResourceReconcileResult tryReconcileClusterResources(
TaskManagerResourceInfoProvider taskManagerResourceInfoProvider) {
ResourceReconcileResult.Builder builder = ResourceReconcileResult.builder();
List<TaskManagerInfo> taskManagersIdleTimeout = new ArrayList<>();
... | @Test
void testRedundantResourceShouldBeFulfilled() {
final TaskManagerInfo taskManagerInUse =
new TestingTaskManagerInfo(
DEFAULT_SLOT_RESOURCE.multiply(5),
DEFAULT_SLOT_RESOURCE.multiply(2),
DEFAULT_SLOT_RESOURCE);
... |
public static HttpErrorResponse badRequest(String msg) {
return new HttpErrorResponse(BAD_REQUEST, ErrorCode.BAD_REQUEST.name(), msg);
} | @Test
public void testThatHttpErrorResponseProvidesCorrectErrorMessage() throws IOException {
HttpErrorResponse response = HttpErrorResponse.badRequest("Error doing something");
HandlerTest.assertHttpStatusCodeErrorCodeAndMessage(response, BAD_REQUEST, HttpErrorResponse.ErrorCode.BAD_REQUEST, "Error... |
@Override
public EntityExcerpt createExcerpt(InputWithExtractors inputWithExtractors) {
return EntityExcerpt.builder()
.id(ModelId.of(inputWithExtractors.input().getId()))
.type(ModelTypes.INPUT_V1)
.title(inputWithExtractors.input().getTitle())
... | @Test
public void createExcerpt() {
final ImmutableMap<String, Object> fields = ImmutableMap.of(
"title", "Dashboard Title"
);
final InputImpl input = new InputImpl(fields);
final InputWithExtractors inputWithExtractors = InputWithExtractors.create(input);
fin... |
SchemaTransformer delegate()
{
return transformer;
} | @Test
void shouldAcceptEmptyStringAsTransformConfiguration()
{
final SchemaTransformerFactory schemaTransformerFactory = new SchemaTransformerFactory("");
assertSame(SchemaTransformer.IDENTITY_TRANSFORMER, schemaTransformerFactory.delegate());
} |
public Span nextSpan(Message message) {
TraceContextOrSamplingFlags extracted =
extractAndClearTraceIdProperties(processorExtractor, message, message);
Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler.
// When an upstream context was not present, lookup keys are unl... | @Test void nextSpan_should_clear_propagation_headers() {
Propagation.B3_STRING.injector(SETTER).inject(parent, message);
jmsTracing.nextSpan(message);
assertThat(ITJms.propertiesToMap(message))
.containsOnlyKeys(MessageUtil.JMSXDELIVERYCOUNT); /* always added by getPropertyNames() */
} |
public ConfigKey(String name, String configIdString, String namespace) {
this(name, configIdString, namespace, null);
} | @Test
public void testConfigKey() {
String name = AppConfig.CONFIG_DEF_NAME;
String namespace = AppConfig.CONFIG_DEF_NAMESPACE;
String md5 = AppConfig.CONFIG_DEF_MD5;
String configId = "myId";
ConfigKey<AppConfig> classKey = new ConfigKey<>(AppConfig.class, configId);
... |
@Override
@VisibleForTesting
public void getLoadBalancedClusterAndUriProperties(String clusterName,
Callback<Pair<ClusterProperties, UriProperties>> callback)
{
boolean waitForUpdatedValue = _timeout > 0;
// if timeout is 0, we must not add the timeout callback, otherwise it would trigger immediatel... | @Test
@SuppressWarnings("unchecked")
public void testGetLoadBalancedClusterAndUriProperties() throws InterruptedException, ExecutionException
{
MockStore<ServiceProperties> serviceRegistry = new MockStore<>();
MockStore<ClusterProperties> clusterRegistry = new MockStore<>();
MockStore<UriProperties> u... |
@Override
public String toString() {
return toString(false);
} | @Test
public void testToStringWithQuota() {
long fileAndDirCount = 55555;
long quota = 44444;
long spaceConsumed = 55555;
long spaceQuota = 66665;
QuotaUsage quotaUsage = new QuotaUsage.Builder().
fileAndDirectoryCount(fileAndDirCount).quota(quota).
spaceConsumed(spaceConsumed).sp... |
void processRestartRequests() {
List<RestartRequest> restartRequests;
synchronized (this) {
if (pendingRestartRequests.isEmpty()) {
return;
}
//dequeue into a local list to minimize the work being done within the synchronized block
restartR... | @Test
public void processRestartRequestsFailureSuppression() {
doNothing().when(member).wakeup();
final String connectorName = "foo";
RestartRequest restartRequest = new RestartRequest(connectorName, false, false);
doThrow(new RuntimeException()).when(herder).buildRestartPlan(restar... |
public static <E> BoundedList<E> newArrayBacked(int maxLength) {
return new BoundedList<>(maxLength, new ArrayList<>());
} | @Test
public void testMaxLengthMustNotBeZero() {
assertEquals("Invalid non-positive maxLength of 0",
assertThrows(IllegalArgumentException.class,
() -> BoundedList.newArrayBacked(0)).getMessage());
assertEquals("Invalid non-positive maxLength of 0",
assertThr... |
@Override
public Object toKsqlRow(final Schema connectSchema, final Object connectData) {
if (connectData == null) {
return null;
}
return toKsqlValue(schema, connectSchema, connectData, "");
} | @Test
public void shouldThrowIfNestedFieldTypeDoesntMatch() {
// Given:
final Schema structSchema = SchemaBuilder
.struct()
.field("INT", SchemaBuilder.OPTIONAL_INT32_SCHEMA)
.optional()
.build();
final Schema rowSchema = SchemaBuilder
.struct()
.field("STR... |
@Override
public boolean syncData(DistroData data, String targetServer) {
if (isNoExistTarget(targetServer)) {
return true;
}
DistroDataRequest request = new DistroDataRequest(data, data.getType());
Member member = memberManager.find(targetServer);
if (checkTarget... | @Test
void testSyncDataWithCallbackForMemberNonExist() throws NacosException {
transportAgent.syncData(new DistroData(), member.getAddress(), distroCallback);
verify(distroCallback).onSuccess();
verify(memberManager, never()).find(member.getAddress());
verify(clusterRpcClientProxy, n... |
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor(
DoFn<InputT, OutputT> fn) {
return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn);
} | @Test
public void testSplittableDoFnWithHasDefaultMethods() throws Exception {
class MockFn extends DoFn<String, String> {
@ProcessElement
public void processElement(
ProcessContext c,
RestrictionTracker<RestrictionWithBoundedDefaultTracker, Void> tracker,
WatermarkEstima... |
@Override
public ConsumeMessageDirectlyResult consumeMessageDirectly(MessageExt msg, String brokerName) {
ConsumeMessageDirectlyResult result = new ConsumeMessageDirectlyResult();
result.setOrder(true);
List<MessageExt> msgs = new ArrayList<>();
msgs.add(msg);
MessageQueue m... | @Test
public void testConsumeMessageDirectly() {
when(messageListener.consumeMessage(any(), any(ConsumeOrderlyContext.class))).thenReturn(ConsumeOrderlyStatus.SUCCESS);
ConsumeMessageDirectlyResult actual = popService.consumeMessageDirectly(createMessageExt(), defaultBroker);
assertEquals(CM... |
public void add(double datum) {
dbuf[nd++] = datum;
if (datum < q0) {
q0 = datum;
}
if (datum > qm) {
qm = datum;
}
if (nd == nbuf) {
update();
}
} | @Test
public void testAdd() {
System.out.println("IQAgent");
double[] data = new double[100000];
for (int i = 0; i < data.length; i++)
data[i] = i+1;
MathEx.permutate(data);
IQAgent instance = new IQAgent();
for (double datum : data) instance.ad... |
@Override
public long maxOffset(MessageQueue mq) throws MQClientException {
return defaultMQAdminExtImpl.maxOffset(mq);
} | @Test
@Ignore
public void testMaxOffset() throws Exception {
when(mQClientAPIImpl.getMaxOffset(anyString(), any(MessageQueue.class), anyLong())).thenReturn(100L);
assertThat(defaultMQAdminExt.maxOffset(new MessageQueue(TOPIC1, BROKER1_NAME, 0))).isEqualTo(100L);
} |
public MeasureDto toMeasureDto(Measure measure, Metric metric, Component component) {
MeasureDto out = new MeasureDto();
out.setMetricUuid(metric.getUuid());
out.setComponentUuid(component.getUuid());
out.setAnalysisUuid(analysisMetadataHolder.getUuid());
if (measure.hasQualityGateStatus()) {
... | @Test
public void toMeasureDto_maps_to_only_data_for_STRING_metric() {
MeasureDto trueMeasureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().create(SOME_STRING), SOME_STRING_METRIC, SOME_COMPONENT);
assertThat(trueMeasureDto.getValue()).isNull();
assertThat(trueMeasureDto.getData()).isEqualTo(SO... |
public BinaryRecordData generate(Object[] rowFields) {
checkArgument(
dataTypes.length == rowFields.length,
String.format(
"The types and values must have the same length. But types is %d and values is %d",
dataTypes.length, rowFiel... | @Test
void testOf() {
RowType rowType =
RowType.of(
DataTypes.BOOLEAN(),
DataTypes.BINARY(3),
DataTypes.VARBINARY(10),
DataTypes.BYTES(),
DataTypes.TINYINT(),
... |
@Override
public OAuth2AccessTokenDO grantPassword(String username, String password, String clientId, List<String> scopes) {
// 使用账号 + 密码进行登录
AdminUserDO user = adminAuthService.authenticate(username, password);
Assert.notNull(user, "用户不能为空!"); // 防御性编程
// 创建访问令牌
return oaut... | @Test
public void testGrantPassword() {
// 准备参数
String username = randomString();
String password = randomString();
String clientId = randomString();
List<String> scopes = Lists.newArrayList("read", "write");
// mock 方法(认证)
AdminUserDO user = randomPojo(AdminU... |
public static Deserializer<NeighborSolicitation> deserializer() {
return (data, offset, length) -> {
checkInput(data, offset, length, HEADER_LENGTH);
NeighborSolicitation neighborSolicitation = new NeighborSolicitation();
ByteBuffer bb = ByteBuffer.wrap(data, offset, length... | @Test
public void testDeserializeTruncated() throws Exception {
// Run the truncation test only on the NeighborSolicitation header
byte[] nsHeader = new byte[NeighborSolicitation.HEADER_LENGTH];
ByteBuffer.wrap(bytePacket).get(nsHeader);
PacketTestUtils.testDeserializeTruncated(Neig... |
public SearchResponse search(IssueQuery query, SearchOptions options) {
SearchRequest requestBuilder = EsClient.prepareSearch(TYPE_ISSUE.getMainType());
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
requestBuilder.source(sourceBuilder);
configureSorting(query, sourceBuilder);
confi... | @Test
void search_with_max_limit() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
List<IssueDoc> issues = new ArrayList<>();
for (int i = 0; i < 500; i++) {
String key = "I" + i;
issues.add(newDoc(key, project.uuid(), file));
}
indexIssues... |
public static Db use() {
return use(DSFactory.get());
} | @Test
public void findTest() throws SQLException {
List<Entity> find = Db.use().find(Entity.create("user").set("age", 18));
assertEquals("王五", find.get(0).get("name"));
} |
@GetMapping("/removeVGroup")
public Result<?> removeVGroup(@RequestParam String vGroup) {
Result<?> result = new Result<>();
boolean rst = vGroupMappingStoreManager.removeVGroup(vGroup);
Instance.getInstance().setTerm(System.currentTimeMillis());
if (!rst) {
result.setCod... | @Test
void removeVGroup() {
namingController.removeVGroup("group1");
} |
public static NetworkPolicyPeer createPeer(Map<String, String> podSelector, LabelSelector namespaceSelector) {
return new NetworkPolicyPeerBuilder()
.withNewPodSelector()
.withMatchLabels(podSelector)
.endPodSelector()
.withNamespaceSelector(na... | @Test
public void testCreatePeerWithPodLabelsAndEmptyNamespaceSelector() {
NetworkPolicyPeer peer = NetworkPolicyUtils.createPeer(Map.of("labelKey", "labelValue"), new LabelSelectorBuilder().withMatchLabels(Map.of()).build());
assertThat(peer.getNamespaceSelector().getMatchLabels(), is(Map.of()));... |
public static <T extends CharSequence> T validateChinese(T value, String errorMsg) throws ValidateException {
if (false == isChinese(value)) {
throw new ValidateException(errorMsg);
}
return value;
} | @Test
public void validateTest() throws ValidateException {
assertThrows(ValidateException.class, () -> {
Validator.validateChinese("我是一段zhongwen", "内容中包含非中文");
});
} |
@Override
@Deprecated
public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNul... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowBadTransformerSupplierOnFlatTransformWithNamed() {
final org.apache.kafka.streams.kstream.Transformer<String, String, Iterable<KeyValue<String, String>>> transformer = flatTransformerSupplier.get();
final IllegalArgumentException e... |
public SmppMessage createSmppMessage(CamelContext camelContext, AlertNotification alertNotification) {
SmppMessage smppMessage = new SmppMessage(camelContext, alertNotification, configuration);
smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.AlertNotification.toString());
smpp... | @SuppressWarnings("unchecked")
@Test
public void createSmppMessageFromDeliveryReceiptWithOptionalParametersShouldReturnASmppMessage() throws Exception {
DeliverSm deliverSm = new DeliverSm();
deliverSm.setSmscDeliveryReceipt();
deliverSm.setShortMessage(
"id:2 sub:001 dlv... |
public static void shutdown(final NamesrvController controller) {
controller.shutdown();
} | @Test
public void testShutdown() {
NamesrvStartup.shutdown(namesrvController);
Mockito.verify(namesrvController).shutdown();
} |
@Override
public List<NotifyMessageDO> getUnreadNotifyMessageList(Long userId, Integer userType, Integer size) {
return notifyMessageMapper.selectUnreadListByUserIdAndUserType(userId, userType, size);
} | @Test
public void testGetUnreadNotifyMessageList() {
SqlConstants.init(DbType.MYSQL);
// mock 数据
NotifyMessageDO dbNotifyMessage = randomPojo(NotifyMessageDO.class, o -> { // 等会查询到
o.setUserId(1L);
o.setUserType(UserTypeEnum.ADMIN.getValue());
o.setReadSta... |
JavaClasses getClassesToAnalyzeFor(Class<?> testClass, ClassAnalysisRequest classAnalysisRequest) {
checkNotNull(testClass);
checkNotNull(classAnalysisRequest);
if (cachedByTest.containsKey(testClass)) {
return cachedByTest.get(testClass);
}
LocationsKey locations =... | @Test
public void distinguishes_import_option_when_caching() {
JavaClasses importingWholeClasspathWithFilter =
cache.getClassesToAnalyzeFor(TestClass.class, new TestAnalysisRequest().withImportOptions(TestFilterForJUnitJars.class));
JavaClasses importingWholeClasspathWithEquivalentBu... |
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 testShouldReport1DayFor45Mintues() {
assertEquals(TimeConverter.ABOUT_1_HOUR_AGO, timeConverter.getConvertedTime(45 * 60));
} |
@Deprecated
@Override
public void init(final org.apache.kafka.streams.processor.ProcessorContext context, final StateStore root) {
store.init(context, root);
} | @Deprecated
@Test
public void shouldDeprecatedInitVersionedStore() {
givenWrapperWithVersionedStore();
final org.apache.kafka.streams.processor.ProcessorContext mockContext
= mock(org.apache.kafka.streams.processor.ProcessorContext.class);
wrapper.init(mockContext, wrapper);... |
public List<String> getDatacentersBySubnet(InetAddress address) throws IllegalArgumentException {
if(address instanceof Inet4Address) {
for(Map.Entry<Integer, Map<Integer, List<String>>> t: this.ipv4Map.descendingMap().entrySet()) {
int maskedIp = CidrBlock.IpV4CidrBlock.maskToSize((Inet4Address) add... | @Test
void testGetFastestDataCentersBySubnetOverlappingTable() throws UnknownHostException {
var v4address = Inet4Address.getByName("1.123.123.1");
var actualV4 = overlappingTable.getDatacentersBySubnet(v4address);
assertThat(actualV4).isEqualTo(List.of("datacenter-4"));
var v6address = Inet6Address.... |
protected static Object prepareObjectType( Object o ) {
return ( o instanceof byte[] ) ? Arrays.hashCode( (byte[]) o ) : o;
} | @Test
public void prepareObjectTypeBinaryTest_Equals() throws Exception {
assertEquals( Arrays.hashCode( new byte[] { 1, 2, 3 } ), SwitchCase.prepareObjectType( new byte[] { 1, 2, 3 } ) ) ;
} |
public T valueOf(Class<?> firstNameComponent, String secondNameComponent) {
return valueOf(
checkNotNull(firstNameComponent, "firstNameComponent").getName() +
'#' +
checkNotNull(secondNameComponent, "secondNameComponent"));
} | @Test
public void testIdUniqueness() {
TestConstant one = pool.valueOf("one");
TestConstant two = pool.valueOf("two");
assertThat(one.id(), is(not(two.id())));
} |
public WorkflowInstanceActionResponse kill(
String workflowId, long workflowInstanceId, long workflowRunId, User caller) {
return terminate(
workflowId, workflowInstanceId, workflowRunId, Actions.WorkflowInstanceAction.KILL, caller);
} | @Test
public void testKill() {
when(instanceDao.tryTerminateQueuedInstance(any(), any(), any())).thenReturn(true);
when(instance.getStatus()).thenReturn(WorkflowInstance.Status.CREATED);
boolean res = actionHandler.kill("test-workflow", 1, 1, user).isCompleted();
assertTrue(res);
verify(instanceDa... |
public static WebService.NewParam createRootQualifiersParameter(WebService.NewAction action, QualifierParameterContext context) {
return action.createParam(PARAM_QUALIFIERS)
.setDescription("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers. " +
"Possible v... | @Test
public void test_createRootQualifiersParameter() {
when(resourceTypes.getRoots()).thenReturn(asList(Q1, Q2));
when(newAction.createParam(PARAM_QUALIFIERS)).thenReturn(newParam);
when(newParam.setDescription(startsWith("Comma-separated list of component qualifiers. Filter the results with the specifi... |
@Override
ListOffsetsRequest.Builder buildBatchedRequest(int brokerId, Set<TopicPartition> keys) {
Map<String, ListOffsetsTopic> topicsByName = CollectionUtils.groupPartitionsByTopic(
keys,
topicName -> new ListOffsetsTopic().setName(topicName),
(listOffsetsTopic, partiti... | @Test
public void testBuildRequestSimple() {
ListOffsetsHandler handler =
new ListOffsetsHandler(offsetTimestampsByPartition, new ListOffsetsOptions(), logContext);
ListOffsetsRequest request = handler.buildBatchedRequest(node.id(), mkSet(t0p0, t0p1)).build();
List<ListOffsetsTop... |
public static HttpServerResponse create(@Nullable HttpServletRequest request,
HttpServletResponse response, @Nullable Throwable caught) {
return new HttpServletResponseWrapper(request, response, caught);
} | @Test void method_isRequestMethod() {
HttpServerResponse wrapper = HttpServletResponseWrapper.create(request, response, null);
when(request.getMethod()).thenReturn("POST");
assertThat(wrapper.method()).isEqualTo("POST");
} |
@Override
protected VertexFlameGraph handleRequest(
HandlerRequest<EmptyRequestBody> request, AccessExecutionJobVertex jobVertex)
throws RestHandlerException {
@Nullable Integer subtaskIndex = getSubtaskIndex(request, jobVertex);
if (isTerminated(jobVertex, subtaskIndex)) {
... | @Test
void testHandleFinishedJobVertex() throws Exception {
final ArchivedExecutionJobVertex archivedExecutionJobVertex =
new ArchivedExecutionJobVertex(
new ArchivedExecutionVertex[] {
generateExecutionVertex(0, ExecutionState.FINISHED),
... |
public UnionOperator(OpChainExecutionContext opChainExecutionContext, List<MultiStageOperator> inputOperators,
DataSchema dataSchema) {
super(opChainExecutionContext, inputOperators, dataSchema);
} | @Test
public void testUnionOperator() {
DataSchema schema = new DataSchema(new String[]{"int_col", "string_col"}, new DataSchema.ColumnDataType[]{
DataSchema.ColumnDataType.INT, DataSchema.ColumnDataType.STRING
});
Mockito.when(_leftOperator.nextBlock())
.thenReturn(OperatorTestUtil.block(... |
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory(
final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration,
final Configuration jobConfiguration,
final Configuration clusterConfiguration,
final boolean is... | @Test
void testExponentialDelayRestartStrategySpecifiedInExecutionConfig() {
final Configuration conf = new Configuration();
conf.set(RestartStrategyOptions.RESTART_STRATEGY, FAILURE_RATE.getMainValue());
final RestartBackoffTimeStrategy.Factory factory =
RestartBackoffTimeS... |
public boolean isSuppressed(Device device) {
if (suppressedDeviceType.contains(device.type())) {
return true;
}
final Annotations annotations = device.annotations();
if (containsSuppressionAnnotation(annotations)) {
return true;
}
return false;
... | @Test
public void testSuppressedPortAnnotation() {
Annotations annotation = DefaultAnnotations.builder()
.set("no-lldp", "random")
.build();
Device device = new DefaultDevice(PID,
NON_SUPPRESSED_DID,
... |
@Override
public synchronized int read() throws IOException {
checkNotClosed();
if (finished) {
return -1;
}
file.readLock().lock();
try {
int b = file.read(pos++); // it's ok for pos to go beyond size()
if (b == -1) {
finished = true;
} else {
file.setLas... | @SuppressWarnings("GuardedByChecker")
@Test
public void testFullyReadInputStream_doesNotChangeStateWhenStoreChanges() throws IOException {
JimfsInputStream in = newInputStream(1, 2, 3, 4, 5);
assertThat(in.read(new byte[5])).isEqualTo(5);
assertEmpty(in);
in.file.write(5, new byte[10], 0, 10); // a... |
List<Argument> matchedArguments(Step step) {
return argumentMatcher.argumentsFrom(step, types);
} | @Test
void should_convert_empty_pickle_table_cells_to_null_values() {
Feature feature = TestFeatureParser.parse("" +
"Feature: Test feature\n" +
" Scenario: Test scenario\n" +
" Given I have some step\n" +
" | |\n");
StepDef... |
public boolean cleanupExpiredOffsets(String groupId, List<CoordinatorRecord> records) {
TimelineHashMap<String, TimelineHashMap<Integer, OffsetAndMetadata>> offsetsByTopic =
offsets.offsetsByGroup.get(groupId);
if (offsetsByTopic == null) {
return true;
}
// We e... | @Test
public void testCleanupExpiredOffsetsGroupHasNoOffsets() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder()
.build();
List<CoordinatorRecord> records = new ArrayList<>();
assertTrue(context.cleanupExpiredOffsets("unknown-group-id", ... |
@Override
@MethodNotAvailable
public Map<K, Object> executeOnEntries(com.hazelcast.map.EntryProcessor entryProcessor) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testExecuteOnEntriesWithPredicate() {
adapter.executeOnEntries(new IMapReplaceEntryProcessor("value", "newValue"), Predicates.alwaysTrue());
} |
@Override
public DataFrame select(int... cols) {
return new IndexDataFrame(df.select(cols), index);
} | @Test
public void testDataFrameToArray() {
System.out.println("toArray");
double[][] output = df.select("age", "salary", "gender").toArray(false, CategoricalEncoder.ONE_HOT);
assertEquals(4, output.length);
assertEquals(4, output[0].length);
assertEquals(48., output[0][0], 1E... |
@Nullable
public static Object getValueFromLiteral(ValueLiteralExpression expr) {
LogicalType logicalType = expr.getOutputDataType().getLogicalType();
switch (logicalType.getTypeRoot()) {
case TIMESTAMP_WITHOUT_TIME_ZONE:
return expr.getValueAs(LocalDateTime.class)
.map(ldt -> ldt.to... | @Test
void getValueFromLiteralForNull() {
List<RowType.RowField> fields = ((RowType) ROW_DATA_TYPE.getLogicalType()).getFields();
List<DataType> dataTypes = ROW_DATA_TYPE.getChildren();
CallExpression callExpression;
for (int i = 0; i < fields.size(); i++) {
// 1. Build all types
callExpre... |
public static Coin parseCoinInexact(final String str) {
try {
long satoshis = new BigDecimal(str).movePointRight(SMALLEST_UNIT_EXPONENT).longValue();
return Coin.valueOf(satoshis);
} catch (ArithmeticException e) {
throw new IllegalArgumentException(e); // Repackage e... | @Test
public void testParseCoinInexact() {
assertEquals(1, parseCoinInexact("0.00000001").value);
assertEquals(1, parseCoinInexact("0.000000011").value);
} |
public void validate(Map<String, NewDocumentType> documentDefinitions) {
List<String> conflictingNames = documentDefinitions.keySet().stream()
.filter(this::isReservedName)
.toList();
if (!conflictingNames.isEmpty()) {
throw new IllegalArgumentException(makeRe... | @Test
void exception_thrown_on_reserved_names() {
// Ensure ordering is consistent for testing
Map<String, NewDocumentType> orderedDocTypes = new TreeMap<>(asDocTypeMapping(ReservedDocumentTypeNameValidator.ORDERED_RESERVED_NAMES));
ReservedDocumentTypeNameValidator validator = new Reserved... |
public double bearingTo(final IGeoPoint other) {
final double lat1 = Math.toRadians(this.mLatitude);
final double long1 = Math.toRadians(this.mLongitude);
final double lat2 = Math.toRadians(other.getLatitude());
final double long2 = Math.toRadians(other.getLongitude());
final dou... | @Test
public void test_bearingTo_south() {
final GeoPoint target = new GeoPoint(0.0, 0.0);
final GeoPoint other = new GeoPoint(-10.0, 0.0);
assertEquals("directly south", 180, Math.round(target.bearingTo(other)));
} |
@Nonnull
public static <T> BatchSource<T> list(@Nonnull String listName) {
return batchFromProcessor("listSource(" + listName + ')', readListP(listName));
} | @Test
public void list_byName() {
// Given
List<Integer> input = sequence(itemCount);
addToSrcList(input);
// When
BatchSource<Integer> source = Sources.list(srcName);
// Then
p.readFrom(source).writeTo(sink);
execute();
assertEquals(input, s... |
@Override
public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan,
final boolean restoreInProgress) {
try {
final ExecuteResult result = EngineExecutor
.create(primaryContext, serviceContext, plan.getConfig())
.execut... | @Test
public void shouldCreateSourceTablesQueries() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
givenTopicsExist("t1_topic");
// When:
final List<QueryMetadata> queries = KsqlEngineTestUtil.execute(
serviceContext,
ksqlEngine,
"create source table t1 (f0 bigint ... |
public H3IndexResolution getResolution() {
return _resolution;
} | @Test
public void withDisabledTrue()
throws JsonProcessingException {
String confStr = "{\"disabled\": true}";
H3IndexConfig config = JsonUtils.stringToObject(confStr, H3IndexConfig.class);
assertTrue(config.isDisabled(), "Unexpected disabled");
assertNull(config.getResolution(), "Unexpected re... |
@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_notNull() {
// mock 数据
SocialUserDO socialUser = randomPojo(SocialUserDO.class,
o -> o.setType(SocialTypeEnum.GITEE.getType()).setCode("tudou").setState("yuanma"));
socialUserMapper.insert(socialUser);
// 准备参数
Integer socia... |
@SuppressWarnings("ParameterNumber")
TransientQueryMetadata buildTransientQuery(
final String statementText,
final QueryId queryId,
final Set<SourceName> sources,
final ExecutionStep<?> physicalPlan,
final String planSummary,
final LogicalSchema schema,
final OptionalInt limi... | @Test
public void shouldBuildTransientQueryCorrectly() {
// Given:
givenTransientQuery();
// When:
final TransientQueryMetadata queryMetadata = queryBuilder.buildTransientQuery(
STATEMENT_TEXT,
QUERY_ID,
SOURCES.stream().map(DataSource::getName).collect(Collectors.toSet()),
... |
@PATCH
@Path("/{connector}/offsets")
@Operation(summary = "Alter the offsets for the specified connector")
public Response alterConnectorOffsets(final @Parameter(hidden = true) @QueryParam("forward") Boolean forward,
final @Context HttpHeaders headers, final @PathPa... | @Test
public void testAlterOffsetsNotLeader() throws Throwable {
Map<String, ?> partition = new HashMap<>();
Map<String, ?> offset = new HashMap<>();
ConnectorOffset connectorOffset = new ConnectorOffset(partition, offset);
ConnectorOffsets body = new ConnectorOffsets(Collections.sin... |
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final List<Path> containers = new ArrayList<>();
for(Path file : files.keySet()) {
if(containerService.isContainer(file)) {
container... | @Test(expected = NotfoundException.class)
public void testDeleteNotFoundBucket() throws Exception {
final Path container = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume));
new S3DefaultDeleteFeature(session).delete(Collections.singletonList... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 1) {
onInvalidDataReceived(device, data);
return;
}
//noinspection DataFlowIssue
final int sensorLocation = data.getIntValue(Data.FORMAT_UINT8,... | @Test
public void onInvalidDataReceived() {
success = false;
final Data data = new Data();
response.onDataReceived(null, data);
assertFalse(response.isValid());
assertFalse(success);
} |
public void setSortKey(SortKey sortkey) {
if (Objects.equals(this.sortkey, sortkey)) {
return;
}
invalidate();
if (sortkey != null) {
int column = sortkey.getColumn();
if (valueComparators[column] == null) {
throw new IllegalArgumentEx... | @Test
public void sortKeyDescending() {
sorter.setSortKey(new SortKey(0, SortOrder.DESCENDING));
assertRowOrderAndIndexes(asList(d4(), c1(), b2(), a3()));
} |
public Iterable<CidrBlock> iterableCidrs() {
return () -> new Iterator<>() {
private final BigInteger increment = BigInteger.ONE.shiftLeft(suffixLength());
private final BigInteger maxValue = BigInteger.ONE.shiftLeft(addressLength).subtract(increment);
private BigInteger curr... | @Test
public void iterableCidrs() {
CidrBlock superBlock = CidrBlock.fromString("10.12.14.0/24");
assertEquals(List.of("10.12.14.200/29", "10.12.14.208/29", "10.12.14.216/29", "10.12.14.224/29", "10.12.14.232/29", "10.12.14.240/29", "10.12.14.248/29"),
StreamSupport.stream(CidrBlock.... |
@Override
public String toString() {
StringBuilder builder = new StringBuilder("AfterProcessingTime.pastFirstElementInPane()");
for (TimestampTransform transform : getTimestampTransforms()) {
if (transform instanceof TimestampTransform.Delay) {
TimestampTransform.Delay delay = (TimestampTransfor... | @Test
public void testToString() {
Trigger trigger = AfterProcessingTime.pastFirstElementInPane();
assertEquals("AfterProcessingTime.pastFirstElementInPane()", trigger.toString());
} |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthNewFilter() throws Exception {
EthFilter ethFilter = new EthFilter().addSingleTopic("0x12341234");
web3j.ethNewFilter(ethFilter).send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"eth_newFilter\","
+ "\"params\":[{\"top... |
public PropertyPanel addProp(String key, String label, String value) {
properties.add(new Prop(key, label, value));
return this;
} | @Test
public void longValues() {
basic();
pp.addProp(KEY_A, KEY_A, 200L)
.addProp(KEY_B, KEY_B, 2000L)
.addProp(KEY_C, KEY_C, 1234567L)
.addProp(KEY_Z, KEY_Z, Long.MAX_VALUE);
validateProp(KEY_A, "200");
validateProp(KEY_B, "2,000");
... |
public static Builder builder() {
return new Builder();
} | @Test(expected = IllegalArgumentException.class)
public void testIllegalMulticastTypeConstruction() {
IpPrefix ip = IpPrefix.valueOf(IP_ADDRESS_1);
MappingAddress address = MappingAddresses.ipv4MappingAddress(ip);
DefaultMappingTreatment.builder()
.withAddress(address)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.