focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public List<HasMetadata> buildAccompanyingKubernetesResources() throws IOException {
final List<HasMetadata> resources = new ArrayList<>();
if (!StringUtils.isNullOrWhitespaceOnly(securityConfig.getKeytab())
&& !StringUtils.isNullOrWhitespaceOnly(securityConfig.getPrincip... | @Test
void testConfEditWhenBuildAccompanyingKubernetesResources() throws IOException {
kerberosMountDecorator.buildAccompanyingKubernetesResources();
assertThat(
this.testingKubernetesParameters
.getFlinkConfiguration()
... |
@Override
protected boolean isAddOnEnabledByDefault(@NonNull String addOnId) {
final KeyboardAddOnAndBuilder addOnById = getAddOnById(addOnId);
return super.isAddOnEnabledByDefault(addOnId)
|| (addOnById != null && addOnById.getKeyboardDefaultEnabled());
} | @Test
public void testDefaultKeyboardId() {
final List<KeyboardAddOnAndBuilder> allAddOns = mKeyboardFactory.getAllAddOns();
Assert.assertEquals(13, allAddOns.size());
KeyboardAddOnAndBuilder addon = mKeyboardFactory.getEnabledAddOn();
Assert.assertNotNull(addon);
Assert.assertEquals("c7535083-4fe... |
@POST
@ApiOperation("Get all views that match given parameter value")
@NoAuditEvent("Only returning matching views, not changing any data")
public Collection<ViewParameterSummaryDTO> forParameter(@Context SearchUser searchUser) {
return qualifyingViewsService.forValue()
.stream()
... | @Test
public void returnsSomeViewsIfSomeArePermitted() {
final SearchUser searchUser = TestSearchUser.builder()
.denyView("view1")
.allowView("view2")
.build();
final QualifyingViewsService service = mockViewsService("view1", "view2");
final... |
@Override
public void register(String path, ServiceRecord record) throws IOException {
op(path, record, addRecordCommand);
} | @Test
public void testReverseLookup() throws Exception {
ServiceRecord record = getMarshal().fromBytes("somepath",
CONTAINER_RECORD.getBytes());
getRegistryDNS().register(
"/registry/users/root/services/org-apache-slider/test1/components/"
+ "ctr-e50-1451931954322-0016-01-000002",
... |
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final Map<Path, List<ObjectKeyAndVersion>> map = new HashMap<>();
final List<Path> containers = new ArrayList<>();
for(Path file : files.keySet()) {
... | @Test
public void testDeleteNotFoundKey() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final List<ObjectKeyAndVersion> keys = new ArrayList<>();
for(int i = 0; i < 1010; i++) {
keys.add(new O... |
@GET
@Path("/{entityType}")
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8
/* , MediaType.APPLICATION_XML */})
public TimelineEntities getEntities(
@Context HttpServletRequest req,
@Context HttpServletResponse res,
@PathParam("entityType") String entityType,
@QueryP... | @Test
void testGetEntities() throws Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("timeline")
.path("type_1")
.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils... |
public static StepRuntimeState retrieveStepRuntimeState(
Map<String, Object> data, ObjectMapper objectMapper) {
Object runtimeSummary =
data.getOrDefault(Constants.STEP_RUNTIME_SUMMARY_FIELD, Collections.emptyMap());
if (runtimeSummary instanceof StepRuntimeSummary) {
return ((StepRuntimeSum... | @Test
public void testRetrieveStepRuntimeStateJson() {
StepRuntimeState expected = new StepRuntimeState();
expected.setStatus(StepInstance.Status.RUNNING);
Assert.assertEquals(
expected,
StepHelper.retrieveStepRuntimeState(
singletonMap(
Constants.STEP_RUNTIME_S... |
@Override
public void execute() {
ddbClient.updateTable(UpdateTableRequest.builder().tableName(determineTableName())
.provisionedThroughput(ProvisionedThroughput.builder().readCapacityUnits(determineReadCapacity())
.writeCapacityUnits(determineWriteCapacity()).build()... | @Test
public void testExecute() {
command.execute();
assertEquals("DOMAIN1", ddbClient.updateTableRequest.tableName());
assertEquals(Long.valueOf(20), ddbClient.updateTableRequest.provisionedThroughput().readCapacityUnits());
assertEquals(Long.valueOf(30), ddbClient.updateTableReque... |
public static String getPartitionNameFromPartitionType(MetadataPartitionType partitionType, HoodieTableMetaClient metaClient, String indexName) {
if (MetadataPartitionType.FUNCTIONAL_INDEX.equals(partitionType)) {
checkArgument(metaClient.getIndexMetadata().isPresent(), "Index definition is not present");
... | @Test
public void testGetNonFunctionalIndexPath() {
MetadataPartitionType partitionType = MetadataPartitionType.COLUMN_STATS;
HoodieTableMetaClient metaClient = mock(HoodieTableMetaClient.class);
String result = HoodieIndexUtils.getPartitionNameFromPartitionType(partitionType, metaClient, null);
asse... |
public int getSequenceNumber() {
return this.sequenceNumber;
} | @Test
public void testGetSequenceNumber() throws Exception {
assertEquals(3, buildChunk().getSequenceNumber());
} |
public static SFCertificateTrustPanel sharedCertificateTrustPanel() {
return Rococoa.createClass("SFCertificateTrustPanel", SFCertificateTrustPanel._Class.class).sharedCertificateTrustPanel();
} | @Test
public void sharedCertificateTrustPanel() {
assertNotNull(SFCertificateTrustPanel.sharedCertificateTrustPanel());
} |
@Override
public void commitJob(JobContext originalContext) throws IOException {
commitJobs(Collections.singletonList(originalContext), Operation.OTHER);
} | @Test
public void testSuccessfulUnpartitionedWrite() throws IOException {
HiveIcebergOutputCommitter committer = new HiveIcebergOutputCommitter();
Table table = table(temp.getRoot().getPath(), false);
JobConf conf = jobConf(table, 1);
List<Record> expected = writeRecords(table.name(), 1, 0, true, fal... |
public static String buildRulePath(final String pluginName, final String selectorId, final String ruleId) {
return String.join(PATH_SEPARATOR, buildRuleParentPath(pluginName), String.join(SELECTOR_JOIN_RULE, selectorId, ruleId));
} | @Test
public void testBuildRulePath() {
String pluginName = RandomStringUtils.randomAlphanumeric(10);
String selectorId = RandomStringUtils.randomAlphanumeric(10);
String ruleId = RandomStringUtils.randomAlphanumeric(10);
String rulePath = DefaultPathConstants.buildRulePath(pluginNam... |
public static char randomNumber() {
return randomChar(BASE_NUMBER);
} | @Test
public void randomNumberTest() {
final char c = RandomUtil.randomNumber();
assertTrue(c <= '9');
} |
@VisibleForTesting
static void initAddrUseFqdn(List<InetAddress> addrs) {
useFqdn = true;
analyzePriorityCidrs();
String fqdn = null;
if (PRIORITY_CIDRS.isEmpty()) {
// Get FQDN from local host by default.
try {
InetAddress localHost = InetAdd... | @Test(expected = IllegalAccessException.class)
public void testGetStartWithFQDNGetNameGetNull() {
testInitAddrUseFqdnCommonMock();
List<InetAddress> hosts = NetUtils.getHosts();
new MockUp<InetAddress>() {
@Mock
public InetAddress getLocalHost() throws UnknownHostExce... |
@SuppressWarnings("unchecked")
public static List<Object> asList(final Object key) {
final Optional<Windowed<Object>> windowed = key instanceof Windowed
? Optional.of((Windowed<Object>) key)
: Optional.empty();
final Object naturalKey = windowed
.map(Windowed::key)
.orElse(key... | @Test
public void shouldConvertNullKeyToList() {
// Given:
final GenericKey key = GenericKey.genericKey((Object)null);
// When:
final List<?> result = KeyUtil.asList(key);
// Then:
assertThat(result, is(Collections.singletonList((null))));
} |
@Override
public void setConf(Configuration conf) {
if (conf != null) {
conf = addSecurityConfiguration(conf);
}
super.setConf(conf);
} | @Test
public void testMonitoringOperationsWithAutoHaEnabled() throws Exception {
Mockito.doReturn(STANDBY_READY_RESULT).when(mockProtocol).getServiceStatus();
// Turn on auto-HA
HdfsConfiguration conf = getHAConf();
conf.setBoolean(DFSConfigKeys.DFS_HA_AUTO_FAILOVER_ENABLED_KEY, true);
tool.setCo... |
public URI next() {
URI result = _uris.get(_index);
_index = (_index + 1) % _uris.size();
return result;
} | @Test
public void testHostAddressRoundRobin()
throws URISyntaxException, UnknownHostException {
InetAddress[] testWebAddresses = new InetAddress[]{
InetAddress.getByAddress("testweb.com", InetAddresses.forString("192.168.3.1").getAddress()),
InetAddress.getByAddress("testweb.com", InetAddre... |
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteCodegen(Long tableId) {
// 校验是否已经存在
if (codegenTableMapper.selectById(tableId) == null) {
throw exception(CODEGEN_TABLE_NOT_EXISTS);
}
// 删除 table 表定义
codegenTableMapper.deleteById(tabl... | @Test
public void testDeleteCodegen_notExists() {
assertServiceException(() -> codegenService.deleteCodegen(randomLongId()),
CODEGEN_TABLE_NOT_EXISTS);
} |
@Override
public NativeReader<?> create(
CloudObject spec,
@Nullable Coder<?> coder,
@Nullable PipelineOptions options,
@Nullable DataflowExecutionContext executionContext,
DataflowOperationContext operationContext)
throws Exception {
@SuppressWarnings("unchecked")
Coder<Ob... | @Test
public void testCreateConcatReaderWithManySubSources() throws Exception {
List<List<String>> allData = createInMemorySourceData(15, 10);
Source source = createSourcesWithInMemorySources(allData);
@SuppressWarnings("unchecked")
NativeReader<String> reader =
(NativeReader<String>) Reader... |
@Override
public void preAction(WebService.Action action, Request request) {
Level logLevel = getLogLevel();
String deprecatedSinceEndpoint = action.deprecatedSince();
if (deprecatedSinceEndpoint != null) {
logWebServiceMessage(logLevel, deprecatedSinceEndpoint);
}
action.params().forEach(... | @Test
@UseDataProvider("userSessions")
public void preAction_whenParameterIsDeprecatedAndNoReplacementAndBrowserSession_shouldLogWarning(boolean isLoggedIn, boolean isAuthenticatedBrowserSession, Level expectedLogLevel) {
when(userSession.hasSession()).thenReturn(true);
when(userSession.isLoggedIn()).thenRe... |
public Sensor topicLevelSensor(final String threadId,
final String taskId,
final String processorNodeName,
final String topicName,
final String sensorSuffix,
... | @Test
public void shouldGetNewTopicLevelSensor() {
final Metrics metrics = mock(Metrics.class);
final RecordingLevel recordingLevel = RecordingLevel.INFO;
setupGetNewSensorTest(metrics, recordingLevel);
final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, CLIENT_... |
@Override
public MapperResult findAllConfigInfoBetaForDumpAllFetchRows(MapperContext context) {
Integer startRow = context.getStartRow();
int pageSize = context.getPageSize();
String sql = "SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips "
+... | @Test
void testFindAllConfigInfoBetaForDumpAllFetchRows() {
MapperResult result = configInfoBetaMapperByDerby.findAllConfigInfoBetaForDumpAllFetchRows(context);
String sql = result.getSql();
List<Object> paramList = result.getParamList();
assertEquals(sql, "SELECT t.id,data_id,group_... |
public static <V> SetOnceReference<V> unset() {
return new SetOnceReference<>();
} | @Test
public void testFromUnset() {
checkUnsetReference(SetOnceReference.unset());
} |
public <T> Map<String, Object> schemas(Class<? extends T> cls) {
return this.schemas(cls, false);
} | @SuppressWarnings("unchecked")
@Test
void returnTask() throws URISyntaxException {
Helpers.runApplicationContext((applicationContext) -> {
JsonSchemaGenerator jsonSchemaGenerator = applicationContext.getBean(JsonSchemaGenerator.class);
Map<String, Object> returnSchema = jsonSche... |
static Set<PipelineOptionSpec> getOptionSpecs(
Class<? extends PipelineOptions> optionsInterface, boolean skipHidden) {
Iterable<Method> methods = ReflectHelpers.getClosureOfMethodsOnInterface(optionsInterface);
Multimap<String, Method> propsToGetters = getPropertyNamesToGetters(methods);
ImmutableSe... | @Test
public void testIncludesHiddenInterfaces() {
Set<PipelineOptionSpec> properties =
PipelineOptionsReflector.getOptionSpecs(HiddenOptions.class, false);
assertThat(properties, hasItem(hasName("foo")));
} |
@Override
public Iterator<QueryableEntry> iterator() {
return new It();
} | @Test
public void contains_matchingPredicate_notInResult() {
Set<QueryableEntry> entries = generateEntries(100000);
List<Set<QueryableEntry>> otherIndexedResults = new ArrayList<>();
otherIndexedResults.add(Collections.emptySet());
AndResultSet resultSet = new AndResultSet(entries, o... |
@Override
public alluxio.grpc.JobInfo toProto() throws IOException {
List<alluxio.grpc.JobInfo> taskInfos = new ArrayList<>();
for (JobInfo taskInfo : mChildren) {
taskInfos.add(taskInfo.toProto());
}
alluxio.grpc.JobInfo.Builder jobInfoBuilder = alluxio.grpc.JobInfo.newBuilder().setId(mId)
... | @Test
public void testToProto() throws IOException {
PlanInfo planInfo = new PlanInfo(1, "test", Status.COMPLETED, 10, null);
PlanInfo otherPlanInfo = new PlanInfo(planInfo.toProto());
assertEquals(planInfo, otherPlanInfo);
} |
@Override
public void updateDictData(DictDataSaveReqVO updateReqVO) {
// 校验自己存在
validateDictDataExists(updateReqVO.getId());
// 校验字典类型有效
validateDictTypeExists(updateReqVO.getDictType());
// 校验字典数据的值的唯一性
validateDictDataValueUnique(updateReqVO.getId(), updateReqVO.get... | @Test
public void testUpdateDictData_success() {
// mock 数据
DictDataDO dbDictData = randomDictDataDO();
dictDataMapper.insert(dbDictData);// @Sql: 先插入出一条存在的数据
// 准备参数
DictDataSaveReqVO reqVO = randomPojo(DictDataSaveReqVO.class, o -> {
o.setId(dbDictData.getId());... |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void combines_tag_filters_from_env_if_rerun_file_specified_in_cli() {
RuntimeOptions runtimeOptions = parser
.parse("@src/test/resources/io/cucumber/core/options/runtime-options-rerun.txt")
.build();
RuntimeOptions options = new CucumberPropertiesParser()
... |
public void checkExecutePrerequisites(final ExecutionContext executionContext) {
ShardingSpherePreconditions.checkState(isValidExecutePrerequisites(executionContext), () -> new TableModifyInTransactionException(getTableName(executionContext)));
} | @Test
void assertCheckExecutePrerequisitesWhenExecuteDMLInXATransaction() {
ExecutionContext executionContext = new ExecutionContext(
new QueryContext(createMySQLInsertStatementContext(), "", Collections.emptyList(), new HintValueContext(), mockConnectionContext(), mock(ShardingSphereMetaDat... |
public boolean hasEmptyPart() {
// iterator will not contain an empty leaf queue, so check directly
if (leaf.isEmpty()) {
return true;
}
for (String part : this) {
if (part.isEmpty()) {
return true;
}
}
return false;
} | @Test
public void testEmptyPart() {
Assert.assertTrue(QUEUE_PATH_WITH_EMPTY_PART.hasEmptyPart());
Assert.assertTrue(QUEUE_PATH_WITH_EMPTY_LEAF.hasEmptyPart());
Assert.assertFalse(TEST_QUEUE_PATH.hasEmptyPart());
} |
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
return helper.interpret(session, st, context);
} | @Test
void should_execute_statement_with_consistency_option() {
// Given
String statement = "@consistency=THREE\n" +
"SELECT * FROM zeppelin.artists LIMIT 1;";
// When
final InterpreterResult actual = interpreter.interpret(statement, intrContext);
// Then
assertEquals(Code.ERROR, act... |
public static String toJson(UpdateRequirement updateRequirement) {
return toJson(updateRequirement, false);
} | @Test
public void testAssertLastAssignedFieldIdToJson() {
String requirementType = UpdateRequirementParser.ASSERT_LAST_ASSIGNED_FIELD_ID;
int lastAssignedFieldId = 12;
String expected =
String.format(
"{\"type\":\"%s\",\"last-assigned-field-id\":%d}",
requirementType, lastA... |
public void submitLoggingTask(Collection<Member> connectedMembers, Collection<Member> allMembers) {
if (delayPeriodSeconds <= 0) {
return;
}
if ((submittedLoggingTask != null && !submittedLoggingTask.isDone())) {
submittedLoggingTask.cancel(true);
}
subm... | @Test
void assertTaskCancelledIfSubmittedDuringRunningTask() {
ScheduledFuture mockFuture = mock(ScheduledFuture.class);
List<Member> mockMembers = createMockMembers(2);
HazelcastProperties hzProps = createMockProperties(10);
ClientConnectivityLogger clientConnectivityLogger = new Cl... |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
String method = request.getMethod();
URI uri = request.getUri();
for (Rule rule : rules) {
if (rule.matches(method, uri)) {
log.log(Level.FINE, () ->
String.for... | @Test
void includes_rule_response_headers_in_response_for_blocked_request() throws IOException {
RuleBasedFilterConfig config = new RuleBasedFilterConfig.Builder()
.dryrun(false)
.defaultRule(new DefaultRule.Builder()
.action(DefaultRule.Action.Enum.AL... |
public LoggerContext apply(LogLevelConfig logLevelConfig, Props props) {
if (!ROOT_LOGGER_NAME.equals(logLevelConfig.getRootLoggerName())) {
throw new IllegalArgumentException("Value of LogLevelConfig#rootLoggerName must be \"" + ROOT_LOGGER_NAME + "\"");
}
LoggerContext rootContext = getRootContext(... | @Test
public void apply_sets_domain_property_over_process_and_global_property_if_all_set() {
LogLevelConfig config = newLogLevelConfig().levelByDomain("foo", WEB_SERVER, LogDomain.ES).build();
props.set("sonar.log.level", "DEBUG");
props.set("sonar.log.level.web", "DEBUG");
props.set("sonar.log.level.... |
@Override
public OkHttpClient get() {
final OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.connectTimeout(connectTimeout.getQuantity(), connectTimeout.getUnit())
.writeTimeout(writeTimeout.getQuantity(), writeT... | @Test
public void testDynamicProxy() throws URISyntaxException {
final String TEST_PROXY = "http://proxy.dummy.org";
final InetSocketAddress testProxyAddress = new InetSocketAddress(TEST_PROXY, 59001);
final Proxy testProxy = new Proxy(Proxy.Type.HTTP, testProxyAddress);
final ProxyS... |
@Override
protected Map<String, Object> getOutputFieldValues(PMML4Result pmml4Result, Map<String, Object> resultVariables,
DMNResult dmnr) {
Map<String, Object> toReturn = new HashMap<>();
for (Map.Entry<String, Object> kv : resultVariables.entr... | @Test
void getOutputFieldValues() {
List<Object> values = getValues();
Map<String, Object> resultVariables = new HashMap<>();
for (int i = 0; i < values.size(); i++) {
resultVariables.put("Element-" + i, values.get(i));
}
Map<String, Object> retrieved = dmnKiePMML... |
public void setIncludedProtocols(String protocols) {
this.includedProtocols = protocols;
} | @Test
public void testSetIncludedProtocols() throws Exception {
configurable.setSupportedProtocols(new String[] { "A", "B", "C", "D" });
configuration.setIncludedProtocols("A,B ,C, D");
configuration.configure(configurable);
assertTrue(Arrays.equals(new String[] { "A", "B", "C", "D" ... |
public static Optional<String> extractOrganizationName(String groupName) {
return extractRegexGroupIfMatches(groupName, 1);
} | @Test
public void extractOrganizationName_whenNameIsCorrect_extractsOrganizationName() {
assertThat(GithubTeamConverter.extractOrganizationName("Org1/team1")).isEqualTo(Optional.of("Org1"));
assertThat(GithubTeamConverter.extractOrganizationName("Org1/team1/team2")).isEqualTo(Optional.of("Org1"));
} |
static URI cleanUrl(String originalUrl, String host) {
return URI.create(originalUrl.replaceFirst(host, ""));
} | @Test
void cleanUrlWithMatchingHostAndPart() throws IOException {
URI uri = RibbonClient.cleanUrl("http://questions/questions/answer/123", "questions");
assertThat(uri.toString()).isEqualTo("http:///questions/answer/123");
} |
@Override
public ClusterInfo clusterGetClusterInfo() {
RFuture<Map<String, String>> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.CLUSTER_INFO);
Map<String, String> entries = syncFuture(f);
Properties props = new Properties();
for (Entry<String, Str... | @Test
public void testClusterGetClusterInfo() {
ClusterInfo info = connection.clusterGetClusterInfo();
assertThat(info.getSlotsFail()).isEqualTo(0);
assertThat(info.getSlotsOk()).isEqualTo(MasterSlaveConnectionManager.MAX_SLOT);
assertThat(info.getSlotsAssigned()).isEqualTo(MasterSla... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final DownloadBuilder builder = new DbxUserFilesRequests(session.getClient(file))
.downloadBuilder(containerService.getKey(fil... | @Test
public void testReadCloseReleaseEntity() throws Exception {
final TransferStatus status = new TransferStatus();
final byte[] content = RandomUtils.nextBytes(32769);
final TransferStatus writeStatus = new TransferStatus();
writeStatus.setLength(content.length);
final Pat... |
@Override
public UpsertTarget create(ExpressionEvalContext evalContext) {
return new HazelcastJsonUpsertTarget();
} | @Test
public void test_create() {
HazelcastJsonUpsertTargetDescriptor descriptor = HazelcastJsonUpsertTargetDescriptor.INSTANCE;
// when
UpsertTarget target = descriptor.create(mock());
// then
assertThat(target).isInstanceOf(HazelcastJsonUpsertTarget.class);
} |
@Override
public int run(String launcherVersion, String launcherMd5, ServerUrlGenerator urlGenerator, Map<String, String> env, Map<String, String> context) {
int exitValue = 0;
LOG.info("Agent launcher is version: {}", CurrentGoCDVersion.getInstance().fullVersion());
String[] command = new S... | @Test
@DisabledOnOs(OS.WINDOWS)
public void shouldNotDownloadPluginsZipIfPresent() throws Exception {
TEST_AGENT_PLUGINS.copyTo(AGENT_PLUGINS_ZIP);
AGENT_PLUGINS_ZIP.setLastModified(System.currentTimeMillis() - 10 * 1000);
long expectedModifiedDate = AGENT_PLUGINS_ZIP.lastModified();
... |
@Override
public boolean match(final String rule) {
boolean matches = rule.matches("^list\\|\\[.+]$");
if (matches) {
String candidateData = rule.substring(6, rule.length() - 1);
return !candidateData.matches("^\\s+$");
}
return false;
} | @Test
public void match() {
assertTrue(generator.match("list|[shen\\,yu,gate\\,way]"));
assertTrue(generator.match("list|[shenyu,gateway]"));
assertFalse(generator.match("list|[shenyu,gateway"));
assertFalse(generator.match("list|[]"));
assertFalse(generator.match("list|[ ]")... |
@Override
public void acknowledge(OutputBufferId bufferId, long sequenceId)
{
checkState(!Thread.holdsLock(this), "Can not acknowledge pages while holding a lock on this");
requireNonNull(bufferId, "bufferId is null");
getBuffer(bufferId).acknowledgePages(sequenceId);
} | @Test
public void testAcknowledge()
{
OutputBuffers outputBuffers = createInitialEmptyOutputBuffers(ARBITRARY);
ArbitraryOutputBuffer buffer = createArbitraryBuffer(outputBuffers, sizeOfPages(10));
// add three items
for (int i = 0; i < 3; i++) {
addPage(buffer, crea... |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
final boolean satisfied = cross.getValue(index);
traceIsSatisfied(index, satisfied);
return satisfied;
} | @Test
public void repeatedlyHittingThresholdAfterCrossUp() {
Indicator<Num> evaluatedIndicator = new FixedDecimalIndicator(series, 9, 10, 11, 10, 11, 10, 11);
CrossedUpIndicatorRule rule = new CrossedUpIndicatorRule(evaluatedIndicator, 10);
assertFalse(rule.isSatisfied(0));
assertFa... |
public void putUserProperty(final String name, final String value) {
if (MessageConst.STRING_HASH_SET.contains(name)) {
throw new RuntimeException(String.format(
"The Property<%s> is used by system, input another please", name));
}
if (value == null || value.trim().i... | @Test(expected = IllegalArgumentException.class)
public void putUserNullValuePropertyWithException() throws Exception {
Message m = new Message();
m.putUserProperty("prop1", null);
} |
@Override
public void run() {
while (!schedulerState.isShuttingDown()) {
if (!schedulerState.isPaused()) {
try {
toRun.run();
} catch (Throwable e) {
LOG.error("Unhandled exception. Will keep running.", e);
schedulerListeners.onSchedulerEvent(SchedulerEventType.... | @Test
public void should_wait_on_ok_execution() {
Assertions.assertTimeoutPreemptively(
Duration.ofSeconds(1),
() -> {
runUntilShutdown.run();
assertThat(countingWaiter.counter, is(2));
});
} |
NewExternalIssue mapResult(String driverName, @Nullable Result.Level ruleSeverity, @Nullable Result.Level ruleSeverityForNewTaxonomy, Result result) {
NewExternalIssue newExternalIssue = sensorContext.newExternalIssue();
newExternalIssue.type(DEFAULT_TYPE);
newExternalIssue.engineId(driverName);
newExte... | @Test
public void mapResult_mapsSimpleFieldsCorrectly() {
NewExternalIssue newExternalIssue = resultMapper.mapResult(DRIVER_NAME, WARNING, WARNING, result);
verify(newExternalIssue).type(RuleType.VULNERABILITY);
verify(newExternalIssue).engineId(DRIVER_NAME);
verify(newExternalIssue).severity(DEFAULT... |
public static TableFactoryHelper createTableFactoryHelper(
DynamicTableFactory factory, DynamicTableFactory.Context context) {
return new TableFactoryHelper(factory, context);
} | @Test
void testFactoryHelperWithDeprecatedOptions() {
final Map<String, String> options = new HashMap<>();
options.put("deprecated-target", "MyTarget");
options.put("fallback-buffer-size", "1000");
options.put("value.format", "test-format");
options.put("value.test-format.dep... |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchIPv6NDTargetAddressTest() {
Criterion criterion =
Criteria.matchIPv6NDTargetAddress(
Ip6Address.valueOf("1111:2222::"));
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion... |
@Override
@DSTransactional // 多数据源,使用 @DSTransactional 保证本地事务,以及数据源的切换
public void updateTenant(TenantSaveReqVO updateReqVO) {
// 校验存在
TenantDO tenant = validateUpdateTenant(updateReqVO.getId());
// 校验租户名称是否重复
validTenantNameDuplicate(updateReqVO.getName(), updateReqVO.getId());
... | @Test
public void testUpdateTenant_success() {
// mock 数据
TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setStatus(randomCommonStatus()));
tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据
// 准备参数
TenantSaveReqVO reqVO = randomPojo(TenantSaveReqVO.class, o -> {
... |
public static DynamicVoter parse(String input) {
input = input.trim();
int atIndex = input.indexOf("@");
if (atIndex < 0) {
throw new IllegalArgumentException("No @ found in dynamic voter string.");
}
if (atIndex == 0) {
throw new IllegalArgumentException(... | @Test
public void testParseDynamicVoterWithNoColonFollowingPort() {
assertEquals("No colon following port could be found.",
assertThrows(IllegalArgumentException.class,
() -> DynamicVoter.parse("5@[2001:4860:4860::8888]:8020__0IZ-0DRNazJ49kCZ1EMQ")).
getMessag... |
public static <T> Global<T> globally() {
return new Global<>();
} | @Test
@Category(NeedsRunner.class)
public void testGloballyWithSchemaAggregateFnNestedFields() {
Collection<OuterAggregate> elements =
ImmutableList.of(
OuterAggregate.of(Aggregate.of(1, 1, 2)),
OuterAggregate.of(Aggregate.of(2, 1, 3)),
OuterAggregate.of(Aggregate.of(... |
@Override public V get(Object o) {
if (o == null) return null; // null keys are not allowed
int i = arrayIndexOfKey(o);
return i != -1 ? value(i + 1) : null;
} | @Test void someNullValues() {
array[0] = "1";
array[1] = "one";
array[2] = "2";
array[3] = "two";
array[4] = "3";
Map<String, String> map = builder.build(array);
assertSize(map, 2);
assertBaseCase(map);
assertThat(map).containsOnly(
entry("1", "one"),
entry("2", "tw... |
protected Set<MediaType> getSupportedMediaTypesForInput() {
return mSupportedMediaTypesUnmodifiable;
} | @Test
public void testReportsMediaTypesAndClearsOnFinish() {
simulateFinishInputFlow();
EditorInfo info = createEditorInfoTextWithSuggestionsForSetUp();
simulateOnStartInputFlow(false, info);
Assert.assertTrue(mPackageScope.getSupportedMediaTypesForInput().isEmpty());
simulateFinishInputFlow();
... |
@Override
public int read() throws IOException {
int read = input.read();
if (read != -1) fp++;
return read;
} | @Test
public void read() throws IOException {
ss.open();
byte[] buff = new byte[10];
int n = ss.read(buff);
byte[] temp = Arrays.copyOfRange(text, 0, buff.length);
assertArrayEquals(temp, buff);
assertEquals(buff.length, n);
} |
@SuppressWarnings("squid:S1181")
// Yes we really do want to catch Throwable
@Override
public V apply(U input) {
int retryAttempts = 0;
while (true) {
try {
return baseFunction.apply(input);
} catch (Throwable t) {
if (!exceptionClass.i... | @Test(expected = RetryableException.class)
public void testFailureAfterOneRetry() {
new RetryingFunction<>(this::succeedAfterTwoFailures, RetryableException.class, 1, 10).apply(null);
} |
@Override
public ScheduledReporter build(MetricRegistry registry) {
final File directory = requireNonNull(getFile(), "File is not set");
final boolean creation = directory.mkdirs();
if (!creation && !directory.exists()) {
throw new RuntimeException("Failed to create" + directory.... | @Test
void directoryCreatedOnStartup() throws Exception {
File dir = new File("metrics");
dir.delete();
assertThat(dir).doesNotExist();
MetricsFactory config = factory.build(new ResourceConfigurationSourceProvider(), "yaml/metrics.yml");
MetricRegistry metricRegistry = new M... |
public static DeploymentDescriptor merge(List<DeploymentDescriptor> descriptorHierarchy, MergeMode mode) {
if (descriptorHierarchy == null || descriptorHierarchy.isEmpty()) {
throw new IllegalArgumentException("Descriptor hierarchy list cannot be empty");
}
if (descriptorHierarchy.si... | @Test
public void testDeploymentDesciptorMergeOverrideEmpty() {
DeploymentDescriptor primary = new DeploymentDescriptorImpl("org.jbpm.domain");
primary.getBuilder()
.addMarshalingStrategy(new ObjectModel("org.jbpm.test.CustomStrategy", new Object[]{"param2"}))
.setLi... |
public List<String> toBatchTaskArgumentString() {
List<String> res = new ArrayList<>(Arrays.asList(
CLUSTER_LIMIT_FLAG, String.valueOf(mClusterLimit),
CLUSTER_START_DELAY_FLAG, mClusterStartDelay,
BENCH_TIMEOUT, mBenchTimeout,
START_MS_FLAG, String.valueOf(mStartMs)));
if (!mPro... | @Test
public void parseParameterToArgumentWithoutJavaOPT() {
String[] inputArgs = new String[]{
// keys with values
"--cluster-limit", "4",
"--cluster-start-delay", "5s",
"--id", "TestID",
// keys with no values
"--cluster",
};
JCommander jc = new JCommande... |
@Override
public final void getSize(@NonNull SizeReadyCallback cb) {
sizeDeterminer.getSize(cb);
} | @Test
public void testDoesNotAddMultipleListenersIfMultipleCallbacksAreAdded() {
SizeReadyCallback cb1 = mock(SizeReadyCallback.class);
SizeReadyCallback cb2 = mock(SizeReadyCallback.class);
target.getSize(cb1);
target.getSize(cb2);
view.getViewTreeObserver().dispatchOnPreDraw();
// assertThat... |
@Override
public boolean trySplitAtPosition(Long splitOffset) {
return trySplitAtPosition(splitOffset.longValue());
} | @Test
public void testSplitAtOffsetFailsIfUnstarted() throws Exception {
OffsetRangeTracker tracker = new OffsetRangeTracker(100, 200);
assertFalse(tracker.trySplitAtPosition(150));
} |
private String serializeDelete(SeaTunnelRow row) {
String key = keyExtractor.apply(row);
Map<String, String> deleteMetadata = createMetadata(row, key);
String deleteMetadataStr;
try {
deleteMetadataStr = objectMapper.writeValueAsString(deleteMetadata);
} catch (JsonPr... | @Test
public void testSerializeDelete() {
String index = "st_index";
String primaryKey = "id";
Map<String, Object> confMap = new HashMap<>();
confMap.put(SinkConfig.INDEX.key(), index);
confMap.put(SinkConfig.PRIMARY_KEYS.key(), Arrays.asList(primaryKey));
ReadonlyCo... |
static <T> Supplier<T> decorateSupplier(Observation observation, Supplier<T> supplier) {
return () -> observation.observe(supplier);
} | @Test
public void shouldDecorateSupplier() throws Throwable {
given(helloWorldService.returnHelloWorld()).willReturn("Hello world");
Supplier<String> timedSupplier = Observations
.decorateSupplier(observation, helloWorldService::returnHelloWorld);
timedSupplier.get();
a... |
@Override
public String getMethod() {
return PATH;
} | @Test
public void testSetMyCommandsWithEmptyCommands() {
SetMyCommands setMyCommands = SetMyCommands
.builder()
.languageCode("en")
.scope(BotCommandScopeDefault.builder().build())
.build();
assertEquals("setMyCommands", setMyCommands.g... |
@Override
public int size(Version version) {
if (version == Version.INET) {
return ipv4Tree.size();
}
if (version == Version.INET6) {
return ipv6Tree.size();
}
return 0;
} | @Test
public void testSize() {
assertThat("Incorrect size of radix tree for IPv4 maps",
radixTree.size(IpAddress.Version.INET), is(4));
assertThat("Incorrect size of radix tree for IPv6 maps",
radixTree.size(IpAddress.Version.INET6), is(6));
} |
@PostMapping("/batchEnabled")
@RequiresPermissions("system:dict:disable")
public ShenyuAdminResult batchEnabled(@Valid @RequestBody final BatchCommonDTO batchCommonDTO) {
final Integer result = shenyuDictService.enabled(batchCommonDTO.getIds(), batchCommonDTO.getEnabled());
return ShenyuAdminRes... | @Test
public void testBatchEnabled() throws Exception {
BatchCommonDTO batchCommonDTO = new BatchCommonDTO();
batchCommonDTO.setEnabled(false);
batchCommonDTO.setIds(Collections.singletonList("123"));
given(this.shenyuDictService.enabled(batchCommonDTO.getIds(), batchCommonDTO.getEna... |
@Override
public PackageMaterialPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
RepositoryConfiguration repositoryConfiguration = extension.getRepositoryConfiguration(descriptor.id());
com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration = ext... | @Test
public void shouldThrowAnExceptionWhenRepoConfigProvidedByPluginIsNull() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
when(extension.getRepositoryConfiguration("plugin1")).thenReturn(null);
assertThatThrownBy(() -> new PackageMaterialPluginInfo... |
public static DateTime convertToDateTime(@Nonnull Object value) {
if (value instanceof DateTime) {
return (DateTime) value;
}
if (value instanceof Date) {
return new DateTime(value, DateTimeZone.UTC);
} else if (value instanceof ZonedDateTime) {
final... | @Test
void convertFromDateTime() {
final DateTime input = new DateTime(2021, 8, 19, 12, 0, DateTimeZone.UTC);
final DateTime output = DateTimeConverter.convertToDateTime(input);
assertThat(output).isEqualTo(input);
} |
@Override
public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) {
if (client.getId() != null) { // if it's not null, it's already been saved, this is an error
throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId());
}
if (client.getRegisteredRedi... | @Test(expected = IllegalArgumentException.class)
public void heartMode_nonLocalHttpRedirect() {
Mockito.when(config.isHeartMode()).thenReturn(true);
ClientDetailsEntity client = new ClientDetailsEntity();
Set<String> grantTypes = new LinkedHashSet<>();
grantTypes.add("authorization_code");
grantTypes.add("r... |
public void copy(final IntHashSet that)
{
if (values.length != that.values.length)
{
throw new IllegalArgumentException("cannot copy object: masks not equal");
}
System.arraycopy(that.values, 0, values, 0, values.length);
this.sizeOfArrayValues = that.sizeOfArray... | @Test
void copiesOtherIntHashSet()
{
addTwoElements(testSet);
final IntHashSet other = new IntHashSet(100);
other.copy(testSet);
assertContainsElements(other);
} |
@SuppressWarnings("unchecked")
@Override
public void punctuate(final ProcessorNode<?, ?, ?, ?> node,
final long timestamp,
final PunctuationType type,
final Punctuator punctuator) {
if (processorContext.currentNode() != null) ... | @Test
public void punctuateShouldNotHandleTaskCorruptedExceptionAndThrowItAsIs() {
when(stateManager.taskId()).thenReturn(taskId);
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
task = createStatelessTask(createConfig(
AT_LEAST_ONCE,
"100",
Log... |
@VisibleForTesting
public void validateDictDataValueUnique(Long id, String dictType, String value) {
DictDataDO dictData = dictDataMapper.selectByDictTypeAndValue(dictType, value);
if (dictData == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典数据
if (id == null) ... | @Test
public void testValidateDictDataValueUnique_valueDuplicateForCreate() {
// 准备参数
String dictType = randomString();
String value = randomString();
// mock 数据
dictDataMapper.insert(randomDictDataDO(o -> {
o.setDictType(dictType);
o.setValue(value);
... |
@VisibleForTesting
void validateRoleDuplicate(String name, String code, Long id) {
// 0. 超级管理员,不允许创建
if (RoleCodeEnum.isSuperAdmin(code)) {
throw exception(ROLE_ADMIN_CODE_ERROR, code);
}
// 1. 该 name 名字被其它角色所使用
RoleDO role = roleMapper.selectByName(name);
... | @Test
public void testValidateRoleDuplicate_codeDuplicate() {
// mock 数据
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setCode("code"));
roleMapper.insert(roleDO);
// 准备参数
String code = "code";
// 调用,并断言异常
assertServiceException(() -> roleService.validateRo... |
@Override
public <VR> KTable<Windowed<K>, VR> aggregate(final Initializer<VR> initializer,
final Aggregator<? super K, ? super V, VR> aggregator) {
return aggregate(initializer, aggregator, Materialized.with(keySerde, null));
} | @Test
public void shouldThrowNullPointerOnMaterializedAggregateIfInitializerIsNull() {
assertThrows(NullPointerException.class, () -> windowedStream.aggregate(null, MockAggregator.TOSTRING_ADDER, Materialized.as("store")));
} |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void securityException() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/crash-report/security.txt")),
CrashReportAnalyzer.Rule.FILE_CHANGED);
assertEquals("assets/minecraft/texts/splashes.t... |
public HollowOrdinalIterator findKeysWithPrefix(String prefix) {
TST current;
HollowOrdinalIterator it;
do {
current = prefixIndexVolatile;
it = current.findKeysWithPrefix(prefix);
} while (current != this.prefixIndexVolatile);
return it;
} | @Test
public void testMovieMapReference() throws Exception {
Map<Integer, String> idActorMap = new HashMap<>();
idActorMap.put(1, "Keanu Reeves");
idActorMap.put(2, "Laurence Fishburne");
idActorMap.put(3, "Carrie-Anne Moss");
MovieMapReference movieMapReference = new MovieMa... |
@Deprecated
public static <T> Task<T> withSideEffect(final Task<T> parent, final Task<?> sideEffect) {
return parent.withSideEffect(t -> sideEffect);
} | @Test
public void testSideEffectCancelled() throws InterruptedException {
// this task will not complete.
Task<String> settableTask = new BaseTask<String>() {
@Override
protected Promise<? extends String> run(Context context) throws Exception {
return Promises.settable();
}
};
... |
@Override
public ExecuteContext doAfter(ExecuteContext context) {
if (isHasMethodLoadSpringFactories()) {
// 仅当在高版本采用LoadSpringFactories的方式注入, 高版本存在缓存会更加高效, 仅需注入一次
if (IS_INJECTED.compareAndSet(false, true)) {
injectConfigurations(context.getResult());
}
... | @Test
public void doAfterHighVersion() throws NoSuchMethodException, IllegalAccessException {
final SpringFactoriesInterceptor interceptor = new SpringFactoriesInterceptor();
hasMethodLoadSpringFactoriesFiled.set(interceptor, Boolean.TRUE);
ExecuteContext executeContext = ExecuteContext.forM... |
public void setSortOrder(@Nullable SortOrder sortOrder) {
if (sortOrder != null && sortOrder.scope != SortOrder.Scope.INTRA_FEED) {
throw new IllegalArgumentException("The specified sortOrder " + sortOrder
+ " is invalid. Only those with INTRA_FEED scope are allowed.");
}... | @Test
public void testSetSortOrder_NullAllowed() {
original.setSortOrder(null); // should be okay
} |
public static Serializer getDefault() {
return SERIALIZER_MAP.get(defaultSerializer);
} | @Test
void testListSerialize() {
Serializer serializer = SerializeFactory.getDefault();
List<Integer> logsList = new ArrayList<>();
for (int i = 0; i < 4; i++) {
logsList.add(i);
}
byte[] data = serializer.serialize(logsList);
assertNotEquals(0, d... |
public static Builder builder() {
return new Builder();
} | @Test
public void testBuilderDoesNotCreateInvalidObjects() {
List<String> listContainingNull = Lists.newArrayList("a", null, null);
// updated
assertThatThrownBy(
() -> UpdateNamespacePropertiesResponse.builder().addUpdated((String) null).build())
.isInstanceOf(NullPointerException.cl... |
static String removeWhiteSpaceFromJson(String json) {
//reparse the JSON to ensure that all whitespace formatting is uniform
String flattend = FLAT_GSON.toJson(JsonParser.parseString(json));
return flattend;
} | @Test
public void removeWhiteSpaceFromJson_removesNewLines() {
String input = "{\n\"a\":123,\n\"b\":456\n}";
String output = "{\"a\":123,\"b\":456}";
assertThat(
removeWhiteSpaceFromJson(input),
is(output)
);
} |
public static <E, K, D> Map<K, D> groupBy(Collection<E> collection, Function<E, K> key, Collector<E, ?, D> downstream) {
if (CollUtil.isEmpty(collection)) {
return MapUtil.newHashMap(0);
}
return groupBy(collection, key, downstream, false);
} | @Test
public void testGroupBy() {
// groupBy作为之前所有group函数的公共部分抽取出来,并更接近于jdk原生,灵活性更强
// 参数null测试
Map<Long, List<Student>> map = CollStreamUtil.groupBy(null, Student::getTermId, Collectors.toList());
assertEquals(map, Collections.EMPTY_MAP);
// 参数空数组测试
List<Student> list = new ArrayList<>();
map = CollSt... |
public static <T> Iterator<T> iterator(Class<T> expectedType, String factoryId, ClassLoader classLoader) throws Exception {
Iterator<Class<T>> classIterator = classIterator(expectedType, factoryId, classLoader);
return new NewInstanceIterator<>(classIterator);
} | @Test
public void loadServicesSimpleDifferentThreadContextClassLoader() throws Exception {
Class<ServiceLoaderTestInterface> type = ServiceLoaderTestInterface.class;
String factoryId = "com.hazelcast.ServiceLoaderTestInterface";
Thread current = Thread.currentThread();
ClassLoader t... |
@Override
public boolean isDataNodeAvailable(long dataNodeId) {
// DataNode and ComputeNode is exchangeable in SHARED_DATA mode
return availableID2ComputeNode.containsKey(dataNodeId);
} | @Test
public void testCollocationBackendSelectorWithSharedDataWorkerProvider() {
HostBlacklist blockList = SimpleScheduler.getHostBlacklist();
blockList.hostBlacklist.clear();
SystemInfoService sysInfo = GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo();
List<Long> avail... |
public static String convertToCamelCase(String str) {
StringBuilder result = new StringBuilder();
if (isNullOrWhitespaceOnly(str)) {
return "";
} else if (!str.contains("_") && !str.contains(" ")) {
return str.toLowerCase();
}
String[] camels = str.split("... | @Test
public void testConvertToCamelCase() {
String str = "AA_BB CC";
String camelCaseStr = StringUtils.convertToCamelCase(str);
Assert.assertEquals("aaBbCc", camelCaseStr);
} |
@Override
public DbSession openSession(boolean batch) {
if (!CACHING_ENABLED.get()) {
return myBatis.openSession(batch);
}
if (batch) {
return new NonClosingDbSession(batchDbSession.get().get());
}
return new NonClosingDbSession(regularDbSession.get().get());
} | @Test
void openSession_without_caching_always_returns_a_new_batch_session_when_parameter_is_true() {
DbSession[] expected = {mock(DbSession.class), mock(DbSession.class), mock(DbSession.class), mock(DbSession.class)};
when(myBatis.openSession(true))
.thenReturn(expected[0])
.thenReturn(expected[1]... |
public ClusterStateBundle.FeedBlock inferContentClusterFeedBlockOrNull(ContentCluster cluster) {
if (!feedBlockEnabled) {
return null;
}
var nodeInfos = cluster.getNodeInfos();
var exhaustions = enumerateNodeResourceExhaustionsAcrossAllNodes(nodeInfos);
if (exhaustion... | @Test
void node_must_be_available_in_reported_state_to_trigger_feed_block() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
forNode(2... |
public static void addNumImmutableMemTableMetric(final StreamsMetricsImpl streamsMetrics,
final RocksDBMetricContext metricContext,
final Gauge<BigInteger> valueProvider) {
addMutableMetric(
str... | @Test
public void shouldAddNumImmutableMemTablesMetric() {
final String name = "num-immutable-mem-table";
final String description = "Number of immutable memtables that have not yet been flushed";
runAndVerifyMutableMetric(
name,
description,
() -> RocksDB... |
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) {
return new CreateStreamCommand(
outputNode.getSinkName().get(),
outputNode.getSchema(),
outputNode.getTimestampColumn(),
outputNode.getKsqlTopic().getKafkaTopicName(),
Formats.from... | @Test
public void shouldThrowIfStreamExists() {
// Given:
final CreateStream ddlStatement =
new CreateStream(SOME_NAME, STREAM_ELEMENTS, false, false, withProperties, false);
// When:
final Exception e = assertThrows(
KsqlException.class, () -> createSourceFactory
.createS... |
@Override
public ByteBuf readBytes(int length) {
checkReadableBytes(length);
if (length == 0) {
return Unpooled.EMPTY_BUFFER;
}
ByteBuf buf = alloc().buffer(length, maxCapacity);
buf.writeBytes(this, readerIndex, length);
readerIndex += length;
re... | @Test
public void testReadBytesAfterRelease4() {
final ByteBuf buffer = buffer(8);
try {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().readBytes(buffer, 0, 1);
... |
public static boolean isGE(String base, String other) {
return isGE(base, other, false);
} | @Test
public void testGE() throws Exception {
assertTrue(isGE("2.15.0", "2.15.0"));
assertTrue(isGE("2.15.0", "2.15.1"));
assertTrue(isGE("2.15.0", "2.16.0"));
assertTrue(isGE("2.15.0", "2.16-SNAPSHOT"));
assertTrue(isGE("2.15.0", "2.16-foo"));
assertFalse(isGE("2.15... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void fabricConflicts() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/logs/fabric-mod-conflict.txt")),
CrashReportAnalyzer.Rule.MOD_RESOLUTION_CONFLICT);
assertEquals("phosphor", result.get... |
@Override
public void stop() throws Exception {
LOG.info("Stopping DefaultLeaderRetrievalService.");
synchronized (lock) {
if (!running) {
return;
}
running = false;
}
leaderRetrievalDriver.close();
} | @Test
void testErrorIsIgnoredAfterBeingStop() throws Exception {
new Context() {
{
runTest(
() -> {
final Exception testException = new Exception("test exception");
leaderRetrievalService.stop();
... |
@Override
public void write(DataOutput out) throws IOException {
throw new UnsupportedOperationException("LazyHCatRecord is intended to wrap"
+ " an object/object inspector as a HCatRecord "
+ "- it does not need to be written to a DataOutput.");
} | @Test
public void testWrite() throws Exception {
HCatRecord r = new LazyHCatRecord(getHCatRecord(), getObjectInspector());
boolean sawException = false;
try {
r.write(null);
} catch (UnsupportedOperationException uoe) {
sawException = true;
}
Assert.assertTrue(sawException);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.