focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public void notifyMasterOnline() {
for (ManyPullRequest mpr : this.pullRequestTable.values()) {
if (mpr == null || mpr.isEmpty()) {
continue;
}
for (PullRequest request : mpr.cloneListAndClear()) {
try {
log.info("notify mas... | @Test
public void notifyMasterOnlineTest() {
Assertions.assertThatCode(() -> pullRequestHoldService.suspendPullRequest(TEST_TOPIC, DEFAULT_QUEUE_ID, pullRequest)).doesNotThrowAnyException();
Assertions.assertThatCode(() -> pullRequestHoldService.notifyMasterOnline()).doesNotThrowAnyException();
... |
public static <X extends Throwable> void check(boolean expression, Supplier<? extends X> exceptionSupplier) throws X {
if (!expression)
throw exceptionSupplier.get();
} | @Test(expected = ArithmeticException.class)
public void check_false() {
Preconditions.check(false, ArithmeticException::new);
} |
@Override
public ClassLoaderLease registerClassLoaderLease(JobID jobId) {
synchronized (lockObject) {
return cacheEntries
.computeIfAbsent(jobId, jobID -> new LibraryCacheEntry(jobId))
.obtainLease();
}
} | @Test
public void closingAllLeases_willReleaseUserCodeClassLoader() throws IOException {
final TestingClassLoader classLoader = new TestingClassLoader();
final BlobLibraryCacheManager libraryCacheManager =
new TestingBlobLibraryCacheManagerBuilder()
.setClassL... |
public static byte[] hexString2Bytes(String hexString) {
if (isSpace(hexString)) return null;
int len = hexString.length();
if (len % 2 != 0) {
hexString = "0" + hexString;
len = len + 1;
}
char[] hexBytes = hexString.toUpperCase().toCharArray();
b... | @Test
public void hexString2Bytes() throws Exception {
TestCase.assertTrue(
Arrays.equals(
mBytes,
ConvertKit.hexString2Bytes(hexString)
)
);
} |
@SuppressWarnings("rawtypes")
@Converter(fallback = true)
public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
if (value instanceof JavaResult.ResultMap) {
for (Object mapValue : ((Map) value).values()) {
if (type.isI... | @Test
public void convertStringResultToStreamSource() throws Exception {
StringResult stringResult = createStringResult("Bajja");
StreamSource streamSource = typeConverter.convertTo(StreamSource.class, stringResult);
BufferedReader reader = new BufferedReader(streamSource.getReader());
... |
@Override
public void run() {
try {
backgroundJobServer.getJobSteward().notifyThreadOccupied();
MDCMapper.loadMDCContextFromJob(job);
performJob();
} catch (Exception e) {
if (isJobDeletedWhileProcessing(e)) {
// nothing to do anymore a... | @Test
void allStateChangesArePassingViaTheApplyStateFilterOnSuccess() {
Job job = anEnqueuedJob().build();
when(backgroundJobServer.getBackgroundJobRunner(job)).thenReturn(new BackgroundStaticFieldJobWithoutIocRunner());
BackgroundJobPerformer backgroundJobPerformer = new BackgroundJobPerf... |
static ViewHistoryEntry fromJson(String json) {
return JsonUtil.parse(json, ViewHistoryEntryParser::fromJson);
} | @Test
public void testViewHistoryEntryMissingFields() {
assertThatThrownBy(() -> ViewHistoryEntryParser.fromJson("{}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse missing int: version-id");
assertThatThrownBy(() -> ViewHistoryEntryParser.fromJson("{\"timestamp-ms\... |
public static HazelcastInstance getOrCreateHazelcastClient() {
return getOrCreateClientInternal(null);
} | @Test
public void testGetOrCreateHazelcastClientConcurrently() throws ExecutionException, InterruptedException {
String instanceName = randomString();
ClientConfig config = new ClientConfig();
config.setInstanceName(instanceName);
int clientCount = 10;
List<HazelcastInstance... |
public static String getSDbl( double Value, int DecPrec ) {
//
String Result = "";
//
if ( Double.isNaN( Value ) ) return "NaN";
//
if ( DecPrec < 0 ) DecPrec = 0;
//
String DFS = "###,###,##0";
//
if ( DecPrec > 0 ) {
int idx = 0;
DFS += ".";
while ( idx < DecPrec ) {
DFS = DFS + "0";
... | @Test
public void testgetSDbl() throws Exception {
//
assertEquals( "NaN", BTools.getSDbl( Double.NaN, 0 ) );
assertEquals( "-6", BTools.getSDbl( -5.5D, 0 ) );
assertEquals( "-5.50", BTools.getSDbl( -5.5D, 2 ) );
assertEquals( "-5.30", BTools.getSDbl( -5.3D, 2 ) );
assertEquals( "-5", BTools.getSDbl( -5.3D... |
public static boolean isDigits(String str) {
if (StringUtils.isEmpty(str)) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
} | @Test
void testIsDigits() {
assertFalse(NumberUtils.isDigits(null));
assertFalse(NumberUtils.isDigits(""));
assertTrue(NumberUtils.isDigits("12345"));
assertFalse(NumberUtils.isDigits("1234.5"));
assertFalse(NumberUtils.isDigits("1ab"));
assertFalse(NumberUtils.isDigi... |
public Optional<Branch> findDefaultBranch() {
return branches.stream().filter(Branch::isDefault).findFirst();
} | @Test
public void findDefaultBranch_givenNoBranches_returnEmptyOptional(){
BranchesList branchesList = new BranchesList();
Optional<Branch> defaultBranch = branchesList.findDefaultBranch();
assertThat(defaultBranch).isNotPresent();
} |
@Override
public Health health() {
Map<String, Health> healths = circuitBreakerRegistry.getAllCircuitBreakers().stream()
.filter(this::isRegisterHealthIndicator)
.collect(Collectors.toMap(CircuitBreaker::getName,
this::mapBackendMonitorState));
Status status ... | @Test
public void healthIndicatorMaxImpactCanBeOverridden() {
CircuitBreaker openCircuitBreaker = mock(CircuitBreaker.class);
CircuitBreaker halfOpenCircuitBreaker = mock(CircuitBreaker.class);
CircuitBreaker closeCircuitBreaker = mock(CircuitBreaker.class);
Map<CircuitBreaker.State... |
@Override
public List<MemberLevelDO> getLevelList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return Collections.emptyList();
}
return memberLevelMapper.selectBatchIds(ids);
} | @Test
public void testGetLevelList() {
// mock 数据
MemberLevelDO dbLevel = randomPojo(MemberLevelDO.class, o -> { // 等会查询到
o.setName("黄金会员");
o.setStatus(1);
});
memberlevelMapper.insert(dbLevel);
// 测试 name 不匹配
memberlevelMapper.insert(cloneIgn... |
@Override
public FSDataOutputStream create(Path path, boolean overwrite, int bufferSize, short replication,
long blockSize, Progressable progress) throws IOException {
String confUmask = mAlluxioConf.getString(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK);
Mode mode =... | @Test
public void resetContextFromZookeeperToMultiMaster() throws Exception {
URI uri = URI.create(Constants.HEADER + "zk@zkHost:2181/tmp/path.txt");
FileSystem fs = getHadoopFilesystem(org.apache.hadoop.fs.FileSystem.get(uri, getConf()));
assertTrue(fs.mFileSystem.getConf().getBoolean(PropertyKey.ZOOKEEP... |
public SearchChainRegistry getSearchChainRegistry() { return executionFactory.searchChainRegistry();
} | @Test
synchronized void testWorkingReconfiguration() throws Exception {
assertJsonResult("http://localhost?query=abc", driver);
// reconfiguration
IOUtils.copyDirectory(new File(testDir, "handlers2"), new File(tempDir), 1);
generateComponentsConfigForActive();
configurer.rel... |
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
CommandContext commandContext = HttpCommandDecoder.decode(msg);
// return 404 when fail to construct command context
if (commandContext == null) {
log.warn(QOS_UNEXPECTED_EXCEPTIO... | @Test
void test3() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future);
HttpRequest message = Mockito.mock(HttpRequest.class... |
public static PinotFS getLocalPinotFs() {
return new LocalPinotFS();
} | @Test
public void testGetLocalPinotFs() {
assertTrue(MinionTaskUtils.getLocalPinotFs() instanceof LocalPinotFS);
} |
@Override
public V get() throws InterruptedException, ExecutionException {
return resolve(super.get());
} | @Test
public void test_get_Data_withTimeout() throws Exception {
Object value = "value";
DeserializingCompletableFuture<Object> future = new DeserializingCompletableFuture<>(serializationService, deserialize);
future.complete(serializationService.toData(value));
if (deserialize) {
... |
public static String processPattern(String pattern, TbMsg tbMsg) {
try {
String result = processPattern(pattern, tbMsg.getMetaData());
JsonNode json = JacksonUtil.toJsonNode(tbMsg.getData());
if (json.isObject()) {
Matcher matcher = DATA_PATTERN.matcher(result... | @Test
public void testArrayReplacementDoesNotWork() {
String pattern = "ABC ${key} $[key1.key2[0].key3]";
TbMsgMetaData md = new TbMsgMetaData();
md.putValue("key", "metadata_value");
ObjectNode key2Node = JacksonUtil.newObjectNode();
key2Node.put("key3", "value3");
... |
@Override
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
final String tag = namespace.getString("tag");
final Integer count = namespace.getInt("count");
final Date date = namespace.get("date");
final boolean dryRun = namespace.getBoolean("dry-run") != nu... | @Test
void testRollbackToDate() throws Exception {
// Migrate some DDL changes to the database
long migrationDate = System.currentTimeMillis();
migrateCommand.run(null, new Namespace(Map.of()), conf);
try (Handle handle = dbi.open()) {
assertThat(MigrationTestSupport.tab... |
@Override
public boolean isAvailable() {
try {
return multicastSocket != null;
} catch (Throwable t) {
return false;
}
} | @Test
void testAvailability() {
int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000));
MulticastRegistry registry = new MulticastRegistry(URL.valueOf("multicast://224.5.6.8:" + port));
assertTrue(registry.isAvailable());
} |
private Map<String, Object> augmentAndFilterConnectorConfig(String connectorConfigs) throws IOException {
return augmentAndFilterConnectorConfig(connectorConfigs, instanceConfig, secretsProvider,
componentClassLoader, componentType);
} | @Test
public void testSourceConfigParsingPreservesOriginalType() throws Exception {
final Map<String, Object> parsedConfig = JavaInstanceRunnable.augmentAndFilterConnectorConfig(
"{\"ttl\": 9223372036854775807}",
new InstanceConfig(),
new EnvironmentBasedSecre... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void deleteStickerFromSet() {
InputSticker inputSticker = new InputSticker("BQADAgADuAAD7yupS4eB23UmZhGuAg", Sticker.Format.Static, new String[]{"\uD83D\uDE15"});
BaseResponse response = bot.execute(new AddStickerToSet(chatId, stickerSet, inputSticker));
assertTrue(response.isOk... |
@Udf
public <T> T asValue(final T keyColumn) {
return keyColumn;
} | @Test
public void shouldHandlePrimitiveTypes() {
assertThat(udf.asValue(Boolean.TRUE), is(Boolean.TRUE));
assertThat(udf.asValue(Integer.MIN_VALUE), is(Integer.MIN_VALUE));
assertThat(udf.asValue(Long.MAX_VALUE), is(Long.MAX_VALUE));
assertThat(udf.asValue(Double.MAX_VALUE), is(Double.MAX_VALUE));
... |
@Override public Message receive() {
Message message = delegate.receive();
handleReceive(message);
return message;
} | @Test void receive_creates_consumer_span() throws Exception {
ActiveMQTextMessage message = new ActiveMQTextMessage();
receive(message);
MutableSpan consumer = testSpanHandler.takeRemoteSpan(CONSUMER);
assertThat(consumer.name()).isEqualTo("receive");
assertThat(consumer.name()).isEqualTo("receive"... |
public static byte[] checkPassword(String passwdString) {
if (Strings.isNullOrEmpty(passwdString)) {
return EMPTY_PASSWORD;
}
byte[] passwd;
passwdString = passwdString.toUpperCase();
passwd = passwdString.getBytes(StandardCharsets.UTF_8);
if (passwd.length !... | @Test
public void testCheckPassword() {
Assert.assertEquals("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32",
new String(MysqlPassword.checkPassword("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32")));
Assert.assertEquals("", new String(MysqlPassword.checkPassword(null)));
} |
@Override
public void execute(Exchange exchange) throws SmppException {
SubmitSm[] submitSms = createSubmitSm(exchange);
List<String> messageIDs = new ArrayList<>(submitSms.length);
String messageID = null;
for (int i = 0; i < submitSms.length; i++) {
SubmitSm submitSm =... | @Test
public void executeWithConfigurationData() throws Exception {
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm");
exchange.getIn().setHeader(SmppConstants.ID, "1");
exchange.ge... |
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (existsInTfsJar(name)) {
return jarClassLoader.loadClass(name);
}
return super.loadClass(name);
} | @Test
public void canLoadClassFromTopLevelOfJar() throws Exception {
assertThat(nestedJarClassLoader.loadClass(JAR_CLASS))
.isNotNull()
.hasPackage("");
} |
public Map<String, String> getLabels(String labelType) {
if (CollectionUtils.isEmpty(labels)) {
return Collections.emptyMap();
}
Map<String, String> subLabels = labels.get(labelType);
if (CollectionUtils.isEmpty(subLabels)) {
return Collections.emptyMap();
}
return Collections.unmodifiableMap(subLabel... | @Test
public void testGetEmptyRouterContext() {
PolarisRouterContext routerContext = new PolarisRouterContext();
assertThat(routerContext.getLabels(RouterConstant.TRANSITIVE_LABELS).size()).isEqualTo(0);
assertThat(routerContext.getLabels(RouterConstant.ROUTER_LABELS).size()).isEqualTo(0);
} |
@PostMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE)
public Boolean createNamespace(@RequestParam("customNamespaceId") String namespaceId,
@RequestParam("namespaceName") String namespaceName,
@RequestParam(value = "namesp... | @Test
void testCreateNamespaceWithIllegalCustomId() throws Exception {
assertFalse(namespaceController.createNamespace("test.Id", "testName", "testDesc"));
verify(namespaceOperationService, never()).createNamespace("test.Id", "testName", "testDesc");
} |
public void trackReceiveMessageData(String sfDate, String msgId) {
try {
if (mPushHandler.hasMessages(GT_PUSH_MSG) && mGeTuiPushInfoMap.containsKey(msgId)) {
mPushHandler.removeMessages(GT_PUSH_MSG);
SALog.i(TAG, "remove GeTui Push Message");
Notificat... | @Test
public void trackReceiveMessageData() {
SAHelper.initSensors(mApplication);
PushProcess.getInstance().trackReceiveMessageData("sdajh-asdjfhjas", "mock_123213");
} |
@Override
public void afterJob(JobExecution jobExecution) {
LOG.debug("sending after job execution event [{}]...", jobExecution);
producerTemplate.sendBodyAndHeader(endpointUri, jobExecution, EventType.HEADER_KEY, EventType.AFTER.name());
LOG.debug("sent after job execution event");
} | @Test
public void shouldSendAfterJobEvent() throws Exception {
// When
jobExecutionListener.afterJob(jobExecution);
// Then
assertEquals(jobExecution, consumer().receiveBody("seda:eventQueue"));
} |
@Override
public void handleTenantInfo(TenantInfoHandler handler) {
// 如果禁用,则不执行逻辑
if (isTenantDisable()) {
return;
}
// 获得租户
TenantDO tenant = getTenant(TenantContextHolder.getRequiredTenantId());
// 执行处理器
handler.handle(tenant);
} | @Test
public void testHandleTenantInfo_disable() {
// 准备参数
TenantInfoHandler handler = mock(TenantInfoHandler.class);
// mock 禁用
when(tenantProperties.getEnable()).thenReturn(false);
// 调用
tenantService.handleTenantInfo(handler);
// 断言
verify(handler,... |
@Override
public K8sNode removeNode(String hostname) {
checkArgument(!Strings.isNullOrEmpty(hostname), ERR_NULL_HOSTNAME);
K8sNode node = nodeStore.removeNode(hostname);
log.info(String.format(MSG_NODE, hostname, MSG_REMOVED));
return node;
} | @Test(expected = IllegalArgumentException.class)
public void testRemoveNullNode() {
target.removeNode(null);
} |
public void setSourceConnectorWrapper(SourceConnectorWrapper sourceConnectorWrapper) {
this.sourceConnectorWrapper = sourceConnectorWrapper;
} | @Test
void should_require_projectionFn() {
var wrapper = new SourceConnectorWrapper(minimalProperties(), 0, context);
assertThatThrownBy(() -> new ReadKafkaConnectP<>(noEventTime(), null)
.setSourceConnectorWrapper(wrapper))
.isInstanceOf(NullPointerException.class)
... |
public PackageDefinition getPackageDefinition() {
return packageDefinition;
} | @Test
public void shouldAddErrorIfPackageDoesNotExistsForGivenPackageId() throws Exception {
PipelineConfigSaveValidationContext configSaveValidationContext = mock(PipelineConfigSaveValidationContext.class);
when(configSaveValidationContext.findPackageById(anyString())).thenReturn(mock(PackageReposi... |
public static HttpRequestMessage getRequestFromChannel(Channel ch) {
return ch.attr(ATTR_ZUUL_REQ).get();
} | @Test
void headersAllCopied() {
ClientRequestReceiver receiver = new ClientRequestReceiver(null);
EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestEncoder());
PassportLoggingHandler loggingHandler = new PassportLoggingHandler(new DefaultRegistry());
// Required for messa... |
@Override
public InterpreterResult interpret(String st, InterpreterContext context)
throws InterpreterException {
try {
Properties finalProperties = new Properties();
finalProperties.putAll(getProperties());
Properties newProperties = new Properties();
newProperties.load(new StringR... | @Test
void testRunningAfterOtherInterpreter() throws InterpreterException {
assertTrue(interpreterFactory.getInterpreter("test.conf", executionContext) instanceof ConfInterpreter);
ConfInterpreter confInterpreter = (ConfInterpreter) interpreterFactory.getInterpreter("test.conf", executionContext);
Interp... |
@Description("natural logarithm")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double ln(@SqlType(StandardTypes.DOUBLE) double num)
{
return Math.log(num);
} | @Test
public void testLn()
{
for (double doubleValue : DOUBLE_VALUES) {
assertFunction("ln(" + doubleValue + ")", DOUBLE, Math.log(doubleValue));
}
assertFunction("ln(NULL)", DOUBLE, null);
} |
double nextRate(double rate, long periodNanos, long totalPublished, long totalReceived) {
long expected = (long) ((rate / ONE_SECOND_IN_NANOS) * periodNanos);
long published = totalPublished - previousTotalPublished;
long received = totalReceived - previousTotalReceived;
previousTotalPu... | @Test
void publishBacklog() {
assertThat(rateController.getRampingFactor()).isEqualTo(1);
// no backlog
rate = rateController.nextRate(rate, periodNanos, 10_000, 10_000);
assertThat(rate).isEqualTo(20_000);
assertThat(rateController.getRampingFactor()).isEqualTo(1);
... |
public static Deserializer<NeighborSolicitation> deserializer() {
return (data, offset, length) -> {
checkInput(data, offset, length, HEADER_LENGTH);
NeighborSolicitation neighborSolicitation = new NeighborSolicitation();
ByteBuffer bb = ByteBuffer.wrap(data, offset, length... | @Test
public void testDeserializeBadInput() throws Exception {
PacketTestUtils.testDeserializeBadInput(NeighborSolicitation.deserializer());
} |
public static String getTagValue( Node n, KettleAttributeInterface code ) {
return getTagValue( n, code.getXmlCode() );
} | @Test
public void getTagValueEmptyTagYieldsEmptyValue() {
System.setProperty( Const.KETTLE_XML_EMPTY_TAG_YIELDS_EMPTY_VALUE, "Y" );
assertEquals( "", XMLHandler.getTagValue( getNode(), "text" ) );
} |
@Override
@Deprecated
public <VR> KStream<K, VR> flatTransformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, Iterable<VR>> valueTransformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(valueTransf... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullStoreNamesOnFlatTransformValuesWithFlatValueSupplier() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransformValues(
flatValueTransforme... |
public static void initRequestEntity(HttpRequestBase requestBase, Object body, Header header) throws Exception {
if (body == null) {
return;
}
if (requestBase instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) reques... | @Test
void testInitRequestEntity2() throws Exception {
BaseHttpMethod.HttpGetWithEntity httpRequest = new BaseHttpMethod.HttpGetWithEntity("");
Header header = Header.newInstance();
header.addParam(HttpHeaderConsts.CONTENT_TYPE, "text/html");
HttpUtils.initRequestEntity(http... |
@Override
public CompletableFuture<Acknowledge> updateJobResourceRequirements(
JobResourceRequirements jobResourceRequirements) {
schedulerNG.updateJobResourceRequirements(jobResourceRequirements);
return CompletableFuture.completedFuture(Acknowledge.get());
} | @Test
public void testSuccessfulResourceRequirementsUpdate() throws Exception {
final CompletableFuture<JobResourceRequirements> schedulerUpdateFuture =
new CompletableFuture<>();
final TestingSchedulerNG scheduler =
TestingSchedulerNG.newBuilder()
... |
boolean convertDeviceProfileForVersion330(JsonNode profileData) {
boolean isUpdated = false;
if (profileData.has("alarms") && !profileData.get("alarms").isNull()) {
JsonNode alarms = profileData.get("alarms");
for (JsonNode alarm : alarms) {
if (alarm.has("createR... | @Test
void convertDeviceProfileAlarmRulesForVersion330NoAlarmNode() throws JsonProcessingException {
JsonNode spec = JacksonUtil.toJsonNode("{ \"configuration\": { \"type\": \"DEFAULT\" } }");
JsonNode expected = JacksonUtil.toJsonNode("{ \"configuration\": { \"type\": \"DEFAULT\" } }");
as... |
@SuppressWarnings("rawtypes")
public static ShardingStrategy newInstance(final ShardingStrategyConfiguration shardingStrategyConfig, final ShardingAlgorithm shardingAlgorithm, final String defaultShardingColumn) {
if (shardingStrategyConfig instanceof StandardShardingStrategyConfiguration && shardingAlgorit... | @Test
void assertNewInstanceForStandardShardingStrategyWithDefaultColumnStrategy() {
ShardingStrategy actual = ShardingStrategyFactory.newInstance(mock(StandardShardingStrategyConfiguration.class), mock(CoreStandardShardingAlgorithmFixture.class), "order_id");
assertTrue(actual.getShardingColumns().... |
@Override
public void verify(X509Certificate certificate, Date date) {
logger.debug("Verifying {} issued by {}", certificate.getSubjectX500Principal(),
certificate.getIssuerX500Principal());
// Create trustAnchors
final Set<TrustAnchor> trustAnchors = getTrusted().stream().map(
... | @Test
public void shouldVerifyCertificate() {
createCertificateService(
new String[] { "root.crt" }, new String[] { "intermediate.crt"},
new String[0], false
).verify(readCert("normal.crt"));
} |
protected void writeLogTableInformation( JobLogTable jobLogTable, LogStatus status ) throws KettleJobException,
KettleDatabaseException {
boolean cleanLogRecords = status.equals( LogStatus.END );
String tableName = jobLogTable.getActualTableName();
DatabaseMeta logcon = jobLogTable.getDatabaseMeta();
... | @Ignore( "Test is validating against a mock object... not a real test" )
@Test
public void recordsCleanUpMethodIsCalled_JobLogTable() throws Exception {
JobLogTable jobLogTable = JobLogTable.getDefault( mockedVariableSpace, hasDatabasesInterface );
setAllTableParamsDefault( jobLogTable );
doCallRealMet... |
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testRebalanceTimeoutLifecycle() {
String groupId = "fooup";
// Use a static member id as it makes the test easier.
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
Uuid fooTopicId = Uuid.randomUuid();
... |
public void onCheckpointComplete(long checkpointId) {
assignmentsByCheckpointId.entrySet().removeIf(entry -> entry.getKey() <= checkpointId);
} | @Test
void testOnCheckpointComplete() throws Exception {
final long checkpointId1 = 100L;
final long checkpointId2 = 101L;
SplitAssignmentTracker<MockSourceSplit> tracker = new SplitAssignmentTracker<>();
// Assign some splits to subtask 0 and 1.
tracker.recordSplitAssignmen... |
@SuppressWarnings("unchecked")
protected Set<PathSpec> getFields()
{
Object fields = _queryParams.get(RestConstants.FIELDS_PARAM);
if (fields == null) {
return Collections.emptySet();
}
if (fields instanceof Set)
{
return (Set<PathSpec>) fields;
}
else if (fields instanceof ... | @Test
public void testStringFieldsParam()
{
GetRequest<TestRecord> getRequest =
generateDummyRequestBuilder().setParam(RestConstants.FIELDS_PARAM, "id").build();
assertEquals(getRequest.getFields(), Collections.singleton(new PathSpec("id")));
} |
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> properties) throws Exception {
AS400ConnectionPool connectionPool;
if (properties.containsKey(CONNECTION_POOL)) {
LOG.trace("AS400ConnectionPool instance specified in the URI - will look it up."... | @Test
public void testCreatePgmSecuredEndpoint() throws Exception {
Endpoint endpoint = component
.createEndpoint(
"jt400://user:password@host/qsys.lib/library.lib/queue.pgm?connectionPool=#mockPool&secured=true");
assertNotNull(endpoint);
assertTrue(e... |
@Override
public Processor<KO, SubscriptionWrapper<K>, CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>> get() {
return new ContextualProcessor<KO, SubscriptionWrapper<K>, CombinedKey<KO, K>, Change<ValueAndTimestamp<SubscriptionWrapper<K>>>>() {
private TimestampedKeyValu... | @Test
public void shouldPropagateNullIfNoFKValAvailableV1() {
final StoreBuilder<TimestampedKeyValueStore<Bytes, SubscriptionWrapper<String>>> storeBuilder = storeBuilder();
final SubscriptionReceiveProcessorSupplier<String, String> supplier = supplier(storeBuilder);
final Processor<String,
... |
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) {
return containsAtLeastEntriesIn(accumulateMultimap(k0, v0, rest));
} | @Test
public void containsAtLeastVarargFailureMissing() {
ImmutableMultimap<Integer, String> expected =
ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four");
ListMultimap<Integer, String> actual = LinkedListMultimap.create(expected);
actual.remove(3, "six");
actual.remove(4... |
@Override
public Endpoints endpoints(String uid) {
checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_ENDPOINTS_UID);
return k8sEndpointsStore.endpoints(uid);
} | @Test
public void testGetEndpointsByUid() {
createBasicEndpoints();
assertNotNull("Endpoints did not match", target.endpoints(ENDPOINTS_UID));
assertNull("Endpoints did not match", target.endpoints(UNKNOWN_UID));
} |
@Override
public void callback(CallbackContext context) {
try {
onCallback(context);
} catch (IOException | ExecutionException e) {
throw new IllegalStateException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
... | @Test
public void callback_whenOrganizationsAreNotDefinedAndUserDoesntBelongToInstallationOrganization_shouldThrow() throws IOException, ExecutionException, InterruptedException {
UserIdentity userIdentity = mock(UserIdentity.class);
CallbackContext context = mockUserNotBelongingToOrganization(userIdentity);
... |
@Override
public boolean tryReturnRecordAt(boolean isAtSplitPoint, Long recordStart) {
return tryReturnRecordAt(isAtSplitPoint, recordStart.longValue());
} | @Test
public void testTryReturnRecordContinuesUntilSplitPoint() throws Exception {
OffsetRangeTracker tracker = new OffsetRangeTracker(9, 18);
// Return records with gaps of 2; every 3rd record is a split point.
assertTrue(tracker.tryReturnRecordAt(true, 10));
assertTrue(tracker.tryReturnRecordAt(fals... |
public static Instruction popMpls() {
return new L2ModificationInstruction.ModMplsHeaderInstruction(
L2ModificationInstruction.L2SubType.MPLS_POP,
EthType.EtherType.MPLS_UNICAST.ethType());
} | @Test
public void testPopMplsEthertypeMethod() {
final Instruction instruction = Instructions.popMpls(new EthType(1));
final L2ModificationInstruction.ModMplsHeaderInstruction pushHeaderInstruction =
checkAndConvert(instruction,
Instruction.Type.L2MODI... |
public static CommandContext decode(HttpRequest request) {
CommandContext commandContext = null;
if (request != null) {
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
String path = queryStringDecoder.path();
String[] array = path.split(... | @Test
void decodeGet() {
HttpRequest request = mock(HttpRequest.class);
when(request.uri()).thenReturn("localhost:80/test");
when(request.method()).thenReturn(HttpMethod.GET);
CommandContext context = HttpCommandDecoder.decode(request);
assertThat(context.getCommandName(), eq... |
@SafeVarargs
public static <T> List<T> unionAll(Collection<T> coll1, Collection<T> coll2, Collection<T>... otherColls) {
if (CollUtil.isEmpty(coll1) && CollUtil.isEmpty(coll2) && ArrayUtil.isEmpty(otherColls)) {
return new ArrayList<>(0);
}
// 计算元素总数
int totalSize = 0;
totalSize += size(coll1);
totalSi... | @SuppressWarnings({"ConfusingArgumentToVarargsMethod", "ConstantValue"})
@Test
public void unionAllNullTest() {
final List<String> list1 = new ArrayList<>();
final List<String> list2 = null;
final List<String> list3 = null;
final List<String> list = CollUtil.unionAll(list1, list2, list3);
assertNotNull(list... |
@SuppressWarnings("unchecked")
public static <S, F> S visit(final Schema schema, final Visitor<S, F> visitor) {
final BiFunction<Visitor<?, ?>, Schema, Object> handler = HANDLER.get(schema.type());
if (handler == null) {
throw new UnsupportedOperationException("Unsupported schema type: " + schema.type()... | @Test
public void shouldVisitPrimitives() {
// Given:
visitor = new Visitor<String, Integer>() {
@Override
public String visitPrimitive(final Schema schema) {
return "Expected";
}
};
primitiveSchemas().forEach(schema -> {
// When:
final String result = SchemaWal... |
@Bean
public RetryRegistry retryRegistry(RetryConfigurationProperties retryConfigurationProperties,
EventConsumerRegistry<RetryEvent> retryEventConsumerRegistry,
RegistryEventConsumer<Retry> retryRegistryEventConsumer,
@Qualifier("compositeRetryCustomizer") CompositeCustomizer<RetryConfigCus... | @Test
public void testRetryRegistry() {
InstanceProperties instanceProperties1 = new InstanceProperties();
instanceProperties1.setMaxAttempts(3);
InstanceProperties instanceProperties2 = new InstanceProperties();
instanceProperties2.setMaxAttempts(2);
RetryConfigurationProper... |
public static DenseSparseMatrix createIdentity(int dimension) {
SparseVector[] newValues = new SparseVector[dimension];
for (int i = 0; i < dimension; i++) {
newValues[i] = new SparseVector(dimension, new int[]{i}, new double[]{1.0});
}
return new DenseSparseMatrix(newValues)... | @Test
public void testCreateIdentity() {
DenseSparseMatrix identity = DenseSparseMatrix.createIdentity(5);
assertMatrixEquals(new DenseMatrix(new double[][]{new double[]{1.0, 0.0, 0.0, 0.0, 0.0}, new double[]{0.0, 1.0, 0.0, 0.0, 0.0}, new double[]{0.0, 0.0, 1.0, 0.0, 0.0}, new double[]{0.0, 0.0, 0.0... |
public static URL parseURL(String address, Map<String, String> defaults) {
if (StringUtils.isEmpty(address)) {
throw new IllegalArgumentException("Address is not allowed to be empty, please re-enter.");
}
String url;
if (address.contains("://") || address.contains(URL_PARAM_S... | @Test
void testDefaultUrl() {
String address = "127.0.0.1";
URL url = UrlUtils.parseURL(address, null);
assertEquals(localAddress + ":9090", url.getAddress());
assertEquals(9090, url.getPort());
assertEquals("dubbo", url.getProtocol());
assertNull(url.getUsername());
... |
public List<Periodical> getAll() {
return Lists.newArrayList(periodicals);
} | @Test
public void testGetAll() throws Exception {
periodicals.registerAndStart(periodical);
assertEquals("getAll() did not return all periodicals", Lists.newArrayList(periodical), periodicals.getAll());
} |
public Schema mergeTables(
Map<FeatureOption, MergingStrategy> mergingStrategies,
Schema sourceSchema,
List<SqlNode> derivedColumns,
List<SqlWatermark> derivedWatermarkSpecs,
SqlTableConstraint derivedPrimaryKey) {
SchemaBuilder schemaBuilder =
... | @Test
void mergeOverwritingGeneratedColumnsDuplicate() {
Schema sourceSchema =
Schema.newBuilder()
.column("one", DataTypes.INT())
.columnByExpression("two", "one + 1")
.build();
List<SqlNode> derivedColumns =
... |
@Override
@Async
public void updateJobLogResultAsync(Long logId, LocalDateTime endTime, Integer duration, boolean success, String result) {
try {
JobLogDO updateObj = JobLogDO.builder().id(logId).endTime(endTime).duration(duration)
.status(success ? JobLogStatusEnum.SUCCE... | @Test
public void testUpdateJobLogResultAsync_failure() {
// mock 数据
JobLogDO log = randomPojo(JobLogDO.class, o -> {
o.setExecuteIndex(1);
o.setStatus(JobLogStatusEnum.RUNNING.getStatus());
});
jobLogMapper.insert(log);
// 准备参数
Long logId = lo... |
public static ProxyBackendHandler newInstance(final DatabaseType databaseType, final String sql, final SQLStatement sqlStatement,
final ConnectionSession connectionSession, final HintValueContext hintValueContext) throws SQLException {
if (sqlStatement instanceo... | @Test
void assertNewInstanceWithRQLStatementInTransaction() throws SQLException {
when(connectionSession.getTransactionStatus().isInTransaction()).thenReturn(true);
String sql = "SHOW DEFAULT SINGLE TABLE STORAGE UNIT";
SQLStatement sqlStatement = ProxySQLComQueryParser.parse(sql, databaseTy... |
@Override
public void start(Callback<None> callback) {
LOG.info("{} enabled", _printName);
Callback<None> prepareWarmUpCallback = new Callback<None>() {
@Override
public void onError(Throwable e) {
if (e instanceof TimeoutException)
{
LOG.info("{} hit timeout: {}ms. The ... | @Test(timeOut = 10000, retryAnalyzer = ThreeRetries.class)
public void testHitTimeout() throws URISyntaxException, InterruptedException, ExecutionException, TimeoutException
{
int NRequests = 5000;
int warmUpTimeout = 2;
int concurrentRequests = 5;
int requestTime = 100;
float requestsPerSecond... |
public static Code httpStatusToGrpcCode(int httpStatusCode) {
if (httpStatusCode >= 100 && httpStatusCode < 200) {
return Code.INTERNAL;
}
if (httpStatusCode == HttpResponseStatus.BAD_REQUEST.code()
|| httpStatusCode == HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LAR... | @Test
void httpStatusToGrpcCode() {
Assertions.assertEquals(Code.UNIMPLEMENTED, TriRpcStatus.httpStatusToGrpcCode(404));
Assertions.assertEquals(
Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.BAD_GATEWAY.code()));
Assertions.assertEquals(
... |
public static List<String> mergeValues(
ExtensionDirector extensionDirector, Class<?> type, String cfg, List<String> def) {
List<String> defaults = new ArrayList<>();
if (def != null) {
for (String name : def) {
if (extensionDirector.getExtensionLoader(type).hasEx... | @Test
void testMergeValues() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"aaa,bbb,default.custom",
asList("fixed", "default.limited", "cached"));
assertEqual... |
@Override
public TopicList fetchAllTopicList() throws RemotingException, MQClientException, InterruptedException {
return this.defaultMQAdminExtImpl.fetchAllTopicList();
} | @Test
public void testFetchAllTopicList() throws RemotingException, MQClientException, InterruptedException {
TopicList topicList = defaultMQAdminExt.fetchAllTopicList();
assertThat(topicList.getTopicList().size()).isEqualTo(2);
assertThat(topicList.getTopicList()).contains("topic_one");
... |
public static String getJsonToSave(@Nullable final List<Tab> tabList) {
final JsonStringWriter jsonWriter = JsonWriter.string();
jsonWriter.object();
jsonWriter.array(JSON_TABS_ARRAY_KEY);
if (tabList != null) {
for (final Tab tab : tabList) {
tab.writeJsonOn... | @Test
public void testSaveAndReading() throws JsonParserException {
// Saving
final Tab.BlankTab blankTab = new Tab.BlankTab();
final Tab.DefaultKioskTab defaultKioskTab = new Tab.DefaultKioskTab();
final Tab.SubscriptionsTab subscriptionsTab = new Tab.SubscriptionsTab();
fin... |
@Override public void pluginAdded( final Object serviceObject ) {
try {
SpoonPluginInterface spoonPluginInterface =
(SpoonPluginInterface) getPluginRegistry().loadClass( (PluginInterface) serviceObject );
if ( plugins.get( serviceObject ) != null ) {
return;
}
SpoonPluginC... | @Test
public void testPluginAdded() throws Exception {
spoonPluginManager.pluginAdded( plugin1 );
verify( spoonPerspectiveManager ).addPerspective( spoonPerspective );
assertEquals( 1, spoonPluginManager.getPlugins().size() );
assertSame( spoonPluginInterface1, spoonPluginManager.getPlugins().get( 0 ... |
@Override
public void eventAdded( KettleLoggingEvent event ) {
Object messageObject = event.getMessage();
checkNotNull( messageObject, "Expected log message to be defined." );
if ( messageObject instanceof LogMessage ) {
LogMessage message = (LogMessage) messageObject;
LoggingObjectInterface l... | @Test
public void testAddLogEventTrans() {
when( logObjProvider.apply( logChannelId ) ).thenReturn( loggingObject );
when( loggingObject.getObjectType() ).thenReturn( LoggingObjectType.TRANS );
when( loggingObject.getFilename() ).thenReturn( "filename" );
when( message.getLevel() ).thenReturn( LogLeve... |
@Override
public Num calculate(BarSeries series, Position position) {
if (position.isClosed()) {
Num loss = excludeCosts ? position.getGrossProfit() : position.getProfit();
return loss.isNegative() ? loss : series.zero();
}
return series.zero();
} | @Test
public void calculateOnlyWithProfitPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series),
Trade.buyAt(3, series), Trade.sellAt(5, seri... |
@PostMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX
+ "namespaces", action = ActionTypes.WRITE, signType = SignType.CONSOLE)
public Result<Boolean> createNamespace(NamespaceForm namespaceForm) throws NacosException {
namespaceForm.validate();
... | @Test
void testCreateNamespaceWithNonUniqueId() {
when(namespacePersistService.tenantInfoCountByTenantId("test-id")).thenReturn(1);
NamespaceForm form = new NamespaceForm();
form.setNamespaceId("test-id");
form.setNamespaceDesc("testDesc");
form.setNamespaceName("testName");
... |
public Operation parseMethod(
Method method,
List<Parameter> globalParameters,
JsonView jsonViewAnnotation) {
JavaType classType = TypeFactory.defaultInstance().constructType(method.getDeclaringClass());
return parseMethod(
classType.getClass(),
... | @Test(description = "Deprecated Method")
public void testDeprecatedMethod() {
Reader reader = new Reader(new OpenAPI());
Method[] methods = DeprecatedFieldsResource.class.getMethods();
Operation deprecatedOperation = reader.parseMethod(methods[0], null, null);
assertNotNull(deprecate... |
public static PrimitiveIterator.OfInt all(int pageCount) {
return new IndexIterator(0, pageCount, i -> true, i -> i);
} | @Test
public void testAll() {
assertEquals(IndexIterator.all(10), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
} |
public SourceWithMetadata lookupSource(int globalLineNumber, int sourceColumn)
throws IncompleteSourceWithMetadataException {
LineToSource lts = this.sourceReferences().stream()
.filter(lts1 -> lts1.includeLine(globalLineNumber))
.findFirst()
.orElseTh... | @Test
public void testSourceAndLineRemapping_pipelineDefinedMInMultipleFiles() throws IncompleteSourceWithMetadataException {
final SourceWithMetadata[] parts = {
new SourceWithMetadata("file", "/tmp/input", 0, 0, PIPELINE_CONFIG_PART_1),
new SourceWithMetadata("file", "/tmp/... |
@Override
public <T> List<T> toList(DataTable dataTable, Type itemType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(itemType, "itemType may not be null");
if (dataTable.isEmpty()) {
return emptyList();
}
ListOrProblems<T> result = to... | @Test
void convert_to_list__double_column__single_row__throws_exception() {
DataTable table = parse("",
"| 3 | 5 |");
CucumberDataTableException exception = assertThrows(
CucumberDataTableException.class,
() -> converter.toList(table, Integer.class));
ass... |
@Override
public Mono<GetExternalServiceCredentialsResponse> getExternalServiceCredentials(final GetExternalServiceCredentialsRequest request) {
final ExternalServiceCredentialsGenerator credentialsGenerator = this.credentialsGeneratorByType
.get(request.getExternalService());
if (credentialsGenerator... | @Test
public void testRateLimitExceeded() throws Exception {
final Duration retryAfter = MockUtils.updateRateLimiterResponseToFail(
rateLimiters, RateLimiters.For.EXTERNAL_SERVICE_CREDENTIALS, AUTHENTICATED_ACI, Duration.ofSeconds(100), false);
Mockito.reset(ART_CREDENTIALS_GENERATOR);
assertRateL... |
@Override
public void onNewActivity(Activity activity) {
} | @Test
public void onNewActivity_activityIsNotTheOneLaunchedByNotifs_dontClearInitialNotification() throws Exception {
Activity activity = mock(Activity.class);
Intent intent = mock(Intent.class);
when(activity.getIntent()).thenReturn(intent);
when(mAppLaunchHelper.isLaunchIntentsActi... |
public static Instant fromMillisOrIso8601(String time, String fieldName) {
try {
return Instant.ofEpochMilli(Long.parseLong(time));
} catch (NumberFormatException nfe) {
// TODO: copied from PluginConfigurationProcessor, find a way to share better
try {
DateTimeFormatter formatter =
... | @Test
public void testFromMillisOrIso8601_millis() {
Instant parsed = Instants.fromMillisOrIso8601("100", "ignored");
Assert.assertEquals(Instant.ofEpochMilli(100), parsed);
} |
@Override
public ResultSet getColumnPrivileges(final String catalog, final String schema, final String table, final String columnNamePattern) throws SQLException {
return createDatabaseMetaDataResultSet(
getDatabaseMetaData().getColumnPrivileges(getActualCatalog(catalog), getActualSchema(sch... | @Test
void assertGetColumnPrivileges() throws SQLException {
when(databaseMetaData.getColumnPrivileges("test", null, null, null)).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getColumnPrivileges("test", null, null, null), instanceOf(DatabaseMetaDataResultSet.class));
} |
public Person create(Person person) {
return persist(person);
} | @Test
void handlesNullFullName() {
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(()->
daoTestRule.inTransaction(() -> personDAO.create(new Person(null, "The null", 0))));
} |
@Override
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
int type = columnDef.getColumnMeta() >> 8;
int length = columnDef.getColumnMeta() & 0xff;
// unpack type & length, see https://bugs.mysql.com/bug.php?id=37426.
if (0x30 != (ty... | @Test
void assertReadLongStringValue() {
String expected = "test_value";
columnDef.setColumnMeta((MySQLBinaryColumnType.STRING.getValue() ^ ((256 & 0x300) >> 4)) << 8);
when(payload.getByteBuf()).thenReturn(byteBuf);
when(byteBuf.readUnsignedShortLE()).thenReturn(expected.length());
... |
@Udf
public String trim(
@UdfParameter(
description = "The string to trim") final String input) {
if (input == null) {
return null;
}
return input.trim();
} | @Test
public void shouldRemoveLeadingWhitespace() {
final String result = udf.trim(" \t Foo Bar");
assertThat(result, is("Foo Bar"));
} |
public static void main(String[] args) {
var simpleWizard = new SimpleWizard();
simpleWizard.smoke();
var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());
advancedWizard.smoke();
var advancedSorceress = new AdvancedSorceress();
advancedSorceress.setTobacco(new SecondBreakfast... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
CommandContext commandContext = HttpCommandDecoder.decode(msg);
// return 404 when fail to construct command context
if (commandContext == null) {
log.warn(QOS_UNEXPECTED_EXCEPTIO... | @Test
void test2() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
ChannelFuture future = mock(ChannelFuture.class);
when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future);
HttpRequest message = Mockito.mock(HttpRequest.class... |
@Override
public Consumer createConsumer(Processor aProcessor) throws Exception {
// validate that all of the endpoint is configured properly
if (getMonitorType() != null) {
if (!isPlatformServer()) {
throw new IllegalArgumentException(ERR_PLATFORM_SERVER);
}... | @Test
public void noNotifyDifferOrNotifyMatch() throws Exception {
JMXEndpoint ep = context.getEndpoint(
"jmx:platform?objectDomain=FooDomain&objectName=theObjectName&monitorType=string&observedAttribute=foo&stringToCompare=foo",
JMXEndpoint.class);
try {
... |
WhitespaceArgumentDelimiter getSqlDelimiter() {
return this.sqlDelimiter;
} | @Test
void testSqlDelimiterCharacters() {
assertTrue(sqlCompleter.getSqlDelimiter().isDelimiterChar("r,", 1));
assertTrue(sqlCompleter.getSqlDelimiter().isDelimiterChar("SS,", 2));
assertTrue(sqlCompleter.getSqlDelimiter().isDelimiterChar(",", 0));
assertTrue(sqlCompleter.getSqlDelimiter().isDelimiter... |
@Override
public MapperResult getGroupIdList(MapperContext context) {
return new MapperResult(
"SELECT group_id FROM config_info WHERE tenant_id ='" + NamespaceUtil.getNamespaceDefaultId()
+ "' GROUP BY group_id OFFSET " + context.getStartRow() + " ROWS FETCH... | @Test
void testGetGroupIdList() {
MapperResult mapperResult = configInfoMapperByDerby.getGroupIdList(context);
assertEquals(mapperResult.getSql(),
"SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id OFFSET " + startRow + " ROWS FETCH NEXT " + pageSize
... |
@Override
public <T_OTHER, OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> connectAndProcess(
NonKeyedPartitionStream<T_OTHER> other,
TwoInputNonBroadcastStreamProcessFunction<T, T_OTHER, OUT> processFunction) {
validateStates(
processFunction.usesStates(),
... | @Test
void testConnectBroadcastStream() throws Exception {
ExecutionEnvironmentImpl env = StreamTestUtils.getEnv();
NonKeyedPartitionStreamImpl<Long> stream =
new NonKeyedPartitionStreamImpl<>(
env, new TestingTransformation<>("t1", Types.LONG, 1));
st... |
public synchronized String get() {
ConfidentialStore cs = ConfidentialStore.get();
if (secret == null || cs != lastCS) {
lastCS = cs;
try {
byte[] payload = load();
if (payload == null) {
payload = cs.randomBytes(length / 2);
... | @Test
public void loadingExistingKey() {
HexStringConfidentialKey key1 = new HexStringConfidentialKey("test", 8);
key1.get(); // this causes the ke to be generated
// this second key of the same ID will cause it to load the key from the disk
HexStringConfidentialKey key2 = new HexSt... |
@Override
public ByteBuf getBytes(int index, byte[] dst) {
getBytes(index, dst, 0, dst.length);
return this;
} | @Test
public void testGetBytesAfterRelease4() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().getBytes(0, new byte[8]);
}
});
} |
public static long getPreMinuteMills(long rightnow) {
return rightnow - (rightnow % MILLISECONDS_PER_MINUTE) - 1;
} | @Test
public void getPreMinuteMills() throws Exception {
long now = System.currentTimeMillis();
long pre = DateUtils.getPreMinuteMills(now);
Assert.assertTrue(now - pre < 60000);
} |
@Override
public void checkAuthorization(
final KsqlSecurityContext securityContext,
final MetaStore metaStore,
final Statement statement
) {
if (statement instanceof Query) {
validateQuery(securityContext, metaStore, (Query)statement);
} else if (statement instanceof InsertInto) {
... | @Test
public void shouldThrowWhenJoinSelectWithoutReadPermissionsDenied() {
// Given:
givenTopicAccessDenied(KAFKA_TOPIC, AclOperation.READ);
final Statement statement = givenStatement(String.format(
"SELECT * FROM %s A JOIN %s B ON A.F1 = B.F1;", KAFKA_STREAM_TOPIC, AVRO_STREAM_TOPIC)
);
... |
@Override
public boolean add(FilteredBlock block) throws VerificationException, PrunedException {
boolean success = super.add(block);
if (success) {
trackFilteredTransactions(block.getTransactionCount());
}
return success;
} | @Test(expected = VerificationException.class)
public void difficultyTransitions_unexpectedChange() throws Exception {
Context.propagate(new Context(100, Coin.ZERO, false, true));
BlockChain chain = new BlockChain(BitcoinNetwork.MAINNET, new MemoryBlockStore(MAINNET.getGenesisBlock()));
// ge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.