focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@SuppressWarnings("unchecked")
public static <T> TypeInformation<T> convert(String jsonSchema) {
Preconditions.checkNotNull(jsonSchema, "JSON schema");
final ObjectMapper mapper = JacksonMapperFactory.createObjectMapper();
mapper.getFactory()
.enable(JsonParser.Feature.ALLOW_... | @Test
void testReferenceSchema() throws Exception {
final URL url = getClass().getClassLoader().getResource("reference-schema.json");
Objects.requireNonNull(url);
final String schema = FileUtils.readFileUtf8(new File(url.getFile()));
final TypeInformation<?> result = JsonRowSchemaCon... |
public static CheckpointStorage load(
@Nullable CheckpointStorage fromApplication,
StateBackend configuredStateBackend,
Configuration jobConfig,
Configuration clusterConfig,
ClassLoader classLoader,
@Nullable Logger logger)
throws Illeg... | @Test
void testLoadFileSystemCheckpointStorageMixed() throws Exception {
final Path appCheckpointDir = new Path(TempDirUtils.newFolder(tmp).toURI());
final String checkpointDir = new Path(TempDirUtils.newFolder(tmp).toURI()).toString();
final String savepointDir = new Path(TempDirUtils.newFo... |
public static CsvIOParse<Row> parseRows(Schema schema, CSVFormat csvFormat) {
CsvIOParseHelpers.validateCsvFormat(csvFormat);
CsvIOParseHelpers.validateCsvFormatWithSchema(csvFormat, schema);
RowCoder coder = RowCoder.of(schema);
CsvIOParseConfiguration.Builder<Row> builder = CsvIOParseConfiguration.bui... | @Test
public void givenMismatchedCsvFormatAndSchema_throws() {
Pipeline pipeline = Pipeline.create();
CSVFormat csvFormat =
CSVFormat.DEFAULT
.withHeader("a_string", "an_integer", "a_double")
.withAllowDuplicateHeaderNames(true);
Schema schema = Schema.builder().addStringFi... |
@Override
public void scheduleCommand(Command command) {
scheduleCommand(command, DEFAULT_SCHEDULING_TIMEOUT);
} | @Test
public void testScheduleCommand() throws Exception {
final WaitHelper.ResultHolder resultHolder = new WaitHelper.ResultHolder();
command.setCommandExecutionListener(new CommandExecutionListener() {
@Override
public void commandExecuted(Object result) {
a... |
public Seckill getSeckill(long seckillId) {
String key = "seckill:" + seckillId;
Seckill seckill = (Seckill) redisTemplate.opsForValue().get(key);
if (seckill != null) {
return seckill;
} else {
seckill = seckillMapper.selectById(seckillId);
if (seckil... | @Test
void getSeckillError() {
long seckillId = 1001L;
when(redisTemplate.opsForValue()).thenReturn(mock(ValueOperations.class));
assertThrows(RuntimeException.class, () -> redisService.getSeckill(seckillId));
} |
@Override
public String create(final Local file) {
return null;
} | @Test
public void testCreate() {
assertNull(new DisabledFilesystemBookmarkResolver().create(new NullLocal("/t")));
} |
public CommonContext conclude()
{
if (0 != IS_CONCLUDED_UPDATER.getAndSet(this, 1))
{
throw new ConcurrentConcludeException();
}
concludeAeronDirectory();
cncFile = new File(aeronDirectory, CncFileDescriptor.CNC_FILE);
return this;
} | @Test
void shouldNotAllowConcludeMoreThanOnce()
{
final CommonContext ctx = new CommonContext();
ctx.conclude();
assertThrows(ConcurrentConcludeException.class, ctx::conclude);
} |
public List<AnalyzedInstruction> getAnalyzedInstructions() {
return analyzedInstructions.getValues();
} | @Test
public void testInstanceOfNarrowingEqz_dalvik() throws IOException {
MethodImplementationBuilder builder = new MethodImplementationBuilder(2);
builder.addInstruction(new BuilderInstruction22c(Opcode.INSTANCE_OF, 0, 1,
new ImmutableTypeReference("Lmain;")));
builder.add... |
public boolean didTimeout(long duration, TimeUnit unit) {
if (completed) {
return false;
}
return timeSinceLastLine(unit) > duration;
} | @Test
public void shouldKnowIfPumperExpired() throws Exception {
PipedOutputStream output = new PipedOutputStream();
try (output) {
InputStream inputStream = new PipedInputStream(output);
TestingClock clock = new TestingClock();
StreamPumper pumper = new StreamPum... |
@Override
public void addTask(Object key, AbstractDelayTask newTask) {
lock.lock();
try {
AbstractDelayTask existTask = tasks.get(key);
if (null != existTask) {
newTask.merge(existTask);
}
tasks.put(key, newTask);
} finally {
... | @Test
void testRetryTaskAfterFail() throws InterruptedException {
when(taskProcessor.process(abstractTask)).thenReturn(false, true);
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
TimeUnit.MILLISECONDS.sleep(300);
verify(taskProcessor, new Times(2)).process(abstractTask);... |
public static Driver load(String className) throws DriverLoadException {
final ClassLoader loader = DriverLoader.class.getClassLoader();
return load(className, loader);
} | @Test(expected = DriverLoadException.class)
public void testLoad_String_String_badClassName() throws Exception {
String className = "com.mybad.jdbc.Driver";
//we know this is in target/test-classes
//File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jet... |
public static <T> T getBean(Class<T> interfaceClass, Class typeClass) {
Object object = serviceMap.get(interfaceClass.getName() + "<" + typeClass.getName() + ">");
if(object == null) return null;
if(object instanceof Object[]) {
return (T)Array.get(object, 0);
} else {
... | @Test
public void testSingleWithProperties() {
G g = SingletonServiceFactory.getBean(G.class);
Assert.assertEquals("Sky Walker", g.getName());
Assert.assertEquals(23, g.getAge());
} |
@Override
public void visit(final Entry target) {
final String actionName = target.getName();
if (!actionName.isEmpty() && new EntryAccessor().getAction(target) == null) {
AFreeplaneAction action = freeplaneActions.getAction(actionName);
if(action == null) {
for (final Class<? extends AFreeplaneAction> a... | @Test
public void attachesExistingFreeplaneAction() {
FreeplaneActions freeplaneActions = mock(FreeplaneActions.class);
Entry entry = new Entry();
entry.setName("action");
final AFreeplaneAction someAction = Mockito.mock(AFreeplaneAction.class);
when(freeplaneActions.getAction("action")).thenReturn(someActio... |
@Override
public Character getCharAndRemove(K name) {
return null;
} | @Test
public void testGetCharAndRemove() {
assertNull(HEADERS.getCharAndRemove("name1"));
} |
static Node selectNodeByRequesterAndStrategy(/*@NonNull*/ FlowRule rule, Context context, DefaultNode node) {
// The limit app should not be empty.
String limitApp = rule.getLimitApp();
int strategy = rule.getStrategy();
String origin = context.getOrigin();
if (limitApp.equals(o... | @Test
public void testCustomOriginFlowSelectNode() {
String origin = "appA";
String limitAppB = "appB";
DefaultNode node = mock(DefaultNode.class);
DefaultNode originNode = mock(DefaultNode.class);
ClusterNode cn = mock(ClusterNode.class);
when(node.getClusterNode())... |
@Override
public void selectWorker(long workerId) throws NonRecoverableException {
if (getWorkerById(workerId) == null) {
reportWorkerNotFoundException(workerId);
}
selectWorkerUnchecked(workerId);
} | @Test
public void testSelectWorker() throws UserException {
HostBlacklist blockList = SimpleScheduler.getHostBlacklist();
SystemInfoService sysInfo = GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo();
List<Long> availList = prepareNodeAliveAndBlock(sysInfo, blockList);
... |
public Map<TopicPartition, Long> endOffsets(Set<TopicPartition> partitions) {
if (partitions == null || partitions.isEmpty()) {
return Collections.emptyMap();
}
Map<TopicPartition, OffsetSpec> offsetSpecMap = partitions.stream().collect(Collectors.toMap(Function.identity(), tp -> Off... | @Test
public void endOffsetsShouldReturnOffsetsForOnePartition() {
String topicName = "myTopic";
TopicPartition tp1 = new TopicPartition(topicName, 0);
Set<TopicPartition> tps = Collections.singleton(tp1);
long offset = 1000L;
Cluster cluster = createCluster(1, topicName, 1);... |
@Override
public <VO, VR> KStream<K, VR> outerJoin(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return outerJoin(otherStream, toValueJoin... | @SuppressWarnings("deprecation")
@Test
public void shouldNotAllowNullValueJoinerWithKeyOnOuterJoin() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.outerJoin(testStream, (ValueJoinerWithKey<? super String, ? super String, ? sup... |
public Optional<String> getHostName(String nodeId) {
return hostNameCache.getUnchecked(nodeId);
} | @Test
public void getHostNameUsesCache() {
when(cluster.nodeIdToHostName("node_id")).thenReturn(Optional.of("node-hostname"));
nodeInfoCache.getHostName("node_id");
nodeInfoCache.getHostName("node_id");
verify(cluster, times(1)).nodeIdToHostName("node_id");
} |
public static void isTrue(boolean expression, String message) {
if (!expression) {
throw new IllegalArgumentException(message);
}
} | @Test(expected = IllegalArgumentException.class)
public void assertIsTrue() {
Assert.isTrue(false, "test message");
} |
ControllerResult<Map<String, ApiError>> updateFeatures(
Map<String, Short> updates,
Map<String, FeatureUpdate.UpgradeType> upgradeTypes,
boolean validateOnly
) {
TreeMap<String, ApiError> results = new TreeMap<>();
List<ApiMessageAndVersion> records =
BoundedL... | @Test
public void testUpdateFeatures() {
SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
FeatureControlManager manager = new FeatureControlManager.Builder().
setQuorumFeatures(features("foo", 1, 2)).
setSnapshotRegistry(snapshotRegistry).
... |
static java.sql.Date parseSqlDate(final String value) {
try {
// JDK format in Date.valueOf is compatible with DATE_FORMAT
return java.sql.Date.valueOf(value);
} catch (IllegalArgumentException e) {
return throwRuntimeParseException(value, new ParseException(value, 0)... | @Test
public void testSqlDate() {
long now = System.currentTimeMillis();
java.sql.Date date1 = new java.sql.Date(now);
java.sql.Date date2 = DateHelper.parseSqlDate(date1.toString());
assertSqlDatesEqual(date1, date2);
} |
@Override
public boolean test(Pickle pickle) {
URI picklePath = pickle.getUri();
if (!lineFilters.containsKey(picklePath)) {
return true;
}
for (Integer line : lineFilters.get(picklePath)) {
if (Objects.equals(line, pickle.getLocation().getLine())
... | @Test
void matches_rule() {
LinePredicate predicate = new LinePredicate(singletonMap(
featurePath,
singletonList(2)));
assertTrue(predicate.test(firstPickle));
assertTrue(predicate.test(secondPickle));
assertTrue(predicate.test(thirdPickle));
assertTru... |
@Override
public void removeFlowRules(FlowRule... flowRules) {
FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
for (FlowRule flowRule : flowRules) {
builder.remove(flowRule);
}
apply(builder.build());
} | @Test
public void removeFlowRules() {
FlowRule f1 = addFlowRule(1);
FlowRule f2 = addFlowRule(2);
FlowRule f3 = addFlowRule(3);
assertEquals("3 rules should exist", 3, flowCount(vnetFlowRuleService1));
FlowEntry fe1 = new DefaultFlowEntry(f1);
FlowEntry fe2 = new Def... |
@Override
public MaskRuleConfiguration findRuleConfiguration(final ShardingSphereDatabase database) {
return database.getRuleMetaData().findSingleRule(MaskRule.class)
.map(optional -> getConfiguration(optional.getConfiguration())).orElseGet(() -> new MaskRuleConfiguration(new LinkedList<>(),... | @Test
void assertFindRuleConfigurationWhenTableDoesNotExist() {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getRuleMetaData().findSingleRule(MaskRule.class)).thenReturn(Optional.of(new MaskRule(new MaskRuleConfiguration(Collections.emptyLis... |
@Override
public void ignoreAutoTrackActivities(List<Class<?>> activitiesList) {
} | @Test
public void ignoreAutoTrackActivities() {
List<Class<?>> activities = new ArrayList<>();
activities.add(EmptyActivity.class);
activities.add(ListActivity.class);
mSensorsAPI.ignoreAutoTrackActivities(activities);
Assert.assertTrue(mSensorsAPI.isActivityAutoTrackAppClick... |
public String name() {
return name;
} | @Test
public void testConstruction() {
assertThat(bridgeName1.name(), is(NAME1));
} |
public static boolean isHttp(String url) {
return StrUtil.startWithIgnoreCase(url, "http:");
} | @Test
public void isHttpTest(){
assertTrue(HttpUtil.isHttp("Http://aaa.bbb"));
assertTrue(HttpUtil.isHttp("HTTP://aaa.bbb"));
assertFalse(HttpUtil.isHttp("FTP://aaa.bbb"));
} |
@Udf
public <T> List<String> mapKeys(final Map<String, T> input) {
if (input == null) {
return null;
}
return Lists.newArrayList(input.keySet());
} | @Test
public void shouldReturnNullForNullInput() {
List<String> result = udf.mapKeys((Map<String, Long>) null);
assertThat(result, is(nullValue()));
} |
public ProducerConnection getProducerConnectionList(final String addr, final String producerGroup,
final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
GetProducerConnectionListRequest... | @Test
public void assertGetProducerConnectionList() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
ProducerConnection responseBody = new ProducerConnection();
responseBody.getConnectionSet().add(new Connection());
setResponseBody(responseBody);
... |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaskPreference that = (TaskPreference) o;
if (!taskConfig.equals(that.taskConfig)) return false;
if (!taskView.equals(that.taskView)) return fa... | @Test
public void shouldTestEquals() throws Exception {
Task task1 = mock(Task.class);
TaskConfig config1 = new TaskConfig();
TaskView taskView1 = mock(TaskView.class);
when(task1.config()).thenReturn(config1);
when(task1.view()).thenReturn(taskView1);
TaskPreference ... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testHerbiboar()
{
ChatMessage chatMessageEvent = new ChatMessage(null, GAMEMESSAGE, "", "Your herbiboar harvest count is: <col=ff0000>4091</col>.", null, 0);
chatCommandsPlugin.onChatMessage(chatMessageEvent);
verify(configManager).setRSProfileConfiguration("killcount", "herbiboar", 4091);
} |
@GetMapping("/auth/delete")
public Mono<String> clean(@RequestParam("appKey") final String appKey) {
if (CollectionUtils.isEmpty(subscribers)) {
return Mono.just(Constants.SUCCESS);
}
LOG.info("delete apache shenyu local AppAuth data");
AppAuthData appAuthData = AppAuthDa... | @Test
public void testClean() throws Exception {
String appKey = "D9FD95F496C9495DB5604778A13C3D08";
final MockHttpServletResponse response = this.mockMvc.perform(MockMvcRequestBuilders.get("/shenyu/auth/delete")
.contentType(MediaType.APPLICATION_JSON)
.queryParam("a... |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testUnknownSpdyPingFrameFlags() throws Exception {
short type = 6;
byte flags = (byte) 0xFF; // undefined flags
int length = 4;
int id = RANDOM.nextInt();
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, ... |
public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException {
if ( dbMetaData == null ) {
throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" ) );
}
... | @Test( expected = KettleDatabaseException.class )
public void testGetLegacyColumnNameNullRSMetaDataException() throws Exception {
new MySQLDatabaseMeta().getLegacyColumnName( mock( DatabaseMetaData.class ), null, 1 );
} |
@Override
public Optional<String> getContentHash() {
return Optional.ofNullable(mContentHash);
} | @Test
public void flush() throws Exception {
int partSize = (int) FormatUtils.parseSpaceSize(PARTITION_SIZE);
byte[] b = new byte[2 * partSize - 1];
mStream.write(b, 0, b.length);
Mockito.verify(mMockObsClient)
.initiateMultipartUpload(any(InitiateMultipartUploadRequest.class));
Mockito.v... |
@Override
public JobDO getJob(Long id) {
return jobMapper.selectById(id);
} | @Test
public void testGetJob() {
// mock 数据
JobDO dbJob = randomPojo(JobDO.class);
jobMapper.insert(dbJob);
// 调用
JobDO job = jobService.getJob(dbJob.getId());
// 断言
assertPojoEquals(dbJob, job);
} |
CreateConnectorRequest parseConnectorConfigurationFile(String filePath) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
File connectorConfigurationFile = Paths.get(filePath).toFile();
try {
Map<String, String> connectorConfigs = objectMapper.readValue(
... | @Test
public void testParseJsonFileWithCreateConnectorRequest() throws Exception {
CreateConnectorRequest requestToWrite = new CreateConnectorRequest(
CONNECTOR_NAME,
CONNECTOR_CONFIG,
CreateConnectorRequest.InitialState.STOPPED
);
try (FileWriter writer ... |
@Override
public void pushMsgToRuleEngine(TopicPartitionInfo tpi, UUID msgId, ToRuleEngineMsg msg, TbQueueCallback callback) {
log.trace("PUSHING msg: {} to:{}", msg, tpi);
producerProvider.getRuleEngineMsgProducer().send(tpi, new TbProtoQueueMsg<>(msgId, msg), callback);
toRuleEngineMsgs.in... | @Test
public void testPushMsgToRuleEngineWithTenantIdIsNullUuidAndEntityIsDevice() {
TenantId tenantId = TenantId.SYS_TENANT_ID;
DeviceId deviceId = new DeviceId(UUID.fromString("aa6d112d-2914-4a22-a9e3-bee33edbdb14"));
TbMsg requestMsg = TbMsg.newMsg(TbMsgType.REST_API_REQUEST, deviceId, Tb... |
public static Boolean matches(String raw, String encoded) {
return new BCryptPasswordEncoder().matches(raw, encoded);
} | @Test
void matches() {
Boolean result1 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXYxhzTmjWGJ21T.WX8thVsw0K2mO");
assertTrue(result1);
Boolean result2 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXcxhzTmjWGJ21T.WX8thVsw0K2mO");
... |
public void record(Uuid topicId) {
// Topic IDs should not differ, but we defensively check here to fail earlier in the case that the IDs somehow differ.
dirtyTopicIdOpt.ifPresent(dirtyTopicId -> {
if (!dirtyTopicId.equals(topicId)) {
throw new InconsistentTopicIdException("T... | @Test
public void testSetRecordWithDifferentTopicId() {
PartitionMetadataFile partitionMetadataFile = new PartitionMetadataFile(file, null);
Uuid topicId = Uuid.randomUuid();
partitionMetadataFile.record(topicId);
Uuid differentTopicId = Uuid.randomUuid();
assertThrows(Incons... |
@Override
public String toString() {
return "ResourceConfig{" +
"url=" + url +
", id='" + id + '\'' +
", resourceType=" + resourceType +
'}';
} | @Test
public void when_attachNonexistentFileWithFileAndId_then_throwsException() {
// Given
String id = "exist";
String path = Paths.get("/i/do/not/" + id).toString();
File file = new File(path);
// Then
expectedException.expect(JetException.class);
expectedE... |
static BlockStmt getKiePMMLLocalTransformationsVariableDeclaration(final LocalTransformations localTransformations) {
final MethodDeclaration methodDeclaration =
LOCAL_TRANSFORMATIONS_TEMPLATE.getMethodsByName(GETKIEPMMLLOCALTRANSFORMATIONS).get(0).clone();
final BlockStmt transformation... | @Test
void getKiePMMLTransformationDictionaryVariableDeclaration() throws IOException {
LocalTransformations localTransformations = new LocalTransformations();
localTransformations.addDerivedFields(getDerivedFields());
BlockStmt retrieved =
KiePMMLLocalTransformationsFactory... |
@Override
public boolean add(V value) {
lock.lock();
try {
checkComparator();
BinarySearchResult<V> res = binarySearch(value);
int index = 0;
if (res.getIndex() < 0) {
index = -(res.getIndex() + 1);
} else {
... | @Test
public void testReadAll() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("simple");
set.add(2);
set.add(0);
set.add(1);
set.add(5);
assertThat(set.readAll()).containsExactly(0, 1, 2, 5);
} |
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
super.startElement(uri, localName, qName, attributes);
if ("img".equals(localName) && attributes.getValue("alt") != null) {
String nfo = "[image: " + a... | @Test
public void imgTagTest() throws Exception {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
XHTMLContentHandler xhtml = new XHTMLContentHandler(new RichTextContentHandler(
new OutputStreamWriter(buffer, UTF_8)), new Metadata());
xhtml.startDocument();
... |
public static boolean isInvalidStanzaSentPriorToResourceBinding(final Packet stanza, final ClientSession session)
{
// Openfire sets 'authenticated' only after resource binding.
if (session.getStatus() == Session.Status.AUTHENTICATED) {
return false;
}
// Beware, the 'to... | @Test
public void testIsInvalid_addressedAtThirdPartyUser_authenticated() throws Exception
{
// Setup test fixture.
final Packet stanza = new Message();
stanza.setTo(new JID("foobar123", XMPPServer.getInstance().getServerInfo().getXMPPDomain(), "test123"));
final LocalClientSessi... |
@Udf
public String concat(@UdfParameter final String... jsonStrings) {
if (jsonStrings == null) {
return null;
}
final List<JsonNode> nodes = new ArrayList<>(jsonStrings.length);
boolean allObjects = true;
for (final String jsonString : jsonStrings) {
if (jsonString == null) {
... | @Test
public void shouldWrapObjectInArray() {
// When:
final String result = udf.concat("[1, 2]", "{\"a\": 1}");
// Then:
assertEquals("[1,2,{\"a\":1}]", result);
} |
public static boolean containsAbfsUrl(final String string) {
if (string == null || string.isEmpty()) {
return false;
}
return ABFS_URI_PATTERN.matcher(string).matches();
} | @Test
public void testIfUriContainsAbfs() throws Exception {
Assert.assertTrue(UriUtils.containsAbfsUrl("abfs.dfs.core.windows.net"));
Assert.assertTrue(UriUtils.containsAbfsUrl("abfs.dfs.preprod.core.windows.net"));
Assert.assertFalse(UriUtils.containsAbfsUrl("abfs.dfs.cores.windows.net"));
Assert.as... |
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) {
return new CreateStreamCommand(
outputNode.getSinkName().get(),
outputNode.getSchema(),
outputNode.getTimestampColumn(),
outputNode.getKsqlTopic().getKafkaTopicName(),
Formats.from... | @Test
public void shouldValidateKeyFormatCanHandleKeySchema() {
// Given:
givenCommandFactoriesWithMocks();
final CreateStream statement = new CreateStream(SOME_NAME, STREAM_ELEMENTS, false, true,
withProperties, false);
when(keySerdeFactory.create(
FormatInfo.of(KAFKA.name()),
... |
public static String getContentIdentity(String content) {
int index = content.indexOf(WORD_SEPARATOR);
if (index == -1) {
throw new IllegalArgumentException("The content does not contain separator!");
}
return content.substring(0, index);
} | @Test
void testGetContentIdentity() {
String content = "abc" + Constants.WORD_SEPARATOR + "edf";
String result = ContentUtils.getContentIdentity(content);
assertEquals("abc", result);
content = "test";
try {
ContentUtils.getContentIdentity(content);
... |
public static String resolveMainClass(
@Nullable String configuredMainClass, ProjectProperties projectProperties)
throws MainClassInferenceException, IOException {
if (configuredMainClass != null) {
if (isValidJavaClass(configuredMainClass)) {
return configuredMainClass;
}
thro... | @Test
public void testResolveMainClass_noneInferredWithoutMainClassFromJar() throws IOException {
Mockito.when(mockProjectProperties.getClassFiles())
.thenReturn(ImmutableList.of(Paths.get("ignored")));
try {
MainClassResolver.resolveMainClass(null, mockProjectProperties);
Assert.fail();
... |
public static KafkaRebalanceState rebalanceState(KafkaRebalanceStatus kafkaRebalanceStatus) {
if (kafkaRebalanceStatus != null) {
Condition rebalanceStateCondition = rebalanceStateCondition(kafkaRebalanceStatus);
String statusString = rebalanceStateCondition != null ? rebalanceStateCondi... | @Test
public void testNoConditions() {
KafkaRebalanceStatus kafkaRebalanceStatus = new KafkaRebalanceStatusBuilder().build();
KafkaRebalanceState state = KafkaRebalanceUtils.rebalanceState(kafkaRebalanceStatus);
assertThat(state, is(nullValue()));
} |
@VisibleForTesting
RoleDO validateRoleForUpdate(Long id) {
RoleDO role = roleMapper.selectById(id);
if (role == null) {
throw exception(ROLE_NOT_EXISTS);
}
// 内置角色,不允许删除
if (RoleTypeEnum.SYSTEM.getType().equals(role.getType())) {
throw exception(ROLE_C... | @Test
public void testValidateUpdateRole_systemRoleCanNotBeUpdate() {
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.SYSTEM.getType()));
roleMapper.insert(roleDO);
// 准备参数
Long id = roleDO.getId();
assertServiceException(() -> roleService.validateRoleFo... |
@GetMapping("/vscode/gallery/publishers/{namespaceName}/vsextensions/{extensionName}/{version}/vspackage")
@CrossOrigin
public ModelAndView download(
@PathVariable String namespaceName, @PathVariable String extensionName, @PathVariable String version,
@RequestParam(defaultValue = TargetP... | @Test
public void testDownload() throws Exception {
mockExtensionVersion();
mockMvc.perform(get("/vscode/gallery/publishers/{namespace}/vsextensions/{extension}/{version}/vspackage",
"redhat", "vscode-yaml", "0.5.2"))
.andExpect(status().isFound())
.an... |
public static boolean isNotBlank(String str) {
return !isBlank(str);
} | @Test
public void testIsNotBlank() {
Assert.assertFalse(StringUtil.isNotBlank(""));
Assert.assertTrue(StringUtil.isNotBlank("\"###"));
} |
@Override
public boolean match(Message msg, StreamRule rule) {
Double msgVal = getDouble(msg.getField(rule.getField()));
if (msgVal == null) {
return false;
}
Double ruleVal = getDouble(rule.getValue());
if (ruleVal == null) {
return false;
}
... | @Test
public void testMissedMatch() {
StreamRule rule = getSampleRule();
rule.setValue("25");
Message msg = getSampleMessage();
msg.addField("something", "27");
StreamRuleMatcher matcher = getMatcher(rule);
assertFalse(matcher.match(msg, rule));
} |
@Override
public boolean apply(Collection<Member> members) {
if (members.size() < minimumClusterSize) {
return false;
}
int count = 0;
long timestamp = Clock.currentTimeMillis();
for (Member member : members) {
if (!isAlivePerIcmp(member)) {
... | @Test
public void testSplitBrainProtectionAbsent_whenHeartbeatsLate() throws Exception {
// will do 5 heartbeats with 500msec interval starting from now
long now = System.currentTimeMillis();
// initialize clock offset +1 minute --> last heartbeat received was too far in the past
lon... |
public final DisposableServer bindNow() {
return bindNow(Duration.ofSeconds(45));
} | @Test
void testBindTimeout() {
assertThatExceptionOfType(IllegalStateException.class)
.isThrownBy(() -> new TestServerTransport(Mono.never()).bindNow(Duration.ofMillis(1)));
} |
@GET
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Get prekey count",
description = "Gets the number of one-time prekeys uploaded for this device and still available")
@ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", use... | @Test
void putKeysTestV2EmptySingleUseKeysList() {
final ECSignedPreKey signedPreKey = KeysHelper.signedECPreKey(31338, AuthHelper.VALID_IDENTITY_KEY_PAIR);
final SetKeysRequest setKeysRequest = new SetKeysRequest(List.of(), signedPreKey, List.of(), null);
try (final Response response =
resource... |
@Override
protected int getJDBCPort() {
return DEFAULT_ORACLE_INTERNAL_PORT;
} | @Test
public void testGetJDBCPortReturnsCorrectValue() {
assertThat(testManager.getJDBCPort()).isEqualTo(DEFAULT_ORACLE_INTERNAL_PORT);
} |
@Override
public Response toResponse(Throwable e) {
if (log.isDebugEnabled()) {
log.debug("Uncaught exception in REST call: ", e);
} else if (log.isInfoEnabled()) {
log.info("Uncaught exception in REST call: {}", e.getMessage());
}
if (e instanceof NotFoundExc... | @Test
public void testToResponseUnknownException() {
RestExceptionMapper mapper = new RestExceptionMapper();
Response resp = mapper.toResponse(new Exception("Unknown exception"));
assertEquals(resp.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} |
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testConsumerGroupHeartbeatFullResponse() {
String groupId = "fooup";
String memberId = Uuid.randomUuid().toString();
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicName = "foo";
// Create a context with an empty consumer group.
MockPartitionAs... |
@Override
public FastAppend appendManifest(ManifestFile manifest) {
Preconditions.checkArgument(
!manifest.hasExistingFiles(), "Cannot append manifest with existing files");
Preconditions.checkArgument(
!manifest.hasDeletedFiles(), "Cannot append manifest with deleted files");
Precondition... | @TestTemplate
public void testInvalidAppendManifest() throws IOException {
assertThat(listManifestFiles()).isEmpty();
TableMetadata base = readMetadata();
assertThat(base.currentSnapshot()).isNull();
ManifestFile manifestWithExistingFiles =
writeManifest("manifest-file-1.avro", manifestEntry... |
public static List<Criterion> parse(String filter) {
return StreamSupport.stream(CRITERIA_SPLITTER.split(filter).spliterator(), false)
.map(FilterParser::parseCriterion)
.toList();
} | @Test
public void search_is_case_insensitive() {
List<Criterion> criterion = FilterParser.parse("ncloc > 10 AnD coverage <= 80 AND debt = 10 AND issues = 20");
assertThat(criterion).hasSize(4);
} |
public static List<Field> getDeclaredFieldsIncludingInherited(Class<?> clazz) {
List<Field> fields = new ArrayList<Field>();
while (clazz != null) {
Field[] sortedFields = clazz.getDeclaredFields();
Arrays.sort(sortedFields, new Comparator<Field>() {
public int compare(Field a, Field b) {
... | @Test
public void testGetDeclaredFieldsIncludingInherited() {
Parent child = new Parent() {
private int childField;
@SuppressWarnings("unused")
public int getChildField() { return childField; }
};
List<Field> fields = ReflectionUtils.getDeclaredFieldsIncludingInherited(
chil... |
public String getExcludeName() {
return excludeName;
} | @Test
public void getExcludeName() throws Exception {
Assert.assertEquals(new ExcludeFilter("*").getExcludeName(), "*");
} |
private boolean check(char exp) {
return desc.charAt(pos) == exp;
} | @Test
public void testPrimitives() {
check("()V", "V");
check("(I)D", "D", "I");
} |
public static Optional<SchemaAndId> getLatestSchemaAndId(
final SchemaRegistryClient srClient,
final String topic,
final boolean isKey
) {
final String subject = KsqlConstants.getSRSubject(topic, isKey);
return getLatestSchemaId(srClient, topic, isKey)
.map(id -> {
try {
... | @Test
public void shouldReturnParsedSchemaFromSubjectValue() throws Exception {
// Given:
when(schemaMetadata.getId()).thenReturn(123);
when(schemaRegistryClient.getLatestSchemaMetadata("bar-value"))
.thenReturn(schemaMetadata);
when(schemaRegistryClient.getSchemaById(123))
.thenReturn... |
@Override
public void write(DataOutput out) throws IOException {
super.write(out);
jobId.write(out);
WritableUtils.writeEnum(out, type);
} | @Test
public void testWrite() throws Exception {
JobID jobId = new JobID("1234", 1);
TaskID taskId = new TaskID(jobId, TaskType.JOB_SETUP, 0);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
taskId.write(out);
DataInputByteBuffer i... |
@Udf(description = "Converts a number of milliseconds since 1970-01-01 00:00:00 UTC/GMT into the"
+ " string representation of the timestamp in the given format. Single quotes in the"
+ " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'."
+ " The system default time zon... | @Test
public void shouldBeThreadSafe() {
IntStream.range(0, 10_000)
.parallel()
.forEach(idx -> {
shouldConvertTimestampToString();
udf.timestampToString(1538361611123L, "yyyy-MM-dd HH:mm:ss.SSS");
});
} |
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
} | @Test
public void testDuplicateVcoresDefinitionPercentage() throws Exception {
expectInvalidResourcePercentage("cpu");
parseResourceConfigValue("50% memory, 50% 100%cpu");
} |
public void error( Throwable throwable ) {
publishProcessor.onError( throwable );
} | @Test
public void testError() {
// verifies that calling .error() results in an exception being thrown
// by the .rows() blocking iterable.
final String exceptionMessage = "Exception raised during acceptRows loop";
streamSource = new BlockingQueueStreamSource<String>( streamStep ) {
@Override p... |
public CaseInsensitiveString getDirectParentName() {
String stringPath = path();
if (stringPath == null) {
return null;
}
int index = stringPath.lastIndexOf(DELIMITER);
return index == -1 ? path : new CaseInsensitiveString(stringPath.substring(index + 1));
} | @Test
public void shouldUnderstandDirectParentName() {
PathFromAncestor path = new PathFromAncestor(new CaseInsensitiveString("grand-parent/parent/child"));
assertThat(path.getDirectParentName(), is(new CaseInsensitiveString("child")));
} |
public static WalletFile createLight(String password, ECKeyPair ecKeyPair)
throws CipherException {
return create(password, ecKeyPair, N_LIGHT, P_LIGHT);
} | @Test
public void testCreateLight() throws Exception {
testCreate(Wallet.createLight(SampleKeys.PASSWORD, SampleKeys.KEY_PAIR));
} |
public void insertPausedStepInstanceAttempt(
Connection conn,
String workflowId,
long version,
long instanceId,
long runId,
String stepId,
long stepAttemptId)
throws SQLException {
try (PreparedStatement stmt = conn.prepareStatement(CREATE_PAUSED_STEP_INSTANCE_ATTEMPT... | @Test
public void testInsertPausedStepInstanceAttempt() throws SQLException {
when(workflowDao.getWorkflowDefinition(anyString(), anyString())).thenReturn(wfd);
String workflowId = wfd.getPropertiesSnapshot().getWorkflowId();
maestroStepBreakpointDao.insertPausedStepInstanceAttempt(
conn,
... |
public Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> newChannelInitializers() {
Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> channelInitializers = new HashMap<>();
Set<InetSocketAddress> addresses = new HashSet<>();
for (Map.Entry<String, Proxy... | @Test(expectedExceptions = RuntimeException.class)
public void testNewChannelInitializersOverlapped() {
ChannelInitializer<SocketChannel> i1 = mock(ChannelInitializer.class);
ChannelInitializer<SocketChannel> i2 = mock(ChannelInitializer.class);
Map<InetSocketAddress, ChannelInitializer<Sock... |
@Udf
public <T extends Comparable<? super T>> T arrayMin(@UdfParameter(
description = "Array of values from which to find the minimum") final List<T> input) {
if (input == null) {
return null;
}
T candidate = null;
for (T thisVal : input) {
if (thisVal != null) {
if (candida... | @Test
public void shouldFindDoubleMin() {
final List<Double> input =
Arrays.asList(Double.valueOf(1.1), Double.valueOf(3.1), Double.valueOf(-1.1));
assertThat(udf.arrayMin(input), is(Double.valueOf(-1.1)));
} |
@Override
public int getOrder() {
return PluginEnum.DIVIDE.getCode();
} | @Test
public void getOrderTest() {
assertEquals(PluginEnum.DIVIDE.getCode(), dividePlugin.getOrder());
} |
public boolean shouldDropFrame(final InetSocketAddress address, final UnsafeBuffer buffer, final int length)
{
return false;
} | @Test
void singleSmallGapRX()
{
final MultiGapLossGenerator generator = new MultiGapLossGenerator(0, 8, 4, 1);
assertFalse(generator.shouldDropFrame(null, null, 123, 456, 0, 0, 8));
assertTrue(generator.shouldDropFrame(null, null, 123, 456, 0, 8, 8));
assertFalse(generator.should... |
public static Field p(String fieldName) {
return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName);
} | @Test
void basic_group_syntax() {
/*
example from vespa document:
https://docs.vespa.ai/en/grouping.html
all( group(a) max(5) each(output(count())
all(max(1) each(output(summary())))
all(group(b) each(output(count())
all(max(1) each(output(summ... |
public String name() {
return name;
} | @Test
void nameCannotBeNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> DefaultBot.getDefaultBuilder().name(null).build());
} |
public DropSourceCommand create(final DropStream statement) {
return create(
statement.getName(),
statement.getIfExists(),
statement.isDeleteTopic(),
DataSourceType.KSTREAM
);
} | @Test
public void shouldFailDropSourceOnMissingSourceWithNoIfExistsForStream() {
// Given:
final DropStream dropStream = new DropStream(SOME_NAME, false, true);
when(metaStore.getSource(SOME_NAME)).thenReturn(null);
// When:
final Exception e = assertThrows(
KsqlException.class,
(... |
@Override
public String quoteIdentifier(String identifier) {
if (identifier.contains(".")) {
String[] parts = identifier.split("\\.");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parts.length - 1; i++) {
sb.append("\"").append(parts[i]).app... | @Test
public void testIdentifierCaseSensitive() {
DmdbDialectFactory factory = new DmdbDialectFactory();
JdbcDialect dialect = factory.create();
Assertions.assertEquals("\"test\"", dialect.quoteIdentifier("test"));
Assertions.assertEquals("\"TEST\"", dialect.quoteIdentifier("TEST"))... |
@Override
public EntityStatementJWS establishIdpTrust(URI issuer) {
var trustedFederationStatement = fetchTrustedFederationStatement(issuer);
// the federation statement from the master will establish trust in the JWKS and the issuer URL
// of the idp,
// we still need to fetch the entity configurat... | @Test
void establishTrust_configurationWithBadJwks() throws JOSEException {
var client = new FederationMasterClientImpl(FEDERATION_MASTER, federationApiClient, clock);
var issuer = URI.create("https://idp-tk.example.com");
var federationFetchUrl = FEDERATION_MASTER.resolve("/fetch");
var fedmasterK... |
static Comparator<String> compareBySnapshot(Map<String, SnapshotDto> snapshotByProjectUuid) {
return (uuid1, uuid2) -> {
SnapshotDto snapshot1 = snapshotByProjectUuid.get(uuid1);
SnapshotDto snapshot2 = snapshotByProjectUuid.get(uuid2);
if (snapshot1 == null && snapshot2 == null) {
return ... | @Test
public void verify_comparator_transitivity() {
Map<String, SnapshotDto> map = new HashMap<>();
map.put("A", new SnapshotDto().setCreatedAt(1L));
map.put("B", new SnapshotDto().setCreatedAt(2L));
map.put("C", new SnapshotDto().setCreatedAt(-1L));
List<String> uuids = new ArrayList<>(map.keySe... |
public List<String> toPrefix(String in) {
List<String> tokens = buildTokens(alignINClause(in));
List<String> output = new ArrayList<>();
List<String> stack = new ArrayList<>();
for (String token : tokens) {
if (isOperand(token)) {
if (token.equals(")")) {
... | @Test
public void testNot() {
String query = "a and not(b) OR c not in ( 4, 5, 6 )";
List<String> list = parser.toPrefix(query);
assertEquals(Arrays.asList("a", "b", "not", "and", "c", "4,5,6", "in", "not", "OR"), list);
} |
public static List<ComponentDto> sortComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest, List<MetricDto> metrics,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
List<String> sortParameters = wsRequest.getSort();
if (sortParameters == null || sor... | @Test
void sort_by_numerical_metric_key_descending() {
components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure"));
ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_SORT), false, NUM_METRIC_KEY);
List<ComponentDto> result = so... |
public static LeaseRenewer getInstance(final String authority,
final UserGroupInformation ugi, final DFSClient dfsc) {
final LeaseRenewer r = Factory.INSTANCE.get(authority, ugi);
r.addClient(dfsc);
return r;
} | @Test
public void testInstanceSharing() throws IOException {
// Two lease renewers with the same UGI should return
// the same instance
LeaseRenewer lr = LeaseRenewer.getInstance(
FAKE_AUTHORITY, FAKE_UGI_A, MOCK_DFSCLIENT);
LeaseRenewer lr2 = LeaseRenewer.getInstance(
FAKE_AUTHORITY, ... |
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload,
final ConnectionSession connectionSession) {
switch (commandPacketType) {
case COM_QUIT:
return new MySQLCom... | @Test
void assertNewInstanceWithComShutDownPacket() {
assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_SHUTDOWN, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class));
} |
public ProjectList getProjects(String serverUrl, String token) {
HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/projects");
return doGet(token, url, body -> buildGson().fromJson(body, ProjectList.class));
} | @Test
public void get_projects_failed() {
server.enqueue(new MockResponse()
.setBody(new Buffer().write(new byte[4096]))
.setSocketPolicy(SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.getProjects(serve... |
public static BadRequestException appAlreadyExists(String appId) {
return new BadRequestException("app already exists for appId:%s", appId);
} | @Test
public void testAppAlreadyExists(){
BadRequestException appAlreadyExists = BadRequestException.appAlreadyExists(appId);
assertEquals("app already exists for appId:app-1001", appAlreadyExists.getMessage());
} |
public static <T> T newInstance(ClassLoader classLoader, String name) {
try {
return ClassLoaderUtil.newInstance(classLoader, name);
} catch (Exception e) {
throw sneakyThrow(e);
}
} | @Test
public void when_newInstance_then_returnsInstance() {
// When
OuterClass instance = ReflectionUtils.newInstance(OuterClass.class.getClassLoader(), OuterClass.class.getName());
// Then
assertThat(instance).isNotNull();
} |
public void stop() {
if (!isRunning()) {
return;
}
super.stop();
// At the end save cookies to the file specified in the order file.
if (getCookieStore() != null) {
AbstractCookieStore r = getCookieStore();
if (r.getCookiesSaveFile() != null) {... | @Test
public void testSocksProxy() throws Exception {
// create a fetcher with socks enabled
FetchHTTP socksFetcher = newSocksTestFetchHttp(getUserAgentString(), "localhost", 7800);
CrawlURI curi = makeCrawlURI("http://localhost:7777/");
socksFetcher().process(curi);
runDefa... |
@Override
public Collection<LocalDataQueryResultRow> getRows(final ShowReadwriteSplittingRulesStatement sqlStatement, final ContextManager contextManager) {
Collection<LocalDataQueryResultRow> result = new LinkedList<>();
Map<String, Map<String, String>> exportableDataSourceMap = getExportableDataSo... | @Test
void assertGetRowDataWithoutLoadBalancer() throws SQLException {
engine = setUp(mock(ShowReadwriteSplittingRulesStatement.class), createRuleConfigurationWithoutLoadBalancer());
engine.executeQuery();
Collection<LocalDataQueryResultRow> actual = engine.getRows();
assertThat(actu... |
@Override
public void update(Component component, Metric metric, Measure measure) {
requireNonNull(component);
checkValueTypeConsistency(metric, measure);
Optional<Measure> existingMeasure = find(component, metric);
if (!existingMeasure.isPresent()) {
throw new UnsupportedOperationException(
... | @Test
public void update_throws_NPE_if_Component_measure_is_null() {
assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, metric1, null))
.isInstanceOf(NullPointerException.class);
} |
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle(
final LifecycleScopeProvider<E> provider) throws OutsideScopeException {
return resolveScopeFromLifecycle(provider, true);
} | @Test
public void lifecycleDefault_withStart_shouldFailIfEnded() {
TestLifecycleScopeProvider lifecycle = TestLifecycleScopeProvider.createInitial(STOPPED);
try {
testSource(resolveScopeFromLifecycle(lifecycle));
throw new AssertionError("Lifecycle resolution should have failed due to it being en... |
@Override
public Http clone() throws CloneNotSupportedException {
final Http config = new Http();
config.setPath(getPath());
config.setHeaders(getHeaders());
config.setExpectedResponseCode(getExpectedResponseCode());
return config;
} | @Test
void testClone() throws CloneNotSupportedException {
Http cloned = http.clone();
assertEquals(http.hashCode(), cloned.hashCode());
assertEquals(http, cloned);
} |
@Override
public void writeComment(String data) throws XMLStreamException {
String filteredData = nonXmlCharFilterer.filter(data);
writer.writeComment(filteredData);
} | @Test
public void testWriteComment() throws XMLStreamException {
filteringXmlStreamWriter.writeComment("value");
verify(xmlStreamWriterMock).writeComment("filteredValue");
} |
public static String humanReadableByteSize(long size) {
String measure = "B";
if (size < 1024) {
return size + " " + measure;
}
double number = size;
if (number >= 1024) {
number = number / 1024;
measure = "KiB";
if (number >= 1024)... | @Test
@Issue("JENKINS-16630")
public void testHumanReadableFileSize() {
Locale defaultLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.ENGLISH);
assertEquals("0 B", Functions.humanReadableByteSize(0));
assertEquals("1023 B", Functions.humanReadable... |
@Override
public <T> Future<T> submit(Callable<T> task) {
return delegate.submit(task);
} | @Test
public void submit_runnable_with_result_delegates_to_executorService() {
underTest.submit(SOME_RUNNABLE, SOME_STRING);
inOrder.verify(executorService).submit(SOME_RUNNABLE, SOME_STRING);
inOrder.verifyNoMoreInteractions();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.