focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static File generate(String content, int width, int height, File targetFile) {
String extName = FileUtil.extName(targetFile);
switch (extName) {
case QR_TYPE_SVG:
String svg = generateAsSvg(content, new QrConfig(width, height));
FileUtil.writeString(svg, targetFile, StandardCharsets.UTF_8);
br... | @Test
@Disabled
public void comparePngAndSvgAndAsciiArtTest() {
final QrConfig qrConfig = QrConfig.create()
.setForeColor(null)
.setBackColor(Color.WHITE)
.setWidth(200)
.setHeight(200).setMargin(1);
QrCodeUtil.generate("https://hutool.cn", qrConfig, FileUtil.touch("d:/test/compare/config_null_col... |
@Override
protected Response filter(Request request, RequestMeta meta, Class handlerClazz) {
Method method;
try {
method = getHandleMethod(handlerClazz);
} catch (NacosException e) {
return null;
}
if (method.isAnnotationPresent(TpsCo... | @Test
void testRejected() {
HealthCheckRequest healthCheckRequest = new HealthCheckRequest();
RequestMeta requestMeta = new RequestMeta();
TpsCheckResponse tpsCheckResponse = new TpsCheckResponse(false, 5031, "rejected");
Mockito.when(tpsControlManager.check(any(TpsCheckRequest.class... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
final AttributedList<ch.cyberduck.core.Path> paths = new AttributedList<>();
final java.nio.file.Path p = session.toPath(directory);
if(!Files.exists(p)) {
... | @Test(expected = NotfoundException.class)
public void testListNotfound() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLogin... |
public boolean getUseAwsDefaultCredentials() {
if ( ValueMetaBase.convertStringToBoolean( Const.NVL( EnvUtil.getSystemProperty( Const.KETTLE_USE_AWS_DEFAULT_CREDENTIALS ), "N" ) ) ) {
return true;
} else if ( StringUtil.isEmpty( awsAccessKey ) && StringUtil.isEmpty( awsSecretKey ) ) {
return true;
... | @Test
public void getUseAwsDefaultCredentialsWithoutCredentials() {
S3CsvInputMeta meta = new S3CsvInputMeta();
assertTrue( meta.getUseAwsDefaultCredentials() );
} |
public static List<Integer> getJoinOrder(JoinGraph graph)
{
ImmutableList.Builder<PlanNode> joinOrder = ImmutableList.builder();
Map<PlanNodeId, Integer> priorities = new HashMap<>();
for (int i = 0; i < graph.size(); i++) {
priorities.put(graph.getNode(i).getId(), i);
}... | @Test
public void testDoNotReorderCrossJoins()
{
PlanNode plan =
joinNode(
joinNode(
values(variable("a")),
values(variable("b"))),
values(variable("c")),
... |
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 positiveFloatLiteral() {
String inputExpression = "+10.5";
BaseNode number = parse( inputExpression );
assertThat( number).isInstanceOf(SignedUnaryNode.class);
assertThat( number.getResultType()).isEqualTo(BuiltInType.NUMBER);
assertLocation( inputExpression, numb... |
public Host deserialize(final T serialized) {
final Deserializer<T> dict = factory.create(serialized);
Object protocolObj = dict.stringForKey("Protocol");
if(protocolObj == null) {
log.warn(String.format("Missing protocol key in %s", dict));
return null;
}
... | @Test
public void testDeserialize() {
final Serializer<NSDictionary> dict = SerializerFactory.get();
dict.setStringForKey("test", "Protocol");
dict.setStringForKey("unknown provider", "Provider");
dict.setStringForKey("h", "Hostname");
dict.setStringListForKey(Arrays.asList("... |
public void fromShort(short n) {
Bits[] v = Bits.values();
set(v[(n >>> 6) & 7], v[(n >>> 3) & 7], v[n & 7]);
} | @Test
public void fromShort() {
Mode mode = new Mode((short) 0777);
assertEquals(Mode.Bits.ALL, mode.getOwnerBits());
assertEquals(Mode.Bits.ALL, mode.getGroupBits());
assertEquals(Mode.Bits.ALL, mode.getOtherBits());
mode = new Mode((short) 0644);
assertEquals(Mode.Bits.READ_WRITE, mode.getO... |
@SuppressWarnings("deprecation")
public static void setClasspath(Map<String, String> environment,
Configuration conf) throws IOException {
boolean userClassesTakesPrecedence =
conf.getBoolean(MRJobConfig.MAPREDUCE_JOB_USER_CLASSPATH_FIRST, false);
String classpathEnvVar =
conf.getBoolean(M... | @Test
@Timeout(3000000)
public void testSetClasspathWithFramework() throws IOException {
final String FRAMEWORK_NAME = "some-framework-name";
final String FRAMEWORK_PATH = "some-framework-path#" + FRAMEWORK_NAME;
Configuration conf = new Configuration();
conf.setBoolean(MRConfig.MAPREDUCE_APP_SUBMIS... |
@Udf(schema = "ARRAY<STRUCT<K STRING, V INT>>")
public List<Struct> entriesInt(
@UdfParameter(description = "The map to create entries from") final Map<String, Integer> map,
@UdfParameter(description = "If true then the resulting entries are sorted by key")
final boolean sorted
) {
return entr... | @Test
public void shouldComputeIntEntriesSorted() {
final Map<String, Integer> map = createMap(i -> i);
shouldComputeEntriesSorted(map, () -> entriesUdf.entriesInt(map, true));
} |
@Override
public Iterable<DiscoveryNode> discoverNodes() {
try {
List<GcpAddress> gcpAddresses = gcpClient.getAddresses();
logGcpAddresses(gcpAddresses);
List<DiscoveryNode> result = new ArrayList<>();
for (GcpAddress gcpAddress : gcpAddresses) {
... | @Test
public void discoverNodesEmpty() {
// given
given(gcpClient.getAddresses()).willReturn(new ArrayList<>());
// when
Iterable<DiscoveryNode> nodes = gcpDiscoveryStrategy.discoverNodes();
// then
assertFalse(nodes.iterator().hasNext());
} |
@Override
public NSImage documentIcon(final String extension, final Integer size) {
NSImage image = this.load(extension, size);
if(null == image) {
return this.cache(extension,
this.convert(extension, workspace.iconForFileType(extension), size), size);
}
... | @Test
public void testDocumentIcon() {
final NSImage icon = new NSImageIconCache().documentIcon("txt", 64);
assertNotNull(icon);
assertTrue(icon.isValid());
assertFalse(icon.isTemplate());
assertEquals(64, icon.size().width.intValue());
assertEquals(64, icon.size().he... |
@Override
public void stopTrackingDeploymentOf(ExecutionAttemptID executionAttemptId) {
pendingDeployments.remove(executionAttemptId);
ResourceID host = hostByExecution.remove(executionAttemptId);
if (host != null) {
executionsByHost.computeIfPresent(
host,
... | @Test
void testStopTrackingUnknownExecutionDoesNotThrowException() {
final DefaultExecutionDeploymentTracker tracker = new DefaultExecutionDeploymentTracker();
final ExecutionAttemptID attemptId2 = createExecutionAttemptId();
tracker.stopTrackingDeploymentOf(attemptId2);
} |
@Override
public boolean add(String str) {
boolean flag = false;
for (BloomFilter filter : filters) {
flag |= filter.add(str);
}
return flag;
} | @Test
@Disabled
public void testIntMap(){
IntMap intMap = new IntMap();
for (int i = 0 ; i < 32; i++) {
intMap.add(i);
}
intMap.remove(30);
for (int i = 0; i < 32; i++) {
System.out.println(i + "是否存在-->" + intMap.contains(i));
}
} |
public String nonNullValue(String key) {
String value = value(key);
if (value == null) {
throw new IllegalArgumentException("Missing property: " + key);
}
return value;
} | @Test
@UseDataProvider("beforeAndAfterBlanks")
public void nonNullValue(String blankBefore, String blankAfter) {
Properties p = new Properties();
p.setProperty("foo", blankBefore + "bar" + blankAfter);
Props props = new Props(p);
assertThat(props.nonNullValue("foo")).isEqualTo("bar");
} |
public static SpectralClustering fit(Matrix W, int k) {
return fit(W, k, 100, 1E-4);
} | @Test
public void testUSPS() throws Exception {
System.out.println("USPS");
MathEx.setSeed(19650218); // to get repeatable results.
double[][] x = USPS.x;
int[] y = USPS.y;
SpectralClustering model = SpectralClustering.fit(x, 10, 8.0);
System.out.println(model);
... |
@Override
public String createToken(Authentication authentication) throws AccessException {
return createToken(authentication.getName());
} | @Test
void testCreateToken1() throws AccessException {
assertEquals("token", cachedJwtTokenManager.createToken(authentication));
} |
static void cleanStackTrace(Throwable throwable) {
new StackTraceCleaner(throwable).clean(Sets.<Throwable>newIdentityHashSet());
} | @Test
public void allFramesAboveStandardSubjectBuilderCleaned() {
Throwable throwable =
createThrowableWithStackTrace(
"com.google.random.Package",
"com.google.common.base.collection.ImmutableMap",
"com.google.common.truth.StandardSubjectBuilder",
"com.googl... |
@Override
public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
if(null == status.getStorageClass()) {
// Keep same storage class
status.setStorageClass(new S3... | @Test
public void testCopyFile() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final TransferStatus status = new TransferStatus();
status.setMetadata(Collections.singletonMap("cyberduck", "m"));
f... |
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
String[] lines = splitAndRemoveEmpty(st, "\n");
return interpret(lines, context);
} | @Test
void copyToLocalTest() throws IOException {
FileSystemTestUtils.createByteFile(fs, "/testFile", WritePType.MUST_CACHE, 10, 10);
InterpreterResult output = alluxioInterpreter.interpret("copyToLocal /testFile " +
mLocalAlluxioCluster.getAlluxioHome() + "/testFile", null);
assertEquals(
... |
public static VerificationMode atLeast(final int count) {
checkArgument(count > 0, "Times count must be greater than zero");
return new AtLeastVerification(count);
} | @Test
public void should_verify_expected_request_for_at_least() throws Exception {
final HttpServer server = httpServer(port(), hit);
server.get(by(uri("/foo"))).response("bar");
running(server, () -> {
assertThat(helper.get(remoteUrl("/foo")), is("bar"));
assertThat... |
@Override
public void run() {
final Instant now = time.get();
try {
final Collection<PersistentQueryMetadata> queries = engine.getPersistentQueries();
final Optional<Double> saturation = queries.stream()
.collect(Collectors.groupingBy(PersistentQueryMetadata::getQueryApplicationId))
... | @Test
public void shouldCleanupQueryMetricWhenRuntimeRemoved() {
// Given:
final Instant start = Instant.now();
when(clock.get()).thenReturn(start);
givenMetrics(kafkaStreams1)
.withThreadStartTime("t1", start)
.withBlockedTime("t1", Duration.ofMinutes(0));
collector.run();
whe... |
public int writeSliInt64(long value) {
ensure(writerIndex + 9);
return _unsafeWriteSliInt64(value);
} | @Test
public void testWriteSliInt64() {
MemoryBuffer buf = MemoryUtils.buffer(8);
checkSliInt64(buf, -1, 4);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < i; j++) {
checkSliInt64(buf(i), -1, 4);
checkSliInt64(buf(i), 1, 4);
checkSliInt64(buf(i), 1L << 6, 4);
chec... |
@Override
public void startMediaRequest(
@NonNull String[] mimeTypes, int requestId, @NonNull InsertionRequestCallback callback) {
mCurrentRunningLocalProxy.dispose();
mCurrentRequest = requestId;
mCurrentCallback = callback;
final Intent pickingIntent = getMediaInsertRequestIntent(mimeTypes, ... | @Test
public void testIncorrectRequestBroadcast() {
mUnderTest.startMediaRequest(new String[] {"media/png"}, 123, mCallback);
mShadowApplication.getRegisteredReceivers().stream()
.filter(
wrapper ->
wrapper.broadcastReceiver
instanceof RemoteInsertionIm... |
public static List<String> toStringLines(String text) {
return new BufferedReader(new StringReader(text)).lines().collect(Collectors.toList());
} | @Test
void testToStringLines() {
List<String> expected = Arrays.asList("foo", "bar");
assertEquals(expected, StringUtils.toStringLines("foo\nbar\n"));
} |
@Override
public void accumulate(Object value) {
if (value != null && !values.add(value)) {
return;
}
delegate.accumulate(value);
} | @Test
public void test_accumulate() {
SqlAggregation aggregation = new DistinctSqlAggregation(delegate);
aggregation.accumulate("1");
aggregation.accumulate("2");
aggregation.accumulate("1");
verify(delegate).accumulate("1");
verify(delegate).accumulate("2");
... |
public static Object value(String strValue, Field field) {
requireNonNull(field);
// if field is not primitive type
Type fieldType = field.getGenericType();
if (fieldType instanceof ParameterizedType) {
Class<?> clazz = (Class<?>) ((ParameterizedType) field.getGenericType()).... | @Test
public void testNullStrValue() throws Exception {
class TestMap {
public List<String> list;
public Set<String> set;
public Map<String, String> map;
public Optional<String> optional;
}
Field listField = TestMap.class.getField("list");
... |
@ProcessElement
public ProcessContinuation processElement(
@Element KafkaSourceDescriptor kafkaSourceDescriptor,
RestrictionTracker<OffsetRange, Long> tracker,
WatermarkEstimator<Instant> watermarkEstimator,
MultiOutputReceiver receiver)
throws Exception {
final LoadingCache<TopicPar... | @Test
public void testProcessElementWithEmptyPoll() throws Exception {
MockMultiOutputReceiver receiver = new MockMultiOutputReceiver();
consumer.setNumOfRecordsPerPoll(-1);
OffsetRangeTracker tracker = new OffsetRangeTracker(new OffsetRange(0L, Long.MAX_VALUE));
ProcessContinuation result =
d... |
@Override
public Optional<String> getReturnTo(HttpRequest request) {
return getParameter(request, RETURN_TO_PARAMETER)
.flatMap(OAuth2AuthenticationParametersImpl::sanitizeRedirectUrl);
} | @Test
public void get_return_to_is_empty_when_no_cookie() {
when(request.getCookies()).thenReturn(new Cookie[]{});
Optional<String> redirection = underTest.getReturnTo(request);
assertThat(redirection).isEmpty();
} |
private synchronized boolean validateClientAcknowledgement(long h) {
if (h < 0) {
throw new IllegalArgumentException("Argument 'h' cannot be negative, but was: " + h);
}
if (h > MASK) {
throw new IllegalArgumentException("Argument 'h' cannot be larger than 2^32 -1, but wa... | @Test
public void testValidateClientAcknowledgement_rollover_edgecase1() throws Exception
{
// Setup test fixture.
final long MAX = new BigInteger( "2" ).pow( 32 ).longValue() - 1;
final long h = MAX;
final long oldH = MAX;
final Long lastUnackedX = null;
// Exec... |
@VisibleForTesting
List<String> getIpAddressFields(Message message) {
return message.getFieldNames()
.stream()
.filter(e -> (!enforceGraylogSchema || ipAddressFields.containsKey(e))
&& !e.startsWith(Message.INTERNAL_FIELD_PREFIX))
.coll... | @Test
public void testGetIpAddressFieldsEnforceGraylogSchemaFalse() {
GeoIpResolverConfig conf = config.toBuilder().enforceGraylogSchema(false).build();
final GeoIpResolverEngine engine = new GeoIpResolverEngine(geoIpVendorResolverService, conf, s3GeoIpFileService, metricRegistry);
Map<Str... |
public static String escape(final String raw) {
if (raw == null) {
return null;
}
final String escapedCurlyBrackets = CURLY_BRACKET_ESCAPE.matcher(raw).replaceAll("\\\\$1\\}");
return URL_ESCAPE.matcher(escapedCurlyBrackets).replaceAll("\\\\$1");
} | @Test
public void shouldBeRobustAtEscaping() {
assertThat(MvelHelper.escape(null)).isNull();
assertThat(MvelHelper.escape("")).isEmpty();
assertThat(MvelHelper.escape(" ")).isEqualTo(" ");
} |
@Override
public void putTransient(K key, V value, long ttl, TimeUnit timeunit) {
map.putTransient(key, value, ttl, timeunit);
} | @Test
public void testPutTransient() {
adapter.putTransient(42, "value", 1000, TimeUnit.MILLISECONDS);
String value = map.get(42);
if (value != null) {
assertEquals("value", value);
sleepMillis(1100);
assertNull(map.get(42));
}
} |
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 concatenatesClassNamesWithStringsToFormADottedName() {
assertThat(name(MetricRegistryTest.class, "one", "two"))
.isEqualTo("com.codahale.metrics.MetricRegistryTest.one.two");
} |
static void scan(Class<?> aClass, BiConsumer<Method, Annotation> consumer) {
// prevent unnecessary checking of Object methods
if (Object.class.equals(aClass)) {
return;
}
if (!isInstantiable(aClass)) {
return;
}
for (Method method : safelyGetMeth... | @Test
void loadGlue_fails_when_class_is_not_method_declaring_class() {
InvalidMethodException exception = assertThrows(InvalidMethodException.class,
() -> MethodScanner.scan(ExtendedSteps.class, backend));
assertThat(exception.getMessage(), is(
"You're not allowed to extend c... |
public static void doRegister(final String json, final String url, final String type, final String accessToken) throws IOException {
if (StringUtils.isBlank(accessToken)) {
LOGGER.error("{} client register error accessToken is null, please check the config : {} ", type, json);
return;
... | @Test
public void testDoRegisterWhenError() throws IOException {
when(okHttpTools.post(url, json)).thenReturn("Error parameter!");
Headers headers = new Headers.Builder().add(Constants.X_ACCESS_TOKEN, accessToken).build();
when(okHttpTools.post(url, json, headers)).thenReturn("Error paramete... |
@SuppressWarnings("unchecked")
public static <S, F> S visit(final Schema schema, final Visitor<S, F> visitor) {
final BiFunction<Visitor<?, ?>, Schema, Object> handler = HANDLER.get(schema.type());
if (handler == null) {
throw new UnsupportedOperationException("Unsupported schema type: " + schema.type()... | @Test
public void shouldThrowByDefaultFromStructured() {
// Given:
visitor = new Visitor<String, Integer>() {
@Override
public String visitPrimitive(final Schema schema) {
return null;
}
};
structuredSchemas().forEach(schema -> {
try {
// When:
SchemaW... |
public static Builder builder() {
return new Builder();
} | @Test
public void testBuilder_missingValues() throws CacheDirectoryCreationException {
// Target image is missing
try {
BuildContext.builder()
.setBaseImageConfiguration(
ImageConfiguration.builder(Mockito.mock(ImageReference.class)).build())
.setBaseImageLayersCacheDir... |
@Override
public PMML_MODEL getPMMLModelType() {
return PMML_MODEL_TYPE;
} | @Test
void getPMMLModelType() {
assertThat(PROVIDER.getPMMLModelType()).isEqualTo(PMML_MODEL.MINING_MODEL);
} |
@Override
public String getNString(final int columnIndex) throws SQLException {
return getString(columnIndex);
} | @Test
void assertGetNStringWithColumnIndex() throws SQLException {
when(mergeResultSet.getValue(1, String.class)).thenReturn("value");
assertThat(shardingSphereResultSet.getNString(1), is("value"));
} |
@Override
public T getValue() {
return value;
} | @Test
public void newSettableGaugeWithDefaultReturnsDefault() {
DefaultSettableGauge<String> gauge = new DefaultSettableGauge<>("default");
assertThat(gauge.getValue()).isEqualTo("default");
} |
@Nullable
@Override
public byte[] chunk(@NonNull final byte[] message,
@IntRange(from = 0) final int index,
@IntRange(from = 20) final int maxLength) {
final int offset = index * maxLength;
final int length = Math.min(maxLength, message.length - offset);
if (length <= 0)
return null;
final by... | @Test
public void chunk_23() {
final int MTU = 23;
final DefaultMtuSplitter splitter = new DefaultMtuSplitter();
final byte[] result = splitter.chunk(text.getBytes(), 1, MTU - 3);
assertArrayEquals(text.substring(MTU - 3, 2 * (MTU - 3)).getBytes(), result);
} |
public static BasicAuthorizationHeader fromString(final String header) throws InvalidAuthorizationHeaderException {
try {
if (StringUtils.isBlank(header)) {
throw new InvalidAuthorizationHeaderException("Blank header");
}
final int spaceIndex = header.indexOf(' ');
if (spaceIndex =... | @Test
void fromString() throws InvalidAuthorizationHeaderException {
{
final BasicAuthorizationHeader header =
BasicAuthorizationHeader.fromString("Basic YWxhZGRpbjpvcGVuc2VzYW1l");
assertEquals("aladdin", header.getUsername());
assertEquals("opensesame", header.getPassword());
... |
public PrivateKey convertPrivateKey(final String privatePemKey) {
StringReader keyReader = new StringReader(privatePemKey);
try {
PrivateKeyInfo privateKeyInfo = PrivateKeyInfo
.getInstance(new PEMParser(keyReader).readObject());
return new JcaPEMKeyConverter... | @Test
void givenMalformedPrivateKey_whenConvertPrivateKey_thenThrowRuntimeException() {
// Given
String malformedPrivatePemKey = "-----BEGIN PRIVATE KEY-----\n" +
"malformedkey\n" +
"-----END PRIVATE KEY-----";
// When & Then
assertThatThrownBy(() -> ... |
@Override
public List<ValidationMessage> validate(ValidationContext context) {
return context.query().tokens().stream()
.filter(this::isInvalidOperator)
.map(token -> {
final String errorMessage = String.format(Locale.ROOT, "Query contains invalid operator... | @Test
void testLowercaseNegation() {
final ValidationContext context = TestValidationContext.create("not(foo:bar)")
.build();
final List<ValidationMessage> messages = sut.validate(context);
assertThat(messages.size()).isEqualTo(1);
final ValidationMessage message = me... |
Object getEventuallyWeightedResult(Object rawObject, MULTIPLE_MODEL_METHOD multipleModelMethod,
double weight) {
switch (multipleModelMethod) {
case MAJORITY_VOTE:
case MODEL_CHAIN:
case SELECT_ALL:
case SELECT_FIRST:
... | @Test
void getEventuallyWeightedResultValueWeightNumber() {
final Integer rawObject = 24;
final double weight = 2.23;
VALUE_WEIGHT_METHODS.forEach(multipleModelMethod -> {
Object retrieved = evaluator.getEventuallyWeightedResult(rawObject, multipleModelMethod, weight);
... |
public static Bech32Data decode(final String str) throws AddressFormatException {
boolean lower = false, upper = false;
if (str.length() < 8)
throw new AddressFormatException.InvalidDataLength("Input too short: " + str.length());
if (str.length() > 90)
throw new AddressFo... | @Test(expected = AddressFormatException.InvalidChecksum.class)
public void decode_invalidNetwork() {
Bech32.decode("A12UEL5X");
} |
public static String truncateUtf8(String str, int maxBytes) {
Charset charset = StandardCharsets.UTF_8;
//UTF-8编码单个字符最大长度4
return truncateByByteLength(str, charset, maxBytes, 4, true);
} | @Test
public void truncateUtf8Test() {
final String str = "这是This一段中英文";
String ret = StrUtil.truncateUtf8(str, 12);
assertEquals("这是Thi...", ret);
ret = StrUtil.truncateUtf8(str, 13);
assertEquals("这是This...", ret);
ret = StrUtil.truncateUtf8(str, 14);
assertEquals("这是This...", ret);
ret = StrUtil.... |
@PublicAPI(usage = ACCESS)
public static <T extends Comparable<T>> DescribedPredicate<T> greaterThanOrEqualTo(T value) {
return new GreaterThanOrEqualToPredicate<>(value);
} | @Test
public void greaterThanOrEqualTo_works() {
assertThat(greaterThanOrEqualTo(5))
.accepts(6)
.hasDescription("greater than or equal to '5'")
.accepts(5)
.rejects(4);
assertThat(greaterThanOrEqualTo(Foo.SECOND))
.rej... |
public RouteResult<T> route(HttpMethod method, String path) {
return route(method, path, Collections.emptyMap());
} | @Test
void testIgnoreSlashesAtBothEnds() {
assertThat(router.route(GET, "articles").target()).isEqualTo("index");
assertThat(router.route(GET, "/articles").target()).isEqualTo("index");
assertThat(router.route(GET, "//articles").target()).isEqualTo("index");
assertThat(router.route(G... |
public static Request.Builder buildRequestBuilder(final String url, final Map<String, ?> form,
final HTTPMethod method) {
switch (method) {
case GET:
return new Request.Builder()
.url(buildHttpUrl(url, form))
.get();
case HE... | @Test
public void buildRequestBuilderForDELETETest() {
Request.Builder builder = HttpUtils.buildRequestBuilder(TEST_URL, formMap, HttpUtils.HTTPMethod.DELETE);
Assert.assertNotNull(builder);
Assert.assertNotNull(builder.build().body());
Assert.assertEquals(builder.build().method(), H... |
@VisibleForTesting
void put(DirectoryEntry entry) {
put(entry, false);
} | @Test
public void testPutEntryForExistingNameIsIllegal() {
dir.put(entry("foo"));
try {
dir.put(entry("foo"));
fail();
} catch (IllegalArgumentException expected) {
}
} |
@Override
public void enableAutoTrack(List<AutoTrackEventType> eventTypeList) {
} | @Test
public void testEnableAutoTrack() {
List<SensorsDataAPI.AutoTrackEventType> types = new ArrayList<>();
types.add(SensorsDataAPI.AutoTrackEventType.APP_START);
types.add(SensorsDataAPI.AutoTrackEventType.APP_END);
mSensorsAPI.enableAutoTrack(types);
Assert.assertFalse(mS... |
@Override
@SuppressWarnings("unchecked")
public TypeSerializer<T> restoreSerializer() {
final int numFields = snapshotData.getFieldSerializerSnapshots().size();
final ArrayList<Field> restoredFields = new ArrayList<>(numFields);
final ArrayList<TypeSerializer<?>> restoredFieldSerializer... | @Test
void testRestoreSerializerWithNewFields() {
final PojoSerializerSnapshot<TestPojo> testSnapshot =
buildTestSnapshot(Collections.singletonList(HEIGHT_FIELD));
final TypeSerializer<TestPojo> restoredSerializer = testSnapshot.restoreSerializer();
assertThat(restoredSerial... |
@VisibleForTesting
void clearStartTimeCache() {
startTimeWriteCache.clear();
startTimeReadCache.clear();
} | @Test
public void testGetSingleEntity() throws IOException {
super.testGetSingleEntity();
((LeveldbTimelineStore)store).clearStartTimeCache();
super.testGetSingleEntity();
loadTestEntityData();
} |
boolean handleCorruption(final Set<TaskId> corruptedTasks) {
final Set<TaskId> activeTasks = new HashSet<>(tasks.activeTaskIds());
// We need to stop all processing, since we need to commit non-corrupted tasks as well.
maybeLockTasks(activeTasks);
final Set<Task> corruptedActiveTasks =... | @Test
public void shouldNotCommitNonCorruptedRestoringActiveTasksAndNotCommitRunningStandbyTasksWithStateUpdaterEnabled() {
final StreamTask activeRestoringTask = statefulTask(taskId00, taskId00ChangelogPartitions)
.withInputPartitions(taskId00Partitions)
.inState(State.RESTORING).bu... |
void setRequestPath(ServletRequest req, final String destinationPath) {
if (req instanceof AwsProxyHttpServletRequest) {
((AwsProxyHttpServletRequest) req).getAwsProxyRequest().setPath(dispatchTo);
return;
}
if (req instanceof AwsHttpApiV2ProxyHttpServletRequest) {
... | @Test
void setPathForWrappedRequestWithoutGatewayEvent_forwardByPath_throwsException() {
AwsProxyRequest proxyRequest = new AwsProxyRequestBuilder("/hello", "GET").build();
AwsProxyHttpServletRequest servletRequest = new AwsProxyHttpServletRequest(proxyRequest, new MockLambdaContext(), null);
... |
@Override
public void updateTableSchema(String tableName, MessageType schema, SchemaDifference schemaDifference) {
try (RestEmitter emitter = config.getRestEmitter()) {
DatahubResponseLogger responseLogger = new DatahubResponseLogger();
MetadataChangeProposalWrapper schemaChange = createSchemaMetadata... | @Test
public void testUpdateTableSchemaInvokesRestEmitter() throws IOException {
Properties props = new Properties();
props.put(META_SYNC_PARTITION_EXTRACTOR_CLASS.key(), DummyPartitionValueExtractor.class.getName());
props.put(META_SYNC_BASE_PATH.key(), tableBasePath);
Mockito.when(
restEmit... |
public <OutputT extends @NonNull Object> CsvIOParse<T> withCustomRecordParsing(
String fieldName, SerializableFunction<String, OutputT> customRecordParsingFn) {
Map<String, SerializableFunction<String, Object>> customProcessingMap =
getConfigBuilder().getOrCreateCustomProcessingMap();
customProc... | @Test
public void givenSingleCustomParsingLambda_parsesPOJOs() {
PCollection<String> records =
csvRecords(
pipeline,
"instant,instantList",
"2024-01-23T10:00:05.000Z,10-00-05-2024-01-23;12-59-59-2024-01-24");
TimeContaining want =
timeContaining(
... |
@Override
public OAuth2AccessTokenDO getAccessToken(String accessToken) {
// 优先从 Redis 中获取
OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenRedisDAO.get(accessToken);
if (accessTokenDO != null) {
return accessTokenDO;
}
// 获取不到,从 MySQL 中获取
accessToken... | @Test
public void testGetAccessToken() {
// mock 数据(访问令牌)
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class)
.setExpiresTime(LocalDateTime.now().plusDays(1));
oauth2AccessTokenMapper.insert(accessTokenDO);
// 准备参数
String accessToken = ac... |
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (readError == null) {
try {
processSymbols(lineBuilder);
} catch (RangeOffsetConverter.RangeOffsetConverterException e) {
readError = new ReadError(Data.SYMBOLS, lineBuilder.getLine());
LOG.w... | @Test
public void symbol_declaration_should_be_sorted_by_line() {
SymbolsLineReader symbolsLineReader = newReader(
newSymbol(
newSingleLineTextRangeWithExpectedLabel(LINE_2, OFFSET_0, OFFSET_1, RANGE_LABEL_1),
newSingleLineTextRangeWithExpectedLabel(LINE_3, OFFSET_2, OFFSET_3, RANGE_LABEL_2)... |
@Override
public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
switch (newRole) {
case MASTER:
controller.setRole(dpid(deviceId.uri()), RoleState.MASTER);
break;
case STANDBY:
controller.setRole(dpid(deviceId.uri()), Rol... | @Test
public void roleChanged() {
provider.roleChanged(DID1, MASTER);
assertEquals("Should be MASTER", RoleState.MASTER, controller.roleMap.get(DPID1));
provider.roleChanged(DID1, STANDBY);
assertEquals("Should be EQUAL", RoleState.EQUAL, controller.roleMap.get(DPID1));
provi... |
public static boolean matchIpRange(String pattern, String host, int port) throws UnknownHostException {
if (pattern == null || host == null) {
throw new IllegalArgumentException(
"Illegal Argument pattern or hostName. Pattern:" + pattern + ", Host:" + host);
}
pat... | @Test
void testMatchIpv6WithIpPort() throws UnknownHostException {
assertTrue(NetUtils.matchIpRange("[234e:0:4567::3d:ee]", "234e:0:4567::3d:ee", 8090));
assertTrue(NetUtils.matchIpRange("[234e:0:4567:0:0:0:3d:ee]", "234e:0:4567::3d:ee", 8090));
assertTrue(NetUtils.matchIpRange("[234e:0:4567... |
public Site addCookie(String name, String value) {
defaultCookies.put(name, value);
return this;
} | @Test
public void addCookieTest(){
Site site=Site.me().setDefaultCharset(StandardCharsets.UTF_8.name());
site.addCookie("cookieDefault","cookie-webmagicDefault");
String firstDomain="example.com";
String secondDomain="exampleCopy.com";
site.addCookie(firstDomain, "cookie", "c... |
Optional<TextRange> mapRegion(@Nullable Region region, InputFile file) {
if (region == null) {
return Optional.empty();
}
int startLine = Objects.requireNonNull(region.getStartLine(), "No start line defined for the region.");
int endLine = Optional.ofNullable(region.getEndLine()).orElse(startLine)... | @Test
public void mapRegion_whenStartEndLinesDefined() {
Region fullRegion = mockRegion(null, null, 3, 8);
Optional<TextRange> optTextRange = regionMapper.mapRegion(fullRegion, INPUT_FILE);
assertThat(optTextRange).isPresent();
TextRange textRange = optTextRange.get();
assertThat(textRange.start... |
public void verifyPassword(AttendeePassword other) {
this.password.verifyPassword(other);
} | @DisplayName("참가자의 비밀번호가 일치하지 않으면 예외를 발생시킨다.")
@Test
void throwsExceptionIfPasswordDoesNotMatch() {
Meeting meeting = MeetingFixture.DINNER.create();
Attendee attendee = new Attendee(meeting, "jazz", "1111", Role.GUEST);
AttendeePassword other = new AttendeePassword("1234");
ass... |
static ParseResult parse(String expression, NameValidator validator, ClassHelper helper) {
ParseResult result = new ParseResult();
try {
Parser parser = new Parser(new Scanner("ignore", new StringReader(expression)));
Java.Atom atom = parser.parseConditionalExpression();
... | @Test
public void protectUsFromStuff() {
NameValidator allNamesInvalid = s -> false;
for (String toParse : Arrays.asList(
"",
"new Object()",
"java.lang.Object",
"Test.class",
"new Object(){}.toString().length",
... |
@Override
protected Mono<Void> doFilter(final ServerWebExchange exchange) {
return dispatcherHandler.handle(exchange);
} | @Test
public void testDoFilter() {
ServerWebExchange webExchange =
MockServerWebExchange.from(MockServerHttpRequest
.post("http://localhost:8080/"));
Mono<Void> filter = fallbackFilter.doFilter(webExchange);
StepVerifier.create(filter).verifyComplete()... |
public static String calculateSha256Hex(@Nonnull byte[] data) throws NoSuchAlgorithmException {
return calculateSha256Hex(data, data.length);
} | @Test
public void test_exception_whenDirectory() {
Path path = Paths.get("src", "test", "resources");
assertThrows(IOException.class, () -> Sha256Util.calculateSha256Hex(path));
} |
@Override
public boolean hasContentLength() {
switch (super.getVersion()) {
case DEFAULT_VERSION:
return true;
default:
return true;
}
} | @Test
public void testHasContentLength() {
assertTrue(verDefault.hasContentLength());
assertTrue(verCurrent.hasContentLength());
} |
@Override
public Buffer allocate() {
return allocate(this.pageSize);
} | @Test
public void testDoubleRelease() throws Exception {
final PooledBufferAllocatorImpl allocator = new PooledBufferAllocatorImpl(4096);
final Buffer buffer = allocator.allocate(10000);
buffer.release();
buffer.release(); // To printStackTrace of the first release, but no errors.
... |
@Override
public Optional<FieldTypes> get(final String fieldName) {
return Optional.ofNullable(get(ImmutableSet.of(fieldName)).get(fieldName));
} | @Test
public void getMultipleFields() {
dbService.save(createDto("graylog_0", "abc", Collections.emptySet()));
dbService.save(createDto("graylog_1", "xyz", Collections.emptySet()));
dbService.save(createDto("graylog_2", "xyz", of(
FieldTypeDTO.create("yolo1", "boolean")
... |
@Override
public void smoke() {
tobacco.smoke(this);
} | @Test
void testSmokeEveryThingThroughInjectionFramework() {
List<Class<? extends Tobacco>> tobaccos = List.of(
OldTobyTobacco.class,
RivendellTobacco.class,
SecondBreakfastTobacco.class
);
// Configure the tobacco in the injection framework ...
// ... and create a new wizard ... |
public static Labels fromString(String stringLabels) throws IllegalArgumentException {
Map<String, String> labels = new HashMap<>();
try {
if (stringLabels != null && !stringLabels.isEmpty()) {
String[] labelsArray = stringLabels.split(",");
for (String label... | @Test
public void testParseEmptyLabels() {
String validLabels = "";
assertThat(Labels.fromString(validLabels), is(Labels.EMPTY));
} |
Iterator<StructSpec> commonStructs() {
return new Iterator<StructSpec>() {
private final Iterator<String> iter = commonStructNames.iterator();
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public ... | @Test
public void testCommonStructs() throws Exception {
MessageSpec testMessageSpec = MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList(
"{",
" \"type\": \"request\",",
" \"name\": \"LeaderAndIsrRequest\",",
" \"validVersi... |
public static RSAPublicKey parseRSAPublicKey(String pem) throws ServletException {
String fullPem = PEM_HEADER + pem + PEM_FOOTER;
PublicKey key = null;
try {
CertificateFactory fact = CertificateFactory.getInstance("X.509");
ByteArrayInputStream is = new ByteArrayInputStream(
fullPem.... | @Test
public void testInvalidPEMWithHeaderAndFooter() throws Exception {
String pem = "-----BEGIN CERTIFICATE-----\n"
+ "MIICOjCCAaOgAwIBAgIJANXi/oWxvJNzMA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNVBAYTAlVTMQ0w"
+ "CwYDVQQIEwRUZXN0MQ0wCwYDVQQHEwRUZXN0MQ8wDQYDVQQKEwZIYWRvb3AxDTALBgNVBAsTBFRl"
+ "c3QxEjA... |
@Override
public NativeEntity<NotificationDto> createNativeEntity(Entity entity, Map<String, ValueReference> parameters, Map<EntityDescriptor, Object> nativeEntities, String username) {
if (entity instanceof EntityV1) {
final User user = Optional.ofNullable(userService.load(username)).orElseThro... | @Test
public void createNativeEntity() {
final EntityV1 entityV1 = createTestEntity();
final JobDefinitionDto jobDefinitionDto = mock(JobDefinitionDto.class);
when(jobDefinitionService.save(any(JobDefinitionDto.class))).thenReturn(jobDefinitionDto);
final UserImpl kmerzUser = new Us... |
@Override
public void importData(JsonReader reader) throws IOException {
logger.info("Reading configuration for 1.2");
// this *HAS* to start as an object
reader.beginObject();
while (reader.hasNext()) {
JsonToken tok = reader.peek();
switch (tok) {
case NAME:
String name = reader.nextName();... | @Test
public void testImportAuthenticationHolders() throws IOException {
OAuth2Request req1 = new OAuth2Request(new HashMap<String, String>(), "client1", new ArrayList<GrantedAuthority>(),
true, new HashSet<String>(), new HashSet<String>(), "http://foo.com",
new HashSet<String>(), null);
Authentication moc... |
public long rangeSize() {
long result = 0;
Sequence sequence = getHead();
while (sequence != null) {
result += sequence.range();
sequence = sequence.getNext();
}
return result;
} | @Test
public void testRangeSize() {
SequenceSet set = new SequenceSet();
set.add(1);
assertEquals(1, set.rangeSize());
set.add(10);
set.add(20);
assertEquals(3, set.rangeSize());
set.clear();
assertEquals(0, set.rangeSize());
} |
static void enableStatisticManagementOnNodes(HazelcastClientInstanceImpl client, String cacheName,
boolean statOrMan, boolean enabled) {
Collection<Member> members = client.getClientClusterService().getMemberList();
Collection<Future> futures = new ArrayL... | @Test(expected = IllegalArgumentException.class)
public void testEnableStatisticManagementOnNodes_sneakyThrowsException() {
Member member = mock(Member.class);
when(member.getUuid()).thenThrow(new IllegalArgumentException("expected"));
Collection<Member> members = singletonList(member);
... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStart,
final Range<Instant> windowEnd,
final Optional<Position> position
) {
try {
final WindowRangeQuery<GenericKey, GenericRow> query = WindowR... | @Test
public void shouldReturnEmptyIfKeyNotPresent() {
// When:
final Iterator<WindowedRow> rowIterator = table.get(
A_KEY, PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS).rowIterator;
// Then:
assertThat(rowIterator.hasNext(), is(false));
} |
@Override
public void validate(Context context) {
if (! context.deployState().isHosted()) return;
if (context.model().getAdmin().getApplicationType() != ApplicationType.DEFAULT) return;
for (ContainerCluster<?> cluster : context.model().getContainerClusters().values()) {
if (clu... | @Test
void app_without_athenz_in_deployment_fails_validation() throws Exception {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
DeployState deployState = deployState(servicesXml(), deploymentXml(false));
VespaModel model = new VespaModel(new NullConfigMo... |
public static Properties getProperties(File file) throws AnalysisException {
try (BufferedReader utf8Reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
return getProperties(utf8Reader);
} catch (IOException | IllegalArgumentException e) {
throw new Analysi... | @Test
public void getProperties_should_properly_parse_multiline_description() throws IOException {
String payload = "Metadata-Version: 1.0\r\n"
+ "Description: This is the first line\r\n"
+ " | and this the second\r\n"
+ " ... |
@Override
public void profileIncrement(Map<String, ? extends Number> properties) {
} | @Test
public void profileIncrement() {
mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
Assert.fail();
return false;
}
});
... |
@Override
public boolean tryFence(HAServiceTarget target, String argsStr)
throws BadFencingConfigurationException {
Args args = new Args(argsStr);
InetSocketAddress serviceAddr = target.getAddress();
String host = serviceAddr.getHostName();
Session session;
try {
session = create... | @Test(timeout=20000)
public void testFence() throws BadFencingConfigurationException {
Assume.assumeTrue(isConfigured());
Configuration conf = new Configuration();
conf.set(SshFenceByTcpPort.CONF_IDENTITIES_KEY, TEST_KEYFILE);
SshFenceByTcpPort fence = new SshFenceByTcpPort();
fence.setConf(conf);... |
@Override
public List<String> listPartitionNamesByFilter(String catName, String dbName, String tblName,
GetPartitionsArgs args) throws MetaException, NoSuchObjectException {
catName = normalizeIdentifier(catName);
dbName = normalizeIdentifier(dbName);
tblName = normalizeIdentifier(tblName);
MT... | @Test
public void testListPartitionNamesByFilter() throws Exception {
Database db1 = new DatabaseBuilder()
.setName(DB1)
.setDescription("description")
.setLocation("locationurl")
.build(conf);
try (AutoCloseable c = deadline()) {
objectStore.createDatabase(db1);
}
... |
@Override
public void pushMsgToRuleEngine(TopicPartitionInfo tpi, UUID msgId, ToRuleEngineMsg msg, TbQueueCallback callback) {
log.trace("PUSHING msg: {} to:{}", msg, tpi);
producerProvider.getRuleEngineMsgProducer().send(tpi, new TbProtoQueueMsg<>(msgId, msg), callback);
toRuleEngineMsgs.in... | @Test
public void testPushMsgToRuleEngineUseQueueFromMsgIsFalse() {
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> tbREQueueProducer = mock(TbQueueProducer.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TenantId tenantId = TenantId.fromUUID(UUID.fromStrin... |
@Override
public InstancePort instancePort(MacAddress macAddress) {
checkNotNull(macAddress, ERR_NULL_MAC_ADDRESS);
return instancePortStore.instancePorts().stream()
.filter(port -> port.macAddress().equals(macAddress))
.findFirst().orElse(null);
} | @Test
public void testGetInstancePortByIpAndNetId() {
createBasicInstancePorts();
InstancePort port = target.instancePort(IP_ADDRESS_1, NETWORK_ID_1);
assertEquals("Instance port did not match", port, instancePort1);
} |
@Override
public boolean supports(Job job) {
JobDetails jobDetails = job.getJobDetails();
return jobDetails.hasStaticFieldName();
} | @Test
void supportsJobIfJobIsStaticMethodCall() {
Job job = anEnqueuedJob()
.withJobDetails(systemOutPrintLnJobDetails("This is a test"))
.build();
assertThat(backgroundStaticFieldJobWithoutIocRunner.supports(job)).isTrue();
} |
@Override
public V put(K key, V value, long ttl, TimeUnit unit) {
return get(putAsync(key, value, ttl, unit));
} | @Test
public void testEntryUpdate() throws InterruptedException {
RMapCache<Integer, Integer> map = redisson.getMapCache("simple");
map.put(1, 1, 1, TimeUnit.SECONDS);
assertThat(map.get(1)).isEqualTo(1);
Thread.sleep(1000);
assertThat(map.put(1, 1, 0, TimeUnit.SECONDS)).is... |
void unassignStandby(final TaskId task) {
final Set<TaskId> taskIds = assignedStandbyTasks.taskIds();
if (!taskIds.contains(task)) {
throw new IllegalArgumentException("Tried to unassign standby task " + task + ", but it is not currently assigned: " + this);
}
taskIds.remove(... | @Test
public void shouldRefuseToUnassignNotAssignedStandbyTask() {
final ClientState clientState = new ClientState(1);
assertThrows(IllegalArgumentException.class, () -> clientState.unassignStandby(TASK_0_0));
} |
@Override
public <I> void foreach(List<I> data, SerializableConsumer<I> consumer, int parallelism) {
data.stream().forEach(throwingForeachWrapper(consumer));
} | @Test
public void testForeach() {
List<Integer> mapList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> result = new ArrayList<>(10);
context.foreach(mapList, result::add, 2);
Assertions.assertEquals(result.size(), mapList.size());
Assertions.assertTrue(result.containsAll(mapList));... |
@Override
public void removeLoadBalancer(String name) {
checkArgument(name != null, ERR_NULL_LOAD_BALANCER_NAME);
synchronized (this) {
if (isLoadBalancerInUse(name)) {
final String error = String.format(MSG_LOAD_BALANCER, name, ERR_IN_USE);
throw new Ille... | @Test(expected = IllegalArgumentException.class)
public void testRemoveLoadBalancerWithNull() {
target.removeLoadBalancer(null);
} |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
if(containerService.isContainer(file)) {
try {
if(log.isDebugEnabled()) {
... | @Test
public void testFindUnknownBucket() throws Exception {
final Path test = new Path(UUID.randomUUID().toString(), EnumSet.of(Path.Type.volume, Path.Type.directory));
assertFalse(new S3FindFeature(session, new S3AccessControlListFeature(session)).find(test));
} |
@Override
public void captureData(PrintWriter writer) {
writer.println("<html>");
writer.println("<h1>Channelz</h1>");
appendTopChannels(writer);
writer.println("</html>");
} | @Test
public void testRendersOnlyWindmillChannels() throws UnsupportedEncodingException {
String windmill1 = "WindmillHost1";
String windmill2 = "WindmillHost2";
String nonWindmill1 = "NonWindmillHost1";
String someOtherHost1 = "SomeOtherHost2";
ManagedChannel[] unusedChannels =
new Manage... |
public void union(Block block)
{
currentBlockIndex++;
ensureBlocksCapacity(currentBlockIndex + 1);
blocks[currentBlockIndex] = block;
int positionCount = block.getPositionCount();
int[] positions = new int[positionCount];
// Add the elements to the hash table. Since... | @Test
public void testExceptWithDistinctValues()
{
OptimizedTypedSet typedSet = new OptimizedTypedSet(BIGINT, BIGINT_DISTINCT_METHOD_HANDLE, POSITIONS_PER_PAGE);
Block block = createLongSequenceBlock(0, POSITIONS_PER_PAGE - 1).appendNull();
typedSet.union(block);
testExcept(typ... |
@Override
public void calculate() {
setValue(this.total / getDurationInMinute());
} | @Test
public void testCalculate() {
long time1 = 1597113318673L;
long time2 = 1597113447737L;
function.accept(MeterEntity.newService("sum_sync_time", Layer.GENERAL), time1);
function.accept(MeterEntity.newService("sum_sync_time", Layer.GENERAL), time2);
function.calculate();
... |
public int add(Object o) {
HollowTypeMapper typeMapper = getTypeMapper(o.getClass(), null, null);
return typeMapper.write(o);
} | @Test
public void testEnumAndInlineClass() throws IOException {
HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine);
mapper.add(TestEnum.ONE);
mapper.add(TestEnum.TWO);
mapper.add(TestEnum.THREE);
roundTripSnapshot();
HollowPrimaryKeyIndex idx = ne... |
@Override
public ExecuteContext doAfter(ExecuteContext context) {
final Object result = context.getResult();
if (isValidResult(result)) {
if (result == null) {
RegisterContext.INSTANCE.compareAndSet(true, false);
return context;
}
l... | @Test
public void doAfter() throws Exception {
REGISTER_CONFIG.setEnableSpringRegister(true);
REGISTER_CONFIG.setOpenMigration(true);
final ExecuteContext context = buildContext();
RegisterContext.INSTANCE.setAvailable(true);
interceptor.after(context);
Assert.assertF... |
public T maxInitialLineLength(int value) {
if (value <= 0) {
throw new IllegalArgumentException("maxInitialLineLength must be strictly positive");
}
this.maxInitialLineLength = value;
return get();
} | @Test
void maxInitialLineLengthBadValues() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> conf.maxInitialLineLength(0))
.as("rejects 0")
.withMessage("maxInitialLineLength must be strictly positive");
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrow... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.