focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public boolean isUnion() {
return this instanceof UnionSchema;
} | @Test
void isUnionOnRecord() {
Schema schema = createDefaultRecord();
assertFalse(schema.isUnion());
} |
public IsJson(Matcher<? super ReadContext> jsonMatcher) {
this.jsonMatcher = jsonMatcher;
} | @Test
public void shouldMatchOnJsonObject() {
assertThat("{ \"hi\" : \"there\" }", isJson());
} |
@Override
public void delete(final Host bookmark) throws BackgroundException {
{
final String account = TripleCryptKeyPair.toServiceName(bookmark, UserKeyPair.Version.RSA2048);
if(log.isDebugEnabled()) {
log.debug(String.format("Delete credentials for %s in keychain %... | @Test
public void testDelete() throws Exception {
new TripleCryptCleanupFeature().delete(session.getHost());
} |
static Time toTime(final JsonNode object) {
if (object instanceof NumericNode) {
return returnTimeOrThrow(object.asLong());
}
if (object instanceof TextNode) {
try {
return returnTimeOrThrow(Long.parseLong(object.textValue()));
} catch (final NumberFormatException e) {
thro... | @Test
public void shouldNotConvertNegativeStringToTime() {
try {
JsonSerdeUtils.toTime(JsonNodeFactory.instance.textNode("-5"));
} catch (Exception e) {
assertThat(e.getMessage(), equalTo("Time values must use number of milliseconds greater than 0 and less than 86400000."));
}
} |
public SortedMap<String, HealthCheck.Result> runHealthChecks() {
return runHealthChecks(HealthCheckFilter.ALL);
} | @Test
public void runsRegisteredHealthChecksWithNonMatchingFilter() {
final Map<String, HealthCheck.Result> results = registry.runHealthChecks((name, healthCheck) -> false);
assertThat(results).isEmpty();
} |
@Override
public void convert(File v2SegmentDirectory)
throws Exception {
Preconditions.checkNotNull(v2SegmentDirectory, "Segment directory should not be null");
Preconditions.checkState(v2SegmentDirectory.exists() && v2SegmentDirectory.isDirectory(),
"Segment directory: " + v2SegmentDirectory ... | @Test
public void testConvert()
throws Exception {
SegmentMetadataImpl beforeConversionMeta = new SegmentMetadataImpl(_segmentDirectory);
SegmentV1V2ToV3FormatConverter converter = new SegmentV1V2ToV3FormatConverter();
converter.convert(_segmentDirectory);
File v3Location = SegmentDirectoryPat... |
@SneakyThrows({InterruptedException.class, ExecutionException.class})
@Override
public void persist(final String key, final String value) {
buildParentPath(key);
client.getKVClient().put(ByteSequence.from(key, StandardCharsets.UTF_8), ByteSequence.from(value, StandardCharsets.UTF_8)).get();
... | @Test
void assertPersist() {
repository.persist("key1", "value1");
verify(kv).put(any(ByteSequence.class), any(ByteSequence.class));
} |
@Override
public ConnectionProperties parse(final String url, final String username, final String catalog) {
JdbcUrl jdbcUrl = new StandardJdbcUrlParser().parse(url);
return new StandardConnectionProperties(jdbcUrl.getHostname(), jdbcUrl.getPort(DEFAULT_PORT),
null == catalog ? jdbcU... | @Test
void assertNewConstructorFailure() {
assertThrows(UnrecognizedDatabaseURLException.class, () -> parser.parse("jdbc:mysql:xxxxxxxx", null, null));
} |
@Override
public boolean test(final String resourceName) {
return resourceName.matches(blackList);
} | @SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void shouldNotBlacklistAnythingIfBlacklistFileIsEmpty() {
final Blacklist blacklist = new Blacklist(this.blacklistFile);
assertFalse(blacklist.test("java.lang.Process"));
assertFalse(blacklist.test("java.util.List"));
assertFalse(blacklist.... |
public static PostgreSQLErrorResponsePacket newInstance(final Exception cause) {
Optional<ServerErrorMessage> serverErrorMessage = findServerErrorMessage(cause);
return serverErrorMessage.map(PostgreSQLErrorPacketFactory::createErrorResponsePacket)
.orElseGet(() -> createErrorResponsePac... | @Test
void assertRuntimeException() throws ReflectiveOperationException {
PostgreSQLErrorResponsePacket actual = PostgreSQLErrorPacketFactory.newInstance(new RuntimeException("No reason"));
Map<Character, String> fields = (Map<Character, String>) Plugins.getMemberAccessor().get(PostgreSQLErrorRespon... |
@Override
public int hashCode() {
return underlying().hashCode();
} | @Test
public void testHashCode() {
final TreePSet<Object> mock = mock(TreePSet.class);
assertEquals(mock.hashCode(), new PCollectionsImmutableNavigableSet<>(mock).hashCode());
final TreePSet<Object> someOtherMock = mock(TreePSet.class);
assertNotEquals(mock.hashCode(), new PCollectio... |
static byte[] hmacSha512(HMac hmacSha512, byte[] input) {
hmacSha512.reset();
hmacSha512.update(input, 0, input.length);
byte[] out = new byte[64];
hmacSha512.doFinal(out, 0);
return out;
} | @Test
public void testHmac() {
String[] tv = {
"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" +
"0b0b0b0b",
"4869205468657265",
"87aa7cdea5ef619d4ff0b4241a1d6cb0" +
"2379f4e2ce4ec2787ad0b30545e17cde" +
... |
@Override
public Optional<ExecuteResult> getSaneQueryResult(final SQLStatement sqlStatement, final SQLException ex) {
if (ER_PARSE_ERROR == ex.getErrorCode()) {
return Optional.empty();
}
if (sqlStatement instanceof SelectStatement) {
return createQueryResult((SelectS... | @Test
void assertGetSaneQueryResultForSetStatement() {
Optional<ExecuteResult> actual = new MySQLDialectSaneQueryResultEngine().getSaneQueryResult(new MySQLSetStatement(), new SQLException(""));
assertTrue(actual.isPresent());
assertThat(actual.get(), instanceOf(UpdateResult.class));
} |
public static String getFullUrl(HttpServletRequest request) {
if (request.getQueryString() == null) {
return request.getRequestURI();
}
return request.getRequestURI() + "?" + request.getQueryString();
} | @Test
void formatsBasicURIs() throws Exception {
assertThat(Servlets.getFullUrl(request))
.isEqualTo("/one/two");
} |
@Override
@ManagedOperation(description = "Remove the key from the store")
public boolean remove(String key) {
cache.remove(key);
return true;
} | @Test
void testRemove() {
// add key to remove
assertTrue(repo.add(key01));
assertTrue(repo.add(key02));
assertTrue(cache.containsKey(key01));
assertTrue(cache.containsKey(key02));
// clear repo
repo.clear();
assertFalse(cache.containsKey(key01));
... |
public static IdGenerator decrementingLongs() {
AtomicLong longs = new AtomicLong();
return () -> Long.toString(longs.decrementAndGet());
} | @Test
public void decrementing() {
IdGenerator gen = IdGenerators.decrementingLongs();
assertThat(gen.getId(), equalTo("-1"));
assertThat(gen.getId(), equalTo("-2"));
} |
@Override
public RemotingCommand invokeSync(String addr, final RemotingCommand request, long timeoutMillis)
throws InterruptedException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException {
long beginStartTime = System.currentTimeMillis();
final Channel channel ... | @Test
public void testInvokeSync() throws RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
remotingClient.registerRPCHook(rpcHookMock);
Channel channel = new LocalChannel();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.PULL_MESSAGE... |
@Override
public Optional<SimpleAddress> selectAddress(Optional<String> addressSelectionContext)
{
if (addressSelectionContext.isPresent()) {
return addressSelectionContext
.map(HostAndPort::fromString)
.map(SimpleAddress::new);
}
List<... | @Test
public void testAddressSelectionContextPresent()
{
InMemoryNodeManager internalNodeManager = new InMemoryNodeManager();
RandomCatalogServerAddressSelector selector = new RandomCatalogServerAddressSelector(internalNodeManager);
HostAndPort hostAndPort = HostAndPort.fromParts("abc",... |
@Override
public void onSwipeRight(boolean twoFingers) {} | @Test
public void testOnSwipeRight() {
mUnderTest.onSwipeRight(true);
Mockito.verifyZeroInteractions(mMockParentListener, mMockKeyboardDismissAction);
} |
public static <T> JSONSchema<T> of(SchemaDefinition<T> schemaDefinition) {
SchemaReader<T> reader = schemaDefinition.getSchemaReaderOpt()
.orElseGet(() -> new JacksonJsonReader<>(jsonMapper(), schemaDefinition.getPojo()));
SchemaWriter<T> writer = schemaDefinition.getSchemaWriterOpt()
... | @Test(expectedExceptions = SchemaSerializationException.class)
public void testAllowNullDecodeWithInvalidContent() {
JSONSchema<Foo> jsonSchema = JSONSchema.of(SchemaDefinition.<Foo>builder().withPojo(Foo.class).build());
jsonSchema.decode(new byte[0]);
} |
@Operation(summary = "Gets the status of ongoing database migrations, if any", description = "Return the detailed status of ongoing database migrations" +
" including starting date. If no migration is ongoing or needed it is still possible to call this endpoint and receive appropriate information.")
@GetMapping
... | @Test
void getStatus_whenDbRequiresUpgradeButDialectIsNotSupported_returnNotSupported() throws Exception {
when(databaseVersion.getStatus()).thenReturn(DatabaseVersion.Status.FRESH_INSTALL);
when(dialect.supportsMigration()).thenReturn(false);
mockMvc.perform(get(DATABASE_MIGRATIONS_ENDPOINT)).andExpectA... |
@Override
public PageResult<JobDO> getJobPage(JobPageReqVO pageReqVO) {
return jobMapper.selectPage(pageReqVO);
} | @Test
public void testGetJobPage() {
// mock 数据
JobDO dbJob = randomPojo(JobDO.class, o -> {
o.setName("定时任务测试");
o.setHandlerName("handlerName 单元测试");
o.setStatus(JobStatusEnum.INIT.getStatus());
});
jobMapper.insert(dbJob);
// 测试 name 不匹配... |
public Connection updateAttributes(Long id, ConnectionDTO connectionDTO) {
Connection connection = getConnectionById(id);
return connectionMapper.toUpdatedConnection(connection, connectionDTO);
} | @Test
void updateAttributes() {
Connection connectionOld = new Connection();
connectionOld.setName("old");
connectionOld.setStatus(new Status());
Optional<Connection> connectionOptional = Optional.of(connectionOld);
when(connectionRepositoryMock.findById(anyLong())).thenRet... |
@Override
public long getDelay() {
return config.getLong(DELAY_IN_MILISECONDS_PROPERTY).orElse(10_000L);
} | @Test
public void getDelay_returnNumberFromConfig() {
config.put("sonar.server.monitoring.ce.initial.delay", "100000");
long delay = underTest.getDelay();
assertThat(delay).isEqualTo(100_000L);
} |
public Properties getProperties()
{
return properties;
} | @Test
public void testNonEmptyPassword()
throws SQLException
{
PrestoDriverUri parameters = createDriverUri("presto://localhost:8080?password=secret");
assertEquals(parameters.getProperties().getProperty("password"), "secret");
} |
@Override
public Throwable getException() {
return exception;
} | @Test
void testAppResponseWithEmptyStackTraceException() {
Throwable throwable = buildEmptyStackTraceException();
assumeFalse(throwable == null);
AppResponse appResponse = new AppResponse(throwable);
StackTraceElement[] stackTrace = appResponse.getException().getStackTrace();
... |
@Override
public String getSubchannelsInfo() {
return "[]";
} | @Test
public void testGetSubchannelsInfo() {
EmptyPicker picker = new EmptyPicker(mock(Status.class));
assertNotNull(picker.getSubchannelsInfo());
} |
@Override
public String getName() {
return FUNCTION_NAME;
} | @Test
public void testCastTransformFunction() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("CAST(%s AS string)", INT_SV_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
assertTrue(transformFunction instanc... |
public static boolean checkpointsMatch(
Collection<CompletedCheckpoint> first, Collection<CompletedCheckpoint> second) {
if (first.size() != second.size()) {
return false;
}
List<Tuple2<Long, JobID>> firstInterestingFields = new ArrayList<>(first.size());
for (C... | @Test
void testCompareCheckpointsWithSameCheckpointId() {
JobID jobID1 = new JobID();
JobID jobID2 = new JobID();
CompletedCheckpoint checkpoint1 =
new CompletedCheckpoint(
jobID1,
0,
0,
... |
@Override
protected boolean isSecure(String key) {
AuthorizationPluginInfo pluginInfo = this.metadataStore().getPluginInfo(getPluginId());
if (pluginInfo == null
|| pluginInfo.getAuthConfigSettings() == null
|| pluginInfo.getAuthConfigSettings().getConfiguration(key)... | @Test
public void postConstruct_shouldEncryptSecureConfigurations() throws Exception {
PluggableInstanceSettings profileSettings = new PluggableInstanceSettings(List.of(new PluginConfiguration("password", new Metadata(true, true))));
AuthorizationPluginInfo pluginInfo = new AuthorizationPluginInfo(p... |
public static void trim(String[] strs) {
if (null == strs) {
return;
}
String str;
for (int i = 0; i < strs.length; i++) {
str = strs[i];
if (null != str) {
strs[i] = trim(str);
}
}
} | @Test
public void trimTest() {
final String blank = " 哈哈 ";
final String trim = StrUtil.trim(blank);
assertEquals("哈哈", trim);
} |
public static RestSettingBuilder get(final String id) {
return get(eq(checkId(id)));
} | @Test
public void should_get_resource_by_id() throws Exception {
Plain resource1 = new Plain();
resource1.code = 1;
resource1.message = "hello";
Plain resource2 = new Plain();
resource2.code = 2;
resource2.message = "world";
server.resource("targets",
... |
@VisibleForTesting
void validateParentMenu(Long parentId, Long childId) {
if (parentId == null || ID_ROOT.equals(parentId)) {
return;
}
// 不能设置自己为父菜单
if (parentId.equals(childId)) {
throw exception(MENU_PARENT_ERROR);
}
MenuDO menu = menuMapper... | @Test
public void testValidateParentMenu_parentNotExist() {
// 调用,并断言异常
assertServiceException(() -> menuService.validateParentMenu(randomLongId(), null),
MENU_PARENT_NOT_EXISTS);
} |
public static void zipDirectory(File sourceDirectory, File zipFile) throws IOException {
zipDirectory(sourceDirectory, zipFile, false);
} | @Test
public void testEmptySubdirectoryHasZipEntry() throws Exception {
File zipDir = new File(tmpDir, "zip");
File subDirEmpty = new File(zipDir, "subDirEmpty");
assertTrue(subDirEmpty.mkdirs());
ZipFiles.zipDirectory(tmpDir, zipFile);
assertZipOnlyContains("zip/subDirEmpty/");
} |
public static List<ComponentDto> sortComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest, List<MetricDto> metrics,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
List<String> sortParameters = wsRequest.getSort();
if (sortParameters == null || sor... | @Test
void sort_by_numerical_metric_period_5_key() {
components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure"));
ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_SORT), false, NUM_METRIC_KEY).setMetricPeriodSort(5);
List<Comp... |
static DeduplicationResult ensureSingleProducer(
QueryablePipeline pipeline,
Collection<ExecutableStage> stages,
Collection<PipelineNode.PTransformNode> unfusedTransforms) {
RunnerApi.Components.Builder unzippedComponents = pipeline.getComponents().toBuilder();
Multimap<PipelineNode.PCollecti... | @Test
public void duplicateOverStages() {
/* When multiple stages and a runner-executed transform produce a PCollection, all should be
* replaced with synthetic flattens.
* original graph:
* --> one -> .out \
* red -> .out | -> shared -> .out -> blue -> .out
* ... |
@Override
public RateLimiter rateLimiter(final String name) {
return rateLimiter(name, getDefaultConfig());
} | @Test
public void rateLimiterNewWithNullName() throws Exception {
exception.expect(NullPointerException.class);
exception.expectMessage(NAME_MUST_NOT_BE_NULL);
RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config);
registry.rateLimiter(null);
} |
public static <T> T newInstanceOrNull(Class<? extends T> clazz, Object... params) {
Constructor<T> constructor = selectMatchingConstructor(clazz, params);
if (constructor == null) {
return null;
}
try {
return constructor.newInstance(params);
} catch (Ill... | @Test
public void newInstanceOrNull_createInstanceWithNoArguments() {
ClassWithNonArgConstructor instance = InstantiationUtils.newInstanceOrNull(ClassWithNonArgConstructor.class);
assertNotNull(instance);
} |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, final Callback<RestResponse> callback)
{
if (HttpMethod.POST != HttpMethod.valueOf(request.getMethod()))
{
_log.error("POST is expected, but " + request.getMethod() + " received");
callback.onError(RestExcept... | @Test(dataProvider = "multiplexerConfigurations")
public void testRequestHeaderWhiteListing(MultiplexerRunMode multiplexerRunMode) throws Exception
{
// Validating request header white listing logic
// Create a mockHandler. Make it return different cookies based on the request
SynchronousRequestHandle... |
public double getLongitudeSpan() {
return this.maxLongitude - this.minLongitude;
} | @Test
public void getLongitudeSpanTest() {
BoundingBox boundingBox = new BoundingBox(MIN_LATITUDE, MIN_LONGITUDE, MAX_LATITUDE, MAX_LONGITUDE);
Assert.assertEquals(MAX_LONGITUDE - MIN_LONGITUDE, boundingBox.getLongitudeSpan(), 0);
} |
public void invalidateAll(UUID callerUuid) {
for (WaitSetEntry entry : queue) {
if (!entry.isValid()) {
continue;
}
Operation op = entry.getOperation();
if (callerUuid.equals(op.getCallerUuid())) {
entry.setValid(false);
... | @Test
public void invalidateAll() {
WaitSet waitSet = newWaitSet();
UUID uuid = UUID.randomUUID();
UUID anotherUuid = UUID.randomUUID();
BlockedOperation op1 = newBlockingOperationWithCallerUuid(uuid);
waitSet.park(op1);
BlockedOperation op2 = newBlockingOperationWi... |
public Point lastPoint() {
return points.getLast();
} | @Test
public void testLastPoint() {
Point<?> firstPoint = Point.builder().time(EPOCH.minusSeconds(5)).latLong(0.0, 0.0).build();
Point<?> secondPoint = Point.builder().time(EPOCH).latLong(0.0, 0.0).build();
TrackUnderConstruction tip = new TrackUnderConstruction(firstPoint);
tip.ad... |
public static String revertValue(Object cleanValue) {
if (cleanValue == null) {
return "null";
}
Class<?> clazz = cleanValue.getClass();
if (clazz.isAssignableFrom(String.class)) {
return String.valueOf(cleanValue);
} else if (clazz.isAssignableFrom(BigD... | @Test
public void revertValue_manyCases() {
assertThat(revertValue("Test")).isEqualTo("Test");
assertThat(revertValue(BigDecimal.valueOf(10000.83))).isEqualTo("10000.83");
assertThat(revertValue(BigDecimal.valueOf(10000))).isEqualTo("10000");
assertThat(revertValue(BigInteger.valueOf... |
public static boolean isIPv4(String addr) {
return InetAddressValidator.isIPv4Address(addr);
} | @Test
void testIsIPv4() {
assertTrue(InternetAddressUtil.isIPv4("127.0.0.1"));
assertFalse(InternetAddressUtil.isIPv4("[::1]"));
assertFalse(InternetAddressUtil.isIPv4("asdfasf"));
assertFalse(InternetAddressUtil.isIPv4("ffgertert"));
assertFalse(InternetAddressUtil.isIPv4("1... |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateFileConfigMaster(Long id) {
// 校验存在
validateFileConfigExists(id);
// 更新其它为非 master
fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false));
// 更新
fileConfigMapper.updateById(new Fi... | @Test
public void testUpdateFileConfigMaster_notExists() {
// 调用, 并断言异常
assertServiceException(() -> fileConfigService.updateFileConfigMaster(randomLongId()), FILE_CONFIG_NOT_EXISTS);
} |
@Override
public <U> StateFuture<Collection<U>> onNext(Function<T, StateFuture<? extends U>> iterating) {
// Public interface implementation, this is on task thread.
// We perform the user code on cache, and create a new request and chain with it.
if (isEmpty()) {
return StateFut... | @Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void testPartialLoadingWithReturnValue() {
TestIteratorStateExecutor stateExecutor = new TestIteratorStateExecutor(100, 3);
AsyncExecutionController aec =
new AsyncExecutionController(
new SyncMailb... |
@Override
public boolean syncData(DistroData data, String targetServer) {
if (isNoExistTarget(targetServer)) {
return true;
}
DistroDataRequest request = new DistroDataRequest(data, data.getType());
Member member = memberManager.find(targetServer);
if (checkTarget... | @Test
void testSyncDataWithCallbackFailure() throws NacosException {
when(memberManager.hasMember(member.getAddress())).thenReturn(true);
when(memberManager.find(member.getAddress())).thenReturn(member);
member.setState(NodeState.UP);
response.setErrorInfo(ResponseCode.FAIL.getCode()... |
@ApiOperation(value = "Create Or Update Edge (saveEdge)",
notes = "Create or update the Edge. When creating edge, platform generates Edge Id as " + UUID_WIKI_LINK +
"The newly created edge id will be present in the response. " +
"Specify existing Edge id to update the... | @Test
public void testSaveEdge() throws Exception {
Edge edge = constructEdge("My edge", "default");
Mockito.reset(tbClusterService, auditLogService);
Edge savedEdge = doPost("/api/edge", edge, Edge.class);
Assert.assertNotNull(savedEdge);
Assert.assertNotNull(savedEdge.ge... |
@Override
public void close() {
loggerFactory.getLoggersWithPrefix(queryId.toString()).forEach(ProcessingLogger::close);
sharedKafkaStreamsRuntime.stop(queryId, true);
scalablePushRegistry.ifPresent(ScalablePushRegistry::close);
listener.onClose(this);
} | @Test
public void shouldCloseProcessingLoggers() {
// Given:
final ProcessingLogger processingLogger1 = mock(ProcessingLogger.class);
final ProcessingLogger processingLogger2 = mock(ProcessingLogger.class);
when(loggerFactory.getLoggersWithPrefix(QUERY_ID.toString())).thenReturn(Arra... |
@Override
public Ring<T> createRing(Map<T, Integer> pointsMap) {
return _ringFactory.createRing(pointsMap);
} | @Test(groups = { "small", "back-end" })
public void testFactoryWithDistributionBasedAndRegix() {
RingFactory<String> factory = new DelegatingRingFactory<>(configBuilder("distributionBased", "uriRegex"));
Ring<String> ring = factory.createRing(buildPointsMap(10));
assertTrue(ring instanceof MPConsistentHa... |
@VisibleForTesting
static Instant getCreationTime(String configuredCreationTime, ProjectProperties projectProperties)
throws DateTimeParseException, InvalidCreationTimeException {
try {
switch (configuredCreationTime) {
case "EPOCH":
return Instant.EPOCH;
case "USE_CURRENT_T... | @Test
public void testGetCreationTime_isoDateTimeValueRequiresTimeZone() {
// getCreationTime should fail if timezone not specified.
// this is the expected behavior, not specifically designed like this for any reason, feel
// free to change this behavior and update the test
assertThrows(
Inva... |
@Override
public KsMaterializedQueryResult<Row> get(
final GenericKey key,
final int partition,
final Optional<Position> position
) {
try {
final KeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query = KeyQuery.withKey(key);
StateQueryRequest<ValueAndTimestamp<GenericRow>>
... | @Test
public void shouldRangeQueryWithCorrectParams_upperBound() {
// Given:
when(kafkaStreams.query(any())).thenReturn(getIteratorResult());
// When:
table.get(PARTITION, null, A_KEY2);
// Then:
verify(kafkaStreams).query(queryTypeCaptor.capture());
StateQueryRequest request = queryType... |
public QueryMetadata parse(String queryString) {
if (Strings.isNullOrEmpty(queryString)) {
return QueryMetadata.empty();
}
Map<String, List<SubstringMultilinePosition>> positions = new LinkedHashMap<>();
final String[] lines = queryString.split("\n");
for (int line... | @Test
void testParamPositionsMultiline() {
final QueryMetadata metadata = queryStringParser.parse("foo:$bar$ AND\nlorem:$bar$ OR ipsum:$bar$");
assertThat(metadata.usedParameters().size()).isEqualTo(1);
final QueryParam param = metadata.usedParameters().iterator().next();
assertThat(... |
@Override
public Collection<Subscriber> getFuzzySubscribers(String namespaceId, String serviceName) {
Collection<Subscriber> result = new LinkedList<>(
subscriberServiceLocal.getFuzzySubscribers(namespaceId, serviceName));
if (memberManager.getServerList().size() > 1) {
g... | @Test
void testGetFuzzySubscribersByStringWithLocal() {
Collection<Subscriber> actual = aggregation.getFuzzySubscribers(namespace, serviceName);
assertEquals(1, actual.size());
assertEquals("local", actual.iterator().next().getAddrStr());
} |
public List<String> getServices() {
try {
return Optional.of(nacosServiceDiscovery.getServices()).map(services -> {
ServiceCache.setServiceIds(services);
return services;
}).get();
} catch (NacosException e) {
LOGGER.log(Level.SEVERE, S... | @Test
public void testGetServices() throws NacosException {
mockNamingService();
Assert.assertNotNull(nacosClient.getServices());
} |
static List<String> locateScripts(ArgsMap argsMap) {
String script = argsMap.get(SCRIPT);
String scriptDir = argsMap.get(SCRIPT_DIR);
List<String> scripts = new ArrayList<>();
if (script != null) {
StringTokenizer tokenizer = new StringTokenizer(script, ":");
if (log.isDebugEnabled()) {
... | @Test
void locateScriptsMulti() {
ArgsMap argsMap = new ArgsMap(new String[] {"script=script1:script2"});
List<String> scripts = Main.locateScripts(argsMap);
assertEquals(2, scripts.size());
} |
protected RepositoryMeta createPurRepositoryMetaRepositoryMeta( String url ) {
RepositoryMeta purRepositoryMeta = null;
try {
Class<?> purRepositoryLocationClass = purPluginClassLoader.loadClass( "org.pentaho.di.repository.pur"
+ ".PurRepositoryLocation" );
Constructor<?> purRepositoryLoc... | @Test
public void createPurRepositoryMetaRepositoryMetaTest() {
RepositoryMeta repositoryMeta = null;
try {
Mockito.<Class<?>>when( mockClassLoader.loadClass( "org.pentaho.di.repository.pur"
+ ".PurRepositoryLocation" ) ).thenReturn( Class.forName( "org.pentaho.di.repository.pur"
+ "... |
protected boolean isLoadBalancerSheddingBundlesWithPoliciesEnabled(LoadManagerContext context,
NamespaceBundle namespaceBundle) {
if (isolationPoliciesHelper != null
&& isolationPoliciesHelper.hasIsolationPolicy(namespaceBund... | @Test
public void testIsLoadBalancerSheddingBundlesWithPoliciesEnabled() {
var counter = new UnloadCounter();
TransferShedder transferShedder = new TransferShedder(pulsar, counter, new ArrayList<>(),
isolationPoliciesHelper, antiAffinityGroupPolicyHelper);
var ctx = setupCon... |
public static void pauseConsumers(final Queue<Consumer<byte[]>> consumers) {
consumers.forEach(Consumer::pause);
} | @Test
public void pauseConsumers() {
Consumer<byte[]> consumer = mock(Consumer.class);
Queue<Consumer<byte[]>> consumers = new ConcurrentLinkedQueue<>();
consumers.add(consumer);
PulsarUtils.pauseConsumers(consumers);
verify(consumer).pause();
} |
public List<String> getShowInfo() {
Database db = GlobalStateMgr.getCurrentState().getDb(dbId);
Table tbl = null;
if (db != null) {
Locker locker = new Locker();
locker.lockDatabase(db, LockType.READ);
try {
tbl = db.getTable(tableId);
... | @Test
public void testGetShowInfo() throws UserException {
{
// PAUSE state
KafkaRoutineLoadJob routineLoadJob = new KafkaRoutineLoadJob();
Deencapsulation.setField(routineLoadJob, "state", RoutineLoadJob.JobState.PAUSED);
ErrorReason errorReason = new ErrorRe... |
@Override
public void close() {
try {
restHighLevelClient.close();
} catch (IOException e) {
throw new ElasticsearchException("Could not close ES Rest high level client", e);
}
} | @Test
public void should_rethrow_ex_when_close_client_throws() throws IOException {
doThrow(IOException.class).when(restClient).close();
assertThatThrownBy(() -> underTest.close())
.isInstanceOf(ElasticsearchException.class);
} |
@Override
public Object getValue(final int columnIndex, final Class<?> type) throws SQLException {
if (boolean.class == type) {
return resultSet.getBoolean(columnIndex);
}
if (byte.class == type) {
return resultSet.getByte(columnIndex);
}
if (short.cla... | @Test
void assertGetValueByFloat() throws SQLException {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getFloat(1)).thenReturn(1.0F);
assertThat(new JDBCStreamQueryResult(resultSet).getValue(1, float.class), is(1.0F));
} |
@SuppressWarnings("unchecked")
@Override
public void execute(String mapName, Predicate predicate, Collection<Integer> partitions, Result result) {
runUsingPartitionScanWithoutPaging(mapName, predicate, partitions, result);
if (predicate instanceof PagingPredicateImpl pagingPredicate) {
... | @Test
public void execute_fail() {
PartitionScanRunner runner = mock(PartitionScanRunner.class);
ParallelPartitionScanExecutor executor = executor(runner);
Predicate<Object, Object> predicate = Predicates.equal("attribute", 1);
QueryResult queryResult = new QueryResult(IterationType.... |
@Override
public AuthLoginRespVO refreshToken(String refreshToken) {
OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT);
return AuthConvert.INSTANCE.convert(accessTokenDO);
} | @Test
public void testRefreshToken() {
// 准备参数
String refreshToken = randomString();
// mock 方法
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class);
when(oauth2TokenService.refreshAccessToken(eq(refreshToken), eq("default")))
.thenReturn(... |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testOnWindowExpirationDisallowedParameter() throws Exception {
// Timers are not allowed in OnWindowExpiration
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Illegal parameter type");
thrown.expectMessage("TimerParameter");
thrown.expectMessage("myTimer");
... |
@Override
protected ExecuteContext doBefore(ExecuteContext context) throws Exception {
LogUtils.printHttpRequestBeforePoint(context);
final InvokerService invokerService = PluginServiceManager.getPluginService(InvokerService.class);
final Optional<Request> rawRequest = getRequest(context);
... | @Test
public void testRestTemplateInterceptor() throws Exception {
Optional<?> configMapOptional = ReflectUtils.getStaticFieldValue(ConfigManager.class, "CONFIG_MAP");
DiscoveryPluginConfig discoveryPluginConfig = new DiscoveryPluginConfig();
if (configMapOptional.isPresent()) {
... |
public static NacosRestTemplate getNacosRestTemplate(Logger logger) {
return getNacosRestTemplate(new DefaultHttpClientFactory(logger));
} | @Test
void testGetNacosRestTemplateWithCustomFactory() {
assertTrue(restMap.isEmpty());
HttpClientBeanHolder.getNacosRestTemplate((Logger) null);
assertEquals(1, restMap.size());
NacosRestTemplate actual = HttpClientBeanHolder.getNacosRestTemplate(mockFactory);
assertEquals(2... |
public static void main(String[] args) {
var wizard = new Wizard();
var goblin = new Goblin();
goblin.printStatus();
wizard.castSpell(goblin::changeSize);
goblin.printStatus();
wizard.castSpell(goblin::changeVisibility);
goblin.printStatus();
wizard.undoLastSpell();
goblin.printS... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
@Override
public Dataset<Row> apply(
final JavaSparkContext jsc,
final SparkSession sparkSession,
final Dataset<Row> rowDataset,
final TypedProperties props) {
final String sqlFile = getStringWithAltKeys(props, SqlTransformerConfig.TRANSFORMER_SQL_FILE);
final FileSystem fs = HadoopF... | @Test
public void testSqlFileBasedTransformerIllegalArguments() {
// Test if the class throws illegal argument exception when argument not present.
assertThrows(
IllegalArgumentException.class,
() -> sqlFileTransformer.apply(jsc, sparkSession, inputDatasetRows, props));
} |
static String escape(String input) {
return input.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)");
} | @Test
public void testEscapeParentheses() {
assertEquals("\\(bob's name\\)", ClientQuotasImageNode.escape("(bob's name)"));
} |
public static Ip6Address valueOf(byte[] value) {
return new Ip6Address(value);
} | @Test
public void testToStringIPv6() {
Ip6Address ipAddress;
ipAddress =
Ip6Address.valueOf("1111:2222:3333:4444:5555:6666:7777:8888");
assertThat(ipAddress.toString(),
is("1111:2222:3333:4444:5555:6666:7777:8888"));
ipAddress = Ip6Address.valueOf("11... |
public static Source source(InputStream in) {
return source(in, new Timeout());
} | @Test public void sourceFromInputStream() throws Exception {
InputStream in = new ByteArrayInputStream(
("a" + repeat('b', Segment.SIZE * 2) + "c").getBytes(UTF_8));
// Source: ab...bc
Source source = Okio.source(in);
Buffer sink = new Buffer();
// Source: b...bc. Sink: abb.
assertEqua... |
@Override
public AppQueue getAppQueue(HttpServletRequest hsr, String appId)
throws AuthorizationException {
try {
long startTime = clock.getTime();
DefaultRequestInterceptorREST interceptor = getOrCreateInterceptorByAppId(appId);
AppQueue queue = interceptor.getAppQueue(hsr, appId);
... | @Test
public void testGetAppQueue() throws IOException, InterruptedException {
String queueName = "queueName";
// Submit application to multiSubCluster
ApplicationId appId = ApplicationId.newInstance(Time.now(), 1);
ApplicationSubmissionContextInfo context = new ApplicationSubmissionContextInfo();
... |
@Override
public ThreadPoolPlugin disableThreadPoolPlugin(String pluginId) {
ThreadPoolPlugin removed = enableThreadPoolPlugins.remove(pluginId);
if (Objects.nonNull(removed)) {
managedThreadPoolPluginSupports.values().forEach(support -> support.unregister(pluginId));
}
r... | @Test
public void testDisableThreadPoolPlugin() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPlugin(new TestPlugin("1"));
manager.enableThreadPoolPlugin(new TestPlugin("2"));
manager.disableThreadPoolPlugin("2");
... |
@SuppressWarnings("unchecked")
public CompletableFuture<Void> onResponse(final FilterRequestContext requestContext,
final FilterResponseContext responseContext)
{
RestLiResponseData<?> responseData = responseContext.getResponseData();
if (responseData.getResponse... | @Test(dataProvider = "returnEntityValidateOnResponseData")
@SuppressWarnings({"unchecked", "rawtypes"})
public void testReturnEntityValidateOnResponse(ResourceMethod resourceMethod, RestLiResponseData responseData,
boolean isReturnEntityMethod, boolean isReturnEntityRequested)
{
when(filterRequestContex... |
@Override
public boolean equals(Object other) {
if (!(other instanceof Versioned)) {
return false;
}
Versioned<V> that = (Versioned) other;
return Objects.equal(this.value, that.value) &&
Objects.equal(this.version, that.version) &&
Objects.e... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(stats1, stats1)
.addEqualityGroup(stats2)
.testEquals();
} |
public IdentityProvider getEnabledByKey(String key) {
IdentityProvider identityProvider = providersByKey.get(key);
if (identityProvider != null && IS_ENABLED_FILTER.test(identityProvider)) {
return identityProvider;
}
throw new IllegalArgumentException(String.format("Identity provider %s does not ... | @Test
public void return_enabled_provider() {
IdentityProviderRepository underTest = new IdentityProviderRepository(asList(GITHUB, BITBUCKET, DISABLED));
assertThat(underTest.getEnabledByKey(GITHUB.getKey())).isEqualTo(GITHUB);
assertThat(underTest.getEnabledByKey(BITBUCKET.getKey())).isEqualTo(BITBUCKET... |
public static Multimap<String, SourceDescription> fetchSourceDescriptions(
final RemoteHostExecutor remoteHostExecutor
) {
final List<SourceDescription> sourceDescriptions = Maps
.transformValues(
remoteHostExecutor.fetchAllRemoteResults().getLeft(),
SourceDescriptionList.cla... | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void itShouldReturnRemoteSourceDescriptionsGroupedByName() {
// Given
when(augmenter.fetchAllRemoteResults()).thenReturn(new Pair(response, ImmutableSet.of()));
Multimap<String, SourceDescription> res = RemoteSourceDescriptionExecutor.fetchSourc... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testShhHasIdentity() throws Exception {
web3j.shhHasIdentity(
"0x04f96a5e25610293e42a73908e93ccc8c4d4dc0edcfa9fa872f50cb214e08ebf61a03e245533f97284d442460f2998cd41858798ddfd4d661997d3940272b717b1")
.send();
verifyResult(
"{\... |
@Override
public void transitionToActive(final StreamTask streamTask, final RecordCollector recordCollector, final ThreadCache newCache) {
if (stateManager.taskType() != TaskType.ACTIVE) {
throw new IllegalStateException("Tried to transition processor context to active but the state manager's " ... | @Test
public void localKeyValueStoreShouldNotAllowInitOrClose() {
foreachSetUp();
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.getGlobalStore(anyString())).thenReturn(null);
final KeyValueStore<String, Long> keyValueStoreMock = mock(KeyValueStore.cla... |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
public AppInfo get() {
return getAppInfo();
} | @Test
public void testInfo() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("mapreduce")
.path("info").accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON + "; " + Jetty... |
@Override
public String ping(RedisClusterNode node) {
return execute(node, RedisCommands.PING);
} | @Test
public void testClusterPing() {
RedisClusterNode master = getFirstMaster();
String res = connection.ping(master);
assertThat(res).isEqualTo("PONG");
} |
@Override
public Row deserialize(byte[] message) throws IOException {
return deserialize(message, true);
} | @Test
void testTimestampSpecificSerializeDeserializeNewMapping() throws Exception {
final Tuple4<Class<? extends SpecificRecord>, SpecificRecord, GenericRecord, Row> testData =
AvroTestUtils.getTimestampTestData();
final String schemaString = testData.f1.getSchema().toString();
... |
public void handleAssignment(final Map<TaskId, Set<TopicPartition>> activeTasks,
final Map<TaskId, Set<TopicPartition>> standbyTasks) {
log.info("Handle new assignment with:\n" +
"\tNew active tasks: {}\n" +
"\tNew standby tasks: {}\n" +... | @Test
public void shouldKeepReassignedActiveTaskInStateUpdater() {
final StreamTask reassignedActiveTask = statefulTask(taskId03, taskId03ChangelogPartitions)
.inState(State.RESTORING)
.withInputPartitions(taskId03Partitions).build();
final TasksRegistry tasks = mock(TasksReg... |
@Override
public boolean updateReservation(ReservationAllocation reservation)
throws PlanningException {
writeLock.lock();
boolean result = false;
try {
ReservationId resId = reservation.getReservationId();
ReservationAllocation currReservation = getReservationById(resId);
if (curr... | @Test
public void testUpdateReservation() {
Plan plan = new InMemoryPlan(queueMetrics, policy, agent, totalCapacity, 1L,
resCalc, minAlloc, maxAlloc, planName, replanner, true, context);
ReservationId reservationID =
ReservationSystemTestUtil.getNewReservationId();
// First add a reservati... |
public void addAssignmentsForPartitions(final Set<TopicIdPartition> partitions) {
updateAssignments(Objects.requireNonNull(partitions), Collections.emptySet());
} | @Test
public void testAddAssignmentsForPartitions() {
final List<TopicIdPartition> idPartitions = getIdPartitions("sample", 3);
final Map<TopicPartition, Long> endOffsets = idPartitions.stream()
.map(idp -> toRemoteLogPartition(partitioner.metadataPartition(idp)))
.collect(Co... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatTerminateAllQueries() {
// Given:
final TerminateQuery terminateQuery = TerminateQuery.all(Optional.empty());
// When:
final String formatted = SqlFormatter.formatSql(terminateQuery);
// Then:
assertThat(formatted, is("TERMINATE ALL"));
} |
@Override
public void emit(String emitKey, List<Metadata> metadataList, ParseContext parseContext)
throws IOException, TikaEmitterException {
if (metadataList == null || metadataList.size() < 1) {
return;
}
List<EmitData> emitDataList = new ArrayList<>();
emit... | @Test
public void testVarcharTruncation(@TempDir Path tmpDir) throws Exception {
Files.createDirectories(tmpDir.resolve("db"));
Path dbDir = tmpDir.resolve("db/h2");
Path config = tmpDir.resolve("tika-config.xml");
String connectionString = "jdbc:h2:file:" + dbDir.toAbsolutePath();
... |
@Override
public void finish()
throws IOException
{
printRows(ImmutableList.of(), true);
writer.append(format("(%s row%s)%n", rowCount, (rowCount != 1) ? "s" : ""));
writer.flush();
} | @Test
public void testAlignedPrintingNoRows()
throws Exception
{
StringWriter writer = new StringWriter();
List<String> fieldNames = ImmutableList.of("first", "last");
OutputPrinter printer = new AlignedTablePrinter(fieldNames, writer);
printer.finish();
Str... |
@Override
public NetworkClientDelegate.PollResult poll(long currentTimeMs) {
if (!coordinatorRequestManager.coordinator().isPresent() ||
shareMembershipManager.shouldSkipHeartbeat() ||
pollTimer.isExpired()) {
shareMembershipManager.onHeartbeatRequestSkipped();
... | @Test
public void testSuccessfulHeartbeatTiming() {
NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
assertEquals(0, result.unsentRequests.size(),
"No heartbeat should be sent while interval has not expired");
assertEquals(heartbeat... |
public static String serializePublicKey(PublicKey publicKey) throws Exception {
// Serialize the public key
byte[] publicKeyBytes = publicKey.getEncoded();
return Base64.getEncoder().encodeToString(publicKeyBytes);
} | @Test
public void testSerializePublicKey() throws Exception {
KeyPair keyPair = KeyUtil.generateKeyPair("RSA", 2048);
System.out.println("public key = " + KeyUtil.serializePublicKey(keyPair.getPublic()));
System.out.println("private key = " + KeyUtil.serializePrivateKey(keyPair.getPrivate())... |
public float getFloat(HazelcastProperty property) {
return Float.valueOf(getString(property));
} | @Test
public void getFloat() {
HazelcastProperty property = new HazelcastProperty("foo", 10.1F);
float foo = defaultProperties.getFloat(property);
assertEquals(10.1F, foo, 0.0001);
} |
public static boolean isConsumer(URL url) {
return url.getProtocol().equalsIgnoreCase(CONSUMER) || url.getPort() == 0;
} | @Test
public void testIsConsumer() {
String address1 = "remote://root:alibaba@127.0.0.1:9090";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "consumer://root:alibaba@127.0.0.1:9090";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "consumer:/... |
public static List<String> getStackFrameList(final Throwable t, int maxDepth) {
final String stackTrace = getStackTrace(t);
final String linebreak = System.lineSeparator();
final StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
final List<String> list = new ArrayList<... | @Test
void testGetStackFrameList() {
List<String> stackFrameList = ExceptionUtils.getStackFrameList(exception);
Assertions.assertNotEquals(10, stackFrameList.size());
} |
@Override
public String getSinkTableName(Table table) {
String tableName = table.getName();
Map<String, String> sink = config.getSink();
// Add table name mapping logic
String mappingRoute = sink.get(FlinkCDCConfig.TABLE_MAPPING_ROUTES);
if (mappingRoute != null) {
... | @Test
public void testGetSinkTableNameWithNoConfigPrefixOrSuffix() {
Map<String, String> sinkConfig = new HashMap<>();
sinkConfig.put("table.prefix", "");
sinkConfig.put("table.suffix", "");
sinkConfig.put("table.lower", "false");
sinkConfig.put("table.upper", "false");
... |
@ShellMethod(key = "compaction showarchived", value = "Shows compaction details for a specific compaction instant")
public String compactionShowArchived(
@ShellOption(value = "--instant", help = "instant time") final String compactionInstantTime,
@ShellOption(value = {"--limit"}, help = "Limit commits", d... | @Test
public void testCompactionShowArchived() throws IOException {
generateCompactionInstances();
String instance = "001";
// get compaction plan before compaction
HoodieCompactionPlan plan = TimelineMetadataUtils.deserializeCompactionPlan(
HoodieCLI.getTableMetaClient().reloadActiveTimeline... |
static String getAbbreviation(Exception ex,
Integer statusCode,
String storageErrorMessage) {
String result = null;
for (RetryReasonCategory retryReasonCategory : rankedReasonCategories) {
final String abbreviation
= retryReasonCategory.captureAndGetAbbreviation(ex,
statusC... | @Test
public void testUnknownHostRetryReason() {
Assertions.assertThat(RetryReason.getAbbreviation(new UnknownHostException(), null, null)).isEqualTo(
UNKNOWN_HOST_EXCEPTION_ABBREVIATION
);
} |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
public NodeInfo get() {
return getNodeInfo();
} | @Test
public void testNodeInfoSlash() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("node")
.path("info/").accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON + "; " + ... |
@Override
public void execute() {
boolean debugMode = ExtensibleLoadManagerImpl.debug(conf, log);
if (debugMode) {
log.info("Load balancer enabled: {}, Split enabled: {}.",
conf.isLoadBalancerEnabled(), conf.isLoadBalancerAutoBundleSplitEnabled());
}
... | @Test(timeOut = 30 * 1000)
public void testExecuteFailure() {
AtomicReference<List<Metrics>> reference = new AtomicReference();
SplitCounter counter = new SplitCounter();
SplitManager manager = new SplitManager(counter);
SplitScheduler scheduler = new SplitScheduler(pulsar, channel, ... |
public static String get(String urlString, Charset customCharset) {
return HttpRequest.get(urlString).charset(customCharset).execute().body();
} | @Test
@Disabled
public void getNocovTest(){
final String url = "https://qiniu.nocov.cn/medical-manage%2Ftest%2FBANNER_IMG%2F444004467954556928%2F1595215173047icon.png~imgReduce?e=1597081986&token=V2lJYVgQgAv_sbypfEZ0qpKs6TzD1q5JIDVr0Tw8:89cbBkLLwEc9JsMoCLkAEOu820E=";
final String s = HttpUtil.get(url);
Console.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.