focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static synchronized @Nonnull Map<String, Object> loadYamlFile(File file)
throws Exception {
try (FileInputStream inputStream = new FileInputStream((file))) {
Map<String, Object> yamlResult =
(Map<String, Object>) loader.loadFromInputStream(inputStream);
... | @Test
void testLoadEmptyYamlFile() throws Exception {
File confFile = new File(tmpDir, "test.yaml");
confFile.createNewFile();
assertThat(YamlParserUtils.loadYamlFile(confFile)).isEmpty();
} |
@Override
public QuoteCharacter getQuoteCharacter() {
return QuoteCharacter.QUOTE;
} | @Test
void assertGetQuoteCharacter() {
assertThat(dialectDatabaseMetaData.getQuoteCharacter(), is(QuoteCharacter.QUOTE));
} |
@Override
public void isEqualTo(@Nullable Object expected) {
@SuppressWarnings("UndefinedEquals") // method contract requires testing iterables for equality
boolean equal = Objects.equal(actual, expected);
if (equal) {
return;
}
// Fail but with a more descriptive message:
if (actual i... | @Test
public void nullEqualToSomething() {
expectFailureWhenTestingThat(null).isEqualTo(ImmutableList.of());
} |
public static <T extends Message> ProtoCoder<T> of(Class<T> protoMessageClass) {
return new ProtoCoder<>(protoMessageClass, ImmutableSet.of());
} | @Test
public void testCoderEncodeDecodeEqual() throws Exception {
MessageA value =
MessageA.newBuilder()
.setField1("hello")
.addField2(MessageB.newBuilder().setField1(true).build())
.addField2(MessageB.newBuilder().setField1(false).build())
.build();
Co... |
@Override
public boolean trySetPermits(int permits) {
return get(trySetPermitsAsync(permits));
} | @Test
public void testTrySetPermits() throws InterruptedException {
RSemaphore s = redisson.getSemaphore("test");
assertThat(s.trySetPermits(10)).isTrue();
assertThat(s.availablePermits()).isEqualTo(10);
assertThat(s.trySetPermits(15)).isFalse();
assertThat(s.availablePermits... |
@ScalarOperator(MULTIPLY)
@SqlType(StandardTypes.INTEGER)
public static long multiply(@SqlType(StandardTypes.INTEGER) long left, @SqlType(StandardTypes.INTEGER) long right)
{
try {
return Math.multiplyExact((int) left, (int) right);
}
catch (ArithmeticException e) {
... | @Test
public void testMultiply()
{
assertFunction("INTEGER'37' * INTEGER'37'", INTEGER, 37 * 37);
assertFunction("INTEGER'37' * INTEGER'17'", INTEGER, 37 * 17);
assertFunction("INTEGER'17' * INTEGER'37'", INTEGER, 17 * 37);
assertFunction("INTEGER'17' * INTEGER'17'", INTEGER, 17 ... |
@Nullable
public static TNetworkAddress getComputeNodeHost(ImmutableMap<Long, ComputeNode> computeNodes,
Reference<Long> computeNodeIdRef) {
ComputeNode node = getComputeNode(computeNodes);
if (node != null) {
computeNodeIdRef.setRef(n... | @Test
public void testNoAliveComputeNode() {
ImmutableMap.Builder<Long, ComputeNode> builder = ImmutableMap.builder();
for (int i = 0; i < 6; i++) {
ComputeNode node = new ComputeNode(i, "address" + i, 0);
node.setAlive(false);
builder.put(node.getId(), node);
... |
public FEELFnResult<TemporalAmount> invoke(@ParameterName( "from" ) String val) {
if ( val == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));
}
try {
// try to parse as days/hours/minute/seconds
retu... | @Test
void invokeParamStringPeriod() {
FunctionTestUtil.assertResult(durationFunction.invoke("P2Y3M"), ComparablePeriod.of(2, 3, 0));
FunctionTestUtil.assertResult(durationFunction.invoke("P2Y3M4D"), ComparablePeriod.of(2, 3, 4));
} |
public int doWork()
{
final long nowNs = nanoClock.nanoTime();
cachedNanoClock.update(nowNs);
dutyCycleTracker.measureAndUpdate(nowNs);
final int workCount = commandQueue.drain(CommandProxy.RUN_TASK, Configuration.COMMAND_DRAIN_LIMIT);
final long shortSendsBefore = shortSen... | @Test
void shouldSendMultipleSetupFramesOnChannelWhenTimeoutWithoutStatusMessage()
{
sender.doWork();
assertThat(receivedFrames.size(), is(1));
nanoClock.advance(Configuration.PUBLICATION_SETUP_TIMEOUT_NS - 1);
sender.doWork();
nanoClock.advance(10);
sender.doWo... |
@Override
public double[] smoothDerivative(double[] input) {
if (input.length < weights.length) {
return averageDerivativeForVeryShortTrack(input);
}
double[] smoothed = new double[input.length];
int halfWindowFloored = weights.length / 2; // we want to exclude the cent... | @Test
public void Derivative_FromFakeTrackWithSymmetricOutliers_RemoveBumps() {
SavitzkyGolayFilter test = new SavitzkyGolayFilter(1.0);
double[] input = new double[]{
10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0,
13.0, 16.0, 13.0, // <-- outlier points make a symmetric "triang... |
@Override
public Object execute(String command, byte[]... args) {
for (Method method : this.getClass().getDeclaredMethods()) {
if (method.getName().equalsIgnoreCase(command)
&& Modifier.isPublic(method.getModifiers())
&& (method.getParameterTypes().len... | @Test
public void testExecute() {
Long s = (Long) connection.execute("ttl", "key".getBytes());
assertThat(s).isEqualTo(-2);
connection.execute("flushDb");
} |
static int getStringDisplayWidth(String str) {
int numOfFullWidthCh = (int) str.codePoints().filter(TableauStyle::isFullWidth).count();
return str.length() + numOfFullWidthCh;
} | @Test
void testStringDisplayWidth() {
List<String> data =
Arrays.asList(
"abcdefg,12345,ABC",
"to be or not to be that's a question.",
"这是一段中文",
"これは日本語をテストするための文です");
int[] expected = new... |
@Override
public String getOperationName(Exchange exchange, Endpoint endpoint) {
Map<String, String> queryParameters = toQueryParameters(endpoint.getEndpointUri());
return queryParameters.containsKey("operation")
? queryParameters.get("operation")
: super.getOperation... | @Test
public void testOperationName() {
String opName = "INDEX";
Endpoint endpoint = Mockito.mock(Endpoint.class);
Mockito.when(endpoint.getEndpointUri()).thenReturn("elasticsearch://local?operation="
+ opName + "&indexName=twitter&... |
public static boolean isOrHasCause(Throwable t, Class<?> classToFind) {
while (t != null && t.getCause() != t && !classToFind.isAssignableFrom(t.getClass())) {
t = t.getCause();
}
return t != null && classToFind.isAssignableFrom(t.getClass());
} | @Test
public void test_isOrHasCause_when_expectedTypeADeepCause_then_true() {
Throwable throwable = new TargetNotMemberException("");
for (int i = 0; i < 10; i++) {
throwable = new Exception(throwable);
}
assertTrue(isOrHasCause(throwable, TargetNotMemberException.class))... |
@Override
public Optional<AuthProperty> inferAuth(String registry) throws InferredAuthException {
Server server = getServerFromMavenSettings(registry);
if (server == null) {
return Optional.empty();
}
SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(server);
Setting... | @Test
public void testInferredAuth_decrypterFailure() {
try {
mavenSettingsServerCredentials.inferAuth("badServer");
Assert.fail();
} catch (InferredAuthException ex) {
MatcherAssert.assertThat(
ex.getMessage(),
CoreMatchers.startsWith("Unable to decrypt server(badServer)... |
@VisibleForTesting
ExportResult<MusicContainerResource> exportPlaylistItems(
TokensAndUrlAuthData authData,
IdOnlyContainerResource playlistData,
Optional<PaginationData> paginationData, UUID jobId)
throws IOException, InvalidTokenException, PermissionDeniedException, ParseException {
Stri... | @Test
public void exportPlaylistItemSubsequentSet()
throws IOException, InvalidTokenException, PermissionDeniedException, ParseException {
GooglePlaylistItem playlistItem = setUpSinglePlaylistItem("t1_isrc", "r1_icpn");
when(playlistItemExportResponse.getPlaylistItems())
.thenReturn(new GooglePl... |
@Override
public Iterator<E> iterator() {
return Iterators.transform(map.entrySet().iterator(), Map.Entry::getValue);
} | @Test
public void testIterator() {
ExtendedSet<TestValue> set = new ExtendedSet<>(Maps.newConcurrentMap());
TestValue val = new TestValue("foo", 1);
assertTrue(set.add(val));
TestValue nextval = new TestValue("goo", 2);
assertTrue(set.add(nextval));
assertTrue(set.con... |
@Override
public <R> RFuture<R> evalShaAsync(Mode mode, String shaDigest, ReturnType returnType, List<Object> keys, Object... values) {
return evalShaAsync(null, mode, codec, shaDigest, returnType, keys, values);
} | @Test
public void testEvalshaAsync() {
RScript s = redisson.getScript();
String res = s.scriptLoad("return redis.call('get', 'foo')");
Assertions.assertEquals("282297a0228f48cd3fc6a55de6316f31422f5d17", res);
redisson.getBucket("foo").set("bar");
String r = redisson.getScrip... |
@PatchMapping
public ResponseEntity<?> updateProduct(@PathVariable("productId") int productId,
@Valid @RequestBody UpdateProductPayload payload,
BindingResult bindingResult) throws BindException {
if (bindingResult.hasErro... | @Test
void updateProduct_RequestIsValid_ReturnsNoContent() throws BindException {
// given
var payload = new UpdateProductPayload("Новое название", "Новое описание");
var bindingResult = new MapBindingResult(Map.of(), "payload");
// when
var result = this.controller.updatePr... |
public <InputT, OutputT> DoFn<InputT, OutputT> get() throws Exception {
Thread currentThread = Thread.currentThread();
return (DoFn<InputT, OutputT>) outstanding.get(currentThread);
} | @Test
public void getMultipleCallsSingleSetupCall() throws Exception {
TestFn obtained = (TestFn) mgr.get();
TestFn secondObtained = (TestFn) mgr.get();
assertThat(obtained, theInstance(secondObtained));
assertThat(obtained.setupCalled, is(true));
assertThat(obtained.teardownCalled, is(false));
... |
@Override
public void validateDictDataList(String dictType, Collection<String> values) {
if (CollUtil.isEmpty(values)) {
return;
}
Map<String, DictDataDO> dictDataMap = CollectionUtils.convertMap(
dictDataMapper.selectByDictTypeAndValues(dictType, values), DictDat... | @Test
public void testValidateDictDataList_success() {
// mock 数据
DictDataDO dictDataDO = randomDictDataDO().setStatus(CommonStatusEnum.ENABLE.getStatus());
dictDataMapper.insert(dictDataDO);
// 准备参数
String dictType = dictDataDO.getDictType();
List<String> values = si... |
public Optional<JobTriggerDto> cancelTriggerByQuery(Bson query) {
final var update = set(FIELD_IS_CANCELLED, true);
return Optional.ofNullable(collection.findOneAndUpdate(query, update));
} | @Test
@MongoDBFixtures("locked-job-triggers.json")
public void cancelTriggerByQuery() {
// Must return an empty Optional if the query didn't match any trigger
assertThat(dbJobTriggerService.cancelTriggerByQuery(DBQuery.is("foo", "bar"))).isEmpty();
final JobTriggerDto lockedTrigger = db... |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema != null && schema.type() != Schema.Type.BYTES)
throw new DataException("Invalid schema type for ByteArrayConverter: " + schema.type().toString());
if (value != null && !(value instanceof byte... | @Test
public void testFromConnectBadSchema() {
assertThrows(DataException.class,
() -> converter.fromConnectData(TOPIC, Schema.INT32_SCHEMA, SAMPLE_BYTES));
} |
static <T extends CompoundPredicate> T flattenCompound(Predicate predicateLeft, Predicate predicateRight, Class<T> klass) {
// The following could have been achieved with {@link com.hazelcast.query.impl.predicates.FlatteningVisitor},
// however since we only care for 2-argument flattening, we can avoid ... | @Test
public void testOr_whenBothPredicatesOr() {
OrPredicate predicate1 = new OrPredicate(new SqlPredicate("a == 1"), new SqlPredicate("a == 2"));
OrPredicate predicate2 = new OrPredicate(new SqlPredicate("a == 3"));
OrPredicate concatenatedOr = SqlPredicate.flattenCompound(predicate1, pred... |
public static ChannelBuffer directBuffer(int capacity) {
if (capacity == 0) {
return EMPTY_BUFFER;
}
ChannelBuffer buffer = new ByteBufferBackedChannelBuffer(ByteBuffer.allocateDirect(capacity));
buffer.clear();
return buffer;
} | @Test
void testDirectBuffer() {
ChannelBuffer channelBuffer = ChannelBuffers.directBuffer(0);
Assertions.assertEquals(channelBuffer, EMPTY_BUFFER);
channelBuffer = ChannelBuffers.directBuffer(16);
Assertions.assertTrue(channelBuffer instanceof ByteBufferBackedChannelBuffer);
} |
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR
if (splittee == null || splitChar == null) {
return new String[0];
}
final String EMPTY_ELEMENT = "";
int spot;
final int splitLength = splitChar.length();
final Stri... | @Test
public void testSplitStringStringNullWithMultipleDelimiter() {
assertThat(JOrphanUtils.split("a,;bc,;,", ",;", null), CoreMatchers.equalTo(new String[]{"a", "bc"}));
} |
@Nonnull
static String extractJavaScriptUrlWithIframeResource() throws ParsingException {
final String iframeUrl;
final String iframeContent;
try {
iframeUrl = "https://www.youtube.com/iframe_api";
iframeContent = NewPipe.getDownloader()
.get(ifram... | @Test
public void testExtractJavaScriptUrlIframe() throws ParsingException {
assertTrue(YoutubeJavaScriptExtractor.extractJavaScriptUrlWithIframeResource()
.endsWith("base.js"));
} |
@Override
public SplitWeight weightForSplitSizeInBytes(long splitSizeInBytes)
{
// Clamp the value be between the minimum weight and 1.0 (standard weight)
return SplitWeight.fromProportion(Math.min(Math.max(splitSizeInBytes / targetSplitSizeInBytes, minimumWeight), 1.0));
} | @Test
public void testMinimumAndMaximumSplitWeightHandling()
{
DataSize targetSplitSize = DataSize.succinctBytes(megabytesToBytes(64));
SizeBasedSplitWeightProvider provider = new SizeBasedSplitWeightProvider(0.05, targetSplitSize);
assertEquals(provider.weightForSplitSizeInBytes(1), Spl... |
public ProvidePPPPCAOptimizedRequest createPpPpcaRequest(String bsn) throws BsnkException {
ProvidePPPPCAOptimizedRequest request = new ProvidePPPPCAOptimizedRequest();
request.setDateTime(getDateTime());
request.setRequestID("DGD-" + UUID.randomUUID().toString());
request.setRequester(... | @Test
public void createPpPpcaRequest() throws IOException, BsnkException {
String bsn = "PPPPPPPPP";
ProvidePPPPCAOptimizedRequest result = bsnkUtil.createPpPpcaRequest(bsn);
assertNotNull(result.getDateTime());
assertEquals(DatatypeConstants.FIELD_UNDEFINED, result.getDateTime().g... |
public Person getPerson(int key) {
// Try to find person in the identity map
Person person = this.identityMap.getPerson(key);
if (person != null) {
LOGGER.info("Person found in the Map");
return person;
} else {
// Try to find person in the database
person = this.db.find(key);
... | @Test
void personFoundInIdMap(){
// personFinderInstance
PersonFinder personFinder = new PersonFinder();
// init database for our personFinder
PersonDbSimulatorImplementation db = new PersonDbSimulatorImplementation();
// Dummy persons
Person person1 = new Person(1, "John", 27304159);
Pers... |
@ConstantFunction(name = "str2date", argTypes = {VARCHAR, VARCHAR}, returnType = DATE)
public static ConstantOperator str2Date(ConstantOperator date, ConstantOperator fmtLiteral) {
DateTimeFormatterBuilder builder = DateUtils.unixDatetimeFormatBuilder(fmtLiteral.getVarchar(), false);
LocalDate ld = ... | @Test
public void str2Date() {
assertEquals("2013-05-10T00:00", ScalarOperatorFunctions
.str2Date(ConstantOperator.createVarchar("2013,05,10"), ConstantOperator.createVarchar("%Y,%m,%d"))
.getDate().toString());
assertEquals("2013-05-10T00:00", ScalarOperatorFunctions... |
public TemplateResponse mapToTemplateResponse(ReviewGroup reviewGroup, Template template) {
List<SectionResponse> sectionResponses = template.getSectionIds()
.stream()
.map(templateSection -> mapToSectionResponse(templateSection, reviewGroup))
.toList();
... | @Test
void 가이드라인이_없는_경우_가이드_라인을_제공하지_않는다() {
// given
Question question = new Question(true, QuestionType.TEXT, "질문", null, 1);
questionRepository.save(question);
OptionGroup optionGroup = new OptionGroup(question.getId(), 1, 2);
optionGroupRepository.save(optionGroup);
... |
@Override
public Expression getExpression(String tableName, Alias tableAlias) {
// 只有有登陆用户的情况下,才进行数据权限的处理
LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
if (loginUser == null) {
return null;
}
// 只有管理员类型的用户,才进行数据权限的处理
if (ObjectUtil.notEqual(... | @Test // 拼接 Dept 和 User 的条件(字段都不符合)
public void testGetExpression_noDeptColumn_noSelfColumn() {
try (MockedStatic<SecurityFrameworkUtils> securityFrameworkUtilsMock
= mockStatic(SecurityFrameworkUtils.class)) {
// 准备参数
String tableName = "t_user";
Ali... |
@Override
public boolean isGenerateSQLToken(final SQLStatementContext sqlStatementContext) {
return sqlStatementContext instanceof InsertStatementContext && ((InsertStatementContext) sqlStatementContext).containsInsertColumns();
} | @Test
void assertIsGenerateSQLTokenWithInsertColumns() {
InsertStatementContext insertStatementContext = mock(InsertStatementContext.class, RETURNS_DEEP_STUBS);
when(insertStatementContext.containsInsertColumns()).thenReturn(true);
assertTrue(new EncryptInsertDerivedColumnsTokenGenerator(moc... |
@Override
public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey,
@Nullable String projectName) {
String pat = findPersonalAccessTokenOrThrow(dbSession, almSettingDto);
String workspace = ofNullab... | @Test
void createProjectAndBindToDevOpsPlatform_whenNoKeyAndNameSpecified_generatesKeyAndUsersBitbucketRepositoryName() {
mockPatForUser();
when(almSettingDto.getAppId()).thenReturn(WORKSPACE);
mockBitbucketCloudRepository();
String generatedProjectKey = "generatedProjectKey";
when(projectKeyGen... |
@Override
public Boolean exists(final String key) {
try {
List<Instance> instances = namingService.selectInstances(key, groupName, true);
return !instances.isEmpty();
} catch (NacosException e) {
LOGGER.error("Error checking Nacos service existence: {}", e.getMess... | @Test
void testExists() throws NacosException {
List<Instance> mockInstances = new ArrayList<>();
mockInstances.add(mock(Instance.class));
// Mock this service exists
when(namingService.selectInstances(anyString(), anyString(), anyBoolean())).thenReturn(mockInstances);
assert... |
@Override
public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
// JMS allows producers to be created without first specifying a destination. In these cases, every send
// operation must specify a destination. Because of this, we only authorize 'addProducer' if ... | @Test
public void testAddProducerWithoutDestination() throws Exception {
Subject subject = new PermsSubject();
ConnectionContext context = createContext(subject);
ProducerInfo info = new ProducerInfo(null);
filter.addProducer(context, info);
} |
static Properties readProps(List<String> producerProps, String producerConfig) throws IOException {
Properties props = new Properties();
if (producerConfig != null) {
props.putAll(Utils.loadProps(producerConfig));
}
if (producerProps != null)
for (String prop : pr... | @Test
public void testClientIdOverride() throws Exception {
List<String> producerProps = Collections.singletonList("client.id=producer-1");
Properties prop = ProducerPerformance.readProps(producerProps, null);
assertNotNull(prop);
assertEquals("producer-1", prop.getProperty("clien... |
static Optional<String> globalResponseError(Optional<ClientResponse> response) {
if (!response.isPresent()) {
return Optional.of("Timeout");
}
if (response.get().authenticationException() != null) {
return Optional.of("AuthenticationException");
}
if (resp... | @Test
public void testGlobalResponseErrorClassCastException() {
assertEquals(Optional.of("ClassCastException"),
AssignmentsManager.globalResponseError(Optional.of(
new ClientResponse(null, null, "", 0, 0, false, false,
null, null, new ApiVersionsResponse(new A... |
@Override
public String toString() {
Map<String, Object> map = new HashMap<>();
map.put(NUM_SERVERS_QUERIED, getNumServersQueried());
map.put(NUM_SERVERS_RESPONDED, getNumServersResponded());
map.put(NUM_DOCS_SCANNED, getNumDocsScanned());
map.put(NUM_ENTRIES_SCANNED_IN_FILTER, getNumEntriesScanne... | @Test
public void testToString() {
// Run the test
final String result = _executionStatsUnderTest.toString();
// Verify the results
assertNotEquals("", result);
} |
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
return validate(klass, options, false);
} | @Test
public void testWhenOptionIsDefinedOnOtherOptionsClassMeetsGroupRequirement() {
RightOptions rightOpts = PipelineOptionsFactory.as(RightOptions.class);
rightOpts.setFoo("true");
rightOpts.setBoth("bar");
LeftOptions leftOpts = PipelineOptionsFactory.as(LeftOptions.class);
leftOpts.setFoo("U... |
private void decodeSofaResponse(AbstractByteBuf data, SofaResponse sofaResponse, Map<String, String> head) {
if (head == null) {
throw buildDeserializeError("head is null!");
}
String targetService = head.remove(RemotingConstants.HEAD_TARGET_SERVICE);
if (targetService == nul... | @Test
public void testDecodeSofaResponse() {
AbstractByteBuf nullByteBuf = serializer.encode(null, null);
JacksonSerializer jacksonSerializer = new JacksonSerializer();
SofaResponse sofaResponse = new SofaResponse();
Map<String, String> ctx = new HashMap<>();
ctx.put(Remoting... |
public TermsAggregationBuilder buildTermsAggregation(String name,
TopAggregationDefinition<?> topAggregation, @Nullable Integer numberOfTerms) {
TermsAggregationBuilder termsAggregation = AggregationBuilders.terms(name)
.field(topAggregation.getFilterScope().getFieldName())
.order(order)
.minD... | @Test
public void buildTermsAggregation_adds_custom_sub_agg_from_constructor() {
String aggName = randomAlphabetic(10);
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
Stream.of(
underTestWithCustomSubAgg,
underTestWithCustomsSubAggA... |
public static String buildErrorMessage(final Throwable throwable) {
if (throwable == null) {
return "";
}
final List<String> messages = dedup(getErrorMessages(throwable));
final String msg = messages.remove(0);
final String causeMsg = messages.stream()
.filter(s -> !s.isEmpty())
... | @Test
public void shouldBuildErrorMessageFromExceptionWithNoMessage() {
assertThat(
buildErrorMessage(new NullPointerException()),
is("java.lang.NullPointerException")
);
} |
@Override
public long estimate() {
final double raw = (1 / computeE()) * alpha() * m * m;
return applyRangeCorrection(raw);
} | @Test
public void testAlpha_withMemoryFootprintOf64() {
DenseHyperLogLogEncoder encoder = new DenseHyperLogLogEncoder(6);
encoder.estimate();
} |
private Set<TimelineEntity> getEntities(Path dir, String entityType,
TimelineEntityFilters filters, TimelineDataToRetrieve dataToRetrieve)
throws IOException {
// First sort the selected entities based on created/start time.
Map<Long, Set<TimelineEntity>> sortedEntities =
new TreeMap<>(
... | @Test
void testGetFilteredEntities() throws Exception {
// Get entities based on info filters.
TimelineFilterList infoFilterList = new TimelineFilterList();
infoFilterList.addFilter(
new TimelineKeyValueFilter(TimelineCompareOp.EQUAL, "info2", 3.5));
Set<TimelineEntity> result = reader.getEnti... |
@Override
public void update(List<V> values) {
throw MODIFICATION_ATTEMPT_ERROR;
} | @Test
void testUpdate() throws Exception {
List<Long> list = getStateContents();
assertThat(list).containsExactly(42L);
assertThatThrownBy(() -> listState.add(54L))
.isInstanceOf(UnsupportedOperationException.class);
} |
public List<MappingField> resolveAndValidateFields(
List<MappingField> userFields,
Map<String, String> options,
NodeEngine nodeEngine
) {
final InternalSerializationService serializationService = (InternalSerializationService) nodeEngine
.getSerializationS... | @Test
public void when_keyFieldsEmpty_then_doesNotFail() {
Map<String, String> options = ImmutableMap.of(
OPTION_KEY_FORMAT, JAVA_FORMAT,
OPTION_VALUE_FORMAT, JAVA_FORMAT
);
given(resolver.resolveAndValidateFields(eq(true), eq(emptyList()), eq(options), eq(ss)... |
public void resolveAssertionConsumerService(AuthenticationRequest authenticationRequest) throws SamlValidationException {
// set URL if set in authnRequest
final String authnAcsURL = authenticationRequest.getAuthnRequest().getAssertionConsumerServiceURL();
if (authnAcsURL != null) {
... | @Test
void resolveAcsUrlWithIndex0InMultiAcsMetadata() throws SamlValidationException {
AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class);
authnRequest.setAssertionConsumerServiceIndex(0);
AuthenticationRequest authenticationRequest = new AuthenticationRequest();... |
public Vector3 toVector() {
return position;
} | @Test
public void testToVector() throws Exception {
World world = mock(World.class);
Vector3 position = Vector3.at(1, 1, 1);
Location location = new Location(world, position);
assertEquals(position, location.toVector());
} |
public static long getNextScheduledTime(final String cronEntry, long currentTime) throws MessageFormatException {
long result = 0;
if (cronEntry == null || cronEntry.length() == 0) {
return result;
}
// Handle the once per minute case "* * * * *"
// starting the ne... | @Test
public void testgetNextTimeHours() throws MessageFormatException {
String test = "* 1 * * *";
Calendar calender = Calendar.getInstance();
calender.set(1972, 2, 2, 17, 10, 0);
long current = calender.getTimeInMillis();
long next = CronParser.getNextScheduledTime(test, c... |
public static <T> Flattened<T> flattenedSchema() {
return new AutoValue_Select_Flattened.Builder<T>()
.setNameFn(CONCAT_FIELD_NAMES)
.setNameOverrides(Collections.emptyMap())
.build();
} | @Test
@Category(NeedsRunner.class)
public void testFlatSchemaWith2DArrayNestedField() {
Schema banksSchema = Schema.builder().addStringField("name").addStringField("address").build();
Schema transactionSchema =
Schema.builder()
.addArrayField("banks", Schema.FieldType.row(banksSchema))
... |
public static String getTpContentMd5(ThreadPoolParameter config) {
return Md5Util.md5Hex(ContentUtil.getPoolContent(config), "UTF-8");
} | @Test
public void assetGetTpContentMd5() {
final ThreadPoolParameterInfo threadPoolParameterInfo = new ThreadPoolParameterInfo();
final String mockContent = "mockContent";
final String mockContentMd5 = "34cf17bc632ece6e4c81a4ce8aa97d5e";
try (final MockedStatic<ContentUtil> mockedCon... |
public void add() {
add(1L, defaultPosition);
} | @Test
final void testAdd() {
final String metricName = "unitTestCounter";
Counter c = receiver.declareCounter(metricName);
c.add();
Bucket b = receiver.getSnapshot();
final Map<String, List<Entry<Point, UntypedMetric>>> valuesByMetricName = b.getValuesByMetricName();
... |
public static Instant parseDateTime(String s) throws DateTimeParseException {
ValidationUtils.checkArgument(Objects.nonNull(s), "Input String cannot be null.");
try {
return Instant.ofEpochMilli(Long.parseLong(s));
} catch (NumberFormatException e) {
return Instant.parse(s);
}
} | @Test
public void testParseDateTimeWithNull() {
assertThrows(IllegalArgumentException.class, () -> {
DateTimeUtils.parseDateTime(null);
});
} |
public static void addCompactionPendingMetric(final StreamsMetricsImpl streamsMetrics,
final RocksDBMetricContext metricContext,
final Gauge<BigInteger> valueProvider) {
addMutableMetric(
streamsMetri... | @Test
public void shouldAddCompactionPendingMetric() {
final String name = "compaction-pending";
final String description = "Reports 1 if at least one compaction is pending, otherwise it reports 0";
runAndVerifyMutableMetric(
name,
description,
() -> Rocks... |
public void displayGiant(GiantModel giant) {
LOGGER.info(giant.toString());
} | @Test
void testDispalyGiant() {
GiantModel giantModel = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT,
Nourishment.SATURATED);
GiantView giantView = new GiantView();
assertDoesNotThrow(() -> giantView.displayGiant(giantModel));
} |
public CompletableFuture<WorkerStatusResponse> getWorkerStatus() {
WorkerStatusRequest request =
WorkerStatusRequest.newBuilder().setId(idGenerator.getId()).build();
return getWorkerStatus(request);
} | @Test
@SuppressWarnings("FutureReturnValueIgnored")
public void testGetWorkerStatusRequestSent() {
client.getWorkerStatus();
verify(mockObserver).onNext(any(WorkerStatusRequest.class));
} |
public static Response executeRequest(String requestUrl, OAuth20Service scribe, OAuth2AccessToken accessToken) throws IOException {
OAuthRequest request = new OAuthRequest(Verb.GET, requestUrl);
scribe.signRequest(accessToken, request);
try {
Response response = scribe.execute(request);
if (!res... | @Test
public void fail_to_execute_request() throws IOException {
mockWebServer.enqueue(new MockResponse().setResponseCode(404).setBody("Error!"));
assertThatThrownBy(() -> executeRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken))
.isInstanceOf(IllegalStateException.class)
.hasMessage... |
@Override
public byte[] serialize(final String topic, final T data) {
try {
return delegate.serialize(topic, data);
} catch (final RuntimeException e) {
processingLogger.error(new SerializationError<>(e, Optional.of(data), topic, isKey));
throw e;
}
} | @Test
public void shouldThrowIfDelegateThrows() {
// Given:
when(delegate.serialize(any(), any())).thenThrow(ERROR);
// When:
final RuntimeException e = assertThrows(
RuntimeException.class,
() -> serializer.serialize("t", SOME_ROW)
);
// Then:
assertThat(e, is(ERROR));
... |
LetterComposite messageFromOrcs() {
var words = List.of(
new Word('W', 'h', 'e', 'r', 'e'),
new Word('t', 'h', 'e', 'r', 'e'),
new Word('i', 's'),
new Word('a'),
new Word('w', 'h', 'i', 'p'),
new Word('t', 'h', 'e', 'r', 'e'),
new Word('i', 's'),
new ... | @Test
void testMessageFromOrcs() {
final var messenger = new Messenger();
testMessage(
messenger.messageFromOrcs(),
"Where there is a whip there is a way."
);
} |
public static Map<String, String> toMap(List<String> queryString) {
return queryString == null ? null : queryString
.stream()
.map(s -> {
String[] split = s.split("[: ]+");
if (split.length < 2 || split[0] == null || split[0].isEmpty()) {
... | @Test
void toMap() {
final Map<String, String> resultMap = RequestUtils.toMap(List.of("timestamp:2023-12-18T14:32:14Z"));
assertThat(resultMap.get("timestamp"), is("2023-12-18T14:32:14Z"));
} |
@Override
public StageBundleFactory forStage(ExecutableStage executableStage) {
return new SimpleStageBundleFactory(executableStage);
} | @Test
public void doesNotCacheDifferentEnvironments() throws Exception {
Environment envFoo = Environment.newBuilder().setUrn("dummy:urn:another").build();
RemoteEnvironment remoteEnvFoo = mock(RemoteEnvironment.class);
InstructionRequestHandler fooInstructionHandler = mock(InstructionRequestHandler.class... |
@Override
public Map<String, Validator> getValidations() {
return ImmutableMap.<String, Validator>builder()
.put(USERNAME, new LimitedStringValidator(1, MAX_USERNAME_LENGTH))
.put(PASSWORD, new FilledStringValidator())
.put(EMAIL, new LimitedStringValidator(1,... | @Test
public void testLastNameLengthValidation() {
user = createUserImpl(null, null, null);
ValidationResult result = user.getValidations().get(UserImpl.LAST_NAME)
.validate(StringUtils.repeat("*", 10));
assertTrue(result.passed());
result = user... |
@Override
public synchronized void editSchedule() {
updateConfigIfNeeded();
long startTs = clock.getTime();
CSQueue root = scheduler.getRootQueue();
Resource clusterResources = Resources.clone(scheduler.getClusterResource());
containerBasedPreemptOrKill(root, clusterResources);
if (LOG.isDe... | @Test
public void testNaturalTermination() {
int[][] qData = new int[][]{
// / A B C
{ 100, 40, 40, 20 }, // abs
{ 100, 100, 100, 100 }, // maxCap
{ 100, 55, 45, 0 }, // used
{ 20, 10, 10, 0 }, // pending
{ 0, 0, 0, 0 }, // reserved
{ 2, 1, 1, 0 }... |
public Optional<Long> validateAndGetTimestamp(final ExternalServiceCredentials credentials) {
final String[] parts = requireNonNull(credentials).password().split(DELIMITER);
final String timestampSeconds;
final String actualSignature;
// making sure password format matches our expectations based on the... | @Test
public void testValidateValidWithUsernameIsTimestamp() {
final long expectedTimestamp = Instant.ofEpochSecond(TIME_SECONDS).truncatedTo(ChronoUnit.DAYS).getEpochSecond();
assertEquals(expectedTimestamp, usernameIsTimestampGenerator.validateAndGetTimestamp(usernameIsTimestampCredentials).orElseThrow());
... |
public void decrementIndex(int taskIndex) {
moveTask(taskIndex, DECREMENT_INDEX);
} | @Test
public void shouldErrorOutWhenTaskIsNotFoundWhileDecrementing() {
try {
new Tasks().decrementIndex(1);
fail("Should have thrown up");
} catch (Exception e) {
assertThat(e.getMessage(), is("There is not valid task at position 1."));
}
} |
public boolean containsValue(final long value) {
final long[] entries = this.entries;
for (int i = 1; i < entries.length; i += 2) {
final long entryValue = entries[i];
if (entryValue == value) {
return true;
}
}
return false;
} | @Test
public void shouldNotContainValueForAMissingEntry() {
assertFalse(map.containsValue(1L));
} |
public String getGtidSetStr() {
return gtidMap.get(GTID_SET_STRING);
} | @Test
public void getGtidSetStrOutputNull() {
// Arrange
final LogHeader objectUnderTest = new LogHeader(0);
// Act
final String actual = objectUnderTest.getGtidSetStr();
// Assert result
Assert.assertNull(actual);
} |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefi... | @Test
public void testIsNull() {
Expression expr = resolve(Expressions.$("field1").isNull());
Optional<org.apache.iceberg.expressions.Expression> actual = FlinkFilters.convert(expr);
assertThat(actual).isPresent();
UnboundPredicate<Object> expected = org.apache.iceberg.expressions.Expressions.isNull("... |
@Override
public String ping(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<String> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.PING);
return syncFuture(f);
} | @Test
public void testClusterPing() {
RedisClusterNode master = getFirstMaster();
String res = connection.ping(master);
assertThat(res).isEqualTo("PONG");
} |
@Override
protected void doExecute() {
if (vpls == null) {
vpls = get(Vpls.class);
}
if (interfaceService == null) {
interfaceService = get(InterfaceService.class);
}
VplsCommandEnum enumCommand = VplsCommandEnum.enumFromString(command);
if (e... | @Test
public void testShowAll() {
((TestVpls) vplsCommand.vpls).initSampleData();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
System.setOut(ps);
vplsCommand.command = VplsCommandEnum.SHOW.toString();
vplsCommand.do... |
public static AbstractProtocolNegotiatorBuilderSingleton getSingleton() {
return SINGLETON;
} | @Test
void testSingletonInstance() {
AbstractProtocolNegotiatorBuilderSingleton singleton1 = SdkProtocolNegotiatorBuilderSingleton.getSingleton();
AbstractProtocolNegotiatorBuilderSingleton singleton2 = SdkProtocolNegotiatorBuilderSingleton.getSingleton();
assertSame(singleton1, singleton2);... |
@Override
public String toString() {
return "ByteArrayObjectDataOutput{"
+ "size=" + (buffer != null ? buffer.length : 0)
+ ", pos=" + pos
+ '}';
} | @Test
public void testToString() {
assertNotNull(out.toString());
} |
public static CsvIOParse<Row> parseRows(Schema schema, CSVFormat csvFormat) {
CsvIOParseHelpers.validateCsvFormat(csvFormat);
CsvIOParseHelpers.validateCsvFormatWithSchema(csvFormat, schema);
RowCoder coder = RowCoder.of(schema);
CsvIOParseConfiguration.Builder<Row> builder = CsvIOParseConfiguration.bui... | @Test
public void parseRows() {
Pipeline pipeline = Pipeline.create();
PCollection<String> input =
csvRecords(
pipeline,
"# This is a comment",
"aBoolean,aDouble,aFloat,anInteger,aLong,aString",
"true,1.0,2.0,3,4,foo",
"N/A,6.0,7.0,8,9,bar",
... |
public boolean record(final Throwable observation)
{
final long timestampMs;
DistinctObservation distinctObservation;
timestampMs = clock.time();
synchronized (this)
{
distinctObservation = find(distinctObservations, observation);
if (null == distinc... | @Test
void shouldTestRecordingWithoutStackTrace()
{
final CachedEpochClock clock = new CachedEpochClock();
final DistinctErrorLog log = new DistinctErrorLog(DIRECT_BUFFER, clock);
clock.advance(10);
log.record(new TestEvent("event one"));
clock.advance(10);
log.... |
public ConfigCenterBuilder configFile(String configFile) {
this.configFile = configFile;
return getThis();
} | @Test
void configFile() {
ConfigCenterBuilder builder = ConfigCenterBuilder.newBuilder();
builder.configFile("configFile");
Assertions.assertEquals("configFile", builder.build().getConfigFile());
} |
public static Write write() {
return new AutoValue_InfluxDbIO_Write.Builder()
.setRetentionPolicy(DEFAULT_RETENTION_POLICY)
.setDisableCertificateValidation(false)
.setBatchSize(DEFAULT_BUFFER_LIMIT)
.setConsistencyLevel(ConsistencyLevel.QUORUM)
.build();
} | @Test
public void validateWriteTest() {
InfluxDB influxDb = Mockito.mock(InfluxDB.class);
PowerMockito.when(
InfluxDBFactory.connect(
anyString(), anyString(), anyString(), any(OkHttpClient.Builder.class)))
.thenReturn(influxDb);
PowerMockito.when(InfluxDBFactory.connec... |
public String getMysqlType() {
switch (type) {
case INLINE_VIEW:
case VIEW:
case MATERIALIZED_VIEW:
case CLOUD_NATIVE_MATERIALIZED_VIEW:
return "VIEW";
case SCHEMA:
return "SYSTEM VIEW";
default:
... | @Test
public void testGetMysqlType() {
Assert.assertEquals("BASE TABLE", new Table(TableType.OLAP).getMysqlType());
Assert.assertEquals("BASE TABLE", new Table(TableType.OLAP_EXTERNAL).getMysqlType());
Assert.assertEquals("BASE TABLE", new Table(TableType.CLOUD_NATIVE).getMysqlType());
... |
public static int toInt(String val) {
return toInt(val, 0);
} | @Test
void testToInt() {
// ConvertUtils.toInt(String)
assertEquals(0, ConvertUtils.toInt("0"));
assertEquals(-1, ConvertUtils.toInt("-1"));
assertEquals(10, ConvertUtils.toInt("10"));
assertEquals(Integer.MAX_VALUE, ConvertUtils.toInt(String.valueOf(Integer.MAX_VALUE)));
... |
public void initialize(ConnectorContext ctx) {
context = ctx;
} | @Test
public void shouldInitializeContext() {
connector.initialize(context);
assertableConnector.assertInitialized();
assertableConnector.assertContext(context);
assertableConnector.assertTaskConfigs(null);
} |
@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 nonExcludedUrlWillErrorWhenOnBlocklist() throws Exception {
AuthCheckFilter.SERVLET_REQUEST_AUTHENTICATOR.setValue(AdminUserServletAuthenticatorClass.class);
final AuthCheckFilter filter = new AuthCheckFilter(adminManager, loginLimitManager);
AuthCheckFilter.IP_ACCESS_BLOC... |
@Override
public <T> @Nullable Schema schemaFor(TypeDescriptor<T> typeDescriptor) {
checkForDynamicType(typeDescriptor);
return ProtoSchemaTranslator.getSchema((Class<Message>) typeDescriptor.getRawType());
} | @Test
public void testMapSchema() {
Schema schema = new ProtoMessageSchema().schemaFor(TypeDescriptor.of(MapPrimitive.class));
assertEquals(MAP_PRIMITIVE_SCHEMA, schema);
} |
@Override
public Long clusterCountKeysInSlot(int slot) {
RedisClusterNode node = clusterGetNodeForSlot(slot);
MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(new InetSocketAddress(node.getHost(), node.getPort()));
RFuture<Long> f = executorService.readAsync(entry, St... | @Test
public void testClusterCountKeysInSlot() {
Long t = connection.clusterCountKeysInSlot(1);
assertThat(t).isZero();
} |
@Override
public YamlShardingStrategyConfiguration swapToYamlConfiguration(final ShardingStrategyConfiguration data) {
YamlShardingStrategyConfiguration result = new YamlShardingStrategyConfiguration();
if (data instanceof StandardShardingStrategyConfiguration) {
result.setStandard(creat... | @Test
void assertSwapToYamlConfigurationForComplexShardingStrategy() {
ShardingStrategyConfiguration data = new ComplexShardingStrategyConfiguration("region_id, user_id", "core_complex_fixture");
YamlShardingStrategyConfigurationSwapper swapper = new YamlShardingStrategyConfigurationSwapper();
... |
@Override
public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext,
final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException {
if (1 == queryResults.size() && !isNeedAggregateRewri... | @Test
void assertBuildGroupByStreamMergedResultWithSQLServerLimit() throws SQLException {
final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "SQLServer"));
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS... |
public synchronized void start() throws IllegalStateException, StreamsException {
if (setState(State.REBALANCING)) {
log.debug("Starting Streams client");
if (globalStreamThread != null) {
globalStreamThread.start();
}
final int numThreads = proc... | @Test
public void shouldCleanupOldStateDirs() {
prepareStreams();
prepareStreamThread(streamThreadOne, 1);
prepareStreamThread(streamThreadTwo, 2);
try (final MockedStatic<Executors> executorsMockedStatic = mockStatic(Executors.class)) {
final ScheduledExecutorService cl... |
public static Ip4Prefix valueOf(int address, int prefixLength) {
return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength);
} | @Test
public void testValueOfByteArrayIPv4() {
Ip4Prefix ipPrefix;
byte[] value;
value = new byte[] {1, 2, 3, 4};
ipPrefix = Ip4Prefix.valueOf(value, 24);
assertThat(ipPrefix.toString(), is("1.2.3.0/24"));
ipPrefix = Ip4Prefix.valueOf(value, 32);
assertThat(... |
public int remap(int var, int size) {
if ((var & REMAP_FLAG) != 0) {
return unmask(var);
}
int offset = var - argsSize;
if (offset < 0) {
// self projection for method arguments
return var;
}
if (offset >= mapping.length) {
mapping = Arrays.copyOf(mapping, Math.max(mappi... | @Test
public void remapOverflow() {
assertEquals(
0,
instance.remap(
16, 1)); // default mapping array size is 8 so going for double should trigger overflow
// handling
} |
public SchemaMapping fromArrow(Schema arrowSchema) {
List<Field> fields = arrowSchema.getFields();
List<TypeMapping> parquetFields = fromArrow(fields);
MessageType parquetType =
addToBuilder(parquetFields, Types.buildMessage()).named("root");
return new SchemaMapping(arrowSchema, parquetType, pa... | @Test(expected = UnsupportedOperationException.class)
public void testArrowTimestampSecondToParquet() {
converter
.fromArrow(new Schema(asList(field("a", new ArrowType.Timestamp(TimeUnit.SECOND, "UTC")))))
.getParquetSchema();
} |
@Override
public RLock readLock() {
return new RedissonReadLock(commandExecutor, getName());
} | @Test
public void testIsHeldByCurrentThread() {
RReadWriteLock rwlock = redisson.getReadWriteLock("lock");
RLock lock = rwlock.readLock();
Assertions.assertFalse(lock.isHeldByCurrentThread());
lock.lock();
Assertions.assertTrue(lock.isHeldByCurrentThread());
lock.unlo... |
@Override
public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) {
checkPermission(FLOWRULE_WRITE);
if (forwardingObjective.nextId() == null ||
flowObjectiveStore.getNextGroup(forwardingObjective.nextId()) != null ||
!queueFwdObjective(deviceI... | @Test
public void pendingForwardingObjective() throws TestUtilsException {
TrafficSelector selector = DefaultTrafficSelector.emptySelector();
TrafficTreatment treatment = DefaultTrafficTreatment.emptyTreatment();
ForwardingObjective forward4 =
DefaultForwardingObjective.buil... |
@Override
public Object[] toArray() {
return underlying().toArray();
} | @Test
public void testDelegationOfToArrayIntoGivenDestination() {
Object[] destinationArray = new Object[0];
new PCollectionsTreeSetWrapperDelegationChecker<>()
.defineMockConfigurationForFunctionInvocation(mock -> mock.toArray(eq(destinationArray)), new Object[0])
.d... |
public void hasValue(@Nullable Object expected) {
if (expected == null) {
throw new NullPointerException("Optional cannot have a null value.");
}
if (actual == null) {
failWithActual("expected an optional with value", expected);
} else if (!actual.isPresent()) {
failWithoutActual(fact(... | @Test
public void hasValue() {
assertThat(Optional.of("foo")).hasValue("foo");
} |
public HollowHashIndexResult findMatches(Object... query) {
if (hashStateVolatile == null) {
throw new IllegalStateException(this + " wasn't initialized");
}
int hashCode = 0;
for(int i=0;i<query.length;i++) {
if(query[i] == null)
throw new Illega... | @Test
public void testIndexingStringTypeFieldsWithNullValues() throws Exception {
mapper.add(new TypeTwoStrings(null, "onez:"));
mapper.add(new TypeTwoStrings("onez:", "onez:"));
mapper.add(new TypeTwoStrings(null, null));
roundTripSnapshot();
HollowHashIndex index = new Hol... |
public static int parseIntAscii(final CharSequence cs, final int index, final int length)
{
if (length <= 0)
{
throw new AsciiNumberFormatException("empty string: index=" + index + " length=" + length);
}
final boolean negative = MINUS_SIGN == cs.charAt(index);
i... | @Test
void shouldParseInt()
{
assertEquals(0, parseIntAscii("0", 0, 1));
assertEquals(0, parseIntAscii("-0", 0, 2));
assertEquals(7, parseIntAscii("7", 0, 1));
assertEquals(-7, parseIntAscii("-7", 0, 2));
assertEquals(33, parseIntAscii("3333", 1, 2));
assertEquals... |
@Override
public Integer clusterGetSlotForKey(byte[] key) {
RFuture<Integer> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.KEYSLOT, key);
return syncFuture(f);
} | @Test
public void testClusterGetSlotForKey() {
Integer slot = connection.clusterGetSlotForKey("123".getBytes());
assertThat(slot).isNotNull();
} |
public static NettySourceConfig load(Map<String, Object> map) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(mapper.writeValueAsString(map), NettySourceConfig.class);
} | @Test(expectedExceptions = UnrecognizedPropertyException.class)
public void testNettyTcpConfigLoadWithMapWhenInvalidPropertyIsSet() throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("invalidProperty", 1);
NettySourceConfig.load(map);
} |
@Override
public void flush() throws IOException {
mLocalOutputStream.flush();
} | @Test
@PrepareForTest(GCSOutputStream.class)
public void testFlush() throws Exception {
PowerMockito.whenNew(BufferedOutputStream.class)
.withArguments(any(DigestOutputStream.class)).thenReturn(mLocalOutputStream);
GCSOutputStream stream = new GCSOutputStream("testBucketName", "testKey", mClient, sC... |
@ConstantFunction.List(list = {
@ConstantFunction(name = "months_add", argTypes = {DATETIME,
INT}, returnType = DATETIME, isMonotonic = true),
@ConstantFunction(name = "add_months", argTypes = {DATETIME,
INT}, returnType = DATETIME, isMonotonic = true),
... | @Test
public void monthsAdd() {
assertEquals("2016-01-23T09:23:55",
ScalarOperatorFunctions.monthsAdd(O_DT_20150323_092355, O_INT_10).getDatetime().toString());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.