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 testLoadYamlFile() throws Exception {
File confFile = new File(tmpDir, "test.yaml");
try (final PrintWriter pw = new PrintWriter(confFile)) {
pw.println("key1: value1");
pw.println("key2: ");
pw.println(" subKey1: value2");
pw.println("key3... |
public Future<KafkaCluster> prepareKafkaCluster(
Kafka kafkaCr,
List<KafkaNodePool> nodePools,
Map<String, Storage> oldStorage,
Map<String, List<String>> currentPods,
KafkaVersionChange versionChange,
KafkaStatus kafkaStatus,
boolean tr... | @Test
public void testNewClusterWithKRaft(VertxTestContext context) {
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false);
KafkaStatus kafkaStatus = new KafkaStatus();
KafkaClusterCreator creator = new KafkaClusterCreator(vertx, RECONCILIATION, CO_CONFIG, KafkaMetadat... |
@Override
public CommandLineImpl parse(final List<String> originalArgs, final Logger logger) {
return CommandLineImpl.of(originalArgs, logger);
} | @Test
public void testVersion() throws Exception {
final CommandLineParserImpl parser = new CommandLineParserImpl();
final CommandLineImpl commandLine = parse(parser, "--version");
assertEquals(Command.NONE, commandLine.getCommand());
assertEquals("Embulk " + EmbulkVersion.VERSION +... |
@PublicEvolving
public static <IN1, IN2, OUT> TypeInformation<OUT> getCoGroupReturnTypes(
CoGroupFunction<IN1, IN2, OUT> coGroupInterface,
TypeInformation<IN1> in1Type,
TypeInformation<IN2> in2Type) {
return getCoGroupReturnTypes(coGroupInterface, in1Type, in2Type, null, ... | @SuppressWarnings({"rawtypes", "unchecked"})
@Test
void testBasicArray() {
// use getCoGroupReturnTypes()
RichCoGroupFunction<?, ?, ?> function =
new RichCoGroupFunction<String[], String[], String[]>() {
private static final long serialVersionUID = 1L;
... |
static void checkValidIndexName(String indexName) {
if (indexName.length() > MAX_INDEX_NAME_LENGTH) {
throw new IllegalArgumentException(
"Index name "
+ indexName
+ " cannot be longer than "
+ MAX_INDEX_NAME_LENGTH
+ " characters.");
}
... | @Test
public void testCheckValidIndexNameThrowsErrorWhenNameContainsPoundSymbol() {
assertThrows(IllegalArgumentException.class, () -> checkValidIndexName("test#collection"));
} |
@VisibleForTesting
void setTimeout(FTPClient client, Configuration conf) {
long timeout = conf.getLong(FS_FTP_TIMEOUT, DEFAULT_TIMEOUT);
client.setControlKeepAliveTimeout(timeout);
} | @Test
public void testFTPSetTimeout() {
Configuration conf = new Configuration();
FTPClient client = new FTPClient();
FTPFileSystem ftp = new FTPFileSystem();
ftp.setTimeout(client, conf);
assertEquals(client.getControlKeepAliveTimeout(),
FTPFileSystem.DEFAULT_TIMEOUT);
long timeout ... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
// {"code":400,"message":"Bad Request","debugInfo":"Node ID must be positive.","errorCode":-80001}
final PathAttributes attributes = new PathAtt... | @Test(expected = NotfoundException.class)
public void testFindNotFound() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.... |
@Override
public ByteBuffer nioBuffer() {
return nioBuffer(readerIndex, readableBytes());
} | @Test
public void testNioBufferAfterRelease1() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().nioBuffer(0, 1);
}
});
} |
@Udf
public <T> List<T> slice(
@UdfParameter(description = "the input array") final List<T> in,
@UdfParameter(description = "start index") final Integer from,
@UdfParameter(description = "end index") final Integer to) {
if (in == null) {
return null;
}
try {
// ... | @Test
public void shouldReturnNullOnIndexError() {
// Given:
final List<String> list = Lists.newArrayList("a", "b", "c");
// When:
final List<String> slice = new Slice().slice(list, 2, 5);
// Then:
assertThat(slice, nullValue());
} |
@Override
@SuppressWarnings("BanSerializableRead")
protected Object deserialize(byte[] data, ClassLoader classLoader) {
try (var bytes = new ByteArrayInputStream(data);
var input = newInputStream(bytes, classLoader)) {
return input.readObject();
} catch (IOException e) {
throw new Cache... | @Test(dataProvider = "copier")
public void deserializable_badData(JavaSerializationCopier copier) {
assertThrows(CacheException.class, () ->
copier.deserialize(new byte[0], Thread.currentThread().getContextClassLoader()));
} |
@Override
public boolean isAllowedTaskMovement(final ClientState source, final ClientState destination) {
final Map<String, String> sourceClientTags = clientTagFunction.apply(source.processId(), source);
final Map<String, String> destinationClientTags = clientTagFunction.apply(destination.processId(... | @Test
public void shouldPermitSingleTaskMoveWhenDifferentClientTagCountNotChange() {
final ClientState source = createClientStateWithCapacity(PID_1, 1, mkMap(mkEntry(ZONE_TAG, ZONE_1), mkEntry(CLUSTER_TAG, CLUSTER_1)));
final ClientState destination = createClientStateWithCapacity(PID_2, 1, mkMap(mk... |
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> rule... | @Test
public void create_with_rule_key_that_does_not_exist_in_the_db() {
db.users().insertUser(u -> u.setLogin("joanna"));
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
db.components().insertComponent(newFileDto(project));
newRule(RuleKey.of("findbugs", "NullR... |
static String getUsernameFromConf(Configuration conf) {
String oldStyleUgi = conf.get(DEPRECATED_UGI_KEY);
if (oldStyleUgi != null) {
// We can't use the normal configuration deprecation mechanism here
// since we need to split out the username from the configured UGI.
LOG.warn(DEPRECATED_UGI_... | @Test
public void testOldStyleConfiguration() {
Configuration conf = new Configuration();
conf.set("dfs.web.ugi", "joe,group1,group2");
assertEquals("joe", StaticUserWebFilter.getUsernameFromConf(conf));
} |
protected Long getRoleIdByNameNoLock(String name) throws PrivilegeException {
Long roleId = roleNameToId.get(name);
if (roleId == null) {
throw new PrivilegeException(String.format("Role %s doesn't exist!", name));
}
return roleId;
} | @Test
public void testSetRole() throws Exception {
GlobalVariable.setActivateAllRolesOnLogin(false);
AuthorizationMgr manager = ctx.getGlobalStateMgr().getAuthorizationMgr();
// create user
DDLStmtExecutor.execute(UtFrameUtils.parseStmtWithNewParser(
String.format("cr... |
public PrepareResult prepare(HostValidator hostValidator, DeployLogger logger, PrepareParams params,
Optional<ApplicationVersions> activeApplicationVersions, Instant now, File serverDbSessionDir,
ApplicationPackage applicationPackage, SessionZooKeeperCli... | @Test(expected = InvalidApplicationException.class)
public void require_exception_for_overlapping_host() throws IOException {
FilesApplicationPackage app = getApplicationPackage(testApp);
HostRegistry hostValidator = new HostRegistry();
hostValidator.update(applicationId("foo"), List.of("myt... |
@Override
public void validate(final String name, final Object value) {
if (immutableProps.contains(name)) {
throw new IllegalArgumentException(String.format("Cannot override property '%s'", name));
}
final Consumer<Object> validator = HANDLERS.get(name);
if (validator != null) {
validato... | @Test
public void shouldNotThrowOnOtherOffsetReset() {
validator.validate(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "caught-by-normal-mech");
} |
@Override
public void updateGroupDescription(DeviceId deviceId,
GroupKey oldAppCookie,
UpdateType type,
GroupBuckets newBuckets,
GroupKey newAppCookie) {
... | @Test
public void testUpdateGroupDescription() {
GroupBuckets buckets = new GroupBuckets(ImmutableList.of(allGroupBucket2));
groupStore.deviceInitialAuditCompleted(deviceId1, true);
groupStore.storeGroupDescription(groupDescription1);
GroupKey newKey = new DefaultGroupKey("123".get... |
@Override
public Num calculate(BarSeries series, Position position) {
return criterion.calculate(series, position).dividedBy(enterAndHoldCriterion.calculate(series, position));
} | @Test
public void calculateWithNoPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70);
AnalysisCriterion buyAndHold = getCriterion(new ReturnCriterion());
assertNumEquals(1 / 0.7, buyAndHold.calculate(series, new BaseTradingRecord()));
} |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.NOTIFY_TEMPLATE,
allEntries = true) // allEntries 清空所有缓存,因为可能修改到 code 字段,不好清理
public void updateNotifyTemplate(NotifyTemplateSaveReqVO updateReqVO) {
// 校验存在
validateNotifyTemplateExists(updateReqVO.getId());
// 校验站内信编码是否重复... | @Test
public void testUpdateNotifyTemplate_success() {
// mock 数据
NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class);
notifyTemplateMapper.insert(dbNotifyTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
NotifyTemplateSaveReqVO reqVO = randomPojo(NotifyTemplateSaveRe... |
public static String prepareUrl(@NonNull String url) {
url = url.trim();
String lowerCaseUrl = url.toLowerCase(Locale.ROOT); // protocol names are case insensitive
if (lowerCaseUrl.startsWith("feed://")) {
Log.d(TAG, "Replacing feed:// with http://");
return prepareUrl(ur... | @Test
public void testPcastProtocolNoScheme() {
final String in = "pcast://example.com";
final String out = UrlChecker.prepareUrl(in);
assertEquals("http://example.com", out);
} |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuffer buf = new StringBuffer();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_STATE:
handleLiteralState(c,... | @Test
public void testSingleLiteral() throws ScanException {
List<Token> tl = new TokenStream("hello").tokenize();
List<Token> witness = new ArrayList<Token>();
witness.add(new Token(Token.LITERAL, "hello"));
assertEquals(witness, tl);
} |
public static Stream<ItemSet> apply(FPTree tree) {
FPGrowth growth = new FPGrowth(tree);
return StreamSupport.stream(growth.spliterator(), false);
} | @Test
public void testKosarak() {
System.out.println("kosarak");
FPTree tree = FPTree.of(1500, () -> ItemSetTestData.read("transaction/kosarak.dat"));
assertEquals(219725, FPGrowth.apply(tree).count());
} |
@Override
public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) {
Map<Integer, ItemDTO> oldLineNumMapItem = BeanUtils.mapByKey("lineNum", baseItems);
Map<String, ItemDTO> oldKeyMapItem = BeanUtils.mapByKey("key", baseItems);
//remove comment and blank item map.
... | @Test
public void testUpdateCommentItem() {
ItemChangeSets changeSets = resolver.resolve(1, "#ww\n"
+ "a=b\n"
+"\n"
+ "b=c", mockBaseItemWith2Key1Comment1Bla... |
public PipelineTemplateConfig templateByName(CaseInsensitiveString foo) {
for (PipelineTemplateConfig templateConfig : this) {
if (templateConfig.name().equals(foo)) {
return templateConfig;
}
}
return null;
} | @Test
public void shouldReturnNullIfTemplateIsNotFound() {
PipelineTemplateConfig template1 = template("template1");
TemplatesConfig templates = new TemplatesConfig(template1);
assertThat(templates.templateByName(new CaseInsensitiveString("some_invalid_template")), is(nullValue()));
} |
public synchronized long nextGtid() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
timestamp = lastTimestamp;
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & MAX_SEQUENCE;
if (sequence == 0) {
timestamp... | @Test
public void testNextGtidResetsSequenceOnNewMillisecond() throws InterruptedException {
long firstGtid = gtidGenerator.nextGtid();
Thread.sleep(1); // Ensure the next GTID is in a new millisecond
long nextGtid = gtidGenerator.nextGtid();
Assertions.assertTrue((nextGtid & GtidGe... |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldHandleMultipleAliasedJoinDataSources() {
// Given:
final SingleStatementContext stmt = givenQuery("SELECT * FROM TEST1 t1 "
+ "JOIN TEST2 t2 ON t1.col1 = t2.col1 "
+ "JOIN TEST3 t3 ON t1.col1 = t3.col1;");
// When:
final Query result = (Query) builder.buildStat... |
public int getUnknown_000c() {
return unknown_000c;
} | @Test
public void getUnknown_000c() {
assertEquals(TestParameters.VP_UNKNOWN_000C, chmItsfHeader.getUnknown_000c());
} |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateCodegen(CodegenUpdateReqVO updateReqVO) {
// 校验是否已经存在
if (codegenTableMapper.selectById(updateReqVO.getTable().getId()) == null) {
throw exception(CODEGEN_TABLE_NOT_EXISTS);
}
// 校验主表字段存在
... | @Test
public void testUpdateCodegen_sub_masterNotExists() {
// mock 数据
CodegenTableDO table = randomPojo(CodegenTableDO.class,
o -> o.setTemplateType(CodegenTemplateTypeEnum.SUB.getType())
.setScene(CodegenSceneEnum.ADMIN.getScene()));
codegenTableMapp... |
public synchronized Collection<StreamsMetadata> getAllMetadataForStore(final String storeName) {
Objects.requireNonNull(storeName, "storeName cannot be null");
if (topologyMetadata.hasNamedTopologies()) {
throw new IllegalArgumentException("Cannot invoke the getAllMetadataForStore(storeName)... | @Test
public void shouldHaveGlobalStoreInAllMetadata() {
final Collection<StreamsMetadata> metadata = metadataState.getAllMetadataForStore(globalTable);
assertEquals(3, metadata.size());
for (final StreamsMetadata streamsMetadata : metadata) {
assertTrue(streamsMetadata.stateStor... |
@Override
public Long del(byte[]... keys) {
if (isQueueing() || isPipelined()) {
for (byte[] key: keys) {
write(key, LongCodec.INSTANCE, RedisCommands.DEL, key);
}
return null;
}
CommandBatchService es = new CommandBatchService(executorSe... | @Test
public void testDel() {
testInCluster(connection -> {
List<byte[]> keys = new ArrayList<>();
for (int i = 0; i < 10; i++) {
byte[] key = ("test" + i).getBytes();
keys.add(key);
connection.set(key, ("test" + i).getBytes());
... |
@Override
public List<PartitionGroupMetadata> computePartitionGroupMetadata(String clientId, StreamConfig streamConfig,
List<PartitionGroupConsumptionStatus> partitionGroupConsumptionStatuses, int timeoutMillis)
throws IOException, TimeoutException {
List<PartitionGroupMetadata> newPartitionGroupMeta... | @Test
public void getPartitionsGroupInfoEndOfShardTest()
throws Exception {
List<PartitionGroupConsumptionStatus> currentPartitionGroupMeta = new ArrayList<>();
KinesisPartitionGroupOffset kinesisPartitionGroupOffset = new KinesisPartitionGroupOffset("0", "1");
currentPartitionGroupMeta.add(
... |
@Override
public List<String> splitAndEvaluate() {
return Strings.isNullOrEmpty(inlineExpression) ? Collections.emptyList() : flatten(evaluate(GroovyUtils.split(handlePlaceHolder(inlineExpression))));
} | @Test
void assertEvaluateForExpressionIsNull() {
InlineExpressionParser parser = TypedSPILoader.getService(InlineExpressionParser.class, "GROOVY", new Properties());
List<String> expected = parser.splitAndEvaluate();
assertThat(expected, is(Collections.<String>emptyList()));
} |
@Override
protected void doStop() throws Exception {
shutdownReconnectService(reconnectService);
LOG.debug("Disconnecting from: {}...", getEndpoint().getConnectionString());
super.doStop();
closeSession();
LOG.info("Disconnected from: {}", getEndpoint().getConnectionString... | @Test
public void doStopShouldNotCloseTheSMPPSessionIfItIsNull() throws Exception {
when(endpoint.getConnectionString())
.thenReturn("smpp://smppclient@localhost:2775");
when(endpoint.isSingleton()).thenReturn(true);
producer.doStop();
} |
public List<ScanFilterData> createScanFilterDataForBeaconParser(BeaconParser beaconParser, List<Identifier> identifiers) {
ArrayList<ScanFilterData> scanFilters = new ArrayList<ScanFilterData>();
long typeCode = beaconParser.getMatchingBeaconTypeCode();
int startOffset = beaconParser.getMatching... | @Test
public void testGetAltBeaconScanFilter() throws Exception {
org.robolectric.shadows.ShadowLog.stream = System.err;
BeaconParser parser = new AltBeaconParser();
BeaconManager.setManifestCheckingDisabled(true); // no manifest available in robolectric
List<ScanFilterUtils.ScanFilt... |
public Boolean isRevisionSupported() {
if(!zConf.getBoolean(ConfVars.ZEPPELIN_NOTEBOOK_VERSIONED_MODE_ENABLE)) {
return false;
}
if (notebookRepo instanceof NotebookRepoSync) {
return ((NotebookRepoSync) notebookRepo).isRevisionSupportedInDefaultRepo();
} else if (notebookRepo instanceof Not... | @Test
void testRevisionSupported() throws IOException {
NotebookRepo notebookRepo;
Notebook notebook;
notebookRepo = new DummyNotebookRepo();
notebook = new Notebook(zConf, mock(AuthorizationService.class), notebookRepo, new NoteManager(notebookRepo, zConf), interpreterFactory,
interpreterSet... |
@Override
public DataSourceProvenance getProvenance() {
return new DemoLabelDataSourceProvenance(this);
} | @Test
public void testCheckerboard() {
// Check zero samples throws
assertThrows(PropertyException.class, () -> new CheckerboardDataSource(0, 1, 10, 0.0, 1.0));
// Check invalid numSquares throws
assertThrows(PropertyException.class, () -> new CheckerboardDataSource(200, 1, 1, 0.0, 1... |
static String levelToString(String feature, short level) {
if (feature.equals(MetadataVersion.FEATURE_NAME)) {
try {
return MetadataVersion.fromFeatureLevel(level).version();
} catch (Throwable e) {
return "UNKNOWN " + level;
}
}
... | @Test
public void testLevelToString() {
assertEquals("5", FeatureCommand.levelToString("foo.bar", (short) 5));
assertEquals("3.3-IV0",
FeatureCommand.levelToString(MetadataVersion.FEATURE_NAME, MetadataVersion.IBP_3_3_IV0.featureLevel()));
} |
@VisibleForTesting
boolean skipUpdate(int newSize) {
if (newSize == lastBufferSize) {
return true;
}
// According to logic of this class newSize can not be less than min or greater than max
// buffer size but if considering this method independently the behaviour for the... | @Test
void testSkipUpdate() {
int maxBufferSize = 32768;
int minBufferSize = 256;
double threshold = 0.3;
BufferDebloater bufferDebloater =
testBufferDebloater()
.withDebloatTarget(1000)
.withBufferSize(minBufferSize, ma... |
@Override
public boolean isManagedIndex(String indexName) {
return isManagedIndex(findAllMongoIndexSets(), indexName);
} | @Test
public void isManagedIndexWithUnmanagedIndexReturnsFalse() {
final IndexSetConfig indexSetConfig = mock(IndexSetConfig.class);
final List<IndexSetConfig> indexSetConfigs = Collections.singletonList(indexSetConfig);
final MongoIndexSet indexSet = mock(MongoIndexSet.class);
when(... |
public static String toJson(Message message) {
StringWriter json = new StringWriter();
try (JsonWriter jsonWriter = JsonWriter.of(json)) {
write(message, jsonWriter);
}
return json.toString();
} | @Test
public void write_empty_map() {
TestMap.Builder builder = TestMap.newBuilder();
assertThat(toJson(builder.build())).isEqualTo("{\"stringMap\":{},\"nestedMap\":{}}");
} |
public static ImmutableSet<HttpUrl> allSubPaths(String url) {
return allSubPaths(HttpUrl.parse(url));
} | @Test
public void allSubPaths_whenMultipleSubPathsWithTrailingSlash_returnsExpectedUrl() {
assertThat(allSubPaths("http://localhost/a/b/c/"))
.containsExactly(
HttpUrl.parse("http://localhost/"),
HttpUrl.parse("http://localhost/a/"),
HttpUrl.parse("http://localhost/a/b/... |
@Override
public boolean mkdirs(final Path f) throws IOException {
checkNotNull(f, "path is null");
return mkdirsInternal(pathToFile(f));
} | @Test
void testConcurrentMkdirs() throws Exception {
final FileSystem fs = FileSystem.getLocalFileSystem();
final File root = TempDirUtils.newFolder(tempFolder);
final int directoryDepth = 10;
final int concurrentOperations = 10;
final Collection<File> targetDirectories =
... |
@Override
public DescriptiveUrlBag toUrl(final Path file) {
final DescriptiveUrlBag list = new DescriptiveUrlBag();
if(new HostPreferences(session.getHost()).getBoolean("s3.bucket.virtualhost.disable")) {
list.addAll(new DefaultUrlProvider(session.getHost()).toUrl(file));
}
... | @Test
public void testProviderUriRoot() {
final Iterator<DescriptiveUrl> provider = new S3UrlProvider(session, Collections.emptyMap()).toUrl(new Path("/test-eu-west-1-cyberduck",
EnumSet.of(Path.Type.directory))).filter(DescriptiveUrl.Type.provider).iterator();
assertEquals("s3://tes... |
public static <K, V> Cache<K, V> eternal() {
return forMaximumBytes(Long.MAX_VALUE);
} | @Test
public void testEternalCache() throws Exception {
testCache(Caches.eternal());
} |
@SuppressWarnings("unchecked")
public <TCOSBase extends COSBase> TCOSBase cloneForNewDocument(TCOSBase base) throws IOException
{
if (base == null)
{
return null;
}
COSBase retval = clonedVersion.get(base);
if (retval != null)
{
// we are d... | @Test
void testClonePDFWithCosArrayStream() throws IOException
{
try (PDDocument srcDoc = new PDDocument();
PDDocument dstDoc = new PDDocument())
{
PDPage pdPage = new PDPage();
srcDoc.addPage(pdPage);
new PDPageContentStream(srcDoc, pdPage, Appe... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void modResolution0() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/crash-report/mod_resolution0.txt")),
CrashReportAnalyzer.Rule.MOD_RESOLUTION0);
} |
@Nullable
@Override
public AccessToken loadById(String id) {
try {
final DBObject dbObject = get(AccessTokenImpl.class, id);
if (dbObject != null) {
return fromDBObject(dbObject);
}
} catch (IllegalArgumentException e) {
// Happens ... | @Test
@MongoDBFixtures("accessTokensMultipleTokens.json")
public void testLoadById() {
assertThat(accessTokenService.loadById("54e3deadbeefdeadbeefaffe"))
.isNotNull()
.satisfies(token -> {
assertThat(token.getId()).isEqualTo("54e3deadbeefdeadbeefaffe"... |
public Class<?> getTargetClass() {
return targetClass;
} | @Test
void testConstructorWithTargetClass() {
NacosDeserializationException exception = new NacosDeserializationException(
NacosDeserializationExceptionTest.class);
assertEquals(Constants.Exception.DESERIALIZE_ERROR_CODE, exception.getErrCode());
assertEquals(String.format("e... |
@Override
public Object decode(Response response, Type type) throws IOException {
JsonAdapter<Object> jsonAdapter = moshi.adapter(type);
if (response.status() == 404 || response.status() == 204)
return Util.emptyValueOf(type);
if (response.body() == null)
return null;
try (BufferedSource... | @Test
void decodes() throws Exception {
class Zone extends LinkedHashMap<String, Object> {
Zone(String name) {
this(name, null);
}
Zone(String name, String id) {
put("name", name);
if (id != null) {
put("id", id);
}
}
private static final... |
public static ValueLabel formatBytes(long bytes) {
return new ValueLabel(bytes, BYTES_UNIT);
} | @Test
public void formatGigaBytes() {
vl = TopoUtils.formatBytes(4_000_000_000L);
assertEquals(AM_WM, TopoUtils.Magnitude.GIGA, vl.magnitude());
assertEquals(AM_WL, "3.73 GB", vl.toString());
} |
public int getSegmentId() {
return segmentId;
} | @Test
void testGetSegmentId() {
int segmentId = 1;
NettyPayload nettyPayload = NettyPayload.newSegment(segmentId);
assertThat(nettyPayload.getSegmentId()).isEqualTo(segmentId);
assertThatThrownBy(() -> NettyPayload.newSegment(-1))
.isInstanceOf(IllegalStateException.c... |
public String compile(final DataProvider dataProvider,
final String template) {
final InputStream templateStream = this.getClass().getResourceAsStream(template);
return compile(dataProvider,
templateStream);
} | @Test
public void testCompilerObjs() throws Exception {
Collection<Object> objs = new ArrayList<Object>();
final ObjectDataCompiler converter = new ObjectDataCompiler();
final InputStream templateStream =
this.getClass().getResourceAsStream("/templates/rule_template_1.drl");
... |
public static TableElements parse(final String schema, final TypeRegistry typeRegistry) {
return new SchemaParser(typeRegistry).parse(schema);
} | @Test
public void shouldThrowOnInvalidSchema() {
// Given:
final String schema = "foo-bar INTEGER";
// Expect:
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> parser.parse(schema)
);
// Then:
assertThat(e.getMessage(), containsString("Error parsi... |
public PipelineConfigs findGroupByPipeline(CaseInsensitiveString pipelineName) {
for (PipelineConfigs group : this) {
if (group.hasPipeline(pipelineName)) {
return group;
}
}
return null;
} | @Test
public void shouldFindGroupByPipelineName() throws Exception {
PipelineConfig p1Config = createPipelineConfig("pipeline1", "stage1");
PipelineConfig p2Config = createPipelineConfig("pipeline2", "stage1");
PipelineConfig p3Config = createPipelineConfig("pipeline3", "stage1");
P... |
public boolean containsGroup(String group) {
return clusterNodes.containsKey(group);
} | @Test
public void testContainsGroup() {
Assertions.assertFalse(metadata.containsGroup("group"));
} |
@Override
public void execute(ComputationStep.Context context) {
Metric qProfilesMetric = metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY);
new PathAwareCrawler<>(new QProfileAggregationComponentVisitor(qProfilesMetric))
.visit(treeRootHolder.getRoot());
} | @Test
public void fail_if_report_inconsistent() {
treeRootHolder.setRoot(MULTI_MODULE_PROJECT);
QualityProfile qpJava = createQProfile(QP_NAME_1, LANGUAGE_KEY_1);
analysisMetadataHolder.setQProfilesByLanguage(ImmutableMap.of(LANGUAGE_KEY_1, qpJava));
try {
underTest.execute(new TestComputationS... |
Map<String, Object> sourceConsumerConfig(String role) {
Map<String, Object> result = sourceConsumerConfig(originals());
addClientId(result, role);
return result;
} | @Test
public void testSourceConsumerConfig() {
Map<String, String> connectorProps = makeProps(
MirrorConnectorConfig.CONSUMER_CLIENT_PREFIX + "max.poll.interval.ms", "120000",
MirrorConnectorConfig.SOURCE_CLUSTER_PREFIX + "bootstrap.servers", "localhost:2345"
);
... |
@VisibleForTesting
protected void copyFromHost(MapHost host) throws IOException {
// reset retryStartTime for a new host
retryStartTime = 0;
// Get completed maps on 'host'
List<TaskAttemptID> maps = scheduler.getMapsForHost(host);
// Sanity check to catch hosts with only 'OBSOLETE' maps,
... | @Test
public void testReduceOutOfDiskSpace() throws Throwable {
LOG.info("testReduceOutOfDiskSpace");
Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm,
r, metrics, except, key, connection);
String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key);
... |
@Udf(description = "Returns all substrings of the input that matches the given regex pattern")
public List<String> regexpExtractAll(
@UdfParameter(description = "The regex pattern") final String pattern,
@UdfParameter(description = "The input string to apply regex on") final String input
) {
return ... | @Test
public void shouldReturnNullIfGivenGroupNumberGreaterThanAvailableGroupNumbers() {
assertThat(udf.regexpExtractAll("e", "test string", 3), nullValue());
} |
@Override
public boolean offerLast(T t)
{
addLastNode(t);
return true;
} | @Test
public void testOfferLast()
{
List<Integer> control = new ArrayList<>(Arrays.asList(1, 2, 3));
LinkedDeque<Integer> q = new LinkedDeque<>(control);
control.add(99);
Assert.assertTrue(q.offerLast(99));
Assert.assertEquals(q, control);
} |
@Override
public synchronized ListenableFuture<BufferResult> get(OutputBufferId bufferId, long startSequenceId, DataSize maxSize)
{
requireNonNull(bufferId, "outputBufferId is null");
checkArgument(bufferId.getId() == outputBufferId.getId(), "Invalid buffer id");
checkArgument(maxSize.to... | @Test
public void testSimplePendingRead()
{
SpoolingOutputBuffer buffer = createSpoolingOutputBuffer();
// attempt to get a page
ListenableFuture<BufferResult> future = buffer.get(BUFFER_ID, 0, sizeOfPages(2));
assertFalse(future.isDone());
// add three pages
Li... |
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) {
OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers);
if (filteredOpenAPI == null) {
return filte... | @Test(description = "it should clone everything")
public void cloneEverything() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
final OpenAPI filtered = new SpecFilter().filter(openAPI, new NoOpOperationsFilter(), null, null, null);
assertEquals(Json.pretty(filtered)... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path file : files.keySet()) {
callback.delete(file);
try {
if(file.isFile() || file.isSymbolicLink()) {
... | @Test
public void testDeleteDirectory() 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());
new FTPDeleteFeature(session).delet... |
public <T extends ShardingSphereRule> Collection<T> findRules(final Class<T> clazz) {
Collection<T> result = new LinkedList<>();
for (ShardingSphereRule each : rules) {
if (clazz.isAssignableFrom(each.getClass())) {
result.add(clazz.cast(each));
}
}
... | @Test
void assertFindRules() {
assertThat(ruleMetaData.findRules(ShardingSphereRuleFixture.class).size(), is(1));
} |
public LocalComponentIdDrlSession get(String basePath, long identifier) {
return new LocalComponentIdDrlSession(basePath, identifier);
} | @Test
void get() {
long identifier = Math.abs(new Random().nextLong());
String basePath = "/TestingRule/TestedRule";
ModelLocalUriId modelLocalUriId = new ModelLocalUriId(LocalUri.parse("/pmml" + basePath));
assertThat(modelLocalUriId.model()).isEqualTo("pmml");
assertThat(mo... |
@VisibleForTesting
static String formatTimestamp(Long timestampMicro) {
// timestampMicro is in "microseconds since epoch" format,
// e.g., 1452062291123456L means "2016-01-06 06:38:11.123456 UTC".
// Separate into seconds and microseconds.
long timestampSec = timestampMicro / 1_000_000;
long micr... | @Test
public void testFormatTimestamp() {
assertThat(
BigQueryAvroUtils.formatTimestamp(1452062291123456L),
equalTo("2016-01-06 06:38:11.123456 UTC"));
} |
public static String stringEmptyAndThenExecute(String source, Callable<String> callable) {
if (StringUtils.isEmpty(source)) {
try {
return callable.call();
} catch (Exception e) {
LogUtils.NAMING_LOGGER.error("string empty and then ex... | @Test
void testStringEmptyAndThenExecuteSuccess() {
String word = " ";
String actual = TemplateUtils.stringEmptyAndThenExecute(word, () -> "call");
assertEquals("", actual);
} |
@Override
public int writerIndex() {
return writerIndex;
} | @Test
void writerIndexBoundaryCheck1() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
buffer.writerIndex(-1);
});
} |
public static List<Section> order(Collection<Section> sections, String... orderedNames) {
Map<String, Section> alphabeticalOrderedMap = new TreeMap<>();
sections.forEach(section -> alphabeticalOrderedMap.put(section.getName(), section));
List<Section> result = new ArrayList<>(sections.size());
stream(o... | @Test
public void test_order() {
Collection<Section> sections = asList(
newSection("end2"),
newSection("bar"),
newSection("end1"),
newSection("foo"));
List<String> ordered = SystemInfoUtils.order(sections, "foo", "bar").stream()
.map(Section::getName)
.toList();
assert... |
public RingbufferStoreConfig setProperty(String name, String value) {
properties.setProperty(name, value);
return this;
} | @Test
public void setProperty() {
config.setProperty("key", "value");
assertEquals("value", config.getProperty("key"));
} |
public String filterRequest(Order order) {
return filterChain.execute(order);
} | @Test
void testFilterRequest() {
final var target = mock(Target.class);
final var filterManager = new FilterManager();
assertEquals("RUNNING...", filterManager.filterRequest(mock(Order.class)));
verifyNoMoreInteractions(target);
} |
@Override
protected void doStop() throws Exception {
if (connection != null) {
for (IrcChannel channel : getEndpoint().getConfiguration().getChannelList()) {
LOG.debug("Parting: {}", channel);
connection.doPart(channel.getName());
}
connect... | @Test
public void doStopTest() {
producer.stop();
verify(connection).doPart("#chan1");
verify(connection).doPart("#chan2");
verify(connection).removeIRCEventListener(listener);
} |
private void fail(final ChannelHandlerContext ctx, int length) {
fail(ctx, String.valueOf(length));
} | @Test
public void testTooLongLineWithFailFast() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new LenientLineBasedFrameDecoder(16, false, true, false));
try {
ch.writeInbound(copiedBuffer("12345678901234567", CharsetUtil.US_ASCII));
fail();
} catch (Exc... |
public ClusterStateBundle cloneWithMapper(Function<ClusterState, ClusterState> mapper) {
AnnotatedClusterState clonedBaseline = baselineState.cloneWithClusterState(
mapper.apply(baselineState.getClusterState().clone()));
Map<String, AnnotatedClusterState> clonedDerived = derivedBucketSpa... | @Test
void cloning_preserves_distribution_config() {
var bundle = createTestBundleWithDistributionConfig(DistributionBuilder.configForFlatCluster(5));
var derived = bundle.cloneWithMapper(Function.identity());
assertEquals(bundle, derived);
} |
public DrlxParseResult drlxParse(Class<?> patternType, String bindingId, String expression) {
return drlxParse(patternType, bindingId, expression, false);
} | @Test
public void bigDecimalInWithInt() {
SingleDrlxParseSuccess result = (SingleDrlxParseSuccess) parser.drlxParse(Person.class, "$p", "(money in (100, 200))");
assertThat(result.getExpr().toString()).isEqualTo("D.eval(org.drools.model.operators.InOperator.INSTANCE, _this.getMoney(), 100, 200)");
... |
public void triggerNextSuperstep() {
synchronized (monitor) {
if (terminated) {
throw new IllegalStateException("Already terminated.");
}
superstepNumber++;
monitor.notifyAll();
}
} | @Test
public void testWaitAlreadyFulfilled() {
try {
SuperstepKickoffLatch latch = new SuperstepKickoffLatch();
latch.triggerNextSuperstep();
Waiter w = new Waiter(latch, 2);
Thread waiter = new Thread(w);
waiter.setDaemon(true);
waite... |
public List<Bson> parse(final List<String> filterExpressions,
final List<EntityAttribute> attributes) {
if (filterExpressions == null || filterExpressions.isEmpty()) {
return List.of();
}
final Map<String, List<Filter>> groupedByField = filterExpressions.s... | @Test
void returnsEmptyListOnEmptyFilterList() {
assertThat(toTest.parse(List.of(), List.of()))
.isEmpty();
} |
@Override
public boolean shouldFire(TriggerStateMachine.TriggerContext context) throws Exception {
return context.trigger().subTrigger(ACTUAL).invokeShouldFire(context)
|| context.trigger().subTrigger(UNTIL).invokeShouldFire(context);
} | @Test
public void testActualFiresButUntilFinishes() throws Exception {
tester =
TriggerStateMachineTester.forTrigger(
new OrFinallyStateMachine(
RepeatedlyStateMachine.forever(AfterPaneStateMachine.elementCountAtLeast(2)),
AfterPaneStateMachine.elementCountAtLea... |
public OffsetAndMetadata findNextCommitOffset(final String commitMetadata) {
boolean found = false;
long currOffset;
long nextCommitOffset = committedOffset;
for (KafkaSpoutMessageId currAckedMsg : ackedMsgs) { // complexity is that of a linear scan on a TreeMap
currOffset ... | @Test
public void testFindNextCommitOffsetWithOneAck() {
/*
* The KafkaConsumer commitSync API docs: "The committed offset should be the next message your application will consume, i.e.
* lastProcessedMessageOffset + 1. "
*/
emitAndAckMessage(getMessageId(initialFetchOffse... |
@Override
public boolean containsAll(Collection<?> c) {
return get(containsAllAsync(c));
} | @Test
public void testContainsAll() {
Set<Integer> set = redisson.getSet("set");
for (int i = 0; i < 200; i++) {
set.add(i);
}
Assertions.assertTrue(set.containsAll(Collections.emptyList()));
Assertions.assertTrue(set.containsAll(Arrays.asList(30, 11)));
... |
@Override
public void open() throws Exception {
this.timerService =
getInternalTimerService("processing timer", VoidNamespaceSerializer.INSTANCE, this);
this.keySet = new HashSet<>();
super.open();
} | @Test
void testEndInput() throws Exception {
AtomicInteger counter = new AtomicInteger();
OutputTag<Long> sideOutputTag = new OutputTag<Long>("side-output") {};
KeyedTwoOutputProcessOperator<Integer, Integer, Integer, Long> processOperator =
new KeyedTwoOutputProcessOperator... |
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<>();
if(replies.isEmpty()) {
return children;
}
// At least one entry successfully parsed... | @Test
public void testParseMlsdSymbolic() throws Exception {
Path path = new Path(
"/www", EnumSet.of(Path.Type.directory));
String[] replies = new String[]{
"Type=OS.unix=slink:/foobar;Perm=;Unique=keVO1+4G4; foobar"
};
final AttributedList<Path> chi... |
public Set<AuthorizationPluginInfo> getPluginsThatSupportsWebBasedAuthentication() {
return getPluginsThatSupports(SupportedAuthType.Web);
} | @Test
public void shouldGetPluginsThatSupportWebBasedAuthorization() {
Set<AuthorizationPluginInfo> pluginsThatSupportsWebBasedAuthentication = store.getPluginsThatSupportsWebBasedAuthentication();
assertThat(pluginsThatSupportsWebBasedAuthentication.size(), is(2));
assertThat(pluginsThatSup... |
static JavaType constructType(Type type) {
try {
return constructTypeInner(type);
} catch (Exception e) {
throw new InvalidDataTableTypeException(type, e);
}
} | @Test
void raw_list_should_equal_a_list_of_objects() {
JavaType javaType = TypeFactory.constructType(List.class);
JavaType other = TypeFactory.constructType(LIST_OF_OBJECT);
assertThat(javaType, equalTo(other));
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testSkippingAbortedTransactions() {
buildFetcher(OffsetResetStrategy.EARLIEST, new ByteArrayDeserializer(),
new ByteArrayDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED);
ByteBuffer buffer = ByteBuffer.allocate(1024);
int currentOffset = 0;
... |
public static boolean isNormalizedPathOutsideWorkingDir(String path) {
final String normalize = FilenameUtils.normalize(path);
final String prefix = FilenameUtils.getPrefix(normalize);
return (normalize != null && StringUtils.isBlank(prefix));
} | @Test
public void shouldReturnTrueIfGivenFolderWithRelativeKeepsYouInsideSandbox() {
assertThat(FilenameUtil.isNormalizedPathOutsideWorkingDir("tmp/../home/cruise"), is(true));
} |
public final long getWhen() {
return when;
} | @Test
public void getWhenOutputZero() {
// Arrange
final LogHeader objectUnderTest = new LogHeader(0);
// Act
final long actual = objectUnderTest.getWhen();
// Assert result
Assert.assertEquals(0L, actual);
} |
public static void generate(String cluster, OutputStream out,
List<PrometheusRawMetricsProvider> metricsProviders)
throws IOException {
ByteBuf buf = PulsarByteBufAllocator.DEFAULT.heapBuffer();
try {
SimpleTextOutputStream stream = new SimpleTextO... | @Test
public void testGenerateSystemMetricsWithDefaultCluster() throws Exception {
String defaultClusterValue = "cluster_test";
String labelName = "lb_name";
String labelValue = "lb_value";
// default cluster.
String metricsName = "label_use_default_cluster" + randomString();... |
public void wakeup() {
if (hasNotified.compareAndSet(false, true)) {
waitPoint.countDown(); // notify
}
} | @Test
public void testWakeup() {
ServiceThread testServiceThread = startTestServiceThread();
testServiceThread.wakeup();
assertEquals(true, testServiceThread.hasNotified.get());
assertEquals(0, testServiceThread.waitPoint.getCount());
} |
@Override
@CheckForNull
public EmailMessage format(Notification notif) {
if (!(notif instanceof ChangesOnMyIssuesNotification)) {
return null;
}
ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif;
if (notification.getChange() instanceof AnalysisChange) {
... | @Test
public void formats_fails_with_ISE_if_change_from_Analysis_and_no_issue() {
AnalysisChange analysisChange = newAnalysisChange();
assertThatThrownBy(() -> underTest.format(new ChangesOnMyIssuesNotification(analysisChange, Collections.emptySet())))
.isInstanceOf(IllegalStateException.class)
.... |
Object[] findValues(int ordinal) {
return getAllValues(ordinal, type, 0);
} | @Test
public void testMapReference() throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
MapReference mapReference = new MapReference();
mapReference.mapValues = map;
objectMapper.add(mapReference);
StateEngin... |
@Override
public NetconfDevice getNetconfDevice(DeviceId deviceInfo) {
return netconfDeviceMap.get(deviceInfo);
} | @Test
public void testGetNetconfDevice() {
NetconfDevice fetchedDevice1 = ctrl.getNetconfDevice(deviceId1);
assertThat("Incorrect device fetched", fetchedDevice1, is(device1));
NetconfDevice fetchedDevice2 = ctrl.getNetconfDevice(deviceId2);
assertThat("Incorrect device fetched", fe... |
public static Pair<String, String> decryptHandler(String dataId, String secretKey, String content) {
if (!checkCipher(dataId)) {
return Pair.with(secretKey, content);
}
Optional<String> algorithmName = parseAlgorithmName(dataId);
Optional<EncryptionPluginService> optional = a... | @Test
void testUnknownAlgorithmNameDecrypt() {
String dataId = "cipher-mySM4-application";
String content = "content";
Pair<String, String> pair = EncryptionHandler.decryptHandler(dataId, "", content);
assertNotNull(pair);
assertEquals(content, pair.getSecond(), "should retur... |
public static boolean parseBooleanValue(String value, String name) {
if (value.equalsIgnoreCase("ON")
|| value.equalsIgnoreCase("TRUE")
|| value.equalsIgnoreCase("1")) {
return true;
}
if (value.equalsIgnoreCase("OFF")
|| value.equalsIg... | @Test
public void testParseBooleanValueException() {
expectedEx.expect(SemanticException.class);
expectedEx.expectMessage(
"Invalid var: 'tru'. Expected values should be 1, 0, on, off, true, or false (case insensitive)");
ParseUtil.parseBooleanValue("tru", "var");
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, String.valueOf(Path.DELIMITER));
} | @Test
public void testListCommonPrefixSlashOnly() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck-unsupportedprefix", EnumSet.of(Path.Type.directory, Path.Type.volume));
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
assertTrue... |
@Override
@Nullable
public long[] readLongArray(@Nonnull String fieldName) throws IOException {
return readIncompatibleField(fieldName, LONG_ARRAY, super::readLongArray);
} | @Test
public void testReadLongArray() throws Exception {
assertNull(reader.readLongArray("NO SUCH FIELD"));
} |
@Override
public V getValue() {
if (valueObject == null) {
valueObject = serializationService.toObject(valueData);
}
return valueObject;
} | @Override
@Test
public void getValue_caching() {
QueryableEntry entry = createEntry("key", "value");
assertSame(entry.getValue(), entry.getValue());
} |
@Override
public void registerAndStartNewCoordinators(
Collection<OperatorCoordinatorHolder> coordinators,
ComponentMainThreadExecutor mainThreadExecutor,
final int parallelism) {
for (OperatorCoordinatorHolder coordinator : coordinators) {
coordinatorMap.put... | @Test
void testRegisterAndStartNewCoordinators() throws Exception {
final JobVertex[] jobVertices = createJobVertices(BLOCKING);
OperatorID operatorId1 = OperatorID.fromJobVertexID(jobVertices[0].getID());
OperatorID operatorId2 = OperatorID.fromJobVertexID(jobVertices[1].getID());
... |
public DescriptiveUrl find(DescriptiveUrl.Type type) {
for(DescriptiveUrl url : this) {
if(url.getType().equals(type)) {
return url;
}
}
return DescriptiveUrl.EMPTY;
} | @Test
public void testFind() {
final DescriptiveUrlBag list = new DescriptiveUrlBag();
final DescriptiveUrl url = new DescriptiveUrl(URI.create("http://example.net"));
list.add(url);
assertEquals(DescriptiveUrl.EMPTY, list.find(DescriptiveUrl.Type.provider));
assertEquals(url... |
public static <T> Iterator<T> asReadOnlyIterator(Iterator<T> iterator) {
if (iterator instanceof UnmodifiableIterator) {
return iterator;
}
return new UnmodifiableIterator<>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
... | @Test(expected = UnsupportedOperationException.class)
public void test_asReadOnlyIterator_throws_exception_when_remove_called() {
Iterator<Integer> iterator = IterableUtil.asReadOnlyIterator(numbers.iterator());
while (iterator.hasNext()) {
iterator.next();
iterator.remove();... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.