focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public String getColumnLabel() {
return "*";
} | @Test
void assertGetColumnLabel() {
assertTrue(new ShorthandProjection(new IdentifierValue("owner"), Collections.emptyList()).getColumnLabel().contains("*"));
} |
static boolean isSupportedProtocol(URL url) {
String protocol = url.getProtocol().toLowerCase(java.util.Locale.ENGLISH);
return protocol.equals(HTTPConstants.PROTOCOL_HTTP) || protocol.equals(HTTPConstants.PROTOCOL_HTTPS);
} | @Test
public void testHttps() throws Exception {
Assertions.assertTrue(AuthManager.isSupportedProtocol(new URL("https:")));
} |
@Override
protected int rsv(WebSocketFrame msg) {
return msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame?
msg.rsv() | WebSocketExtension.RSV1 : msg.rsv();
} | @Test
public void testIllegalStateWhenCompressionInProgress() {
WebSocketExtensionFilter selectivityCompressionFilter = new WebSocketExtensionFilter() {
@Override
public boolean mustSkip(WebSocketFrame frame) {
return frame.content().readableBytes() < 100;
... |
public PageListResponse<IndexSetFieldTypeSummary> getIndexSetFieldTypeSummary(final Set<String> streamIds,
final String fieldName,
final Predicate<String> i... | @Test
void testComplexPaginationScenario() {
Predicate<String> indexSetPermissionPredicate = indexSetID -> indexSetID.contains("canSee");
final Set<String> allStreams = Set.of("stream_id_1", "stream_id_2", "stream_id_3", "stream_id_4", "stream_id_5");
doReturn(Set.of("canSee1", "cannotSee", ... |
@GET
@Path("sql")
@ManualAuthorization
public String handleGetSql(@QueryParam("sql") String sqlQuery, @QueryParam("trace") String traceEnabled,
@QueryParam("queryOptions") String queryOptions, @Context HttpHeaders httpHeaders) {
try {
LOGGER.debug("Trace: {}, Running query: {}", traceEnabled, sqlQ... | @Test
public void testInvalidQuery() {
String response = _pinotQueryResource.handleGetSql("INVALID QUERY", null, null, null);
Assert.assertTrue(response.contains(String.valueOf(QueryException.SQL_PARSING_ERROR_CODE)));
Assert.assertFalse(response.contains("retry the query using the multi-stage query engin... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void getChatMember() {
restrictChatMember();
ChatMember chatMember = bot.execute(new GetChatMember(groupId, memberBot)).chatMember();
ChatMemberTest.check(chatMember);
assertEquals(ChatMember.Status.restricted, chatMember.status());
assertEquals(Integer.valueOf(0... |
@Override
public boolean isValid() {
return hasOnlyFields(PREFIXES) && prefixes() != null;
} | @Test
public void testIsValid() {
assertTrue(config.isValid());
} |
public void addPipeline(String groupName, PipelineConfig pipeline) {
String sanitizedGroupName = BasicPipelineConfigs.sanitizedGroupName(groupName);
if (!this.hasGroup(sanitizedGroupName)) {
createNewGroup(sanitizedGroupName, pipeline);
return;
}
for (PipelineConf... | @Test
public void shouldSaveNewPipelineGroupOnTheTop() {
PipelineConfigs defaultGroup = createGroup("defaultGroup", createPipelineConfig("pipeline1", "stage1"));
PipelineConfigs defaultGroup2 = createGroup("defaultGroup2", createPipelineConfig("pipeline2", "stage2"));
PipelineGroups pipeline... |
@Override
public Object getDefaultValue() {
return defaultValue;
} | @Test
public void testGetDefaultValue() throws Exception {
NumberField f = new NumberField("test", "Name", 9001, "foo", ConfigurationField.Optional.NOT_OPTIONAL);
assertEquals(9001, f.getDefaultValue());
} |
public static <T> T ifOverridden(Supplier<T> supplier, @NonNull Class<?> base, @NonNull Class<?> derived, @NonNull String methodName, @NonNull Class<?>... types) {
if (isOverridden(base, derived, methodName, types)) {
return supplier.get();
} else {
throw new AbstractMethodError(... | @Test
public void ifOverriddenSuccess() {
assertTrue(Util.ifOverridden(() -> true, BaseClass.class, DerivedClassSuccess.class, "method"));
} |
public void copy(String src, String destination) throws RolloverFailure {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(destination));
... | @Test
public void basicCopyingWorks() throws IOException {
String dir = CoreTestConstants.OUTPUT_DIR_PREFIX + "/fu" + diff;
File dirFile = new File(dir);
dirFile.mkdir();
String src = CoreTestConstants.TEST_INPUT_PREFIX + "compress1.copy";
String target = CoreTestConstants.... |
public final void isNotEmpty() {
if (Iterables.isEmpty(checkNotNull(actual))) {
failWithoutActual(simpleFact("expected not to be empty"));
}
} | @Test
public void iterableIsNotEmptyWithFailure() {
expectFailureWhenTestingThat(asList()).isNotEmpty();
assertFailureKeys("expected not to be empty");
} |
public ScanResults run(ScanTarget scanTarget) throws ExecutionException, InterruptedException {
return runAsync(scanTarget).get();
} | @Test
public void run_whenPortScannerFailed_returnsFailedScanResult()
throws ExecutionException, InterruptedException {
Injector injector =
Guice.createInjector(
new FakeUtcClockModule(),
new FakePluginExecutionModule(),
new FailedPortScannerBootstrapModule(),
... |
public synchronized boolean registerProducer(final String group, final DefaultMQProducerImpl producer) {
if (null == group || null == producer) {
return false;
}
MQProducerInner prev = this.producerTable.putIfAbsent(group, producer);
if (prev != null) {
log.warn(... | @Test
public void testRegisterProducer() {
boolean flag = mqClientInstance.registerProducer(group, mock(DefaultMQProducerImpl.class));
assertThat(flag).isTrue();
flag = mqClientInstance.registerProducer(group, mock(DefaultMQProducerImpl.class));
assertThat(flag).isFalse();
... |
public MemoryRecords build() {
if (aborted) {
throw new IllegalStateException("Attempting to build an aborted record batch");
}
close();
return builtRecords;
} | @Test
public void testUnsupportedCompress() {
BiFunction<Byte, Compression, MemoryRecordsBuilder> builderBiFunction = (magic, compression) ->
new MemoryRecordsBuilder(ByteBuffer.allocate(128), magic, compression, TimestampType.CREATE_TIME, 0L, 0L,
RecordBatch.NO_PRODUCER_ID, ... |
@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 shouldFailOnMissingMigrationFile() throws Exception {
// Given:
final List<String> migratedVersions = ImmutableList.of("1", "2", "3");
final List<String> migrationFiles = ImmutableList.of("1", "3");
final List<String> checksums = givenExistingMigrationFiles(migrationFiles);
given... |
private static void convertToTelemetry(JsonElement jsonElement, long systemTs, Map<Long, List<KvEntry>> result, PostTelemetryMsg.Builder builder) {
if (jsonElement.isJsonObject()) {
parseObject(systemTs, result, builder, jsonElement.getAsJsonObject());
} else if (jsonElement.isJsonArray()) {... | @Test
public void testParseAsDoubleWithZero() {
var result = JsonConverter.convertToTelemetry(JsonParser.parseString("{\"meterReadingDelta\": 42.0}"), 0L);
Assertions.assertEquals(42.0, result.get(0L).get(0).getDoubleValue().get(), 0.0);
} |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.NOTIFY_TEMPLATE,
allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理
public void deleteNotifyTemplate(Long id) {
// 校验存在
validateNotifyTemplateExists(id);
// 删除
notifyTemplateMapper.deleteById(id);
} | @Test
public void testDeleteNotifyTemplate_success() {
// mock 数据
NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class);
notifyTemplateMapper.insert(dbNotifyTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbNotifyTemplate.getId();
// 调用
noti... |
public static void activateParams( VariableSpace childVariableSpace, NamedParams childNamedParams, VariableSpace parent, String[] listParameters,
String[] mappingVariables, String[] inputFields ) {
activateParams( childVariableSpace, childNamedParams, parent, listParameters, ... | @Test
public void activateParamsWithTruePassParametersFlagTest() throws Exception {
String childParam = "childParam";
String childValue = "childValue";
String paramOverwrite = "paramOverwrite";
String parentValue = "parentValue";
String stepValue = "stepValue";
String parentAndChildParameter =... |
@Override
public ResourceAllocationResult tryFulfillRequirements(
Map<JobID, Collection<ResourceRequirement>> missingResources,
TaskManagerResourceInfoProvider taskManagerResourceInfoProvider,
BlockedTaskManagerChecker blockedTaskManagerChecker) {
final ResourceAllocation... | @Test
void testFulFillRequirementShouldTakeRedundantInAccount() {
DefaultResourceAllocationStrategy strategy = createStrategy(1);
final TaskManagerInfo taskManager =
new TestingTaskManagerInfo(
DEFAULT_SLOT_RESOURCE.multiply(5),
DEFAUL... |
@VisibleForTesting
static boolean hasEnoughCurvature(final int[] xs, final int[] ys, final int middlePointIndex) {
// Calculate the radianValue formed between middlePointIndex, and one point in either
// direction
final int startPointIndex = middlePointIndex - CURVATURE_NEIGHBORHOOD;
final int startX ... | @Test
public void testHasEnoughCurvature90Degrees() {
final int[] Xs = new int[3];
final int[] Ys = new int[3];
Xs[0] = -50;
Ys[0] = 0;
Xs[1] = 0;
Ys[1] = 0;
Xs[2] = 0;
Ys[2] = -50;
Assert.assertTrue(GestureTypingDetector.hasEnoughCurvature(Xs, Ys, 1));
Xs[0] = -50;
Ys[... |
static String encodeElement(Object obj, URLEscaper.Escaping escaping, UriComponent.Type componentType)
{
StringBuilder builder = new StringBuilder();
encodeDataObject(obj, escaping, componentType, builder);
return builder.toString();
} | @Test(dataProvider = "unicode")
public void testUnicode(Object obj, String expectedNoEsc, String expectedPathSegEsc, String expectedQueryParamEsc)
{
String actualNoEsc = URIParamUtils.encodeElement(obj, NO_ESCAPING, null);
Assert.assertEquals(actualNoEsc, expectedNoEsc);
String actualPathSegEsc = URIPar... |
public void evaluate(AuthenticationContext context) {
if (context == null) {
return;
}
this.authenticationStrategy.evaluate(context);
} | @Test
public void evaluate4() {
if (MixAll.isMac()) {
return;
}
this.authConfig.setAuthenticationWhitelist("11");
this.evaluator = new AuthenticationEvaluator(authConfig);
DefaultAuthenticationContext context = new DefaultAuthenticationContext();
context.... |
@Override
public void removeTaskManager(InstanceID instanceId) {
Preconditions.checkNotNull(instanceId);
unWantedTaskManagers.remove(instanceId);
final FineGrainedTaskManagerRegistration taskManager =
Preconditions.checkNotNull(taskManagerRegistrations.remove(instanceId));
... | @Test
void testRemoveUnknownTaskManager() {
assertThatThrownBy(
() -> {
final FineGrainedTaskManagerTracker taskManagerTracker =
new FineGrainedTaskManagerTracker();
taskManagerTracker.removeT... |
@Override
public String get(String name) {
checkKey(name);
String value = null;
String[] keyParts = splitKey(name);
String ns = registry.getNamespaceURI(keyParts[0]);
if (ns != null) {
try {
XMPProperty prop = xmpData.getProperty(ns, keyParts[1])... | @Test
public void get_unknownPrefixKey_throw() {
assertThrows(PropertyTypeException.class, () -> {
xmpMeta.get("unknown:key");
});
} |
public MergePolicyConfig setBatchSize(int batchSize) {
this.batchSize = checkPositive("batchSize", batchSize);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void setBatchSize_withNegative() {
config.setBatchSize(-1);
} |
public StringSubject factValue(String key) {
return doFactValue(key, null);
} | @Test
public void factValueFailMultipleKeys() {
Object unused =
expectFailureWhenTestingThat(fact("foo", "the foo"), fact("foo", "the other foo"))
.factValue("foo");
assertFailureKeys("expected to contain a single fact with key", "but contained multiple");
assertFailureValue("expected ... |
@Override
public void resetConfigStats(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_RESETSTAT);
syncFuture(f);
} | @Test
public void testResetConfigStats() {
RedisClusterNode master = getFirstMaster();
connection.resetConfigStats(master);
} |
@Override
public Set<EntityExcerpt> listEntityExcerpts() {
return outputService.loadAll().stream()
.map(this::createExcerpt)
.collect(Collectors.toSet());
} | @Test
@MongoDBFixtures("OutputFacadeTest.json")
public void listEntityExcerpts() {
final EntityExcerpt expectedEntityExcerpt = EntityExcerpt.builder()
.id(ModelId.of("5adf239e4b900a0fdb4e5197"))
.type(ModelTypes.OUTPUT_V1)
.title("STDOUT")
... |
@Override
public Http2Headers decodeHeaders(int streamId, ByteBuf headerBlock) throws Http2Exception {
try {
final Http2Headers headers = newHeaders();
hpackDecoder.decode(streamId, headerBlock, headers, validateHeaders);
headerArraySizeAccumulator = HEADERS_COUNT_WEIGHT_... | @Test
public void decodeLargerThanHeaderListSizeButLessThanGoAwayWithInitialDecoderSettings() throws Exception {
final ByteBuf buf = encode(b(":method"), b("GET"), b("test_header"),
b(String.format("%09000d", 0).replace('0', 'A')));
final int streamId = 1;
try {
Http2... |
public DataSource<T> loadDataSource(Path csvPath, String responseName) throws IOException {
return loadDataSource(csvPath, Collections.singleton(responseName));
} | @Test
public void testLoadMultiOutputAsSingleOutput() throws IOException {
URL path = CSVLoader.class.getResource("/org/tribuo/data/csv/test-multioutput.csv");
Set<String> responses = new LinkedHashSet<>(Arrays.asList("R1", "R2"));
CSVLoader<MockOutput> loader = new CSVLoader<>(new MockOutpu... |
@Override
public Object evaluate(final ProcessingDTO processingDTO) {
return getFromPossibleSources(name, processingDTO)
.orElse(mapMissingTo);
} | @Test
void evaluateNull() {
final KiePMMLConstant kiePMMLConstant = new KiePMMLConstant("NAME", Collections.emptyList(), "WRONG-CONSTANT", null);
final KiePMMLDerivedField kiePMMLDerivedField = KiePMMLDerivedField.builder("ANOTHER_FIELD",
... |
public ResourceID getResourceID() {
return unresolvedTaskManagerLocation.getResourceID();
} | @Test
void testMaximumRegistrationDurationAfterConnectionLoss() throws Exception {
configuration.set(
TaskManagerOptions.REGISTRATION_TIMEOUT, TimeUtils.parseDuration("100 ms"));
final TaskSlotTable<Task> taskSlotTable =
TaskSlotUtils.createTaskSlotTable(1, EXECUTOR_E... |
public <T> HttpRestResult<T> putForm(String url, Header header, Query query, Map<String, String> bodyValues,
Type responseType) throws Exception {
RequestHttpEntity requestHttpEntity = new RequestHttpEntity(
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyVal... | @Test
void testPutForm() throws Exception {
when(requestClient.execute(any(), eq("PUT"), any())).thenReturn(mockResponse);
when(mockResponse.getStatusCode()).thenReturn(200);
when(mockResponse.getBody()).thenReturn(new ByteArrayInputStream("test".getBytes()));
Header header = Header.... |
@Override
public Mono<CheckAccountExistenceResponse> checkAccountExistence(final CheckAccountExistenceRequest request) {
final ServiceIdentifier serviceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
return RateLimitUtil.rateLimitByRemoteAddress(rateLimit... | @Test
void checkAccountExistenceRateLimited() {
final Duration retryAfter = Duration.ofSeconds(11);
when(rateLimiter.validateReactive(anyString()))
.thenReturn(Mono.error(new RateLimitExceededException(retryAfter)));
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertRateLimitExcee... |
public void updateSourceTopics(final Map<String, List<String>> allSourceTopicsByNodeName) {
sourceNodesByTopic.clear();
for (final Map.Entry<String, SourceNode<?, ?>> sourceNodeEntry : sourceNodesByName.entrySet()) {
final String sourceNodeName = sourceNodeEntry.getKey();
final S... | @Test
public void shouldThrowIfSourceNodeToUpdateDoesNotExist() {
final String existingSourceNode = "source-1";
final String nonExistingSourceNode = "source-2";
final String topicOfExistingSourceNode = "topic-1";
final String topicOfNonExistingSourceNode = "topic-2";
topology... |
protected String defaultTransformations(InputStream inputStream) throws IOException {
String html = readFullyAsString(inputStream);
if (!CollectionUtils.isEmpty(swaggerUiOAuthProperties.getConfigParameters()))
html = addInitOauth(html);
if (swaggerUiConfig.isCsrfEnabled()) {
if (swaggerUiConfig.getCsrf().i... | @Test
void setApiDocUrlCorrectly() throws IOException {
var html = underTest.defaultTransformations(is);
assertThat(html, containsString(apiDocUrl));
} |
@SuppressWarnings({"unchecked", "rawtypes"})
public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final NullsOrderType nullsOrderType,
final boolean caseSensitive) {
if (null == thisValue && null == otherVal... | @Test
void assertCompareToWhenBothNull() {
assertThat(CompareUtils.compareTo(null, null, OrderDirection.DESC, NullsOrderType.FIRST, caseSensitive), is(0));
} |
@Override
public void run() {
try {
backgroundJobServer.getJobSteward().notifyThreadOccupied();
MDCMapper.loadMDCContextFromJob(job);
performJob();
} catch (Exception e) {
if (isJobDeletedWhileProcessing(e)) {
// nothing to do anymore a... | @Test
void onFailureAfterAllRetriesServerFilterOnFailedAfterRetriesNotCalled() {
Job job = aFailedJobWithRetries().withEnqueuedState(Instant.now()).build();
when(backgroundJobServer.getBackgroundJobRunner(job)).thenReturn(null);
BackgroundJobPerformer backgroundJobPerformer = new Background... |
public static JsonElement parseString(String json) throws JsonSyntaxException {
return parseReader(new StringReader(json));
} | @Test
public void testParseInvalidJson() {
assertThrows(JsonSyntaxException.class, () -> JsonParser.parseString("[[]"));
} |
DataTableType lookupTableTypeByType(Type type) {
return lookupTableTypeByType(type, Function.identity());
} | @Test
void null_float_transformed_to_null() {
DataTableTypeRegistry registry = new DataTableTypeRegistry(Locale.ENGLISH);
DataTableType dataTableType = registry.lookupTableTypeByType(LIST_OF_LIST_OF_FLOAT);
assertEquals(
singletonList(singletonList(null)),
dataTableTy... |
ImmutableMap<PCollection<?>, FieldAccessDescriptor> getPCollectionFieldAccess() {
return ImmutableMap.copyOf(pCollectionFieldAccess);
} | @Test
public void testFieldAccessKnownAndUnknownMainInputs() {
Pipeline p = Pipeline.create();
FieldAccessVisitor fieldAccessVisitor = new FieldAccessVisitor();
Schema schema =
Schema.of(Field.of("field1", FieldType.STRING), Field.of("field2", FieldType.STRING));
PCollection<Row> source =
... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final ReadOnlyWindowStore<GenericKey, ValueAndTime... | @Test
public void shouldFetchWithEndUpperBoundIfLowest() {
// Given:
final Range<Instant> startBounds = Range.closed(
NOW,
NOW.plusSeconds(20)
);
final Range<Instant> endBounds = Range.closed(
NOW.plusSeconds(5),
NOW.plusSeconds(10)
);
// When:
table.get(A... |
@Override
public void startMediaRequest(
@NonNull String[] mimeTypes, int requestId, @NonNull InsertionRequestCallback callback) {
mCurrentRunningLocalProxy.dispose();
mCurrentRequest = requestId;
mCurrentCallback = callback;
final Intent pickingIntent = getMediaInsertRequestIntent(mimeTypes, ... | @Test
public void testStartsPickActivityWithRequest() {
mUnderTest.startMediaRequest(new String[] {"media/png"}, 123, mCallback);
Mockito.verifyZeroInteractions(mCallback);
final Intent mediaInsertionIntent =
Shadows.shadowOf((Application) ApplicationProvider.getApplicationContext())
... |
@Override
public <V> MultiLabel generateOutput(V label) {
if (label instanceof Collection) {
Collection<?> c = (Collection<?>) label;
List<Pair<String,Boolean>> dimensions = new ArrayList<>();
for (Object o : c) {
dimensions.add(MultiLabel.parseElement(o.t... | @Test
public void testGenerateOutput_labelSet() {
MultiLabelFactory factory = new MultiLabelFactory();
Set<Label> labels = new HashSet<>();
labels.add(new Label("a"));
labels.add(new Label("b"));
labels.add(new Label("c"));
MultiLabel output = factory.generateOutput(l... |
@InvokeOnHeader(Web3jConstants.ETH_GET_WORK)
void ethGetWork(Message message) throws IOException {
Request<?, EthGetWork> request = web3j.ethGetWork();
setRequestId(message, request);
EthGetWork response = request.send();
boolean hasError = checkForError(message, response);
i... | @Test
public void ethGetWorkTest() throws Exception {
EthGetWork response = Mockito.mock(EthGetWork.class);
Mockito.when(mockWeb3j.ethGetWork()).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getResult()).thenReturn(Collections.EMPTY_LIS... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) {
return invoke(n, BigDecimal.ZERO);
} | @Test
void invokeNull() {
FunctionTestUtil.assertResultError(roundHalfDownFunction.invoke(null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(roundHalfDownFunction.invoke((BigDecimal) null, null),
InvalidParametersEvent.class);
... |
@Override
public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return join(otherStream, toValueJoinerWithKey(joiner), w... | @Test
public void shouldNotAllowNullJoinWindowsOnJoin() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.join(testStream, MockValueJoiner.TOSTRING_JOINER, null));
assertThat(exception.getMessage(), equalTo("windows can't be n... |
@SuppressWarnings("unchecked")
public V putIfAbsent(final int key, final V value)
{
final V val = (V)mapNullValue(value);
requireNonNull(val, "value cannot be null");
final int[] keys = this.keys;
final Object[] values = this.values;
@DoNotSub final int mask = values.len... | @Test
void putIfAbsentThrowsNullPointerExceptionIfValueIsNull()
{
final NullPointerException exception =
assertThrowsExactly(NullPointerException.class, () -> intToObjectMap.putIfAbsent(42, null));
assertEquals("value cannot be null", exception.getMessage());
} |
public static void notNull(Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
} | @Test(expected = IllegalArgumentException.class)
public void assertNotNull() {
Assert.notNull(null, "object is null");
} |
public void setRepeated(boolean repeated) {
this.repeated = repeated;
} | @Test
public void setRepeated() {
SAExposureConfig saExposureConfig = new SAExposureConfig(1,1,true);
saExposureConfig.setRepeated(false);
assertFalse(saExposureConfig.isRepeated());
} |
public static String getRmPrincipal(Configuration conf) throws IOException {
String principal = conf.get(YarnConfiguration.RM_PRINCIPAL);
String prepared = null;
if (principal != null) {
prepared = getRmPrincipal(principal, conf);
}
return prepared;
} | @Test
public void testGetRMPrincipalHA_String() throws IOException {
Configuration conf = new Configuration();
conf.set(YarnConfiguration.RM_ADDRESS + ".rm0", "myhost");
conf.setBoolean(YarnConfiguration.RM_HA_ENABLED, true);
conf.set(YarnConfiguration.RM_HA_IDS, "rm0");
String result = YarnClie... |
public @Nullable String formatDiff(A actual, E expected) {
return null;
} | @Test
public void testTransforming_actual_formatDiff() {
assertThat(LENGTHS.formatDiff("foo", 4)).isNull();
} |
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases )
throws KettleException {
try {
databaseMeta = rep.loadDatabaseMetaFromStepAttribute( id_step, "id_connection", databases );
schemaName = rep.getStepAttributeString( id_step, "schema" );
... | @Test
public void testReadRep() throws KettleException {
//check variable
String commitSize = "${test}";
Repository rep = new MemoryRepository();
rep.saveStepAttribute( null, null, "commit", commitSize );
TableOutputMeta tableOutputMeta = new TableOutputMeta();
tableOutputMeta.readRep( rep,... |
@VisibleForTesting
static int checkJar(Path file) throws Exception {
final URI uri = file.toUri();
int numSevereIssues = 0;
try (final FileSystem fileSystem =
FileSystems.newFileSystem(
new URI("jar:file", uri.getHost(), uri.getPath(), uri.getFragment... | @Test
void testRejectedOnMissingLicenseFile(@TempDir Path tempDir) throws Exception {
assertThat(
JarFileChecker.checkJar(
createJar(
tempDir,
Entry.fileEntry(VALID_NOTICE_... |
public static List<String> readLines(Reader input) throws IOException {
BufferedReader reader = toBufferedReader(input);
List<String> list = new ArrayList<>();
while (true) {
String line = reader.readLine();
if (null != line) {
if (StringUtil.isNotEmpty(li... | @Test
public void testReadLines() throws IOException {
File tempFile = new File(tempDir.toFile(), "testReadLines.txt");
try (
PrintWriter writer = new PrintWriter(tempFile)) {
writer.println("test string 1");
writer.println("test string 2");
writer... |
public void publish(DefaultGoPublisher goPublisher, String destPath, File source, JobIdentifier jobIdentifier) {
if (!source.exists()) {
String message = "Failed to find " + source.getAbsolutePath();
goPublisher.taggedConsumeLineWithPrefix(PUBLISH_ERR, message);
bomb(message)... | @Test
public void shouldUploadArtifactChecksumForADirectory() throws IOException {
String data = "Some text whose checksum can be asserted";
String secondData = "some more";
FileUtils.writeStringToFile(tempFile, data, UTF_8);
File anotherFile = artifactFolder.resolve("bond/james_bo... |
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> rule... | @Test
public void application_search_project_issues() {
ProjectData projectData1 = db.components().insertPublicProject();
ComponentDto project1 = projectData1.getMainBranchComponent();
ProjectData projectData2 = db.components().insertPublicProject();
ComponentDto project2 = projectData2.getMainBranchC... |
public static void updateKeyForBlobStore(Map<String, Object> conf, BlobStore blobStore, CuratorFramework zkClient, String key,
NimbusInfo nimbusDetails) {
try {
// Most of clojure tests currently try to access the blobs using getBlob. Since, updateKeyForB... | @Test
public void testUpdateKeyForBlobStore_missingNode() {
zkClientBuilder.withExists(BLOBSTORE_KEY, false);
BlobStoreUtils.updateKeyForBlobStore(conf, blobStore, zkClientBuilder.build(), KEY, nimbusDetails);
zkClientBuilder.verifyExists(true);
zkClientBuilder.verifyGetChildren(fal... |
@Override
public SortedSet<Path> convertFrom(String value) {
if (value == null) {
throw new ParameterException("Path list must not be null.");
}
return Arrays.stream(value.split(SEPARATOR))
.map(StringUtils::trimToNull)
.filter(Objects::... | @Test
public void testConvertFrom() {
// Verify path set sizes.
assertEquals(0, converter.convertFrom("").size());
assertEquals(0, converter.convertFrom(",").size());
assertEquals(0, converter.convertFrom(",,,").size());
assertEquals(1, converter.convertFrom("/another-dir").s... |
@SuppressWarnings("unchecked")
@Override
public void onClosed(final String remoteAddress, final Connection conn) {
final Set<PeerPair> pairs = (Set<PeerPair>) conn.getAttribute(PAIR_ATTR);
if (pairs != null && !pairs.isEmpty()) {
// Clear request contexts when connection disconnected... | @Test
public void testOnClosed() {
mockNode();
final AppendEntriesRequestProcessor processor = (AppendEntriesRequestProcessor) newProcessor();
PeerPair pair = processor.pairOf(this.peerIdStr, this.serverId);
final PeerRequestContext ctx = processor.getOrCreatePeerRequestContext(this... |
public static String formatLocalizedErrorMessage(Message localizedErrorMessage, Locale locale) {
var bundle = ResourceBundle.getBundle(BUNDLE, locale);
var localizedMessage = bundle.getString(localizedErrorMessage.messageKey());
var key = localizedErrorMessage.messageKey();
if (!key.isBlank()) {
... | @Test
void tes_negotiatePreferredLocales_simpleError() {
var errorMessage = new Message("error.serverError");
var locale = Locale.GERMANY;
var result = LocaleUtils.formatLocalizedErrorMessage(errorMessage, locale);
assertEquals("Ohh nein! Unerwarteter Serverfehler. Bitte versuchen Sie es erneut.", ... |
@SuppressWarnings("unchecked")
public static <T> T[] removeValues(T[] values, Predicate<T> shouldRemove, Class<T> type) {
Collection<T> collection = new ArrayList<>(values.length);
for (T value : values) {
if (shouldRemove.negate().test(value)) {
collection.add(value);
}
}
T[] arra... | @Test
void removesEvenNumbers() {
Integer[] values = {22, 23};
assertThat(removeValues(values, number -> number % 2 == 0, Integer.class))
.containsExactly(23);
} |
@Override
public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {
throw new ReadOnlyBufferException();
} | @Test
public void testSetBytesWithChannel() {
final ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try {
assertThrows(ReadOnlyBufferException.class, new Executable() {
@Override
public void execute() throws IOException {
buf.setBy... |
public static void unitize2(double[] array) {
double n = norm(array);
for (int i = 0; i < array.length; i++) {
array[i] /= n;
}
} | @Test
public void testUnitize2() {
System.out.println("unitize2");
double[] data = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
MathEx.unitize2(data);
assertEquals(1, MathEx.norm2(data), 1E-7);
} |
public Service createGenericResourceService(String name, String version, String resource, String referencePayload)
throws EntityAlreadyExistsException {
log.info("Creating a new Service '{}-{}' for generic resource {}", name, version, resource);
// Check if corresponding Service already exists.
... | @Test
void testCreateGenericResourceServiceFailure() throws EntityAlreadyExistsException {
assertThrows(EntityAlreadyExistsException.class, () -> {
try {
Service first = service.createGenericResourceService("Order Service", "1.0", "order", null);
} catch (Exception e) {
... |
@Override
protected Object getContent(ScmGetRequest request) {
GithubScm.validateUserHasPushPermission(request.getApiUrl(), request.getCredentials().getPassword().getPlainText(), request.getOwner(), request.getRepo());
String url = String.format("%s/repos/%s/%s/contents/%s",
request... | @Test
public void unauthorizedAccessToContentForOrgFolderGHEShouldFail() throws UnirestException, IOException {
User alice = User.get("alice");
alice.setFullName("Alice Cooper");
alice.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
String aliceCredentialId = createGit... |
static String generateClassName(final OpenAPI document) {
final Info info = document.getInfo();
if (info == null) {
return DEFAULT_CLASS_NAME;
}
final String title = info.getTitle();
if (title == null) {
return DEFAULT_CLASS_NAME;
}
final... | @Test
public void shouldUseDefaultClassNameIfInfoOrTitleIsNotPresent() {
final OpenAPI openapi = new OpenAPI();
assertThat(RestDslSourceCodeGenerator.generateClassName(openapi))
.isEqualTo(RestDslSourceCodeGenerator.DEFAULT_CLASS_NAME);
openapi.setInfo(new Info());
... |
@Override
public void handleReply(Reply reply) {
if (failure.get() != null) {
return;
}
if (containsFatalErrors(reply.getErrors())) {
failure.compareAndSet(null, new IOException(formatErrors(reply)));
return;
}
long now = System.currentTime... | @Test
public void requireThatDualPutXML2JsonFeederWorks() throws Throwable {
ByteArrayOutputStream dump = new ByteArrayOutputStream();
assertFeed(new FeederParams().setDumpStream(dump),
"<vespafeed>" +
" <document documenttype='simple' documentid='id:simple... |
@Override
public void registerInstance(String serviceName, String ip, int port) throws NacosException {
registerInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME);
} | @Test
void testRegisterInstance7() throws NacosException {
Throwable exception = assertThrows(NacosException.class, () -> {
//given
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
insta... |
public List<NamespaceBO> findNamespaceBOs(String appId, Env env, String clusterName, boolean includeDeletedItems) {
List<NamespaceDTO> namespaces = namespaceAPI.findNamespaceByCluster(appId, env, clusterName);
if (namespaces == null || namespaces.size() == 0) {
throw BadRequestException.namespaceNotExist... | @Test
public void testFindNamespace() {
AppNamespace applicationAppNamespace = mock(AppNamespace.class);
AppNamespace hermesAppNamespace = mock(AppNamespace.class);
NamespaceDTO application = new NamespaceDTO();
application.setId(1);
application.setClusterName(testClusterName);
application.s... |
public GrantDTO create(GrantDTO grantDTO, @Nullable User currentUser) {
return create(grantDTO, requireNonNull(currentUser, "currentUser cannot be null").getName());
} | @Test
public void createWithGrantDTOAndUserObject() {
final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
final GRN grantee = GRNTypes.USER.toGRN("jane");
final GRN target = GRNTypes.DASHBOARD.toGRN("54e3deadbeefdeadbeef0000");
final User user = mock(User.class);
wh... |
public CompletableFuture<Map<ExecutionAttemptID, Collection<ThreadInfoSample>>>
requestThreadInfoSamples(
Map<Long, ExecutionAttemptID> threads,
final ThreadInfoSamplesRequest requestParams) {
checkNotNull(threads, "threads must not be null");
checkNot... | @Test
void testShouldThrowExceptionIfTaskIsNotRunningBeforeSampling()
throws ExecutionException, InterruptedException {
Set<SampleableTask> tasks = new HashSet<>();
tasks.add(new NotRunningTask());
Map<Long, ExecutionAttemptID> threads = collectExecutionAttempts(tasks);
... |
public static Ip4Prefix valueOf(int address, int prefixLength) {
return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfShortArrayIPv4() {
Ip4Prefix ipPrefix;
byte[] value;
value = new byte[] {1, 2, 3};
ipPrefix = Ip4Prefix.valueOf(value, 24);
} |
public boolean matchesBeacon(Beacon beacon) {
// All identifiers must match, or the corresponding region identifier must be null.
for (int i = mIdentifiers.size(); --i >= 0; ) {
final Identifier identifier = mIdentifiers.get(i);
Identifier beaconIdentifier = null;
if ... | @Test
public void testBeaconMatchesRegionWithShorterIdentifierList() {
Beacon beacon = new AltBeacon.Builder().setId1("1").setId2("2").setId3("3").setRssi(4)
.setBeaconTypeCode(5).setTxPower(6).setBluetoothAddress("1:2:3:4:5:6").build();
Region region = new Region("myRegion", Collect... |
@Override
public void execute() throws MojoExecutionException {
if (pathToModelDir == null) {
throw new MojoExecutionException("pathToModelDir parameter must not be null");
}
// skip if input file does not exist
if (inputCamelSchemaFile == null || !inputCamelSchemaFile.e... | @Test
public void testExecuteCamelCoreIsNull() {
eipDocumentationEnricherMojo.camelCoreModelDir = null;
when(mockInputSchema.exists()).thenReturn(true);
when(mockInputSchema.isFile()).thenReturn(true);
try {
eipDocumentationEnricherMojo.execute();
fail("Expe... |
@VisibleForTesting
public Journal getJournal(String jid) {
return journalsById.get(jid);
} | @Test(timeout=100000)
public void testJournalDirPerNameSpace() {
Collection<String> nameServiceIds = DFSUtilClient.getNameServiceIds(conf);
setupStaticHostResolution(2, "journalnode");
for (String nsId : nameServiceIds) {
String jid = "test-journalid-" + nsId;
Journal nsJournal = jn.getJournal... |
public List<ProtobufSystemInfo.Section> load() {
return globalSections.stream()
.map(SystemInfoSection::toProtobuf)
.toList();
} | @Test
public void call_only_SystemInfoSection_that_inherit_Global() {
// two globals and one standard
SystemInfoSection[] sections = new SystemInfoSection[] {
new TestGlobalSystemInfoSection("foo"), new TestSystemInfoSection("bar"), new TestGlobalSystemInfoSection("baz")};
GlobalInfoLoader underTes... |
@Override
public List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames) throws Exception {
List<ZuulFilter<?, ?>> newFilters = new ArrayList<>();
for (String className : classNames) {
newFilters.add(putFilterForClassName(className));
}
return Collections.unmodif... | @Test
void testPutFiltersForClasses() throws Exception {
loader.putFiltersForClasses(new String[] {TestZuulFilter.class.getName()});
Collection<ZuulFilter<?, ?>> filters = registry.getAllFilters();
assertEquals(1, filters.size());
} |
public static String getProcessTriggerInstanceNodePath(final String instanceId, final String taskId) {
return String.join("/", "", ROOT_NODE, COMPUTE_NODE, SHOW_PROCESS_LIST_TRIGGER, String.join(":", instanceId, taskId));
} | @Test
void assertGetProcessTriggerInstanceIdNodePath() {
assertThat(ComputeNode.getProcessTriggerInstanceNodePath("foo_instance", "foo_process_id"),
is("/nodes/compute_nodes/show_process_list_trigger/foo_instance:foo_process_id"));
assertThat(ComputeNode.getProcessTriggerInstanceNode... |
public static String writeValueAsString(Object obj) {
try {
return getInstance().writeValueAsString(obj);
} catch (JsonGenerationException e) {
logger.error(e.getMessage(), e);
} catch (JsonMappingException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(... | @Test
public void shouldWriteValueAsString() {
//given
Map<String, String> map = new HashMap<>();
map.put("aaa", "111");
map.put("bbb", "222");
//when
String json = writeValueAsString(map);
//then
assertEquals(json, "{\"aaa\":\"111\",\"bbb\":\"222\"}... |
public static List<Validation> computeFlagsFromCSVString(String csvString,
Log log) {
List<Validation> flags = new ArrayList<>();
boolean resetFlag = false;
for (String p : csvString.split(",")) {
try {
flag... | @Test
public void testFlagsUnknown() {
List<DMNValidator.Validation> result = DMNValidationHelper.computeFlagsFromCSVString("VALIDATE_SCHEMA,boh", log);
assertThat(result).isNotNull()
.hasSize(0);
} |
public static MessageHeaders createAfnemersberichtAanDGLHeaders(Map<String, Object> additionalHeaders) {
validateHeaders(additionalHeaders);
Map<String, Object> headersMap = createBasicHeaderMap();
headersMap.put(nl.logius.digid.digilevering.lib.model.Headers.X_AUX_ACTION, "BRPAfnemersberichtAa... | @Test
public void testAfnemersBerichtAanDGLHeaders() {
MessageHeaders afnemersberichtAanDGLHeaders = HeaderUtil.createAfnemersberichtAanDGLHeaders(validHeaders());
assertThat(afnemersberichtAanDGLHeaders.get(Headers.X_AUX_PRODUCTION), is("Test"));
assertThat(afnemersberichtAanDGLHeaders.get... |
public static boolean isUri(String potentialUri) {
if (StringUtils.isBlank(potentialUri)) {
return false;
}
try {
URI uri = new URI(potentialUri);
return uri.getScheme() != null && uri.getHost() != null;
} catch (URISyntaxException e) {
re... | @Test public void
returns_false_when_uri_is_blank() {
assertThat(UriValidator.isUri(" "), is(false));
} |
ContentElement(PayloadElement payload, List<AffixElement> affixElements) {
this.payload = payload;
this.affixElements = Collections.unmodifiableList(affixElements);
} | @Test
public void testContentElement() throws ParseException {
Message.Body body = new Message.Body("en", "My battery is low and it’s getting dark"); // :'(
ContentElement contentElement = ContentElement.builder()
.addPayloadItem(body)
.setFrom(AffixElementsTest.JID_... |
public static ClusterHealthStatus isHealth(List<RemoteInstance> remoteInstances) {
if (CollectionUtils.isEmpty(remoteInstances)) {
return ClusterHealthStatus.unHealth("can't get the instance list");
}
if (!CoreModuleConfig.Role.Receiver.equals(ROLE)) {
List<RemoteInstance... | @Test
public void unHealthWithIllegalNodeInstance() {
List<RemoteInstance> remoteInstances = new ArrayList<>();
remoteInstances.add(new RemoteInstance(new Address("192.168.0.1", 8892, true)));
remoteInstances.add(new RemoteInstance(new Address("127.0.0.1", 8892, true)));
ClusterHealt... |
public static <T extends Comparable<? super T>> T max(Collection<T> coll) {
return isEmpty(coll) ? null : Collections.max(coll);
} | @Test
public void minNullTest() {
assertNull(CollUtil.max(null));
} |
public static Builder builder() {
return new Builder(new HashSet<>());
} | @Test
public void shouldImplementEqualsAndHashCode() {
new EqualsTester()
.addEqualityGroup(
RequiredColumns.builder().add(EXP0).build(),
RequiredColumns.builder().addAll(ImmutableSet.of(COL1_REF, COL2_REF, COL3_REF)).build()
)
.addEqualityGroup(
Require... |
public Column getColumn(String value) {
Matcher m = PATTERN.matcher(value);
if (!m.matches()) {
throw new IllegalArgumentException("value " + value + " is not a valid column definition");
}
String name = m.group(1);
String type = m.group(6);
type = type == nu... | @Test
public void testGetArrayColumnSimple() {
ColumnFactory f = new ColumnFactory();
Column column = f.getColumn("column[]");
assertThat(column instanceof ArrayColumn).isTrue();
assertThat(column.getName()).isEqualTo("column");
assertThat(column.getCellType()).isEqualTo("Str... |
@Nullable static String method(String fullMethodName) {
int index = fullMethodName.lastIndexOf('/');
if (index == -1 || index == 0) return null;
return fullMethodName.substring(index + 1);
} | @Test void method_malformed() {
assertThat(GrpcParser.method("/")).isNull();
} |
public static HazelcastInstance getOrCreateHazelcastInstance() {
return HazelcastInstanceFactory.getOrCreateHazelcastInstance(null);
} | @Test
public void getOrCreateDefaultHazelcastInstance() {
String hzConfigProperty = System.getProperty(HAZELCAST_CONFIG);
try {
System.setProperty(HAZELCAST_CONFIG, "classpath:test-hazelcast-jcache.xml");
HazelcastInstance hz1 = Hazelcast.getOrCreateHazelcastInstance();
... |
@Override
public TransferAction action(final Session<?> source, final Session<?> destination, boolean resumeRequested, boolean reloadRequested,
final TransferPrompt prompt, final ListProgressListener listener) throws BackgroundException {
if(log.isDebugEnabled()) {
... | @Test
public void testActionPromptCancel() throws Exception {
final Path test = new Path("t", EnumSet.of(Path.Type.file));
final Host target = new Host(new TestProtocol(), "t");
CopyTransfer t = new CopyTransfer(target,
target,
Collections.singletonMap(test, n... |
@Override
public Graph<Entity> resolveForInstallation(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Entity> entities) {
if (entity instanceof EntityV1) {
return resolveF... | @Test
@MongoDBFixtures("InputFacadeTest.json")
public void resolveForInstallationGrokPattern() throws NotFoundException {
final Input input = inputService.find("5ae2ebbeef27464477f0fd8b");
final InputWithExtractors inputWithExtractors = InputWithExtractors.create(input, inputService.getExtractor... |
@Override
public CompletableFuture<List<Long>> getSplitBoundary(BundleSplitOption bundleSplitOption) {
NamespaceService service = bundleSplitOption.getService();
NamespaceBundle bundle = bundleSplitOption.getBundle();
List<Long> positions = bundleSplitOption.getPositions();
if (posit... | @SuppressWarnings("UnstableApiUsage")
@Test
public void testAlgorithmReturnCorrectResult() {
// -- algorithm
SpecifiedPositionsBundleSplitAlgorithm algorithm = new SpecifiedPositionsBundleSplitAlgorithm();
// -- calculate the mock result
NamespaceService mockNamespaceService = mo... |
public String hashDirectoryId(final String cleartextDirectoryId) {
if(!directoryIdCache.contains(cleartextDirectoryId)) {
directoryIdCache.put(cleartextDirectoryId, impl.hashDirectoryId(cleartextDirectoryId));
}
return directoryIdCache.get(cleartextDirectoryId);
} | @Test
public void TestHashDirectoryId() {
final FileNameCryptor mock = mock(FileNameCryptor.class);
final CryptorCache cryptor = new CryptorCache(mock);
when(mock.hashDirectoryId(anyString())).thenReturn("hashed");
assertEquals("hashed", cryptor.hashDirectoryId("id"));
assert... |
@Override
public String execute(CommandContext commandContext) throws NoSuchCommandException, PermissionDenyException {
String remoteAddress = Optional.ofNullable(commandContext.getRemote())
.map(Channel::remoteAddress)
.map(Objects::toString)
.orElse("unknown... | @Test
void shouldNotThrowPermissionDenyException_GivenPermissionConfigAndMatchDefaultPUBLICCmdPermissionLevel() {
DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel());
final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[] ... |
public MapConfig setNearCacheConfig(NearCacheConfig nearCacheConfig) {
this.nearCacheConfig = nearCacheConfig;
return this;
} | @Test
public void testSetNearCacheConfig() {
NearCacheConfig nearCacheConfig = new NearCacheConfig();
assertEquals(nearCacheConfig, new MapConfig().setNearCacheConfig(nearCacheConfig).getNearCacheConfig());
} |
public static Map<String, Object> parseQuery(String uri) throws URISyntaxException {
return parseQuery(uri, false);
} | @Test
public void testParseQueryCurly() throws Exception {
Map<String, Object> map = URISupport.parseQuery("password=RAW{++?w0rd}&serviceName=somechat");
assertEquals(2, map.size());
assertEquals("RAW{++?w0rd}", map.get("password"));
assertEquals("somechat", map.get("serviceName"));
... |
public static Field p(String fieldName) {
return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName);
} | @Test
void set_group_syntax_string_directly() {
/*
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) ea... |
@Override
public InputStream getInputStream() {
return new RedissonInputStream();
} | @Test
public void testReadArray() throws IOException {
RBinaryStream stream = redisson.getBinaryStream("test");
byte[] value = {1, 2, 3, 4, 5, 6};
stream.set(value);
InputStream s = stream.getInputStream();
byte[] b = new byte[6];
assertThat(s.read(b)).isEqua... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.