focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String utf8Str(Object obj) {
return str(obj, CharsetUtil.CHARSET_UTF_8);
} | @Test
public void wrapAllTest() {
String[] strings = StrUtil.wrapAll("`", "`", StrUtil.splitToArray("1,2,3,4", ','));
assertEquals("[`1`, `2`, `3`, `4`]", StrUtil.utf8Str(strings));
strings = StrUtil.wrapAllWithPair("`", StrUtil.splitToArray("1,2,3,4", ','));
assertEquals("[`1`, `2`, `3`, `4`]", StrUtil.utf8S... |
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 testLiteralNeverIndexedWithLargeValue() throws Http2Exception {
// Ignore header that exceeds max header size
final StringBuilder sb = new StringBuilder();
sb.append("1004");
sb.append(hex("name"));
sb.append("7F813F");
for (int i = 0; i < 8192; i++)... |
public static void main(String[] args) {
var mammoth = new Mammoth();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
} | @Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
public static List<Converter> getConverters() {
return Arrays.asList(CONVERTERS);
} | @Test
public void testSerialization() {
InternalSerializationService ss = new DefaultSerializationServiceBuilder().build();
for (Converter converter : Converters.getConverters()) {
assertSame(converter, ss.toObject(ss.toData(converter)));
}
ss.dispose();
} |
public List<PrometheusQueryResult> queryMetric(String queryString,
long startTimeMs,
long endTimeMs) throws IOException {
URI queryUri = URI.create(_prometheusEndpoint.toURI() + QUERY_RANGE_API_PATH);
H... | @Test
public void testSuccessfulResponseDeserialized() throws Exception {
this.serverBootstrap.registerHandler(PrometheusAdapter.QUERY_RANGE_API_PATH, new HttpRequestHandler() {
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) {
... |
@Override
public Region createRegion(RegionId regionId, String name, Region.Type type,
List<Set<NodeId>> masterNodeIds) {
checkNotNull(regionId, REGION_ID_NULL);
checkNotNull(name, NAME_NULL);
checkNotNull(type, REGION_TYPE_NULL);
return store.createRe... | @Test(expected = IllegalArgumentException.class)
public void duplicateCreate() {
service.createRegion(RID1, "R1", METRO, MASTERS);
service.createRegion(RID1, "R2", CAMPUS, MASTERS);
} |
public static void delete(Collection<ResourceId> resourceIds, MoveOptions... moveOptions)
throws IOException {
if (resourceIds.isEmpty()) {
// Short-circuit.
return;
}
Collection<ResourceId> resourceIdsToDelete;
if (Sets.newHashSet(moveOptions)
.contains(MoveOptions.StandardMo... | @Test
public void testDeleteIgnoreMissingFiles() throws Exception {
Path existingPath = temporaryFolder.newFile().toPath();
Path nonExistentPath = existingPath.resolveSibling("non-existent");
createFileWithContent(existingPath, "content1");
FileSystems.delete(
toResourceIds(ImmutableList.of(... |
public static SqlArgument of(final SqlType type) {
return new SqlArgument(type, null, null);
} | @SuppressWarnings("UnstableApiUsage")
@Test
public void shouldImplementHashCodeAndEqualsProperly() {
new EqualsTester()
.addEqualityGroup(SqlArgument.of(SqlArray.of(SqlTypes.STRING)), SqlArgument.of(SqlArray.of(SqlTypes.STRING)))
.addEqualityGroup(
SqlArgument.of(SqlLambdaResolved.of... |
@Override
public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
try {
final BrickApiClient client = new BrickApiClient(session);
if(status.isExists()) {
... | @Test
public void testCopyDirectory() throws Exception {
final Path directory = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
final String name = new AlphanumericRandomStringService().random();
final P... |
public static void deleteDirectory(File directory) throws IOException {
requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL);
if (!directory.exists()) {
return;
}
Path path = directory.toPath();
if (Files.isSymbolicLink(path)) {
throw new IOException(format("Directory '%s' is a symboli... | @Test
public void deleteDirectory_throws_NPE_if_argument_is_null() throws IOException {
expectDirectoryCanNotBeNullNPE(() -> FileUtils2.deleteDirectory(null));
} |
public int getSinkDefaultDOP() {
// load includes query engine execution and storage engine execution
// so we can't let query engine use up resources
// At the same time, the improvement of performance and concurrency is not linear
// but the memory usage increases linearly, so we contr... | @Test
public void getSinkDefaultDOP() {
BackendResourceStat stat = BackendResourceStat.getInstance();
stat.setNumHardwareCoresOfBe(0L, 23);
stat.setNumHardwareCoresOfBe(1L, 23);
assertThat(stat.getAvgNumHardwareCoresOfBe()).isEqualTo(23);
assertThat(stat.getSinkDefaultDOP())... |
@Override
@CheckForNull
public ScannerReport.Changesets readChangesets(int componentRef) {
ensureInitialized();
return delegate.readChangesets(componentRef);
} | @Test
public void readChangesets_returns_null_if_no_changeset() {
assertThat(underTest.readChangesets(COMPONENT_REF)).isNull();
} |
@Override
public void run() {
if (processor != null) {
processor.execute();
} else {
if (!beforeHook()) {
logger.info("before-feature hook returned [false], aborting: {}", this);
} else {
scenarios.forEachRemaining(this::processScen... | @Test
void testCallArgNull() {
run("call-arg-null.feature");
} |
public StreamsMetadata getLocalMetadata() {
return localMetadata.get();
} | @Test
public void shouldGetLocalMetadataWithRightActiveStandbyInfo() {
assertEquals(hostOne, metadataState.getLocalMetadata().hostInfo());
assertEquals(hostToActivePartitions.get(hostOne), metadataState.getLocalMetadata().topicPartitions());
assertEquals(hostToStandbyPartitions.get(hostOne),... |
@ConstantFunction(name = "replace", argTypes = {VARCHAR, VARCHAR, VARCHAR}, returnType = VARCHAR)
public static ConstantOperator replace(ConstantOperator value, ConstantOperator target,
ConstantOperator replacement) {
return ConstantOperator.createVarchar(value.get... | @Test
public void testReplace() {
assertEquals("20240806", ScalarOperatorFunctions.replace(
new ConstantOperator("2024-08-06", Type.VARCHAR),
new ConstantOperator("-", Type.VARCHAR),
new ConstantOperator("", Type.VARCHAR)
).getVarchar());
} |
@Override
public synchronized void
registerProviderService(NetworkId networkId,
VirtualProviderService virtualProviderService) {
Set<VirtualProviderService> services =
servicesByNetwork.computeIfAbsent(networkId, k -> new HashSet<>());
services.add(vi... | @Test
public void registerProviderServiceTest() {
TestProvider1 provider1 = new TestProvider1();
virtualProviderManager.registerProvider(provider1);
TestProviderService1 providerService1 = new TestProviderService1();
virtualProviderManager.registerProviderService(NETWORK_ID1, provid... |
public static IntrinsicMapTaskExecutor withSharedCounterSet(
List<Operation> operations,
CounterSet counters,
ExecutionStateTracker executionStateTracker) {
return new IntrinsicMapTaskExecutor(operations, counters, executionStateTracker);
} | @Test
public void testGetProgressAndRequestSplit() throws Exception {
TestOutputReceiver receiver =
new TestOutputReceiver(counterSet, NameContextsForTests.nameContextForTest());
TestReadOperation operation = new TestReadOperation(receiver, createContext("ReadOperation"));
ExecutionStateTracker st... |
public static String substVars(String val, PropertyContainer pc1) {
return substVars(val, pc1, null);
} | @Test(timeout = 1000)
public void stubstVarsShouldNotGoIntoInfiniteLoop() {
context.putProperty("v1", "if");
context.putProperty("v2", "${v3}");
context.putProperty("v3", "${v4}");
context.putProperty("v4", "${v2}c");
expectedException.expect(Exception.class);
OptionHelper.substVars(text, con... |
public Plan validateReservationSubmissionRequest(
ReservationSystem reservationSystem, ReservationSubmissionRequest request,
ReservationId reservationId) throws YarnException {
String message;
if (reservationId == null) {
message = "Reservation id cannot be null. Please try again specifying "
... | @Test
public void testSubmitReservationExceedsGangSize() {
ReservationSubmissionRequest request =
createSimpleReservationSubmissionRequest(1, 1, 1, 5, 4);
Resource resource = Resource.newInstance(512, 1);
when(plan.getTotalCapacity()).thenReturn(resource);
Plan plan = null;
try {
pla... |
public void unzip(String from, boolean remove) throws IOException {
String to = Helper.pruneFileEnd(from);
unzip(from, to, remove);
} | @Test
public void testUnzip() throws Exception {
String to = "./target/tmp/test";
Helper.removeDir(new File(to));
new Unzipper().unzip("./src/test/resources/com/graphhopper/util/test.zip", to, false);
assertTrue(new File("./target/tmp/test/file2 bäh").exists());
assertTrue(ne... |
public static TemplateEngine createEngine() {
return TemplateFactory.create();
} | @Test
public void thymeleafEngineTest() {
// 字符串模板
TemplateEngine engine = TemplateUtil.createEngine(
new TemplateConfig("templates").setCustomEngine(ThymeleafEngine.class));
Template template = engine.getTemplate("<h3 th:text=\"${message}\"></h3>");
String result = template.render(Dict.create().set("messa... |
@Override
public void readOne(TProtocol in, TProtocol out) throws TException {
readOneStruct(in, out);
} | @Test
public void testUnionWithStructWithUnknownField() throws Exception {
CountingErrorHandler countingHandler = new CountingErrorHandler();
BufferedProtocolReadToWrite p =
new BufferedProtocolReadToWrite(ThriftSchemaConverter.toStructType(UnionV3.class), countingHandler);
ByteArrayOutputStream i... |
@Override
@NonNull
public Mono<ServerResponse> handle(@NonNull ServerRequest request) {
return request.bodyToMono(Unstructured.class)
.switchIfEmpty(Mono.error(() -> new ExtensionConvertException(
"Cannot read body to " + scheme.groupVersionKind())))
.flatMap(clie... | @Test
void shouldReturnErrorWhenNoBodyProvided() {
var serverRequest = MockServerRequest.builder()
.body(Mono.empty());
var scheme = Scheme.buildFromType(FakeExtension.class);
var getHandler = new ExtensionCreateHandler(scheme, client);
var responseMono = getHandler.handl... |
public PDFMergerUtility()
{
sources = new ArrayList<>();
} | @Test
void testPDFMergerUtility() throws IOException
{
checkMergeIdentical("PDFBox.GlobalResourceMergeTest.Doc01.decoded.pdf",
"PDFBox.GlobalResourceMergeTest.Doc02.decoded.pdf",
"GlobalResourceMergeTestResult1.pdf",
IOUtils.createMemoryOnlyStreamCache())... |
public void createPipe(CreatePipeStmt stmt) throws DdlException {
try {
lock.writeLock().lock();
Pair<Long, String> dbIdAndName = resolvePipeNameUnlock(stmt.getPipeName());
boolean existed = nameToId.containsKey(dbIdAndName);
if (existed) {
if (!st... | @Test
public void executeAutoIngest() throws Exception {
mockRepoExecutor();
mockTaskExecution(Constants.TaskRunState.SUCCESS);
// auto_ingest=false
String pipeP3 = "p3";
String p3Sql = "create pipe p3 properties('auto_ingest'='false') as " +
"insert into tbl1... |
@PostConstruct
public void applyPluginMetadata() {
if (taskPreference() != null) {
for (ConfigurationProperty configurationProperty : configuration) {
if (isValidPluginConfiguration(configurationProperty.getConfigKeyName())) {
Boolean isSecure = pluginConfigur... | @Test
public void postConstructShouldDoNothingForPluggableTaskWithoutCorrespondingPlugin() throws Exception {
ConfigurationProperty configurationProperty = ConfigurationPropertyMother.create("KEY1");
Configuration configuration = new Configuration(configurationProperty);
PluggableTask task ... |
public Status status() { return status; } | @Test
public void test_autoscaling_limits_when_min_equals_max() {
ClusterResources min = new ClusterResources( 2, 1, new NodeResources(1, 1, 1, 1));
var fixture = DynamicProvisioningTester.fixture().awsProdSetup(true).capacity(Capacity.from(min, min)).build();
fixture.tester().clock().advan... |
@Override
protected void rename(
List<HadoopResourceId> srcResourceIds,
List<HadoopResourceId> destResourceIds,
MoveOptions... moveOptions)
throws IOException {
if (moveOptions.length > 0) {
throw new UnsupportedOperationException("Support for move options is not yet implemented.");
... | @Test(expected = FileNotFoundException.class)
public void testRenameRetryScenario() throws Exception {
testRename();
// retry the knowing that sources are already moved to destination
fileSystem.rename(
ImmutableList.of(testPath("testFileA"), testPath("testFileB")),
ImmutableList.of(testPa... |
public static KeyValueIterator<Windowed<GenericKey>, GenericRow> fetch(
final ReadOnlySessionStore<GenericKey, GenericRow> store,
final GenericKey key
) {
Objects.requireNonNull(key, "key can't be null");
final List<ReadOnlySessionStore<GenericKey, GenericRow>> stores = getStores(store);
final... | @Test
public void shouldCallUnderlyingStoreSingleKey() throws IllegalAccessException {
when(provider.stores(any(), any())).thenReturn(ImmutableList.of(meteredSessionStore));
SERDES_FIELD.set(meteredSessionStore, serdes);
when(serdes.rawKey(any())).thenReturn(BYTES);
when(meteredSessionStore.wrapped())... |
@Override
public RouteContext createRouteContext(final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final SingleRule rule,
final ConfigurationProperties props, final ConnectionContext connectionContext) {
... | @Test
void assertCreateRouteContextWithSingleDataSource() throws SQLException {
SingleRule rule = new SingleRule(new SingleRuleConfiguration(),
DefaultDatabase.LOGIC_NAME, new H2DatabaseType(), Collections.singletonMap("foo_ds", new MockedDataSource(mockConnection())), Collections.emptyList(... |
@Override
public boolean isDataDriven( RestMeta meta ) {
// this step is data driven no matter what.
// either the url, method, body, headers, and/or parameters come from the previous step
return true;
} | @Test
public void testIsDataDriven() throws Exception {
assertTrue( consumer.isDataDriven( meta ) );
} |
@Override
public void connect(final SocketAddress endpoint, final int timeout) throws IOException {
final CountDownLatch signal = new CountDownLatch(1);
final Thread t = threadFactory.newThread(new Runnable() {
@Override
public void run() {
try {
... | @Test(expected = SocketTimeoutException.class)
public void testConnect() throws Exception {
new UDTSocket().connect(new InetSocketAddress("localhost", 11111), 1000);
} |
@Bean
public PluginDataHandler dividePluginDataHandler() {
return new DividePluginDataHandler();
} | @Test
public void testDividePluginDataHandler() {
applicationContextRunner.run(context -> {
PluginDataHandler handler = context.getBean("dividePluginDataHandler", PluginDataHandler.class);
assertNotNull(handler);
}
);
} |
public static String escapeHtml4(CharSequence html) {
Html4Escape escape = new Html4Escape();
return escape.replace(html).toString();
} | @Test
public void escapeHtml4Test() {
String escapeHtml4 = EscapeUtil.escapeHtml4("<a>你好</a>");
assertEquals("<a>你好</a>", escapeHtml4);
String result = EscapeUtil.unescapeHtml4("振荡器类型");
assertEquals("振荡器类型", result);
String escape = EscapeUtil.escapeHtml4("*@... |
void addPeerClusterWatches(@Nonnull Set<String> newPeerClusters, @Nonnull FailoutConfig failoutConfig)
{
final Set<String> existingPeerClusters = _peerWatches.keySet();
if (newPeerClusters.isEmpty())
{
removePeerClusterWatches();
return;
}
final Set<String> peerClustersToAdd = new Ha... | @Test
public void testAddPeerClusterWatchesWithPeerClusterAdded()
{
_manager.addPeerClusterWatches(new HashSet<>(Arrays.asList(PEER_CLUSTER_NAME1)), mock(FailoutConfig.class));
_manager.addPeerClusterWatches(new HashSet<>(Arrays.asList(PEER_CLUSTER_NAME1, PEER_CLUSTER_NAME2)), mock(FailoutConfig.class));
... |
public static boolean isAnyNullOrEmptyAfterTrim(String... values) {
if (values == null) {
return false;
}
return Arrays.stream(values).anyMatch(s -> !isNullOrEmptyAfterTrim(s));
} | @Test
void isAnyFilledTest() {
assertTrue(isAnyNullOrEmptyAfterTrim("test-string-1", "test-string-2"));
assertTrue(isAnyNullOrEmptyAfterTrim("test-string-1", ""));
assertFalse(isAnyNullOrEmptyAfterTrim("", "", null));
} |
public void addFilter(Filter filter) {
filterChain.addFilter(filter);
} | @Test
void testAddFilter() {
final var target = mock(Target.class);
final var filterManager = new FilterManager();
verifyNoMoreInteractions(target);
final var filter = mock(Filter.class);
when(filter.execute(any(Order.class))).thenReturn("filter");
filterManager.addFilter(filter);
fina... |
@Override
public Set<String> get(URL url) {
String serviceInterface = url.getServiceInterface();
String registryCluster = getRegistryCluster(url);
MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryCluster);
if (metadataReport == null) {
retu... | @Test
void testGet() {
Set<String> set = new HashSet<>();
set.add("app1");
MetadataReportInstance reportInstance = mock(MetadataReportInstance.class);
Mockito.when(reportInstance.getMetadataReport(any())).thenReturn(metadataReport);
when(metadataReport.getServiceAppMapping(a... |
@Override
public Validation validate(Validation val) {
if (StringUtils.isBlank(systemEnvironment.getPropertyImpl("jetty.home"))) {
systemEnvironment.setProperty("jetty.home", systemEnvironment.getPropertyImpl("user.dir"));
}
systemEnvironment.setProperty("jetty.base", systemEnvir... | @Test
public void shouldRecreateWorkDirIfItExists() throws IOException {
File oldWorkDir = new File(homeDir, "work");
oldWorkDir.mkdir();
new File(oldWorkDir, "junk.txt").createNewFile();
when(systemEnvironment.getPropertyImpl("jetty.home")).thenReturn(homeDir.getAbsolutePath());
... |
@Override
public void setGPSLocation(double latitude, double longitude) {
} | @Test
public void setGPSLocation() {
List<SensorsDataAPI.AutoTrackEventType> types = new ArrayList<>();
types.add(SensorsDataAPI.AutoTrackEventType.APP_START);
types.add(SensorsDataAPI.AutoTrackEventType.APP_END);
mSensorsAPI.setGPSLocation(1000.0, 45.5, "GPS");
} |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testBraceletOfClayBreak()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", BREAK_BRACELET_OF_CLAY, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_BRACELET_OF_CLA... |
public Arguments parse(String[] args) {
JCommander jCommander = new JCommander(this);
jCommander.setProgramName("jsonschema2pojo");
try {
jCommander.parse(args);
if (this.showHelp) {
jCommander.usage();
exit(EXIT_OKAY);
} els... | @Test
public void missingArgsCausesHelp() {
ArgsForTest args = (ArgsForTest) new ArgsForTest().parse(new String[] {});
assertThat(args.status, is(1));
assertThat(new String(systemErrCapture.toByteArray(), StandardCharsets.UTF_8), is(containsString("--target")));
assertThat(new Strin... |
public static boolean canImplicitlyCast(final SqlDecimal s1, final SqlDecimal s2) {
return s1.getScale() <= s2.getScale()
&& (s1.getPrecision() - s1.getScale()) <= (s2.getPrecision() - s2.getScale());
} | @Test
public void shouldAllowImplicitlyCastOnHigherPrecisionAndScale() {
// Given:
final SqlDecimal s1 = SqlTypes.decimal(5, 2);
final SqlDecimal s2 = SqlTypes.decimal(6, 3);
// When:
final boolean compatible = DecimalUtil.canImplicitlyCast(s1, s2);
// Then:
assertThat(compatible, is(tru... |
@Override
public MetadataReport getMetadataReport(URL url) {
url = url.setPath(MetadataReport.class.getName()).removeParameters(EXPORT_KEY, REFER_KEY);
String key = url.toServiceString(NAMESPACE_KEY);
MetadataReport metadataReport = serviceStoreMap.get(key);
if (metadataReport != nu... | @Test
void testGetForDiffGroup() {
URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=aaa");
URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
... |
private boolean isEmpty(ConsumerRecords<K, V> records) {
return records == null || records.isEmpty();
} | @Test
public void when_partitionAddedWhileJobDown_then_consumedFromBeginning() throws Exception {
String sinkListName = randomName();
IList<Entry<Integer, String>> sinkList = instance().getList(sinkListName);
Pipeline p = Pipeline.create();
Properties properties = properties();
... |
public void putAll(Headers headers) {
for (int i = 0; i < headers.size(); i++) {
addNormal(headers.originalName(i), headers.name(i), headers.value(i));
}
} | @Test
void putAll() {
Headers headers = new Headers();
headers.add("Via", "duct");
headers.add("Cookie", "this=that");
headers.add("Cookie", "frizzle=frazzle");
Headers other = new Headers();
other.add("cookie", "a=b");
other.add("via", "com");
heade... |
public static LocalDateTime beginOfDay(LocalDateTime time) {
return time.with(LocalTime.MIN);
} | @Test
public void beginOfDayTest() {
final LocalDateTime localDateTime = LocalDateTimeUtil.parse("2020-01-23T12:23:56");
final LocalDateTime beginOfDay = LocalDateTimeUtil.beginOfDay(localDateTime);
assertEquals("2020-01-23T00:00", beginOfDay.toString());
} |
@Override
public Response replaceLabelsOnNodes(NodeToLabelsEntryList newNodeToLabels,
HttpServletRequest hsr) throws IOException {
// Step1. Check the parameters to ensure that the parameters are not empty.
if (newNodeToLabels == null) {
routerMetrics.incrReplaceLabelsOnNodesFailedRetrieved();
... | @Test
public void testReplaceLabelsOnNodes() throws Exception {
// subCluster0 -> node0:0 -> label:NodeLabel0
// subCluster1 -> node1:1 -> label:NodeLabel1
// subCluster2 -> node2:2 -> label:NodeLabel2
// subCluster3 -> node3:3 -> label:NodeLabel3
NodeToLabelsEntryList nodeToLabelsEntryList = new ... |
@Override
public DirectPipelineResult run(Pipeline pipeline) {
try {
options =
MAPPER
.readValue(MAPPER.writeValueAsBytes(options), PipelineOptions.class)
.as(DirectOptions.class);
} catch (IOException e) {
throw new IllegalArgumentException(
"Pipeli... | @Test
public void testUnencodableOutputFromBoundedRead() throws Exception {
Pipeline p = getPipeline();
p.apply(GenerateSequence.from(0).to(10)).setCoder(new LongNoDecodeCoder());
thrown.expectCause(isA(CoderException.class));
thrown.expectMessage("Cannot decode a long");
p.run();
} |
static void writeImageJson(Optional<Path> imageJsonOutputPath, JibContainer jibContainer)
throws IOException {
if (imageJsonOutputPath.isPresent()) {
ImageMetadataOutput metadataOutput = ImageMetadataOutput.fromJibContainer(jibContainer);
Files.write(
imageJsonOutputPath.get(), metadataO... | @Test
public void testWriteImageJson()
throws InvalidImageReferenceException, IOException, DigestException {
String imageId = "sha256:61bb3ec31a47cb730eb58a38bbfa813761a51dca69d10e39c24c3d00a7b2c7a9";
String digest = "sha256:3f1be7e19129edb202c071a659a4db35280ab2bb1a16f223bfd5d1948657b6fc";
when(moc... |
static SVNClientManager newSvnClientManager(SvnConfiguration configuration) {
ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
final char[] passwordValue = getCharsOrNull(configuration.password());
final char[] passPhraseValue = getCharsOrNull(configuration.passPhrase());
ISVNAuthenticationMa... | @Test
public void newSvnClientManager_whenPasswordConfigured_shouldNotReturnNull() {
when(config.password()).thenReturn("password");
when(config.passPhrase()).thenReturn("passPhrase");
assertThat(newSvnClientManager(config)).isNotNull();
} |
boolean sendRecords() {
int processed = 0;
recordBatch(toSend.size());
final SourceRecordWriteCounter counter =
toSend.isEmpty() ? null : new SourceRecordWriteCounter(toSend.size(), sourceTaskMetricsGroup);
for (final SourceRecord preTransformRecord : toSend) {
... | @Test
public void testSendRecordsTopicDescribeRetriesMidway() {
createWorkerTask();
// Differentiate only by Kafka partition so we can reuse conversion expectations
SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD);
SourceRe... |
static NavigableMap<Integer, Long> buildFilteredLeaderEpochMap(NavigableMap<Integer, Long> leaderEpochs) {
List<Integer> epochsWithNoMessages = new ArrayList<>();
Map.Entry<Integer, Long> previousEpochAndOffset = null;
for (Map.Entry<Integer, Long> currentEpochAndOffset : leaderEpochs.entrySet()... | @Test
public void testBuildFilteredLeaderEpochMap() {
TreeMap<Integer, Long> leaderEpochToStartOffset = new TreeMap<>();
leaderEpochToStartOffset.put(0, 0L);
leaderEpochToStartOffset.put(1, 0L);
leaderEpochToStartOffset.put(2, 0L);
leaderEpochToStartOffset.put(3, 30L);
... |
public static String getTypeName(final int type) {
switch (type) {
case START_EVENT_V3:
return "Start_v3";
case STOP_EVENT:
return "Stop";
case QUERY_EVENT:
return "Query";
case ROTATE_EVENT:
return "... | @Test
public void getTypeNameInputPositiveOutputNotNull3() {
// Arrange
final int type = 39;
// Act
final String actual = LogEvent.getTypeName(type);
// Assert result
Assert.assertEquals("Update_rows_partial", actual);
} |
static EndTransactionMarker deserializeValue(ControlRecordType type, ByteBuffer value) {
ensureTransactionMarkerControlType(type);
if (value.remaining() < CURRENT_END_TXN_MARKER_VALUE_SIZE)
throw new InvalidRecordException("Invalid value size found for end transaction marker. Must have " +
... | @Test
public void testIllegalNegativeVersion() {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putShort((short) -1);
buffer.flip();
assertThrows(InvalidRecordException.class, () -> EndTransactionMarker.deserializeValue(ControlRecordType.ABORT, buffer));
} |
@Override
public String toString() {
return (value == null) ? "(null)" : '"' + getValue() + '"';
} | @Test
void testUnresolvedReference() {
var reference = ModelReference.unresolved(Optional.of("myModelId"),
Optional.of(new UrlReference("https://host:my/path")),
Optional.of(new FileReference("foo.txt")));
... |
public void reset() {
this.count = 0;
this.msgRateIn = 0;
this.msgThroughputIn = 0;
this.msgRateOut = 0;
this.msgThroughputOut = 0;
this.averageMsgSize = 0;
this.storageSize = 0;
this.backlogSize = 0;
this.bytesInCounter = 0;
this.msgInCoun... | @Test
public void testReset() {
TopicStatsImpl stats = new TopicStatsImpl();
stats.earliestMsgPublishTimeInBacklogs = 1L;
stats.reset();
assertEquals(stats.earliestMsgPublishTimeInBacklogs, 0L);
} |
@Nullable
public static ValueReference of(Object value) {
if (value instanceof Boolean) {
return of((Boolean) value);
} else if (value instanceof Double) {
return of((Double) value);
} else if (value instanceof Float) {
return of((Float) value);
} ... | @Test
public void deserializeEnum() throws IOException {
assertThat(objectMapper.readValue("{\"@type\":\"string\",\"@value\":\"A\"}", ValueReference.class)).isEqualTo(ValueReference.of(TestEnum.A));
assertThat(objectMapper.readValue("{\"@type\":\"string\",\"@value\":\"B\"}", ValueReference.class)).i... |
@Override
@CheckForNull
public EmailMessage format(Notification notification) {
if (!BuiltInQPChangeNotification.TYPE.equals(notification.getType())) {
return null;
}
BuiltInQPChangeNotificationBuilder profilesNotification = parse(notification);
StringBuilder message = new StringBuilder("The ... | @Test
public void notification_contains_count_of_updated_rules() {
String profileName = newProfileName();
String languageKey = newLanguageKey();
String languageName = newLanguageName();
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile... |
@ScalarOperator(CAST)
@SqlType(StandardTypes.DOUBLE)
public static double castToDouble(@SqlType(StandardTypes.SMALLINT) long value)
{
return value;
} | @Test
public void testCastToDouble()
{
assertFunction("cast(SMALLINT'37' as double)", DOUBLE, 37.0);
assertFunction("cast(SMALLINT'17' as double)", DOUBLE, 17.0);
} |
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
for (final GarbageCollectorMXBean gc : garbageCollectors) {
final String name = WHITESPACE.matcher(gc.getName()).replaceAll("-");
gauges.put(name(name, "count"), (Gauge<Lon... | @Test
public void hasGaugesForGcCountsAndElapsedTimes() {
assertThat(metrics.getMetrics().keySet())
.containsOnly("PS-OldGen.time", "PS-OldGen.count");
} |
public static <IN, OUT> CompletableFuture<OUT> thenComposeAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
Function<? super IN, ? extends CompletionStage<OUT>> composeFun) {
return completableFuture.isDone()
? completableFuture.thenC... | @Test
void testComposeAsyncIfNotDone() {
testFutureContinuation(
(CompletableFuture<?> future, Executor executor) ->
FutureUtils.thenComposeAsyncIfNotDone(future, executor, o -> null));
} |
@Override
List<DiscoveryNode> resolveNodes() {
try {
return lookup();
} catch (TimeoutException e) {
logger.warning(String.format("DNS lookup for serviceDns '%s' failed: DNS resolution timeout", serviceDns));
return Collections.emptyList();
} catch (Unknow... | @Test
public void resolveTimeout() {
// given
ILogger logger = mock(ILogger.class);
DnsEndpointResolver dnsEndpointResolver = new DnsEndpointResolver(logger, SERVICE_DNS, UNSET_PORT, TEST_DNS_TIMEOUT_SECONDS, timingOutLookupProvider());
// when
List<DiscoveryNode> result = d... |
@VisibleForTesting
Entity exportNativeEntity(Collector collector, EntityDescriptorIds entityDescriptorIds) {
final SidecarCollectorEntity collectorEntity = SidecarCollectorEntity.create(
ValueReference.of(collector.name()),
ValueReference.of(collector.serviceType()),
... | @Test
@MongoDBFixtures("SidecarCollectorFacadeTest.json")
public void exportNativeEntity() {
final Collector collector = collectorService.find("5b4c920b4b900a0024af0001");
final EntityDescriptor descriptor = EntityDescriptor.create(collector.id(), ModelTypes.SIDECAR_COLLECTOR_V1);
final ... |
@Override
public Class<? extends HistogramFunctionBuilder> builder() {
return HistogramFunctionBuilder.class;
} | @Test
public void testBuilder() throws IllegalAccessException, InstantiationException {
HistogramFunctionInst inst = new HistogramFunctionInst();
inst.accept(
MeterEntity.newService("service-test", Layer.GENERAL),
new BucketedValues(
BUCKETS, new long[] {
... |
public FEELFnResult<String> invoke(@ParameterName("list") List<?> list, @ParameterName("delimiter") String delimiter) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
if (list.isEmpty()) {
return ... | @Test
void setStringJoinFunctionNullValues() {
FunctionTestUtil.assertResultError(stringJoinFunction.invoke( null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(stringJoinFunction.invoke((List<?>) null , null), InvalidParametersEvent.class);
} |
@Override
public final void isEqualTo(@Nullable Object other) {
super.isEqualTo(other);
} | @Test
@GwtIncompatible("GWT behavior difference")
public void testJ2clCornerCaseDoubleVsFloat() {
// Under GWT, 1.23f.toString() is different than 1.23d.toString(), so the message omits types.
// TODO(b/35377736): Consider making Truth add the types anyway.
expectFailureWhenTestingThat(1.23).isEqualTo(1... |
@Override
protected CompletableFuture<Void> getCompletionFuture() {
return sourceThread.getCompletionFuture();
} | @Test
void testTriggeringCheckpointAfterSourceThreadFinished() throws Exception {
ResultPartition[] partitionWriters = new ResultPartition[2];
try (NettyShuffleEnvironment env =
new NettyShuffleEnvironmentBuilder()
.setNumNetworkBuffers(partitionWriters.length... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertCompressedBytesMessageToAmqpMessageWithAmqpValueBody() throws Exception {
byte[] expectedPayload = new byte[] { 8, 16, 24, 32 };
ActiveMQBytesMessage outbound = createBytesMessage(true);
outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_VALUE_BINARY);
... |
public static KafkaRoutineLoadJob fromCreateStmt(CreateRoutineLoadStmt stmt) throws UserException {
// check db and table
Database db = GlobalStateMgr.getCurrentState().getDb(stmt.getDBName());
if (db == null) {
ErrorReport.reportDdlException(ErrorCode.ERR_BAD_DB_ERROR, stmt.getDBNam... | @Test
public void testSerializationCsv(@Mocked GlobalStateMgr globalStateMgr,
@Injectable Database database,
@Injectable OlapTable table) throws UserException {
CreateRoutineLoadStmt createRoutineLoadStmt = initCreateRoutineLoadStmt()... |
static Schema toGenericAvroSchema(
String schemaName, List<TableFieldSchema> fieldSchemas, @Nullable String namespace) {
String nextNamespace = namespace == null ? null : String.format("%s.%s", namespace, schemaName);
List<Field> avroFields = new ArrayList<>();
for (TableFieldSchema bigQueryField : ... | @Test
public void testSchemaCollisionsInAvroConversion() {
TableSchema schema = new TableSchema();
schema.setFields(
Lists.newArrayList(
new TableFieldSchema()
.setName("key_value_pair_1")
.setType("RECORD")
.setMode("REPEATED")
... |
public synchronized ConnectionProfile createBQDestinationConnectionProfile(
String connectionProfileId) {
LOG.info(
"Creating BQ Destination Connection Profile {} in project {}.",
connectionProfileId,
projectId);
try {
ConnectionProfile.Builder connectionProfileBuilder =
... | @Test
public void testCreateBQDestinationConnectionShouldCreateSuccessfully()
throws ExecutionException, InterruptedException {
ConnectionProfile connectionProfile = ConnectionProfile.getDefaultInstance();
when(datastreamClient
.createConnectionProfileAsync(any(CreateConnectionProfileRequest... |
@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 shouldResolveProducerConfig() {
assertThat(resolver.resolve(ProducerConfig.BUFFER_MEMORY_CONFIG, true),
is(resolvedItem(ProducerConfig.BUFFER_MEMORY_CONFIG, PRODUCER_CONFIG_DEF)));
} |
public Matrix mm(Transpose transA, Matrix A, Transpose transB, Matrix B) {
return mm(transA, A, transB, B, 1.0f, 0.0f);
} | @Test
public void testMm() {
System.out.println("mm");
float[][] A = {
{ 0.7220180f, 0.07121225f, 0.6881997f},
{-0.2648886f, -0.89044952f, 0.3700456f},
{-0.6391588f, 0.44947578f, 0.6240573f}
};
float[][] B = {
{0.68819... |
@SuppressWarnings("MethodLength")
static void dissectControlRequest(
final ArchiveEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
... | @Test
void controlRequestListRecordingsForUri()
{
internalEncodeLogHeader(buffer, 0, 32, 32, () -> 100_000_000L);
final ListRecordingsForUriRequestEncoder requestEncoder = new ListRecordingsForUriRequestEncoder();
requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder... |
public static URL valueOf(String url) {
return valueOf(url, false);
} | @Test
void test_equals() throws Exception {
URL url1 = URL.valueOf(
"dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan");
assertURLStrDecoder(url1);
Map<String, String> params = new HashMap<String, String>();
params.put("versio... |
public static AztecCode encode(String data) {
return encode(data.getBytes(StandardCharsets.ISO_8859_1));
} | @Test(expected = IllegalArgumentException.class)
public void testBorderCompact4CaseFailed() {
// Compact(4) con hold 608 bits of information, but at most 504 can be data. Rest must
// be error correction
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// encodes as 26 * 5 * 4 = 520 bits of data
S... |
public boolean satisfies(NodeResources other) {
ensureSpecified();
other.ensureSpecified();
if (this.vcpu < other.vcpu) return false;
if (this.memoryGiB < other.memoryGiB) return false;
if (this.diskGb < other.diskGb) return false;
if (this.bandwidthGbps < other.bandwidth... | @Test
void testSatisfies() {
var hostResources = new NodeResources(1, 2, 3, 1);
assertTrue(hostResources.satisfies(new NodeResources(1, 2, 3, 1)));
assertTrue(hostResources.satisfies(new NodeResources(1, 1, 1, 1)));
assertFalse(hostResources.satisfies(new NodeResources(2, 2, 3, 1)));... |
@Override
public void triggerOnIndexCreation() {
try (DbSession dbSession = dbClient.openSession(false)) {
// remove already existing indexing task, if any
removeExistingIndexationTasks(dbSession);
dbClient.branchDao().updateAllNeedIssueSync(dbSession);
List<BranchDto> branchInNeedOfIss... | @Test
public void order_by_last_analysis_date() {
BranchDto dto = new BranchDto()
.setBranchType(BRANCH)
.setKey("branch_1")
.setUuid("branch_uuid1")
.setProjectUuid("project_uuid1")
.setIsMain(false);
dbClient.branchDao().insert(dbTester.getSession(), dto);
dbTester.commit()... |
public static void mergeParams(
Map<String, ParamDefinition> params,
Map<String, ParamDefinition> paramsToMerge,
MergeContext context) {
if (paramsToMerge == null) {
return;
}
Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream())
.forEach(
name ... | @Test
public void testMergeUpstreamMergeWithLessStrictMode() throws JsonProcessingException {
Map<String, ParamDefinition> allParams =
parseParamDefMap(
"{'workflow_default_param': {'type': 'STRING','value': 'default_value','mode': 'MUTABLE_ON_START', 'meta': {'source': 'SYSTEM_DEFAULT'}}}");
... |
@NonNull
@Override
public HealthResponse healthResponse(final Map<String, Collection<String>> queryParams) {
final String type = queryParams.getOrDefault(CHECK_TYPE_QUERY_PARAM, Collections.emptyList())
.stream()
.findFirst()
.orElse(null);
final Collection<H... | @Test
void shouldHandleZeroHealthStateViewsCorrectly() {
// given
// when
when(healthStatusChecker.isHealthy(isNull())).thenReturn(true);
final HealthResponse response = jsonHealthResponseProvider.healthResponse(Collections.emptyMap());
// then
assertThat(response.is... |
@Override
public boolean equals(Object toBeCompared) {
if (toBeCompared instanceof ControllerInfo) {
ControllerInfo that = (ControllerInfo) toBeCompared;
return Objects.equals(this.type, that.type) &&
Objects.equals(this.ip, that.ip) &&
Objects... | @Test
public void testListEquals() {
String target1 = "ptcp:6653:192.168.1.1";
ControllerInfo controllerInfo1 = new ControllerInfo(target1);
String target2 = "ptcp:6653:192.168.1.1";
ControllerInfo controllerInfo2 = new ControllerInfo(target2);
String target3 = "tcp:192.168.1... |
public InstantAndValue<T> remove(MetricKey metricKey) {
return counters.remove(metricKey);
} | @Test
public void testRemoveWithNullKey() {
LastValueTracker<Double> lastValueTracker = new LastValueTracker<>();
assertThrows(NullPointerException.class, () -> lastValueTracker.remove(null));
} |
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception {
CruiseConfig configForEdit;
CruiseConfig config;
LOGGER.debug("[Config Save] Loading config holder");
configForEdit = deserializeConfig(content);
if (callback != null) callback.call... | @Test
void shouldLoadConfigWithEnvironment() throws Exception {
String content = configWithEnvironments(
"""
<environments>
<environment name='uat' />
<environment name='prod' />
</environment... |
@Override
public Reader createReader(ResultSubpartitionView subpartitionView) throws IOException {
checkState(!fileChannel.isOpen());
final FileChannel fc = FileChannel.open(filePath, StandardOpenOption.READ);
return new FileBufferReader(fc, memorySegmentSize, subpartitionView);
} | @TestTemplate
void testReadNextBuffer() throws Exception {
final int numberOfBuffers = 3;
try (final BoundedData data = createBoundedData()) {
writeBuffers(data, numberOfBuffers);
final BoundedData.Reader reader = data.createReader();
final Buffer buffer1 = reade... |
public static <T> boolean contains(T[] array, T value) {
return indexOf(array, value) > INDEX_NOT_FOUND;
} | @Test
public void containsTest() {
Integer[] a = {1, 2, 3, 4, 3, 6};
boolean contains = ArrayUtil.contains(a, 3);
assertTrue(contains);
long[] b = {1, 2, 3, 4, 3, 6};
boolean contains2 = ArrayUtil.contains(b, 3);
assertTrue(contains2);
} |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuffer buf = new StringBuffer();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_STAT... | @Test
public void testWindowsLikeBackSlashes() throws ScanException {
List<Token> tl = new TokenStream("c:\\hello\\world.%i", new AlmostAsIsEscapeUtil()).tokenize();
List<Token> witness = new ArrayList<Token>();
witness.add(new Token(Token.LITERAL, "c:\\hello\\world."));
witness.add... |
@Override
public void excludeFiles(String[] filenames) {
if (filenames != null && filenames.length > 0) {
EXCFILE = filenames;
this.FILEFILTER = true;
}
} | @Test
public void testExcludeFiles() {
testf.excludeFiles(INCL);
for (TestData td : TESTDATA) {
String theFile = td.file;
boolean expect = td.exclfile;
testf.isFiltered(theFile, null);
String line = testf.filter(theFile);
if (line != null)... |
@Udf
public Long round(@UdfParameter final long val) {
return val;
} | @Test
public void shouldRoundLong() {
assertThat(udf.round(123L), is(123L));
} |
@Override
public String getNamenodes() {
final Map<String, Map<String, Object>> info = new LinkedHashMap<>();
if (membershipStore == null) {
return "{}";
}
try {
// Get the values from the store
GetNamenodeRegistrationsRequest request =
GetNamenodeRegistrationsRequest.newI... | @Test
public void testNamenodeStatsDataSource() throws IOException, JSONException {
RBFMetrics metrics = getRouter().getMetrics();
String jsonString = metrics.getNamenodes();
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<?> keys = jsonObject.keys();
int nnsFound = 0;
while (key... |
public static StatsSingleNote getNoteInfo(Note note) {
StatsSingleNote infos = new StatsSingleNote();
int words;
int chars;
if (note.isChecklist()) {
infos.setChecklistCompletedItemsNumber(
StringUtils.countMatches(note.getContent(), CHECKED_SYM));
infos.setChecklistItemsNumber(in... | @Test
public void getNoteInfo() {
var contextMock = getContextMock();
try (
MockedStatic<OmniNotes> omniNotes = mockStatic(OmniNotes.class);
MockedStatic<BuildHelper> buildVersionHelper = mockStatic(BuildHelper.class);
) {
omniNotes.when(OmniNotes::getAppContext).thenReturn(contextMo... |
@Override public GrpcServerRequest request() {
return request;
} | @Test void request() {
assertThat(response.request()).isSameAs(request);
} |
@Override
public String toString() {
return this.toJSONString(0);
} | @Test
@Disabled
public void toStringTest() {
final String str = "{\"code\": 500, \"data\":null}";
final JSONObject jsonObject = new JSONObject(str);
Console.log(jsonObject);
jsonObject.getConfig().setIgnoreNullValue(true);
Console.log(jsonObject.toStringPretty());
} |
NettyPartitionRequestClient createPartitionRequestClient(ConnectionID connectionId)
throws IOException, InterruptedException {
// We map the input ConnectionID to a new value to restrict the number of tcp connections
connectionId =
new ConnectionID(
co... | @TestTemplate
void testNettyClientConnectRetryMultipleThread() throws Exception {
NettyTestUtil.NettyServerAndClient serverAndClient = createNettyServerAndClient();
UnstableNettyClient unstableNettyClient =
new UnstableNettyClient(serverAndClient.client(), 2);
PartitionReque... |
@Override
public void reset() throws IOException {
createDirectory(PATH_DATA.getKey());
createDirectory(PATH_WEB.getKey());
createDirectory(PATH_LOGS.getKey());
File tempDir = createOrCleanTempDirectory(PATH_TEMP.getKey());
try (AllProcessesCommands allProcessesCommands = new AllProcessesCommands(... | @Test
public void reset_deletes_content_of_temp_dir_but_not_temp_dir_itself_if_it_already_exists() throws Exception {
assertThat(tempDir.mkdir()).isTrue();
Object tempDirKey = getFileKey(tempDir);
File fileInTempDir = new File(tempDir, "someFile.txt");
assertThat(fileInTempDir.createNewFile()).isTrue(... |
@Override
public boolean removeFirstOccurrence(Object o) {
return remove(o, 1);
} | @Test
public void testRemoveFirstOccurrence() {
RDeque<Integer> queue1 = redisson.getDeque("deque1");
queue1.addFirst(3);
queue1.addFirst(1);
queue1.addFirst(2);
queue1.addFirst(3);
queue1.removeFirstOccurrence(3);
assertThat(queue1).containsExactly(2, 1, 3)... |
@Override
public String getValue(EvaluationContext context) {
// Use variable name if we just provide this.
if (variableName != null && variable == null) {
variable = context.lookupVariable(variableName);
return (variable != null ? variable.toString() : "");
}
String proper... | @Test
void testJSONPointerValueInArray() {
String jsonString = "[{\"foo\":{\"bar\":111222},\"quantity\":1}]";
EvaluableRequest request = new EvaluableRequest(jsonString, null);
// Create new expression evaluating JSON Pointer path.
VariableReferenceExpression exp = new VariableReferenceExpre... |
public static URL urlForResource(String location) throws MalformedURLException, FileNotFoundException {
if (location == null) {
throw new NullPointerException("location is required");
}
URL url = null;
if (!location.matches(SCHEME_PATTERN)) {
url = Loader.getResou... | @Test
public void testExplicitClasspathUrlWithRootPath() throws Exception {
Assertions.assertThrows(MalformedURLException.class, () -> {
LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME + "/");
});
} |
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
MainSettingsActivity mainSettingsActivity = (MainSettingsActivity) getActivity();
if (mainSettingsActivity == null) return super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_user_word) {
createEmptyItemForAdd()... | @Test
public void testAddNewWordFromMenuAtEmptyState() {
UserDictionaryEditorFragment fragment = startEditorFragment();
RecyclerView wordsRecyclerView = fragment.getView().findViewById(R.id.words_recycler_view);
Assert.assertNotNull(wordsRecyclerView);
Assert.assertEquals(1 /*empty view*/, wordsRecyc... |
public String getQuery() throws Exception {
return getQuery(weatherConfiguration.getLocation());
} | @Test
public void testBoxedStationQuery() throws Exception {
WeatherConfiguration weatherConfiguration = new WeatherConfiguration();
weatherConfiguration.setLon("4");
weatherConfiguration.setLat("52");
weatherConfiguration.setRightLon("6");
weatherConfiguration.setTopLat("54"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.