focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Object read(final MySQLPacketPayload payload, final boolean unsigned) {
return payload.getByteBuf().readDoubleLE();
} | @Test
void assertRead() {
when(byteBuf.readDoubleLE()).thenReturn(1.0D);
assertThat(new MySQLDoubleBinaryProtocolValue().read(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8), false), is(1.0D));
} |
public void setProfile(final Set<String> indexSetsIds,
final String profileId,
final boolean rotateImmediately) {
checkProfile(profileId);
checkAllIndicesSupportProfileChange(indexSetsIds);
for (String indexSetId : indexSetsIds) {
... | @Test
void testThrowsExceptionWhenTryingToSetUnExistingProfile() {
assertThrows(NotFoundException.class, () -> toTest.setProfile(Set.of(), "000000000000000000000042", false));
} |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.precision(column.getColumnLength())
.length(column.getColumn... | @Test
public void testReconvertString() {
Column column =
PhysicalColumn.builder()
.name("test")
.dataType(BasicType.STRING_TYPE)
.columnLength(null)
.build();
BasicTypeDefine typeDefine ... |
@Override
public KeyValueIterator<Windowed<K>, V> fetchAll(final Instant timeFrom,
final Instant timeTo) throws IllegalArgumentException {
return new KeyValueIteratorFacade<>(inner.fetchAll(timeFrom, timeTo));
} | @Test
public void shouldReturnPlainKeyValuePairsOnFetchAllInstantParameters() {
when(mockedKeyValueWindowTimestampIterator.next())
.thenReturn(KeyValue.pair(
new Windowed<>("key1", new TimeWindow(21L, 22L)),
ValueAndTimestamp.make("value1", 22L)))
.the... |
public static boolean isServiceNameCompatibilityMode(final String serviceName) {
return !StringUtils.isBlank(serviceName) && serviceName.contains(Constants.SERVICE_INFO_SPLITER);
} | @Test
void testIsServiceNameCompatibilityMode() {
String serviceName1 = "group@@serviceName";
assertTrue(NamingUtils.isServiceNameCompatibilityMode(serviceName1));
String serviceName2 = "serviceName";
assertFalse(NamingUtils.isServiceNameCompatibilityMode(serviceName2));
... |
public void startAsync() {
try {
udfLoader.load();
ProcessingLogServerUtils.maybeCreateProcessingLogTopic(
serviceContext.getTopicClient(),
processingLogConfig,
ksqlConfig);
if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) {
log.warn... | @Test
public void shouldSetPropertyOnlyOnCommandsFollowingTheSetStatement() {
// Given:
final PreparedStatement<SetProperty> setProp = PreparedStatement.of("SET PROP",
new SetProperty(Optional.empty(), ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"));
final PreparedStatement<CreateStream> cs... |
public RouterQuotaUsage getQuotaUsage(String path) {
readLock.lock();
try {
RouterQuotaUsage quotaUsage = this.cache.get(path);
if (quotaUsage != null && isQuotaSet(quotaUsage)) {
return quotaUsage;
}
// If not found, look for its parent path usage value.
int pos = path.la... | @Test
public void testGetQuotaUsage() {
RouterQuotaUsage quotaGet;
// test case1: get quota with a non-exist path
quotaGet = manager.getQuotaUsage("/non-exist-path");
assertNull(quotaGet);
// test case2: get quota from a no-quota set path
RouterQuotaUsage.Builder quota = new RouterQuotaUsage... |
@Override
public ExecutionState getState() {
return stateSupplier.get();
} | @Test
void testGetExecutionState() {
for (ExecutionState state : ExecutionState.values()) {
stateSupplier.setExecutionState(state);
assertThat(producerVertex.getState()).isEqualTo(state);
}
} |
public static boolean isUnclosedQuote(final String line) {
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
int quoteStart = -1;
for (int i = 0; i < line.length(); ++i) {
if (quoteStart < 0 && isQuoteChar(line, i)) {
quoteStart = i;
} else if (quoteStart >= 0 && isTwoQuoteStart(line, i) && !... | @Test
public void shouldFindUnclosedQuote_escapedEscape() {
// Given:
final String line = "some line 'this is in a quote\\\\'";
// Then:
assertThat(UnclosedQuoteChecker.isUnclosedQuote(line), is(false));
} |
public Stream<Hit> stream() {
if (nPostingLists == 0) {
return Stream.empty();
}
return StreamSupport.stream(new PredicateSpliterator(), false);
} | @Test
void requireThatNoStreamsReturnNoResults() {
PredicateSearch search = new PredicateSearch(new ArrayList<>(), new byte[0], new byte[0], new short[0], 1);
assertEquals(0, search.stream().count());
} |
@Override
public Long createMailLog(Long userId, Integer userType, String toMail,
MailAccountDO account, MailTemplateDO template,
String templateContent, Map<String, Object> templateParams, Boolean isSend) {
MailLogDO.MailLogDOBuilder logDOBuilder ... | @Test
public void testCreateMailLog() {
// 准备参数
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String toMail = randomEmail();
MailAccountDO account = randomPojo(MailAccountDO.class);
MailTemplateDO template = randomPojo(M... |
@Override
public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception {
if (args.isEmpty()) {
printHelp(out);
return 0;
}
OutputStream output = out;
if (args.size() > 1) {
output = Util.fileOrStdout(args.get(args.size() - 1), out);
arg... | @Test
void concat() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData(name.getMethodName() + "-1.avro", Type.STRING, metadata, DEFLATE);
File input2 = generateData(name.getMethodName() + "-2.avro", Type.STRING, meta... |
@Override
public void close() throws Exception {
handlesToClose.forEach(IOUtils::closeQuietly);
handlesToClose.clear();
if (sharedResources != null) {
sharedResources.close();
}
cleanRelocatedDbLogs();
} | @Test
public void testFreeSharedResourcesAfterClose() throws Exception {
LRUCache cache = new LRUCache(1024L);
WriteBufferManager wbm = new WriteBufferManager(1024L, cache);
RocksDBSharedResources sharedResources =
new RocksDBSharedResources(cache, wbm, 1024L, false);
... |
@ConstantFunction(name = "url_extract_parameter", argTypes = {VARCHAR, VARCHAR}, returnType = VARCHAR)
public static ConstantOperator urlExtractParameter(ConstantOperator url, ConstantOperator parameter) {
List<NameValuePair> parametersAndValues = null;
try {
parametersAndValues = URLEnc... | @Test
public void testUrlExtractParameter() {
assertEquals("100", ScalarOperatorFunctions.urlExtractParameter(
new ConstantOperator("https://starrocks.com/doc?k1=100&k2=3", Type.VARCHAR),
new ConstantOperator("k1", Type.VARCHAR)
).getVarchar());
assertEquals(S... |
public String toRegexForFixedDate(Date date) {
StringBuilder buf = new StringBuilder();
Converter<Object> p = headTokenConverter;
while (p != null) {
if (p instanceof LiteralConverter) {
buf.append(p.convert(null));
} else if (p instanceof IntegerTokenConv... | @Test
public void asRegexByDate() {
Calendar cal = Calendar.getInstance();
cal.set(2003, 4, 20, 17, 55);
{
FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", context);
String regex = fnp.toRegexForFixedDate(cal.getTime());
assertEqual... |
@Override
public UseDefaultInsertColumnsToken generateSQLToken(final InsertStatementContext insertStatementContext) {
String tableName = Optional.ofNullable(insertStatementContext.getSqlStatement().getTable()).map(optional -> optional.getTableName().getIdentifier().getValue()).orElse("");
Optional<U... | @Test
void assertGenerateSQLTokensWhenInsertColumnsUseDifferentEncryptorWithSelectProjection() {
generator.setPreviousSQLTokens(EncryptGeneratorFixtureBuilder.getPreviousSQLTokens());
assertThrows(UnsupportedSQLOperationException.class, () -> generator.generateSQLToken(EncryptGeneratorFixtureBuilder... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final AttributedList<Path> children = new AttributedList<>();
for(List<DavResource> list : ListUtils.partition(this.list(directory),
... | @Test(expected = NotfoundException.class)
public void testListNotfound() throws Exception {
new DAVListService(session).list(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)),
new Disabled... |
public static IpPrefix valueOf(int address, int prefixLength) {
return new IpPrefix(IpAddress.valueOf(address), prefixLength);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfAddressNegativePrefixLengthIPv4() {
IpAddress ipAddress;
IpPrefix ipPrefix;
ipAddress = IpAddress.valueOf("1.2.3.4");
ipPrefix = IpPrefix.valueOf(ipAddress, -1);
} |
public static Iterator<String> lineIterator(String input) {
return new LineIterator(input);
} | @Test
public void lines() {
assertThat(ImmutableList.copyOf(Newlines.lineIterator("foo\nbar\n")))
.containsExactly("foo\n", "bar\n");
assertThat(ImmutableList.copyOf(Newlines.lineIterator("foo\nbar")))
.containsExactly("foo\n", "bar");
assertThat(ImmutableList.copyOf(Newlines.lineIterator... |
@Override
public EventNotificationConfigEntity toContentPackEntity(EntityDescriptorIds entityDescriptorIds) {
return TeamsEventNotificationConfigEntity.builder()
.color(ValueReference.of(color()))
.webhookUrl(ValueReference.of(webhookUrl()))
.customMessage(Val... | @Test(expected = NullPointerException.class)
public void toContentPackEntity() {
final TeamsEventNotificationConfig teamsEventNotificationConfig = TeamsEventNotificationConfig.builder().build();
teamsEventNotificationConfig.toContentPackEntity(EntityDescriptorIds.empty());
} |
@Override
public <KEY> URIMappingResult<KEY> mapUris(List<URIKeyPair<KEY>> requestUriKeyPairs)
throws ServiceUnavailableException
{
if (requestUriKeyPairs == null || requestUriKeyPairs.isEmpty())
{
return new URIMappingResult<>(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap... | @Test(dataProvider = "stickyPartitionPermutation")
public void testUnmappedKeys(boolean sticky, boolean partitioned) throws Exception
{
int partitionCount = partitioned ? 10 : 1;
int requestPerPartition = 100;
List<Ring<URI>> rings = new ArrayList<>();
IntStream.range(0, partitionCount).forEach(i -... |
@Override
public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
try {
final BrickApiClient client = new BrickApiClient(session);
if(status.isExists()) {
... | @Test
public void testCopyFile() throws Exception {
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final Local local = new Local(System.getProperty("java.io.tmpdir"), test.getName());
final... |
public abstract Map<String, String> properties(final Map<String, String> defaultProperties, final long additionalRetentionMs); | @Test
public void shouldSetCreateTimeByDefaultForUnwindowedUnversionedChangelog() {
final UnwindowedUnversionedChangelogTopicConfig topicConfig = new UnwindowedUnversionedChangelogTopicConfig("name", Collections.emptyMap());
final Map<String, String> properties = topicConfig.properties(Collections.... |
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final Map<Path, List<ObjectKeyAndVersion>> map = new HashMap<>();
final List<Path> containers = new ArrayList<>();
for(Path file : files.keySet()) {
... | @Test
public void testDeleteFile() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new S3To... |
public static BigInteger signedMessageToKey(byte[] message, SignatureData signatureData)
throws SignatureException {
return signedMessageHashToKey(Hash.sha3(message), signatureData);
} | @Test
public void testInvalidSignature() {
assertThrows(
RuntimeException.class,
() ->
Sign.signedMessageToKey(
TEST_MESSAGE,
new Sign.SignatureData((byte) 27, new byte[] {1}, new byte[] ... |
@Override
@Nullable
public boolean[] readBooleanArray() throws EOFException {
int len = readInt();
if (len == NULL_ARRAY_LENGTH) {
return null;
}
if (len > 0) {
boolean[] values = new boolean[len];
for (int i = 0; i < len; i++) {
... | @Test
public void testReadBooleanArray() throws Exception {
byte[] bytesBE = {0, 0, 0, 0, 0, 0, 0, 1, 1, 9, -1, -1, -1, -1};
byte[] bytesLE = {0, 0, 0, 0, 1, 0, 0, 0, 1, 9, -1, -1, -1, -1};
in.init((byteOrder == BIG_ENDIAN ? bytesBE : bytesLE), 0);
in.position(10);
boolean[]... |
double getErrorRateToDegrade()
{
Map<ErrorType, Integer> errorTypeCounts = _callTrackerStats.getErrorTypeCounts();
Integer connectExceptionCount = errorTypeCounts.getOrDefault(ErrorType.CONNECT_EXCEPTION, 0);
Integer closedChannelExceptionCount = errorTypeCounts.getOrDefault(ErrorType.CLOSED_CHANNEL_EXCEP... | @Test(dataProvider = "loadBalanceStreamExceptionDataProvider")
public void testGetErrorRateToDegrade(Boolean loadBalancerStreamException)
{
Map<ErrorType, Integer> errorTypeCounts = ImmutableMap.of(
ErrorType.CONNECT_EXCEPTION, 1,
ErrorType.CLOSED_CHANNEL_EXCEPTION, 1,
ErrorType.SERVER_E... |
@Override
public void registerInstance(String serviceName, String ip, int port) throws NacosException {
registerInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME);
} | @Test
void testRegisterInstance1() throws NacosException {
//given
String serviceName = "service1";
String ip = "1.1.1.1";
int port = 10000;
//when
client.registerInstance(serviceName, ip, port);
//then
verify(proxy, times(1)).registerService(eq(servic... |
public Path getTargetPath() {
return targetPath;
} | @Test
public void testTargetPath() {
final DistCpOptions options = new DistCpOptions.Builder(
new Path("hdfs://localhost:8020/source/first"),
new Path("hdfs://localhost:8020/target/")).build();
Assert.assertEquals(new Path("hdfs://localhost:8020/target/"),
options.getTargetPath());
} |
public int[] get(int intervalRef) {
assert intervalRef < intervalsList.length;
return intervalsList[intervalRef];
} | @Test
void requireThatEqualIntervalListsReturnsSameReference() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
List<Integer> intervals1 = List.of(0x00010001, 0x00020002);
List<Integer> intervals2 = List.of(0x00010001, 0x00020002);
int ref1 = builder.i... |
@Override
@PublicAPI(usage = ACCESS)
public String getDescription() {
String description = origin.getDescription() + " " + descriptionVerb() + " " + getTarget().getDescription();
return description + " in " + getSourceCodeLocation();
} | @Test
public void when_the_origin_is_an_inner_class_the_toplevel_class_is_displayed_as_location() {
TestJavaAccess access = javaAccessFrom(importClassWithContext(SomeClass.Inner.class), "foo")
.to(SomeEnum.class, "bar")
.inLineNumber(7);
assertThat(access.getDescript... |
@Override
protected void encodeInitialLine(ByteBuf buf, HttpRequest request) throws Exception {
ByteBufUtil.copy(request.method().asciiName(), buf);
String uri = request.uri();
if (uri.isEmpty()) {
// Add " / " as absolute path if uri is not present.
// See https://... | @Test
public void testUriWithPath() throws Exception {
for (ByteBuf buffer : getBuffers()) {
HttpRequestEncoder encoder = new HttpRequestEncoder();
encoder.encodeInitialLine(buffer, new DefaultHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.GET, "http://localhost/"))... |
@Udf(description = "Returns the inverse (arc) tangent of y / x")
public Double atan2(
@UdfParameter(
value = "y",
description = "The ordinate (y) coordinate."
) final Integer y,
@UdfParameter(
value = "x",
descriptio... | @Test
public void shouldHandleZeroYNegativeX() {
assertThat(udf.atan2(0.0, -0.24), closeTo(3.141592653589793, 0.000000000000001));
assertThat(udf.atan2(0.0, -7.1), closeTo(3.141592653589793, 0.000000000000001));
assertThat(udf.atan2(0, -3), closeTo(3.141592653589793, 0.000000000000001));
assertThat(ud... |
@Override
public boolean isExisted(final String originalName) {
return encryptTable.isCipherColumn(originalName) || !encryptTable.isAssistedQueryColumn(originalName) && !encryptTable.isLikeQueryColumn(originalName);
} | @Test
void assertIsExistedWithNormalColumn() {
EncryptTable encryptTable = mock(EncryptTable.class);
EncryptColumnExistedReviser reviser = new EncryptColumnExistedReviser(encryptTable);
assertTrue(reviser.isExisted("normal_column"));
} |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchSctpSrcMaskedTest() {
Criterion criterion = Criteria.matchSctpSrcMasked(tpPort, tpPortMask);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
public static Result find(List<Path> files, Consumer<LogEvent> logger) {
List<String> mainClasses = new ArrayList<>();
for (Path file : files) {
// Makes sure classFile is valid.
if (!Files.exists(file)) {
logger.accept(LogEvent.debug("MainClassFinder: " + file + " does not exist; ignoring")... | @Test
public void testFindMainClass_extension() throws URISyntaxException, IOException {
Path rootDirectory =
Paths.get(Resources.getResource("core/class-finder-tests/extension").toURI());
MainClassFinder.Result mainClassFinderResult =
MainClassFinder.find(new DirectoryWalker(rootDirectory).wa... |
@Override
public DeleteConsumerGroupsResult deleteConsumerGroups(Collection<String> groupIds, DeleteConsumerGroupsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, Void> future =
DeleteConsumerGroupsHandler.newFuture(groupIds);
DeleteConsumerGroupsHandler handler = new DeleteCo... | @Test
public void testDeleteMultipleConsumerGroupsWithOlderBroker() throws Exception {
final List<String> groupIds = asList("group1", "group2");
ApiVersion findCoordinatorV3 = new ApiVersion()
.setApiKey(ApiKeys.FIND_COORDINATOR.id)
.setMinVersion((short) 0)
... |
synchronized void add(int splitCount) {
int pos = count % history.length;
history[pos] = splitCount;
count += 1;
} | @Test
public void testOneMoreThanFullHistory() {
EnumerationHistory history = new EnumerationHistory(3);
history.add(1);
history.add(2);
history.add(3);
history.add(4);
int[] expectedHistorySnapshot = {2, 3, 4};
testHistory(history, expectedHistorySnapshot);
} |
public static Area getArea(String ip) {
return AreaUtils.getArea(getAreaId(ip));
} | @Test
public void testGetArea_long() throws Exception {
// 120.203.123.0|120.203.133.255|360900
long ip = Searcher.checkIP("120.203.123.252");
Area area = IPUtils.getArea(ip);
assertEquals("宜春市", area.getName());
} |
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof ExpiryPolicy)) {
return false;
}
var policy = (ExpiryPolicy) o;
return Objects.equals(creation, policy.getExpiryForCreation())
&& Objects.equals(update, policy.getExpiryForUpdate... | @Test
public void equals_wrongType() {
assertThat(eternal.equals(new Object())).isFalse();
} |
@Override
public void failover(NamedNode master) {
connection.sync(RedisCommands.SENTINEL_FAILOVER, master.getName());
} | @Test
public void testFailover() throws InterruptedException {
Collection<RedisServer> masters = connection.masters();
connection.failover(masters.iterator().next());
Thread.sleep(10000);
RedisServer newMaster = connection.masters().iterator().next();
assert... |
@Override
public JWKSet getJWKSet(JWKSetCacheRefreshEvaluator refreshEvaluator, long currentTime, T context)
throws KeySourceException {
var jwksUrl = discoverJwksUrl();
try (var jwkSetSource = new URLBasedJWKSetSource<>(jwksUrl, new HttpRetriever(httpClient))) {
return jwkSetSource.getJWKSet(null... | @Test
void getJWKSet_noKeys(WireMockRuntimeInfo wm) throws KeySourceException {
var jwks = "{\"keys\": []}";
var discoveryUrl = URI.create(wm.getHttpBaseUrl()).resolve(DISCOVERY_PATH);
var jwksUrl = URI.create(wm.getHttpBaseUrl()).resolve(JWKS_PATH);
stubFor(get(DISCOVERY_PATH).willReturn(okJson("... |
@Override
public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter)
throws IOException {
EthCall ethCall =
web3j.ethCall(
Transaction.createEthCallTransaction(getFromAddress(), to, data),
... | @Test
void sendCallErrorSuccess() throws IOException {
EthCall lookupDataHex = new EthCall();
lookupDataHex.setResult(responseData);
Request request = mock(Request.class);
when(request.send()).thenReturn(lookupDataHex);
when(web3j.ethCall(any(Transaction.class), any(DefaultB... |
@Override
public ConfigInfo findConfigInfo(long id) {
try {
ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO);
return this.jt.queryForObject(configInfoMapper.select(
A... | @Test
void testFindConfigInfoByIdNull() {
long id = 1234567890876L;
ConfigInfo configInfo = new ConfigInfo();
configInfo.setId(id);
Mockito.when(jdbcTemplate.queryForObject(anyString(), eq(new Object[] {id}), eq(CONFIG_INFO_ROW_MAPPER)))
.thenThrow(new EmptyResultData... |
public void setIncludeCallerData(boolean includeCallerData) {
this.includeCallerData = includeCallerData;
} | @Test
public void settingIncludeCallerDataPropertyCausedCallerDataToBeIncluded() {
asyncAppender.addAppender(listAppender);
asyncAppender.setIncludeCallerData(true);
asyncAppender.start();
asyncAppender.doAppend(builder.build(diff));
asyncAppender.stop();
// check t... |
@Override
public <E extends Extension> E convertFrom(Class<E> type, ExtensionStore extensionStore) {
try {
var extension = objectMapper.readValue(extensionStore.getData(), type);
extension.getMetadata().setVersion(extensionStore.getVersion());
return extension;
} ... | @Test
void shouldThrowConvertExceptionWhenDataIsInvalid() {
var store = new ExtensionStore();
store.setName("/registry/fake.halo.run/fakes/fake");
store.setVersion(20L);
store.setData("{".getBytes());
assertThrows(ExtensionConvertException.class,
() -> converter.... |
@Restricted(NoExternalUse.class)
public static void skip(@NonNull Iterator<?> iterator, int count) {
if (count < 0) {
throw new IllegalArgumentException();
}
while (iterator.hasNext() && count-- > 0) {
iterator.next();
}
} | @Issue("JENKINS-51779")
@Test
public void skip() {
List<Integer> lst = Iterators.sequence(1, 4);
Iterator<Integer> it = lst.iterator();
Iterators.skip(it, 0);
assertEquals("[1, 2, 3]", com.google.common.collect.Iterators.toString(it));
it = lst.iterator();
Iterato... |
@Override
public void afterPropertiesSet() throws Exception {
if (dataSource == null) {
throw new IllegalArgumentException("datasource required not null!");
}
dbType = getDbTypeFromDataSource(dataSource);
if (getStateLogStore() == null) {
DbAndReportTcStateLo... | @Test
public void testAfterPropertiesSet() throws Exception {
DbStateMachineConfig dbStateMachineConfig = new DbStateMachineConfig();
Connection connection = Mockito.mock(Connection.class);
DatabaseMetaData databaseMetaData = Mockito.mock(DatabaseMetaData.class);
when(connection.getM... |
@Override
public TableEntryByTypeTransformer tableEntryByTypeTransformer() {
return transformer;
} | @Test
void transforms_nulls_with_correct_method() throws Throwable {
Map<String, String> fromValue = singletonMap("key", null);
Method method = JavaDefaultDataTableEntryTransformerDefinitionTest.class.getMethod("correct_method", Map.class,
Type.class);
JavaDefaultDataTableEntryTr... |
public ProcessingNodesState calculateProcessingState(TimeRange timeRange) {
final DateTime updateThresholdTimestamp = clock.nowUTC().minus(updateThreshold.toMilliseconds());
try (DBCursor<ProcessingStatusDto> statusCursor = db.find(activeNodes(updateThresholdTimestamp))) {
if (!statusCursor... | @Test
@MongoDBFixtures("processing-status-no-nodes.json")
public void processingStateNoActiveNodesBecauseNoNodesExists() {
TimeRange timeRange = AbsoluteRange.create("2019-01-01T00:00:00.000Z", "2019-01-01T00:00:30.000Z");
assertThat(dbService.calculateProcessingState(timeRange)).isEqualTo(Proce... |
public String getFileContentInsideZip(ZipInputStream zipInputStream, String file) throws IOException {
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
if (new File(zipEntry.getName()).getName().equals(file)) {
return IOUtils.toString(zipInputStre... | @Test
void shouldReturnNullIfTheFileByTheNameDoesNotExistInsideZip() throws IOException, URISyntaxException {
try (ZipInputStream zip = new ZipInputStream(new FileInputStream(new File(getClass().getResource("/dummy-plugins.zip").toURI())))) {
String contents = zipUtil.getFileContentInsideZip(zip... |
@Transactional
public ConsumerToken createConsumerToken(ConsumerToken entity) {
entity.setId(0); //for protection
return consumerTokenRepository.save(entity);
} | @Test
public void testCreateConsumerToken() throws Exception {
ConsumerToken someConsumerToken = mock(ConsumerToken.class);
ConsumerToken savedConsumerToken = mock(ConsumerToken.class);
when(consumerTokenRepository.save(someConsumerToken)).thenReturn(savedConsumerToken);
assertEquals(savedConsumerTo... |
@Bean("CiConfiguration")
public CiConfiguration provide(Configuration configuration, CiVendor[] ciVendors) {
boolean disabled = configuration.getBoolean(PROP_DISABLED).orElse(false);
if (disabled) {
return new EmptyCiConfiguration();
}
List<CiVendor> detectedVendors = Arrays.stream(ciVendors)
... | @Test
public void fail_if_multiple_ci_vendor_are_detected() {
Throwable thrown = catchThrowable(() -> underTest.provide(cli.asConfig(), new CiVendor[]{new EnabledCiVendor("vendor1"), new EnabledCiVendor("vendor2")}));
assertThat(thrown)
.isInstanceOf(MessageException.class)
.hasMessage("Multiple ... |
public MethodBuilder deprecated(Boolean deprecated) {
this.deprecated = deprecated;
return getThis();
} | @Test
void deprecated() {
MethodBuilder builder = MethodBuilder.newBuilder();
builder.deprecated(true);
Assertions.assertTrue(builder.build().getDeprecated());
} |
@Override
public long read() {
return gaugeSource.read();
} | @Test
public void whenCacheDynamicMetricSourceGcdReadsDefault() {
NullableDynamicMetricsProvider metricsProvider = new NullableDynamicMetricsProvider();
WeakReference<SomeObject> someObjectWeakRef = new WeakReference<>(metricsProvider.someObject);
metricsProvider.someObject.longField = 42;
... |
public static boolean isPrimitiveTypeName(final String name) {
return PRIMITIVE_TYPE_NAMES.contains(name.toUpperCase());
} | @Test
public void shouldNotSupportRandomTypeName() {
// When:
final boolean isPrimitive = SqlPrimitiveType.isPrimitiveTypeName("WILL ROBINSON");
// Then:
assertThat("expected not primitive!", !isPrimitive);
} |
public void applyConfig(ClientBwListDTO configDTO) {
requireNonNull(configDTO, "Client filtering config must not be null");
requireNonNull(configDTO.mode, "Config mode must not be null");
requireNonNull(configDTO.entries, "Config entries must not be null");
ClientSelector selector;
... | @Test
public void testApplyConfig_whitelist() {
ClientBwListDTO config = createConfig(Mode.WHITELIST,
new ClientBwListEntryDTO(Type.IP_ADDRESS, "127.0.0.*"),
new ClientBwListEntryDTO(Type.IP_ADDRESS, "192.168.0.1"),
new ClientBwListEntryDTO(Type.IP_ADDRESS, "1... |
@Override
public void clear() {
if (!isEmpty()) {
notifyRemoval(0, size());
super.clear();
}
} | @Test
public void testClearWhenAlreadyEmpty() {
modelList.clear();
modelList.clear();
verify(observer).onItemRangeRemoved(0, 3);
verifyNoMoreInteractions(observer);
} |
@Override
protected Object createBody() {
if (command instanceof MessageRequest) {
MessageRequest msgRequest = (MessageRequest) command;
byte[] shortMessage = msgRequest.getShortMessage();
if (shortMessage == null || shortMessage.length == 0) {
return null... | @Test
public void createBodyShouldNotMangle8bitDataCodingShortMessage() {
final Set<String> encodings = Charset.availableCharsets().keySet();
final byte[] dataCodings = {
(byte) 0x02,
(byte) 0x04,
(byte) 0xF6,
(byte) 0xF4
};
... |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
final SMBSession.DiskShareWrapper share = session.openShare(file);
try {
if(new SMBPat... | @Test
public void testFindDirectory() throws Exception {
assertTrue(new SMBFindFeature(session).find(new DefaultHomeFinderService(session).find()));
} |
public static TimestampRange of(Timestamp from, Timestamp to) {
return new TimestampRange(from, to);
} | @Test
public void testTimestampRangeWhenFromIsEqualToTo() {
assertEquals(
new TimestampRange(Timestamp.ofTimeMicroseconds(10L), Timestamp.ofTimeMicroseconds(10L)),
TimestampRange.of(Timestamp.ofTimeMicroseconds(10L), Timestamp.ofTimeMicroseconds(10L)));
} |
@Override
public void updateLevel(int level) {
Preconditions.checkArgument(
level >= 0 && level <= MAX_LEVEL,
"level(" + level + ") must be non-negative and no more than " + MAX_LEVEL);
Preconditions.checkArgument(
level <= this.topLevel + 1,
... | @Test
void testUpdateToMoreThanMaximumAllowed() {
assertThatThrownBy(() -> heapHeadIndex.updateLevel(MAX_LEVEL + 1))
.isInstanceOf(IllegalArgumentException.class);
} |
@Override
public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (TokenReloadAction.tokenReloadEnabled()) {
String pathInfo = request.getPathInfo();
if (pathInfo != null && pathInfo.eq... | @Test
public void crumbExclustionAllowsReloadIfEnabledAndRequestPathMatch() throws Exception {
System.setProperty("casc.reload.token", "someSecretValue");
TokenReloadCrumbExclusion crumbExclusion = new TokenReloadCrumbExclusion();
AtomicBoolean callProcessed = new AtomicBoolean(false);
... |
public static <T> T execute(Single<T> apiCall) {
try {
return apiCall.blockingGet();
} catch (HttpException e) {
try {
if (e.response() == null || e.response().errorBody() == null) {
throw e;
}
String errorBody =... | @Test
void executeParseUnknownProperties() {
// error body contains one unknown property and no message
String errorBody = "{\"error\":{\"unknown\":\"Invalid auth token\",\"type\":\"type\",\"param\":\"param\",\"code\":\"code\"}}";
HttpException httpException = createException(errorBody, 401)... |
@POST
@Path("{networkId}/hosts")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createVirtualHost(@PathParam("networkId") long networkId,
InputStream stream) {
try {
ObjectNode jsonTree = readTreeFromS... | @Test
public void testPostVirtualHost() {
NetworkId networkId = networkId3;
expect(mockVnetAdminService.createVirtualHost(networkId, hId1, mac1, vlan1, loc1, ipSet1))
.andReturn(vhost1);
replay(mockVnetAdminService);
WebTarget wt = target();
InputStream jsonS... |
@Override
public Optional<Asset> findAssetsByTenantIdAndName(UUID tenantId, String name) {
Asset asset = DaoUtil.getData(assetRepository.findByTenantIdAndName(tenantId, name));
return Optional.ofNullable(asset);
} | @Test
public void testFindAssetsByTenantIdAndName() {
UUID assetId = Uuids.timeBased();
String name = "TEST_ASSET";
assets.add(saveAsset(assetId, tenantId2, customerId2, name));
Optional<Asset> assetOpt1 = assetDao.findAssetsByTenantIdAndName(tenantId2, name);
assertTrue("Op... |
@NonNull
@Override
public Object configure(CNode config, ConfigurationContext context) throws ConfiguratorException {
return Stapler.lookupConverter(target)
.convert(
target,
context.getSecretSourceResolver()
... | @Test
public void _Integer_env() throws Exception {
environment.set("ENV_FOR_TEST", "123");
Configurator c = registry.lookupOrFail(Integer.class);
final Object value = c.configure(new Scalar("${ENV_FOR_TEST}"), context);
assertEquals(123, (int) value);
} |
@Override
@Nullable
public byte[] readByteArray(@Nonnull String fieldName) throws IOException {
return readIncompatibleField(fieldName, BYTE_ARRAY, super::readByteArray);
} | @Test(expected = IncompatibleClassChangeError.class)
public void testReadShortArray_IncompatibleClass() throws Exception {
reader.readByteArray("byte");
} |
@Override
public Object convert(String value) {
if (value == null || value.isEmpty()) {
return 0;
}
return value.split(splitByEscaped).length;
} | @Test
public void testConvert() throws Exception {
assertEquals(0, new SplitAndCountConverter(config("x")).convert(""));
assertEquals(1, new SplitAndCountConverter(config("_")).convert("foo-bar-baz"));
assertEquals(1, new SplitAndCountConverter(config("-")).convert("foo"));
assertEqu... |
public void processOnce() throws IOException {
// set status of query to OK.
ctx.getState().reset();
executor = null;
// reset sequence id of MySQL protocol
final MysqlChannel channel = ctx.getMysqlChannel();
channel.setSequenceId(0);
// read packet from channel
... | @Test
public void testFieldListFailNoTable() throws Exception {
MysqlSerializer serializer = MysqlSerializer.newInstance();
serializer.writeInt1(4);
serializer.writeNulTerminateString("emptyTable");
serializer.writeEofString("");
myContext.setDatabase("testDb1");
Con... |
public abstract byte[] encode(MutableSpan input); | @Test void span_noLocalServiceName_JSON_V2() {
clientSpan.localServiceName(null);
assertThat(new String(encoder.encode(clientSpan), UTF_8))
.isEqualTo(
"{\"traceId\":\"7180c278b62e8f6a216a2aea45d08fc9\",\"parentId\":\"6b221d5bc9e6496c\",\"id\":\"5b4185666d50f68b\",\"kind\":\"CLIENT\",\"name... |
@Udf
public String lpad(
@UdfParameter(description = "String to be padded") final String input,
@UdfParameter(description = "Target length") final Integer targetLen,
@UdfParameter(description = "Padding string") final String padding) {
if (input == null) {
return null;
}
if (paddi... | @Test
public void shouldAppendPartialPaddingString() {
final String result = udf.lpad("foo", 4, "Bar");
assertThat(result, is("Bfoo"));
} |
@Bean
public PluginDataHandler jwtPluginDataHandler() {
return new JwtPluginDataHandler();
} | @Test
public void testJwtPluginDataHandler() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JwtPluginConfiguration.class))
.withBean(JwtPluginConfigurationTest.class)
.withPropertyValues("debug=true")
.run(context -> {
... |
@VisibleForTesting
static String extractTableName(MultivaluedMap<String, String> pathParameters,
MultivaluedMap<String, String> queryParameters) {
String tableName = extractTableName(pathParameters);
if (tableName != null) {
return tableName;
}
return extractTableName(queryParameters);
} | @Test
public void testExtractTableNameWithSchemaNameInQueryParams() {
MultivaluedMap<String, String> pathParams = new MultivaluedHashMap<>();
MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
queryParams.putSingle("schemaName", "F");
assertEquals(AuthenticationFilter.extractTabl... |
public static <T> T createInstance(String userClassName,
Class<T> xface,
ClassLoader classLoader) {
Class<?> theCls;
try {
theCls = Class.forName(userClassName, true, classLoader);
} catch (ClassNotFoundExc... | @Test
public void testCreateInstanceAbstractClass() {
try {
createInstance(AbstractClass.class.getName(), classLoader);
fail("Should fail to load abstract class");
} catch (RuntimeException re) {
assertTrue(re.getCause() instanceof InstantiationException);
... |
public static String dateToStr(Date date) {
return dateToStr(date, DATE_FORMAT_TIME);
} | @Test
public void dateToStr1() throws Exception {
long d0 = 0l;
long d1 = 1501127802975l; // 2017-07-27 11:56:42:975 +8
long d2 = 1501127835658l; // 2017-07-27 11:57:15:658 +8
TimeZone timeZone = TimeZone.getDefault();
Date date0 = new Date(d0 - timeZone.getOffset(d0));
... |
@SuppressWarnings("checkstyle:BooleanExpressionComplexity")
public static Optional<KeyStoreOptions> getBcfksTrustStoreOptions(
final Map<String, String> props) {
final String location = getTrustStoreLocation(props);
final String password = getTrustStorePassword(props);
final String trustManagerAlgor... | @Test
public void shouldReturnEmptyTrustStoreBCFKSOptionsIfPasswordIsEmpty() {
// When
final Optional<KeyStoreOptions> keyStoreOptions = VertxSslOptionsFactory.getBcfksTrustStoreOptions(
ImmutableMap.of()
);
// Then
assertThat(keyStoreOptions, is(Optional.empty()));
} |
@Override
@Nonnull
public <T> T invokeAny(@Nonnull Collection<? extends Callable<T>> tasks)
throws ExecutionException {
throwRejectedExecutionExceptionIfShutdown();
Exception exception = null;
for (Callable<T> task : tasks) {
try {
return task.ca... | @Test
void testInvokeAnyWithTimeoutAndNoopShutdown() {
final CompletableFuture<Thread> future = new CompletableFuture<>();
testWithNoopShutdown(
testInstance ->
testInstance.invokeAny(
callableCollectionFromFuture(future), 1, Ti... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testLambdaCapture()
{
analyze("SELECT apply(c1, x -> x + c2) FROM (VALUES (1, 2), (3, 4), (5, 6)) t(c1, c2)");
analyze("SELECT apply(c1 + 10, x -> apply(x + 100, y -> c1)) FROM (VALUES 1) t(c1)");
// reference lambda variable of the not-immediately-enclosing lambda
... |
@Override
public void callback(CallbackContext context) {
try {
onCallback(context);
} catch (IOException | ExecutionException e) {
throw new IllegalStateException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
... | @Test
public void callback_whenOrganizationsAreDefinedAndUserBelongsToOne_shouldAuthenticateAndRedirect() throws IOException, ExecutionException, InterruptedException {
UserIdentity userIdentity = mock(UserIdentity.class);
CallbackContext context = mockUserBelongingToOrganization(userIdentity);
settings.... |
public static boolean isTimeoutException(Throwable exception) {
if (exception == null) return false;
if (exception instanceof ExecutionException) {
exception = exception.getCause();
if (exception == null) return false;
}
return exception instanceof TimeoutExceptio... | @Test
public void testTimeoutExceptionIsTimeoutException() {
assertTrue(isTimeoutException(new TimeoutException()));
} |
public Result parse(final String string) throws DateNotParsableException {
return this.parse(string, new Date());
} | @Test
public void testThisMonth() throws Exception {
DateTime reference = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss").withZoneUTC().parseDateTime("12.06.2021 09:45:23");
NaturalDateParser.Result result = naturalDateParser.parse("this month", reference.toDate());
DateTime first = DateTi... |
@Override
public int read() throws IOException {
return ( (SnappyInputStream) delegate ).read();
} | @Test
public void testRead() throws IOException {
assertEquals( inStream.available(), inStream.read( new byte[100], 0, inStream.available() ) );
} |
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
... | @Test
public void testJsonConversionForSimpleTypes() throws Exception {
SimpleTypes options = PipelineOptionsFactory.as(SimpleTypes.class);
options.setString("TestValue");
options.setInteger(5);
SimpleTypes options2 = serializeDeserialize(SimpleTypes.class, options);
assertEquals(5, options2.getIn... |
@Override
public void start() {
initHealthChecker();
NamespacedPodListInformer.INFORMER.init(config, new K8sResourceEventHandler());
} | @Test
public void queryRemoteNodesWhenInformerNotwork() throws Exception {
withEnvironmentVariable(SELF_UID, SELF_UID + "0").execute(() -> {
providerA = createProvider(SELF_UID);
coordinatorA = getClusterCoordinator(providerA);
coordinatorA.start();
});
K... |
@Override
public void deleteDiscountActivity(Long id) {
// 校验存在
DiscountActivityDO activity = validateDiscountActivityExists(id);
if (CommonStatusEnum.isEnable(activity.getStatus())) { // 未关闭的活动,不能删除噢
throw exception(DISCOUNT_ACTIVITY_DELETE_FAIL_STATUS_NOT_CLOSED);
}
... | @Test
public void testDeleteDiscountActivity_success() {
// mock 数据
DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class,
o -> o.setStatus(PromotionActivityStatusEnum.CLOSE.getStatus()));
discountActivityMapper.insert(dbDiscountActivity);// @Sql: 先插入出一条... |
@Override
public int getColumnLength(final Object value) {
return 4;
} | @Test
void assertGetColumnLength() {
assertThat(new PostgreSQLDateBinaryProtocolValue().getColumnLength(""), is(4));
} |
public List<QueuedCommand> getRestoreCommands(final Duration duration) {
if (commandTopicBackup.commandTopicCorruption()) {
log.warn("Corruption detected. "
+ "Use backup to restore command topic.");
return Collections.emptyList();
}
return getAllCommandsInCommandTopic(
command... | @Test
public void shouldGetRestoreCommandsCorrectlyWithDuplicateKeys() {
// Given:
when(commandConsumer.poll(any(Duration.class)))
.thenReturn(someConsumerRecords(
new ConsumerRecord<>("topic", 0, 0, commandId1, command1),
new ConsumerRecord<>("topic", 0, 1, commandId2, command... |
static URI determineClasspathResourceUri(Path baseDir, String basePackagePath, Path resource) {
String subPackageName = determineSubpackagePath(baseDir, resource);
String resourceName = resource.getFileName().toString();
String classpathResourcePath = of(basePackagePath, subPackageName, resource... | @Test
void determineFullyQualifiedResourceNameFromComPackage() {
Path baseDir = Paths.get("path", "to", "com");
String basePackageName = "com";
Path resourceFile = Paths.get("path", "to", "com", "example", "app", "app.feature");
URI fqn = ClasspathSupport.determineClasspathResourceUr... |
@Override
public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException {
try {
if(!session.getClient().makeDirectory(folder.getAbsolute())) {
throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString());
... | @Test
public void testMakeDirectory() throws Exception {
final Path test = new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory));
new FTPDirectoryFeature(session).mkdir(test, new TransferStatus());
assertTrue(session.getFeature(Find.cl... |
public Analysis analyze(
final Query query,
final Optional<Sink> sink
) {
final Analysis analysis = analyzer.analyze(query, sink);
if (query.isPullQuery()) {
pullQueryValidator.validate(analysis);
} else {
pushQueryValidator.validate(analysis);
}
if (!analysis.getTableFun... | @Test
public void shouldPreThenPostValidateContinuousQueries() {
// Given:
when(query.isPullQuery()).thenReturn(false);
// When:
queryAnalyzer.analyze(query, Optional.of(sink));
// Then:
verify(continuousValidator).validate(analysis);
verifyNoMoreInteractions(staticValidator);
} |
@Nullable
public static URI normalizeURI(@Nullable final URI uri, String scheme, int port, String path) {
return Optional.ofNullable(uri)
.map(u -> getUriWithScheme(u, scheme))
.map(u -> getUriWithPort(u, port))
.map(u -> getUriWithDefaultPath(u, path))
... | @Test
public void normalizeURIReturnsNullIfURIIsNull() {
assertNull(Tools.normalizeURI(null, "http", 1234, "/baz"));
} |
@Override
public MaskRule build(final MaskRuleConfiguration ruleConfig, final String databaseName, final DatabaseType protocolType,
final ResourceMetaData resourceMetaData, final Collection<ShardingSphereRule> builtRules, final ComputeNodeInstanceContext computeNodeInstanceContext) {
... | @SuppressWarnings("unchecked")
@Test
void assertBuild() {
MaskRuleConfiguration ruleConfig = mock(MaskRuleConfiguration.class);
DatabaseRuleBuilder<MaskRuleConfiguration> builder = OrderedSPILoader.getServices(DatabaseRuleBuilder.class, Collections.singleton(ruleConfig)).get(ruleConfig);
... |
public int countScimGroups(DbSession dbSession, ScimGroupQuery query) {
return mapper(dbSession).countScimGroups(query);
} | @Test
void countScimGroups_shouldReturnTheTotalNumberOfScimGroups() {
int totalScimGroups = 15;
generateScimGroups(totalScimGroups);
assertThat(scimGroupDao.countScimGroups(db.getSession(), ScimGroupQuery.ALL)).isEqualTo(totalScimGroups);
} |
public static int isBinary(String str) {
if (str == null || str.isEmpty()) {
return -1;
}
return str.matches("[01]+") ? MIN_RADIX : -1;
} | @Test
public void isBinary_Test() {
Assertions.assertEquals(2, TbUtils.isBinary("1100110"));
Assertions.assertEquals(-1, TbUtils.isBinary("2100110"));
} |
@Override
public final boolean offer(int ordinal, @Nonnull Object item) {
if (ordinal == -1) {
return offerInternal(allEdges, item);
} else {
if (ordinal == bucketCount()) {
// ordinal beyond bucketCount will add to snapshot queue, which we don't allow through... | @Test
public void when_offer1_then_rateLimited() {
do_when_offer_then_rateLimited(e -> outbox.offer(e));
} |
public String format(Date then)
{
if (then == null)
then = now();
Duration d = approximateDuration(then);
return format(d);
} | @Test
public void testDecadesAgo() throws Exception
{
PrettyTime t = new PrettyTime(now);
Assert.assertEquals("3 decades ago", t.format(now.minus(3, ChronoUnit.DECADES)));
} |
@Override
public Destination createTemporaryDestination(final Session session, final boolean topic) throws JMSException {
if (topic) {
return session.createTemporaryTopic();
} else {
return session.createTemporaryQueue();
}
} | @Test
public void testTemporaryTopicCreation() throws Exception {
TemporaryTopic destination = (TemporaryTopic) strategy.createTemporaryDestination(getSession(), true);
assertNotNull(destination);
assertNotNull(destination.getTopicName());
} |
public static MemorySegment wrapCopy(byte[] bytes, int start, int end)
throws IllegalArgumentException {
checkArgument(end >= start);
checkArgument(end <= bytes.length);
MemorySegment copy = allocateUnpooledSegment(end - start);
copy.put(0, bytes, start, copy.size());
... | @Test
void testWrapCopyWrongEnd() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> MemorySegmentFactory.wrapCopy(new byte[] {1, 2, 3}, 0, 10));
} |
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE",
justification = "Handled in switchIfEmpty")
@Override
public HouseTable save(HouseTable entity) {
CreateUpdateEntityRequestBodyUserTable requestBody =
new CreateUpdateEntityRequestBodyUserT... | @Test
public void testRepoSaveWithEmptyMono() {
// Leave the entity as empty.
EntityResponseBodyUserTable putResponse = new EntityResponseBodyUserTable();
mockHtsServer.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody((new Gson()).toJson(putResponse))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.