focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static TableElements of(final TableElement... elements) {
return new TableElements(ImmutableList.copyOf(elements));
} | @Test
public void shouldThrowOnDuplicateKeyValueColumns() {
// Given:
final List<TableElement> elements = ImmutableList.of(
tableElement("v0", INT_TYPE, KEY_CONSTRAINT),
tableElement("v0", INT_TYPE),
tableElement("v1", INT_TYPE, PRIMARY_KEY_CONSTRAINT),
tableElement("v1", INT_T... |
public static String get(@NonNull SymbolRequest request) {
String name = request.getName();
String title = request.getTitle();
String tooltip = request.getTooltip();
String htmlTooltip = request.getHtmlTooltip();
String classes = request.getClasses();
String pluginName = ... | @Test
@DisplayName("IDs in symbol should not be removed")
@Issue("JENKINS-70730")
void getSymbol_idInSymbolIsPresent() {
String symbol = Symbol.get(new SymbolRequest.Builder()
.withId("some-random-id")
.withName("with-id").build());
assertThat(symbol, contain... |
@Override
public boolean containsKey(K key) {
return map.containsKey(key);
} | @Test
public void testContainsKey() {
map.put(23, "value-23");
assertTrue(adapter.containsKey(23));
assertFalse(adapter.containsKey(42));
} |
public Node parse() throws ScanException {
if (tokenList == null || tokenList.isEmpty())
return null;
return E();
} | @Test
public void withDefault() throws ScanException {
Tokenizer tokenizer = new Tokenizer("${b:-c}");
Parser parser = new Parser(tokenizer.tokenize());
Node node = parser.parse();
Node witness = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "b"));
witness.defaultP... |
@Override
public void select(final List<Local> files) {
if(log.isDebugEnabled()) {
log.debug(String.format("Select files for %s", files));
}
previews.clear();
for(final Local selected : files) {
previews.add(new QLPreviewItem() {
@Override
... | @Test
public void testSelect() {
QuickLook q = new QuartzQuickLook();
final List<Local> files = new ArrayList<Local>();
files.add(new NullLocal("f"));
files.add(new NullLocal("b"));
q.select(files);
} |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatStructWithReservedWords() {
// Given:
final Statement statement = parseSingle("CREATE STREAM s (foo STRUCT<`END` VARCHAR>) WITH (kafka_topic='foo', value_format='JSON');");
// When:
final String result = SqlFormatter.formatSql(statement);
// Then:
assertThat(res... |
public Optional<ComputationState> getIfPresent(String computationId) {
return Optional.ofNullable(computationCache.getIfPresent(computationId));
} | @Test
public void testGetIfPresent_computationStateNotCached() {
Optional<ComputationState> computationState =
computationStateCache.getIfPresent("computationId");
assertFalse(computationState.isPresent());
verifyNoInteractions(configFetcher);
} |
public static <T> boolean listEquals(List<T> left, List<T> right) {
if (left == null) {
return right == null;
} else {
if (right == null) {
return false;
}
if (left.size() != right.size()) {
return false;
}
... | @Test
public void testListEquals() {
List left = new ArrayList();
List right = new ArrayList();
Assert.assertTrue(CommonUtils.listEquals(null, null));
Assert.assertFalse(CommonUtils.listEquals(left, null));
Assert.assertFalse(CommonUtils.listEquals(null, right));
Asse... |
@Nonnull
public static String cutOffAtFirst(@Nonnull String text, char cutoff) {
int i = text.indexOf(cutoff);
if (i < 0) return text;
return text.substring(0, i);
} | @Test
void testCutOffAtFirst() {
// chars
assertEquals("", StringUtil.cutOffAtFirst("", 'd'));
assertEquals("abc", StringUtil.cutOffAtFirst("abcdefg", 'd'));
assertEquals("abc", StringUtil.cutOffAtFirst("abcdefgd", 'd'));
// strings
assertEquals("", StringUtil.cutOffAtFirst("", "d"));
assertEquals("abc",... |
@Override
protected void registerMetadata(final MetaDataRegisterDTO dto) {
if (dto.isRegisterMetaData()) {
MetaDataService metaDataService = getMetaDataService();
MetaDataDO exist = metaDataService.findByPath(dto.getPath());
metaDataService.saveOrUpdateMetaData(exist, dto... | @Test
public void testRegisterMetadata() {
MetaDataDO metaDataDO = MetaDataDO.builder().build();
when(metaDataService.findByPath(any())).thenReturn(metaDataDO);
MetaDataRegisterDTO metaDataDTO = MetaDataRegisterDTO.builder().registerMetaData(true).build();
shenyuClientRegisterDivideS... |
public void execute() {
Profiler stepProfiler = Profiler.create(LOGGER).logTimeLast(true);
boolean allStepsExecuted = false;
try {
executeSteps(stepProfiler);
allStepsExecuted = true;
} finally {
if (listener != null) {
executeListener(allStepsExecuted);
}
}
} | @Test
public void execute_calls_listener_finished_method_with_all_step_runs() {
new ComputationStepExecutor(mockComputationSteps(computationStep1, computationStep2), taskInterrupter, listener)
.execute();
verify(listener).finished(true);
verifyNoMoreInteractions(listener);
} |
@Override
public void run() {
if (!redoService.isConnected()) {
LogUtils.NAMING_LOGGER.warn("Grpc Connection is disconnect, skip current redo task");
return;
}
try {
redoForInstances();
redoForSubscribes();
} catch (Exception e) {
... | @Test
void testRunRedoDeRegisterSubscriberWithClientDisabled() throws NacosException {
when(clientProxy.isEnable()).thenReturn(false);
Set<SubscriberRedoData> mockData = generateMockSubscriberData(true, true, false);
when(redoService.findSubscriberRedoData()).thenReturn(mockData);
re... |
@Override
public BufferWithSubpartition getNextBuffer(@Nullable MemorySegment transitBuffer) {
checkState(isFinished, "Sort buffer is not ready to be read.");
checkState(!isReleased, "Sort buffer is already released.");
if (!hasRemaining()) {
freeSegments.add(transitBuffer);
... | @Test
void testBufferIsRecycledWhenGetEvent() throws Exception {
int numSubpartitions = 10;
int bufferPoolSize = 512;
int bufferSizeBytes = 1024;
int numBuffersForSort = 20;
int subpartitionId = 0;
Random random = new Random(1234);
NetworkBufferPool globalPoo... |
public String compile(final String xls,
final String template,
int startRow,
int startCol) {
return compile( xls,
template,
InputType.XLS,
startRow,
... | @Test
public void testLoadCsv() {
final String drl = converter.compile("/data/ComplexWorkbook.drl.csv",
"/templates/test_template2.drl",
InputType.CSV,
10,
... |
public static InstrumentedThreadFactory privilegedThreadFactory(MetricRegistry registry, String name) {
return new InstrumentedThreadFactory(Executors.privilegedThreadFactory(), registry, name);
} | @Test
public void testPrivilegedThreadFactory() throws Exception {
final ThreadFactory threadFactory = InstrumentedExecutors.privilegedThreadFactory(registry);
threadFactory.newThread(new NoopRunnable());
final Field delegateField = InstrumentedThreadFactory.class.getDeclaredField("delegate... |
@VisibleForTesting
static boolean isCompressed(String contentEncoding) {
return contentEncoding.contains(HttpHeaderValues.GZIP.toString())
|| contentEncoding.contains(HttpHeaderValues.DEFLATE.toString())
|| contentEncoding.contains(HttpHeaderValues.BR.toString())
... | @Test
void detectsDeflate() {
assertTrue(HttpUtils.isCompressed("deflate"));
} |
@Override
public Output run(RunContext runContext) throws Exception {
String taskSpec = runContext.render(this.spec);
try {
Task task = OBJECT_MAPPER.readValue(taskSpec, Task.class);
if (task instanceof TemplatedTask) {
throw new IllegalArgumentException("The ... | @Test
void templatedFlowable() {
RunContext runContext = runContextFactory.of();
TemplatedTask templatedTask = TemplatedTask.builder()
.id("template")
.type(TemplatedTask.class.getName())
.spec("""
type: io.kestra.plugin.core.flow.Pause
... |
public static PutMessageResult checkBeforePutMessage(BrokerController brokerController, final MessageExt msg) {
if (brokerController.getMessageStore().isShutdown()) {
LOG.warn("message store has shutdown, so putMessage is forbidden");
return new PutMessageResult(PutMessageStatus.SERVICE_... | @Test
public void testCheckBeforePutMessage() {
BrokerController brokerController = Mockito.mock(BrokerController.class);
MessageStore messageStore = Mockito.mock(MessageStore.class);
MessageStoreConfig messageStoreConfig = new MessageStoreConfig();
RunningFlags runningFlags = Mockit... |
@Override
public Object convertData( ValueMetaInterface meta2, Object data2 ) throws KettleValueException {
switch ( meta2.getType() ) {
case TYPE_STRING:
return convertStringToInternetAddress( meta2.getString( data2 ) );
case TYPE_INTEGER:
return convertIntegerToInternetAddress( meta2... | @Test
public void testConvertNumberIPv4() throws Exception {
ValueMetaInterface vmia = new ValueMetaInternetAddress( "Test" );
ValueMetaNumber vmn = new ValueMetaNumber( "aNumber" );
Object convertedIPv4 = vmia.convertData( vmn, InetAddress2BigInteger( SAMPLE_IPV4_AS_BYTES ).doubleValue() );
assertNo... |
public static List<Criterion> parse(String filter) {
return StreamSupport.stream(CRITERIA_SPLITTER.split(filter).spliterator(), false)
.map(FilterParser::parseCriterion)
.toList();
} | @Test
public void parse_filter_having_value_containing_operator_characters() {
List<Criterion> criterion = FilterParser.parse("languages IN (java, python, <null>)");
assertThat(criterion)
.extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValues, Criterion::getValue)
.containsOn... |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_map_of_non_serializable_value() {
Map<String, NonSerializableObject> original = new HashMap<>();
original.put("key", new NonSerializableObject("value"));
Object cloned = serializer.clone(original);
assertEquals(original, cloned);
assertNotSame(o... |
public SchemaMapping fromParquet(MessageType parquetSchema) {
List<Type> fields = parquetSchema.getFields();
List<TypeMapping> mappings = fromParquet(fields);
List<Field> arrowFields = fields(mappings);
return new SchemaMapping(new Schema(arrowFields), parquetSchema, mappings);
} | @Test
public void testRepeatedParquetToArrow() {
Schema arrow = converter.fromParquet(Paper.schema).getArrowSchema();
assertEquals(paperArrowSchema, arrow);
} |
public B lazy(Boolean lazy) {
this.lazy = lazy;
return getThis();
} | @Test
void lazy() {
ReferenceBuilder builder = new ReferenceBuilder();
builder.lazy(true);
Assertions.assertTrue(builder.build().getLazy());
builder.lazy(false);
Assertions.assertFalse(builder.build().getLazy());
} |
@Override
public List<TransferItem> list(final Session<?> session, final Path remote,
final Local directory, final ListProgressListener listener) throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("List children for %s", directory))... | @Test
public void testList() throws Exception {
final NullLocal local = new NullLocal("t") {
@Override
public AttributedList<Local> list() {
AttributedList<Local> l = new AttributedList<>();
l.add(new NullLocal(this.getAbsolute(), "c"));
... |
@Override
public byte[] serialize(final String topic, final List<?> values) {
if (values == null) {
return null;
}
final T single = extractOnlyColumn(values, topic);
return inner.serialize(topic, single);
} | @Test
public void shouldSerializeNewStyleNulls() {
// When:
final byte[] result = serializer.serialize(TOPIC, HEADERS, null);
// Then:
assertThat(result, is(nullValue()));
} |
@Operation(summary = "Get all certificates based on conditions")
@PostMapping(value = "/search", consumes = "application/json")
@ResponseBody
public Page<Certificate> search(@RequestBody CertSearchRequest request,
@RequestParam(name = "page", defaultValue = "0") int pageI... | @Test
public void getAllCertificatesBasedOnConditions() {
CertSearchRequest request = new CertSearchRequest();
when(certificateServiceMock.searchAll(request, 1, 10)).thenReturn(getPageCertificates());
Page<Certificate> result = controllerMock.search(request, 1, 10);
verify(certific... |
public NugetPackage parse(InputStream stream) throws NuspecParseException {
try {
final DocumentBuilder db = XmlUtils.buildSecureDocumentBuilder();
final Document d = db.parse(stream);
final XPath xpath = XPathFactory.newInstance().newXPath();
final NugetPackage ... | @Test(expected = NuspecParseException.class)
public void testNotNuspec() throws Exception {
XPathNuspecParser parser = new XPathNuspecParser();
//InputStream is = XPathNuspecParserTest.class.getClassLoader().getResourceAsStream("suppressions.xml");
InputStream is = BaseTest.getResourceAsStre... |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PCollectionsImmutableSet<?> that = (PCollectionsImmutableSet<?>) o;
return Objects.equals(underlying(), that.underlying());
} | @Test
public void testEquals() {
final MapPSet<Object> mock = mock(MapPSet.class);
assertEquals(new PCollectionsImmutableSet<>(mock), new PCollectionsImmutableSet<>(mock));
final MapPSet<Object> someOtherMock = mock(MapPSet.class);
assertNotEquals(new PCollectionsImmutableSet<>(mock)... |
public Map<TopicPartition, OffsetAndMetadata> fetchCommittedOffsets(final Set<TopicPartition> partitions,
final Timer timer) {
if (partitions.isEmpty()) return Collections.emptyMap();
final Generation generationForOffsetRequest = g... | @Test
public void testFetchCommittedOffsets() {
client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE));
long offset = 500L;
String metadata = "blahblah";
Optional<Integer> leaderEpoch = Optional.of(... |
@Override
public String toString() {
return toString(true);
} | @Test
public void testToStringHumanWithQuota() {
long length = Long.MAX_VALUE;
long fileCount = 222222222;
long directoryCount = 33333;
long quota = 222256578;
long spaceConsumed = 1073741825;
long spaceQuota = 1;
ContentSummary contentSummary = new ContentSummary.Builder().length(length)... |
@Override
public void write(T record) {
recordConsumer.startMessage();
try {
messageWriter.writeTopLevelMessage(record);
} catch (RuntimeException e) {
Message m = (record instanceof Message.Builder) ? ((Message.Builder) record).build() : (Message) record;
LOG.error("Cannot write message... | @Test
public void testMessageRecursion() {
RecordConsumer readConsumerMock = Mockito.mock(RecordConsumer.class);
Configuration conf = new Configuration();
ProtoSchemaConverter.setMaxRecursion(conf, 1);
ProtoWriteSupport<Trees.BinaryTree> spyWriter =
createReadConsumerInstance(Trees.BinaryTree.... |
public boolean isResolverViewId() {
return viewId.contains(SEPARATOR);
} | @Test
public void testStandardView() {
final ViewResolverDecoder decoder = new ViewResolverDecoder("62068954bd0cd7035876fcec");
assertFalse(decoder.isResolverViewId());
assertThatThrownBy(decoder::getResolverName)
.isExactlyInstanceOf(IllegalArgumentException.class);
... |
@Override
public boolean updateEntryExpiration(K key, long ttl, TimeUnit ttlUnit, long maxIdleTime, TimeUnit maxIdleUnit) {
return get(updateEntryExpirationAsync(key, ttl, ttlUnit, maxIdleTime, maxIdleUnit));
} | @Test
public void testUpdateEntryExpiration() throws InterruptedException {
RMapCache<Integer, Integer> cache = redisson.getMapCache("testUpdateEntryExpiration");
cache.put(1, 2, 3, TimeUnit.SECONDS);
Thread.sleep(2000);
long ttl = cache.remainTimeToLive(1);
assertThat(ttl).i... |
public String getProgress(final boolean running, final long size, final long transferred) {
return this.getProgress(System.currentTimeMillis(), running, size, transferred);
} | @Test
public void testStopped() {
final long start = System.currentTimeMillis();
Speedometer m = new Speedometer(start, true);
assertEquals("0 B of 1.0 MB", m.getProgress(true, 1000000L, 0L));
assertEquals("500.0 KB of 1.0 MB", m.getProgress(false, 1000000L, 1000000L / 2));
} |
@Override
public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) {
if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) {
return resolveRequestConfig(propertyName);
} else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX)
&& !propertyName.starts... | @Test
public void shouldResolveKsqlPrefixedProducerConfig() {
assertThat(resolver.resolve(
KsqlConfig.KSQL_STREAMS_PREFIX + ProducerConfig.BUFFER_MEMORY_CONFIG, true),
is(resolvedItem(ProducerConfig.BUFFER_MEMORY_CONFIG, PRODUCER_CONFIG_DEF)));
} |
@Override
public Iterable<RedisClusterNode> clusterGetNodes() {
return read(null, StringCodec.INSTANCE, CLUSTER_NODES);
} | @Test
public void testClusterGetNodes() {
Iterable<RedisClusterNode> nodes = connection.clusterGetNodes();
assertThat(nodes).hasSize(6);
for (RedisClusterNode redisClusterNode : nodes) {
assertThat(redisClusterNode.getLinkState()).isNotNull();
assertThat(redisClusterN... |
public static int countArguments(String sql) {
int argCount = 0;
for (int i = 0; i < sql.length(); i++) {
if (sql.charAt(i) == '?') {
argCount++;
}
}
return argCount;
} | @Test
public void countArguments() {
assertThat(SqlLogFormatter.countArguments("select * from issues")).isZero();
assertThat(SqlLogFormatter.countArguments("select * from issues where id=?")).isOne();
assertThat(SqlLogFormatter.countArguments("select * from issues where id=? and kee=?")).isEqualTo(2);
} |
public PluginWrapper(PluginManager parent, File archive, Manifest manifest, URL baseResourceURL,
ClassLoader classLoader, File disableFile,
List<Dependency> dependencies, List<Dependency> optionalDependencies) {
this.parent = parent;
this.manifest = manifest;
this.shortNa... | @Test
public void dependencyFailedToLoad() {
pluginWrapper("dependency").version("5").buildFailed();
PluginWrapper pw = pluginWrapper("dependee").deps("dependency:3").buildLoaded();
final IOException ex = assertThrows(IOException.class, pw::resolvePluginDependencies);
assertContains... |
public static Version of(int major, int minor) {
if (major == UNKNOWN_VERSION && minor == UNKNOWN_VERSION) {
return UNKNOWN;
} else {
return new Version(major, minor);
}
} | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void construct_withNegativeMajor() {
Version.of(-1, 1);
} |
@Override
public OAuth2AccessTokenDO checkAccessToken(String accessToken) {
OAuth2AccessTokenDO accessTokenDO = getAccessToken(accessToken);
if (accessTokenDO == null) {
throw exception0(GlobalErrorCodeConstants.UNAUTHORIZED.getCode(), "访问令牌不存在");
}
if (DateUtils.isExpire... | @Test
public void testCheckAccessToken_null() {
// 调研,并断言
assertServiceException(() -> oauth2TokenService.checkAccessToken(randomString()),
new ErrorCode(401, "访问令牌不存在"));
} |
public static void destroyAll() {
synchronized (globalLock) {
for (FrameworkModel frameworkModel : new ArrayList<>(allInstances)) {
frameworkModel.destroy();
}
}
} | @Test
void destroyAll() {
FrameworkModel frameworkModel = new FrameworkModel();
frameworkModel.defaultApplication();
frameworkModel.newApplication();
FrameworkModel.destroyAll();
Assertions.assertTrue(FrameworkModel.getAllInstances().isEmpty());
Assertions.assertTrue... |
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 testScanFilterWithIdentifiers() throws Exception {
org.robolectric.shadows.ShadowLog.stream = System.err;
BeaconParser parser = new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24");
parser.setHardwareAssistManufacturerCodes(new int[] {0x004c});
... |
static String buildRedirect(String redirectUri, Map<String, Object> params) {
String paramsString = params.entrySet()
.stream()
.map(e -> e.getKey() + "=" + urlEncode(String.valueOf(e.getValue())))
.colle... | @Test
public void testBuildRedirect() {
String url = OAuth2AuthorizeController.buildRedirect("http://hsweb.me/callback", Collections.singletonMap("code", "1234"));
assertEquals(url,"http://hsweb.me/callback?code=1234");
} |
void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception {
Http2HeadersSink sink = new Http2HeadersSink(
streamId, headers, maxHeaderListSize, validateHeaders);
// Check for dynamic table size updates, which must occur at the beginning:
... | @Test
public void testIncompleteHeaderFieldRepresentation() throws Http2Exception {
// Incomplete Literal Header Field with Incremental Indexing
byte[] input = {(byte) 0x40};
final ByteBuf in = Unpooled.wrappedBuffer(input);
try {
assertThrows(Http2Exception.class, new Ex... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatTumblingWindowWithRetention() {
// Given:
final String statementString = "CREATE STREAM S AS SELECT ITEMID, COUNT(*) FROM ORDERS WINDOW TUMBLING (SIZE 7 DAYS, RETENTION 14 DAYS) GROUP BY ITEMID;";
final Statement statement = parseSingle(statementString);
final String res... |
public String callServer(String api, Map<String, String> params, Map<String, String> body, String curServer,
String method) throws NacosException {
long start = System.currentTimeMillis();
long end = 0;
String namespace = params.get(CommonParams.NAMESPACE_ID);
String group = ... | @Test
void testCallServerFail304() throws Exception {
//given
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenAnswer(invocationOnMock -> {
//return url
Htt... |
public MethodBuilder stat(Integer stat) {
this.stat = stat;
return getThis();
} | @Test
void stat() {
MethodBuilder builder = MethodBuilder.newBuilder();
builder.stat(1);
Assertions.assertEquals(1, builder.build().getStat());
} |
@Override
public KeyVersion createKey(final String name, final byte[] material,
final Options options) throws IOException {
return doOp(new ProviderCallable<KeyVersion>() {
@Override
public KeyVersion call(KMSClientProvider provider) throws IOException {
return provider.createKey(name, m... | @Test
public void testClientRetriesWithRuntimeException() throws Exception {
Configuration conf = new Configuration();
conf.setInt(
CommonConfigurationKeysPublic.KMS_CLIENT_FAILOVER_MAX_RETRIES_KEY, 3);
KMSClientProvider p1 = mock(KMSClientProvider.class);
when(p1.createKey(Mockito.anyString()... |
private void initialize() {
log.debug("Initializing share partition: {}-{}", groupId, topicIdPartition);
// Initialize the share partition by reading the state from the persister.
ReadShareGroupStateResult response;
try {
response = persister.readState(new ReadShareGroupState... | @Test
public void testInitialize() {
Persister persister = Mockito.mock(Persister.class);
ReadShareGroupStateResult readShareGroupStateResult = Mockito.mock(ReadShareGroupStateResult.class);
Mockito.when(readShareGroupStateResult.topicsData()).thenReturn(Collections.singletonList(
... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<DropConnector> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final String connectorName = statement.getStatement().getConn... | @Test
public void shouldReturnOnSuccess() {
// Given:
when(connectClient.delete(anyString()))
.thenReturn(ConnectResponse.success("foo", HttpStatus.SC_OK));
// When:
final Optional<KsqlEntity> response = DropConnectorExecutor
.execute(DROP_CONNECTOR_CONFIGURED, mock(SessionProperties.... |
public synchronized Topology addSink(final String name,
final String topic,
final String... parentNames) {
internalTopologyBuilder.addSink(name, topic, null, null, null, parentNames);
return this;
} | @Test
public void shouldNotAllowNullTopicWhenAddingSink() {
assertThrows(NullPointerException.class, () -> topology.addSink("name", (String) null));
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testUpdatePositionWithLastRecordMissingFromBatch() {
buildFetcher();
MemoryRecords records = MemoryRecords.withRecords(Compression.NONE,
new SimpleRecord("0".getBytes(), "v".getBytes()),
new SimpleRecord("1".getBytes(), "v".getBytes()),
... |
public Set<Device> getDevicesFromPath(String path) throws IOException {
MutableInt counter = new MutableInt(0);
try (Stream<Path> stream = Files.walk(Paths.get(path), 1)) {
return stream.filter(p -> p.toFile().getName().startsWith("veslot"))
.map(p -> toDevice(p, counter))
.collect... | @Test
public void testDeviceStateNumberTooHigh() throws IOException {
createVeSlotFile(0);
createOsStateFile(5);
when(mockCommandExecutor.getOutput())
.thenReturn("8:1:character special file");
when(udevUtil.getSysPath(anyInt(), anyChar())).thenReturn(testFolder);
Set<Device> devices = disc... |
@Override
public String getPonLinks(String target) {
DriverHandler handler = handler();
NetconfController controller = handler.get(NetconfController.class);
MastershipService mastershipService = handler.get(MastershipService.class);
DeviceId ncDeviceId = handler.data().deviceId();
... | @Test
public void testValidGetPonLinks() throws Exception {
String reply;
String target;
for (int i = ZERO; i < VALID_GET_TCS.length; i++) {
target = VALID_GET_TCS[i];
currentKey = i;
reply = voltConfig.getPonLinks(target);
assertNotNull("Inco... |
@Override
public InstancePublishInfo getInstancePublishInfo(Service service) {
return publishers.get(service);
} | @Test
void getInstancePublishInfo() {
addServiceInstance();
InstancePublishInfo publishInfo = abstractClient.getInstancePublishInfo(service);
assertNotNull(publishInfo);
} |
@VisibleForTesting
void validateUsernameUnique(Long id, String username) {
if (StrUtil.isBlank(username)) {
return;
}
AdminUserDO user = userMapper.selectByUsername(username);
if (user == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的用户
... | @Test
public void testValidateUsernameUnique_usernameExistsForCreate() {
// 准备参数
String username = randomString();
// mock 数据
userMapper.insert(randomAdminUserDO(o -> o.setUsername(username)));
// 调用,校验异常
assertServiceException(() -> userService.validateUsernameUniqu... |
@CheckForNull
static String checkEventCategory(@Nullable String category) {
if (category == null) {
return null;
}
checkArgument(category.length() <= MAX_CATEGORY_LENGTH, "Event category length (%s) is longer than the maximum authorized (%s). '%s' was provided.",
category.length(), MAX_CATEGOR... | @Test
void fail_if_category_longer_than_50() {
assertThatThrownBy(() -> EventValidator.checkEventCategory(repeat("a", 50 + 1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Event category length (51) is longer than the maximum authorized (50). " +
"'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... |
@Override
public void execute(Context context) {
executeForBranch(treeRootHolder.getRoot());
} | @Test
public void givenUpgradeEventWithDifferentSqVersion_whenStepIsExecuted_thenANewUpgradeEventIsCreated() {
when(sonarQubeVersion.get()).thenReturn(Version.parse("10.3"));
when(dbClient.eventDao()).thenReturn(mock());
when(dbClient.eventDao().selectSqUpgradesByMostRecentFirst(any(), any())).thenReturn(... |
@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 globPatternConcat() throws Exception {
Map<String, String> metadata = new HashMap<>();
for (int i = 0; i < 3; i++) {
generateData(name.getMethodName() + "-" + i + ".avro", Type.STRING, metadata, DEFLATE);
}
File output = new File(OUTPUT_DIR, name.getMethodName() + ".avro");
Lis... |
@Override public void accept(K key, V value) {
subject.onNext(Map.entry(key, value));
} | @Test
public void singleKey_mostRecent() {
var timeInWriteBehind = new AtomicReference<ZonedDateTime>();
var numberOfEntries = new AtomicInteger();
// Given this cache...
var writer = new WriteBehindCacheWriter.Builder<Long, ZonedDateTime>()
.coalesce(BinaryOperator.maxBy(ZonedDateTime::compa... |
@Override
public void destroy() {
servletConfig = null;
} | @Test
public void testDestroy() {
new ReportServlet().destroy();
} |
@Override
public void removeProxySelector(final DiscoveryHandlerDTO discoveryHandlerDTO, final ProxySelectorDTO proxySelectorDTO) {
DataChangedEvent dataChangedEvent = new DataChangedEvent(ConfigGroupEnum.PROXY_SELECTOR, DataEventTypeEnum.DELETE,
Collections.singletonList(DiscoveryTransfer.I... | @Test
public void testRemoveProxySelector() {
doNothing().when(eventPublisher).publishEvent(any(DataChangedEvent.class));
localDiscoveryProcessor.removeProxySelector(new DiscoveryHandlerDTO(), new ProxySelectorDTO());
verify(eventPublisher).publishEvent(any(DataChangedEvent.class));
} |
public static URI toURI(URL url) throws UtilException {
return toURI(url, false);
} | @Test
public void issue3676Test() {
String fileFullName = "/Uploads/20240601/aaaa.txt";
final URI uri = URLUtil.toURI(fileFullName);
final URI resolve = uri.resolve(".");
assertEquals("/Uploads/20240601/", resolve.toString());
} |
@Override
public Iterator<QueryableEntry> iterator() {
return new It();
} | @Test(expected = UnsupportedOperationException.class)
public void testIterator_empty_remove() {
result.iterator().remove();
} |
@Override
public boolean isTraceEnabled() {
return logger.isTraceEnabled();
} | @Test
public void testIsTraceEnabled() {
Logger mockLogger = mock(Logger.class);
when(mockLogger.getName()).thenReturn("foo");
when(mockLogger.isTraceEnabled()).thenReturn(true);
InternalLogger logger = new Slf4JLogger(mockLogger);
assertTrue(logger.isTraceEnabled());
... |
public static String toString(int flags) {
if (flags == TMNOFLAGS) {
return "TMNOFLAGS";
}
StringBuilder result = new StringBuilder();
if (hasFlag(flags, TMENDRSCAN)) {
add(result, "TMENDRSCAN");
}
if (hasFlag(flags, TMFAIL)) {
add(res... | @Test
public void test() throws Exception {
assertThat(XASupport.toString(flags), is(expectedResult));
} |
public static TransferAction forName(final String name) {
return registry.get(name);
} | @Test
public void testForName() {
assertEquals(TransferAction.overwrite.hashCode(),
TransferAction.forName(TransferAction.overwrite.name()).hashCode());
} |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchUdpSrcTest() {
Criterion criterion = Criteria.matchUdpSrc(tpPort);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
@Override
public void run() {
while (!schedulerState.isShuttingDown()) {
if (!schedulerState.isPaused()) {
try {
toRun.run();
} catch (Throwable e) {
LOG.error("Unhandled exception. Will keep running.", e);
schedulerListeners.onSchedulerEvent(SchedulerEventType.... | @Test
public void should_wait_on_runtime_exception() {
Assertions.assertTimeoutPreemptively(
Duration.ofSeconds(1),
() -> {
runnable.setAction(
() -> {
throw new RuntimeException();
});
runUntilShutdown.run();
assertThat(cou... |
public WithJsonPath(JsonPath jsonPath, Matcher<T> resultMatcher) {
this.jsonPath = jsonPath;
this.resultMatcher = resultMatcher;
} | @Test
public void shouldMatchJsonPathEvaluatedToDoubleValue() {
assertThat(BOOKS_JSON, withJsonPath(compile("$.store.bicycle.price"), equalTo(19.95)));
assertThat(BOOKS_JSON, withJsonPath("$.store.bicycle.price", equalTo(19.95)));
} |
@PostMapping("/account_status")
@Operation(summary = "Get the data of aan an account")
public DAccountDataResult getAccountData(@RequestBody DAccountRequest request) {
AppSession appSession = validate(request);
long accountId = appSession.getAccountId();
AccountDataResult result = accoun... | @Test
public void validRequest() {
DAccountRequest request = new DAccountRequest();
request.setAppSessionId("id");
AccountDataResult result = new AccountDataResult();
result.setStatus(Status.OK);
result.setError("error");
result.setEmailStatus(EmailStatus.NOT_VERIFIE... |
public ReadOperation getReadOperation() {
if (operations == null || operations.isEmpty()) {
throw new IllegalStateException("Map task has no operation.");
}
Operation readOperation = operations.get(0);
if (!(readOperation instanceof ReadOperation)) {
throw new IllegalStateException("First o... | @Test
public void testNoOperation() throws Exception {
// Test MapTaskExecutor without a single operation.
ExecutionStateTracker stateTracker = ExecutionStateTracker.newForTest();
try (MapTaskExecutor executor =
new MapTaskExecutor(new ArrayList<Operation>(), counterSet, stateTracker)) {
thr... |
protected void maybeCloseFetchSessions(final Timer timer) {
final List<RequestFuture<ClientResponse>> requestFutures = sendFetchesInternal(
prepareCloseFetchSessionRequests(),
this::handleCloseFetchSessionSuccess,
this::handleCloseFetchSessionFailure
);
... | @Test
public void testCloseShouldBeIdempotent() {
buildFetcher();
fetcher.close();
fetcher.close();
fetcher.close();
verify(fetcher, times(1)).maybeCloseFetchSessions(any(Timer.class));
} |
@Override
public Object createWebSocket(final JettyServerUpgradeRequest request, final JettyServerUpgradeResponse response) {
try {
Optional<WebSocketAuthenticator<T>> authenticator = Optional.ofNullable(environment.getAuthenticator());
final ReusableAuth<T> authenticated;
if (authenticator.isP... | @Test
void testErrorAuthorization() throws AuthenticationException, IOException {
when(environment.getAuthenticator()).thenReturn(authenticator);
when(authenticator.authenticate(eq(request))).thenThrow(new AuthenticationException("database failure"));
when(environment.jersey()).thenReturn(jerseyEnvironmen... |
@Operation(summary = "queryResourceListPaging", description = "QUERY_RESOURCE_LIST_PAGING_NOTES")
@Parameters({
@Parameter(name = "type", description = "RESOURCE_TYPE", required = true, schema = @Schema(implementation = ResourceType.class)),
@Parameter(name = "fullName", description = "RESOU... | @Test
public void testQueryResourceListPaging() throws Exception {
Result mockResult = new Result<>();
mockResult.setCode(Status.SUCCESS.getCode());
Mockito.when(resourcesService.queryResourceListPaging(
Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(),
... |
long addNewRecording(
final long startPosition,
final long stopPosition,
final long startTimestamp,
final long stopTimestamp,
final int imageInitialTermId,
final int segmentFileLength,
final int termBufferLength,
final int mtuLength,
final int sess... | @Test
void shouldAppendToExistingIndex()
{
final long newRecordingId;
try (Catalog catalog = new Catalog(archiveDir, null, 0, CAPACITY, () -> 3L, null, segmentFileBuffer))
{
newRecordingId = catalog.addNewRecording(
32,
128,
21,... |
@Override
public CoordinatorRecord deserialize(
ByteBuffer keyBuffer,
ByteBuffer valueBuffer
) throws RuntimeException {
final short recordType = readVersion(keyBuffer, "key");
final ApiMessage keyMessage = apiMessageKeyFor(recordType);
readMessage(keyMessage, keyBuffer, ... | @Test
public void testDeserializeWithInvalidValueBytes() {
GroupCoordinatorRecordSerde serde = new GroupCoordinatorRecordSerde();
ApiMessageAndVersion key = new ApiMessageAndVersion(
new ConsumerGroupMetadataKey().setGroupId("foo"),
(short) 3
);
ByteBuffer ke... |
@Override
public CloseableIterator<String> readLines(Component file) {
requireNonNull(file, "Component should not be null");
checkArgument(file.getType() == FILE, "Component '%s' is not a file", file);
Optional<CloseableIterator<String>> linesIteratorOptional = reportReader.readFileSource(file.getReportA... | @Test
public void read_lines_throws_ISE_when_sourceLines_has_more_elements_then_lineCount() {
reportReader.putFileSourceLines(FILE_REF, "line1", "line2", "line3");
assertThatThrownBy(() -> consume(underTest.readLines(createComponent(2))))
.isInstanceOf(IllegalStateException.class)
.hasMessage("So... |
public FloatArrayAsIterable usingTolerance(double tolerance) {
return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject());
} | @Test
public void usingTolerance_contains_success() {
assertThat(array(1.1f, TOLERABLE_2POINT2, 3.2f))
.usingTolerance(DEFAULT_TOLERANCE)
.contains(2.2f);
} |
@Override
protected String getRootKey() {
return Constants.HEADER_OSS + mBucketName;
} | @Test
public void testGetRootKey() {
Assert.assertEquals(Constants.HEADER_OSS + BUCKET_NAME, mOSSUnderFileSystem.getRootKey());
} |
public FEELFnResult<Boolean> invoke(@ParameterName("negand") Object negand) {
if ( negand != null && !(negand instanceof Boolean) ) {
return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "negand", "must be a boolean value" ) );
}
return FEELFnResult.ofResult( nega... | @Test
void invokeFalse() {
FunctionTestUtil.assertResult(notFunction.invoke(false), true);
} |
@Override
public UserAccount updateDb(final UserAccount userAccount) {
Document id = new Document(USER_ID, userAccount.getUserId());
Document dataSet = new Document(USER_NAME, userAccount.getUserName())
.append(ADD_INFO, userAccount.getAdditionalInfo());
db.getCollection(CachingConstants.USER_... | @Test
void updateDb() {
MongoCollection<Document> mongoCollection = mock(MongoCollection.class);
when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection);
assertDoesNotThrow(()-> {mongoDb.updateDb(userAccount);});
} |
public static String getBirthByIdCard(String idcard) {
return getBirth(idcard);
} | @Test
public void getBirthByIdCardTest() {
String birth = IdcardUtil.getBirthByIdCard(ID_18);
assertEquals(birth, "19781216");
String birth2 = IdcardUtil.getBirthByIdCard(ID_15);
assertEquals(birth2, "19880730");
} |
@Override
public ChannelFuture writeAndFlush(Object msg) {
CompletableFuture<Void> processFuture = new CompletableFuture<>();
try {
if (msg instanceof RemotingCommand) {
ProxyContext context = ProxyContext.createForInner(this.getClass())
.setRemoteAdd... | @Test
public void testWriteAndFlush() throws Exception {
when(this.proxyRelayService.processCheckTransactionState(any(), any(), any(), any()))
.thenReturn(new RelayData<>(mock(TransactionData.class), new CompletableFuture<>()));
ArgumentCaptor<ConsumeMessageDirectlyResultRequestHeader> ... |
public static Instant earlier(Instant time1, Instant time2) {
return time1.isBefore(time2) ? time1 : time2;
} | @Test
public void earlier() {
Instant t1 = Instant.now(); // earlier
Instant t2 = t1.plusSeconds(1); // later
assertEquals(t1, TimeUtils.earlier(t1, t2));
assertEquals(t1, TimeUtils.earlier(t2, t1));
assertEquals(t1, TimeUtils.earlier(t1, t1));
assertEquals(t2, TimeUt... |
public static MessageDigest digest(String algorithm) {
final Matcher matcher = WITH_PATTERN.matcher(algorithm);
final String digestAlgorithm = matcher.matches() ? matcher.group(1) : algorithm;
try {
return MessageDigest.getInstance(digestAlgorithm);
} catch (NoSuchAlgorithmEx... | @Test
public void digestUsingName() {
assertEquals("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS",
Hex.toHexString(DigestUtils.digest("SHA-256").digest(new byte[0]))
);
} |
@Override
public SelDouble assignOps(SelOp op, SelType rhs) {
SelTypeUtil.checkTypeMatch(this.type(), rhs.type());
double another = ((SelDouble) rhs).val;
switch (op) {
case ASSIGN:
this.val = another;
return this;
case ADD_ASSIGN:
this.val += another;
return th... | @Test
public void testAssignOps() {
SelDouble obj = SelDouble.of(2.2);
SelDouble res = one.assignOps(SelOp.ASSIGN, obj);
assertEquals(2.2, res.doubleVal(), 0.01);
res = one.assignOps(SelOp.ASSIGN, SelDouble.of(3.3));
assertEquals(2.2, obj.doubleVal(), 0.01);
assertEquals(3.3, res.doubleVal(), ... |
@Nonnull
@Override
public Result addChunk(ByteBuf buffer) {
final byte[] readable = new byte[buffer.readableBytes()];
buffer.readBytes(readable, buffer.readerIndex(), buffer.readableBytes());
final GELFMessage msg = new GELFMessage(readable);
final ByteBuf aggregatedBuffer;
... | @Test
public void outOfOrderChunks() {
final ByteBuf[] chunks = createChunkedMessage(4096 + 512, 1024); // creates 5 chunks
CodecAggregator.Result result = null;
for (int i = chunks.length - 1; i >= 0; i--) {
result = aggregator.addChunk(chunks[i]);
if (i != 0) {
... |
public void popMessageAsync(
final String brokerName, final String addr, final PopMessageRequestHeader requestHeader,
final long timeoutMillis, final PopCallback popCallback
) throws RemotingException, InterruptedException {
final RemotingCommand request = RemotingCommand.createRequestComman... | @Test
public void testPopLmqMessage_async() throws Exception {
final long popTime = System.currentTimeMillis();
final int invisibleTime = 10 * 1000;
final String lmqTopic = MixAll.LMQ_PREFIX + "lmq1";
doAnswer((Answer<Void>) mock -> {
InvokeCallback callback = mock.getArg... |
public static AscendingLongIterator and(AscendingLongIterator[] iterators) {
return new AndIterator(iterators);
} | @Test
public void testAnd() {
long seed = System.nanoTime();
System.out.println(getClass().getSimpleName() + ".testAnd seed: " + seed);
actual.add(new SparseBitSet());
expected.add(new TreeSet<>());
verifyAnd();
actual.clear();
expected.clear();
gene... |
@SuppressWarnings("unchecked")
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
if (inner != null) {
log.error("Could not configure ListSerializer as the parameter has already been set -- inner: {}", inner);
throw new ConfigException("List serializer was a... | @Test
public void testListValueSerializerNoArgConstructorsShouldThrowKafkaExceptionDueInvalidClass() {
props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_INNER_CLASS, new FakeObject());
final KafkaException exception = assertThrows(
KafkaException.class,
() -> listSeriali... |
@Override
public BeamSqlTable buildBeamSqlTable(Table table) {
return new MongoDbTable(table);
} | @Test
public void testBuildBeamSqlTable_withUsernameOnly() {
Table table = fakeTable("TEST", "mongodb://username@localhost:27017/database/collection");
BeamSqlTable sqlTable = provider.buildBeamSqlTable(table);
assertNotNull(sqlTable);
assertTrue(sqlTable instanceof MongoDbTable);
MongoDbTable m... |
public synchronized void clean() {
try {
cleanStateAndTaskDirectoriesCalledByUser();
} catch (final Exception e) {
throw new StreamsException(e);
}
try {
if (stateDir.exists()) {
Utils.delete(globalStateDir().getAbsoluteFile());
... | @Test
public void shouldRemoveEmptyNamedTopologyDirsWhenCallingClean() throws IOException {
initializeStateDirectory(true, true);
final File namedTopologyDir = new File(appDir, "__topology1__");
assertThat(namedTopologyDir.mkdir(), is(true));
assertThat(namedTopologyDir.exists(), is(... |
@Override
public int size() {
return count(members, selector);
} | @Test
public void testSizeWhenThisLiteMembersSelected() {
Collection<MemberImpl> collection = new MemberSelectingCollection<>(members, LITE_MEMBER_SELECTOR);
assertEquals(2, collection.size());
} |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldCreateWithExplicitVersion() {
// Given:
command = PARSER.parse(DESCRIPTION, "-v", "12");
// When:
final int result = command.command(migrationsDir);
// Then:
assertThat(result, is(0));
final File expectedFile = new File(Paths.get(migrationsDir, "V000012__" + EXPE... |
@Override
public String toString() {
return "CSV Input ("
+ StringUtils.showControlCharacters(String.valueOf(getFieldDelimiter()))
+ ") "
+ Arrays.toString(getFilePaths());
} | @Test
void testPojoType() throws Exception {
File tempFile = File.createTempFile("CsvReaderPojoType", "tmp");
tempFile.deleteOnExit();
tempFile.setWritable(true);
OutputStreamWriter wrt = new OutputStreamWriter(new FileOutputStream(tempFile));
wrt.write("123,AAA,3.123,BBB\n"... |
@Override
public Subnet subnet(String subnetId) {
checkArgument(!Strings.isNullOrEmpty(subnetId), ERR_NULL_SUBNET_ID);
return osNetworkStore.subnet(subnetId);
} | @Test
public void testGetSubnetById() {
createBasicNetworks();
assertTrue("Subnet did not match", target.subnet(SUBNET_ID) != null);
assertTrue("Subnet did not match", target.subnet(UNKNOWN_ID) == null);
} |
@Override
public void setPermission(final Path file, final TransferStatus status) throws BackgroundException {
try {
// Read owner from bucket
final AccessControlList list = this.toAcl(status.getAcl());
final Path bucket = containerService.getContainer(file);
... | @Test(expected = NotfoundException.class)
public void testWriteNotFound() 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(), EnumSe... |
public GoPluginBundleDescriptor build(BundleOrPluginFileDetails bundleOrPluginJarFile) {
if (!bundleOrPluginJarFile.exists()) {
throw new RuntimeException(format("Plugin or bundle jar does not exist: %s", bundleOrPluginJarFile.file()));
}
String defaultId = bundleOrPluginJarFile.fil... | @Test
void shouldThrowExceptionForInvalidPluginIfThePluginJarDoesNotExist() {
BundleOrPluginFileDetails bundleOrPluginFileDetails = new BundleOrPluginFileDetails(new File("not-existing.jar"), true, pluginDirectory);
assertThatCode(() -> goPluginBundleDescriptorBuilder.build(bundleOrPluginFileDetails... |
public static CharSequence unescapeCsv(CharSequence value) {
int length = checkNotNull(value, "value").length();
if (length == 0) {
return value;
}
int last = length - 1;
boolean quoted = isDoubleQuote(value.charAt(0)) && isDoubleQuote(value.charAt(last)) && length !=... | @Test
public void unescapeCsvWithCRAndWithoutQuote() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
unescapeCsv("\r");
}
});
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.