focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public DataTypes handle(GetDataTypes request) {
Set<DataVertical> transferDataTypes = registry.getTransferDataTypes();
if (transferDataTypes.isEmpty()) {
monitor.severe(
() ->
"No transfer data types were registered in "
+ AuthServiceProviderRegistry.c... | @Test
public void testHandle() {
AuthServiceProviderRegistry registry = mock(AuthServiceProviderRegistry.class);
Set<DataVertical> dataTypes = new HashSet<>(Arrays.asList(CONTACTS, PHOTOS));
when(registry.getTransferDataTypes()).thenReturn(dataTypes);
DataTypesAction dataTypesAction = new DataTypesAct... |
public ClientSession toClientSession()
{
return new ClientSession(
parseServer(server),
user,
source,
Optional.empty(),
parseClientTags(clientTags),
clientInfo,
catalog,
schema,
... | @Test
public void testValidateNextUriSource()
{
Console console = singleCommand(Console.class).parse("--validate-nexturi-source");
assertTrue(console.clientOptions.validateNextUriSource);
assertTrue(console.clientOptions.toClientSession().validateNextUriSource());
} |
public CompletableFuture<Object> terminationFuture() {
return onFinish;
} | @Test
public void testJavaErrorResponse() throws Exception {
BlockingQueue<StreamObserver<BeamFnApi.InstructionRequest>> outboundServerObservers =
new LinkedBlockingQueue<>();
BlockingQueue<Throwable> error = new LinkedBlockingQueue<>();
CallStreamObserver<BeamFnApi.InstructionResponse> inboundSer... |
public static ConnectedComponents findComponentsRecursive(Graph graph, EdgeTransitionFilter edgeTransitionFilter, boolean excludeSingleEdgeComponents) {
return new EdgeBasedTarjanSCC(graph, edgeTransitionFilter, excludeSingleEdgeComponents).findComponentsRecursive();
} | @Test
public void linearSimple() {
// 0 - 1 - 2
g.edge(0, 1).setDistance(1).set(speedEnc, 10, 10);
g.edge(1, 2).setDistance(1).set(speedEnc, 10, 10);
ConnectedComponents result = EdgeBasedTarjanSCC.findComponentsRecursive(g, fwdAccessFilter, false);
assertEquals(4, result.get... |
public static void main(String[] args) throws Exception {
Options cliOptions = CliFrontendOptions.initializeOptions();
CommandLineParser parser = new DefaultParser();
CommandLine commandLine = parser.parse(cliOptions, args);
// Help message
if (args.length == 0 || commandLine.ha... | @Test
void testNoArgument() throws Exception {
CliFrontend.main(new String[] {});
assertThat(out.toString()).isEqualTo(HELP_MESSAGE);
assertThat(err.toString()).isEmpty();
} |
@Override
void updateLags() {
if (maxTaskIdleMs != StreamsConfig.MAX_TASK_IDLE_MS_DISABLED) {
for (final TopicPartition tp : partitionQueues.keySet()) {
final OptionalLong l = lagProvider.apply(tp);
if (l.isPresent()) {
fetchedLags.put(tp, l.ge... | @Test
public void shouldUpdateLags() {
final HashMap<TopicPartition, OptionalLong> lags = new HashMap<>();
final PartitionGroup group = new PartitionGroup(
logContext,
mkMap(
mkEntry(partition1, queue1)
),
tp -> lags.getOrDefault(tp, Op... |
@Override
public PageResult<FileConfigDO> getFileConfigPage(FileConfigPageReqVO pageReqVO) {
return fileConfigMapper.selectPage(pageReqVO);
} | @Test
public void testGetFileConfigPage() {
// mock 数据
FileConfigDO dbFileConfig = randomFileConfigDO().setName("芋道源码")
.setStorage(FileStorageEnum.LOCAL.getStorage());
dbFileConfig.setCreateTime(LocalDateTimeUtil.parse("2020-01-23", DatePattern.NORM_DATE_PATTERN));// 等会查询到
... |
@Override
public void fromPB(EncryptionKeyPB pb, KeyMgr mgr) {
super.fromPB(pb, mgr);
if (pb.algorithm == null) {
throw new IllegalArgumentException("no algorithm in EncryptionKeyPB for NormalKey id:" + id);
}
algorithm = pb.algorithm;
if (pb.plainKey != null) {
... | @Test
public void testFromPB_NoEncryptedKey() {
NormalKey key = new NormalKey();
EncryptionKeyPB pb = new EncryptionKeyPB();
pb.algorithm = EncryptionAlgorithmPB.AES_128;
KeyMgr mgr = new KeyMgr();
assertThrows(IllegalArgumentException.class, () -> {
key.fromPB(pb... |
public static byte[] getFiveBytes(long value) {
if (value < 0) {
throw new IllegalArgumentException("negative value not allowed: " + value);
} else if (value > 1099511627775L) {
throw new IllegalArgumentException("value out of range: " + value);
}
return new byte[... | @Test
public void getFiveBytesTest() {
byte[] fiveBytes = Serializer.getFiveBytes(0);
Assert.assertArrayEquals(new byte[]{0, 0, 0, 0, 0}, fiveBytes);
fiveBytes = Serializer.getFiveBytes(5);
Assert.assertArrayEquals(new byte[]{0, 0, 0, 0, 5}, fiveBytes);
} |
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final CloudBlob blob;
if(status.isExists()) {
if(new HostPreferences(session.getHost()).getBoolean("azur... | @Test
public void testWriteOverrideBlockBlob() throws Exception {
final OperationContext context
= new OperationContext();
final TransferStatus status = new TransferStatus();
status.setMime("text/plain");
final byte[] content = RandomUtils.nextBytes(513);
stat... |
public static <T> Class<? extends T> convertStringToClassType(String className, Class<? extends T> targetClassType) {
try {
Class<?> clazz = Class.forName(className);
if (!targetClassType.isAssignableFrom(clazz)){
throw new ConfigParseException("Class " + className + " is... | @Test
public void testConvertStringToClass() {
Class<? extends Throwable> clazz = ClassParseUtil.convertStringToClassType("java.lang.Exception", Throwable.class);
Assertions.assertThat(clazz).isEqualTo(Exception.class);
} |
@Override
public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer,
final Merger<? super K, V> sessionMerger) {
return aggregate(initializer, sessionMerger, Materialized.with(null, null));
} | @Test
public void shouldNotHaveNullSessionMerger2OnAggregate() {
assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT,
null, Materialized.as("test")));
} |
public static <T> ByFields<T> byFieldNames(String... fieldNames) {
return ByFields.of(FieldAccessDescriptor.withFieldNames(fieldNames));
} | @Test
@Category(NeedsRunner.class)
public void testGroupByOneField() throws NoSuchSchemaException {
PCollection<Row> grouped =
pipeline
.apply(
Create.of(
Basic.of("key1", 1, "value1"),
Basic.of("key1", 2, "value2"),
... |
public ParsedQuery parse(final String query) throws ParseException {
final TokenCollectingQueryParser parser = new TokenCollectingQueryParser(ParsedTerm.DEFAULT_FIELD, ANALYZER);
parser.setSplitOnWhitespace(true);
parser.setAllowLeadingWildcard(allowLeadingWildcard);
final Query parsed ... | @Test
void testLeadingWildcardsParsingDependsOnParserSettings() throws ParseException {
assertThatThrownBy(() -> parser.parse("foo:*bar"))
.isInstanceOf(ParseException.class);
assertThatThrownBy(() -> parser.parse("foo:?bar"))
.isInstanceOf(ParseException.class);
... |
public QR qr() {
return qr(false);
} | @Test
public void testQR() {
System.out.println("QR");
double[][] A = {
{0.9000, 0.4000, 0.7000f},
{0.4000, 0.5000, 0.3000f},
{0.7000, 0.3000, 0.8000f}
};
double[] b = {0.5, 0.5, 0.5f};
double[] x = {-0.2027027, 0.8783784, 0.47... |
@Override
public void processElement(StreamRecord<RowData> element) throws Exception {
RowData rowData = element.getValue();
int localRowCount = rowData.getInt(0);
if (globalRowCount == OVER_MAX_ROW_COUNT) {
// Current global filter is already over-max-row-count, do nothing.
... | @Test
void testOverMaxRowCountInput() throws Exception {
try (StreamTaskMailboxTestHarness<RowData> testHarness =
createGlobalRuntimeFilterBuilderOperatorHarness(10)) {
// process elements
testHarness.processElement(
new StreamRecord<RowData>(
... |
public int getNumRefreshServiceAclsFailedRetrieved() {
return numRefreshServiceAclsFailedRetrieved.value();
} | @Test
public void testRefreshServiceAclsRetrievedFailed() {
long totalBadBefore = metrics.getNumRefreshServiceAclsFailedRetrieved();
badSubCluster.getRefreshServiceAclsFailedRetrieved();
Assert.assertEquals(totalBadBefore + 1,
metrics.getNumRefreshServiceAclsFailedRetrieved());
} |
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception {
CruiseConfig configForEdit;
CruiseConfig config;
LOGGER.debug("[Config Save] Loading config holder");
configForEdit = deserializeConfig(content);
if (callback != null) callback.call... | @Test
void shouldAllowOnlyOneTimerOnAPipeline() {
String content = configWithPipeline(
"""
<pipeline name='pipeline1'>
<timer>1 1 1 * * ? *</timer>
<timer>2 2 2 * * ? *</timer>
<materi... |
@Override
public Resource parseResource(Request request, Secured secured) {
if (StringUtils.isNotBlank(secured.resource())) {
return parseSpecifiedResource(secured);
}
String type = secured.signType();
AbstractGrpcResourceParser parser = resourceParserMap.get(type);
... | @Test
@Secured(signType = "non-exist")
void testParseResourceWithNonExistType() throws NoSuchMethodException {
Secured secured = getMethodSecure("testParseResourceWithNonExistType");
Resource actual = protocolAuthService.parseResource(namingRequest, secured);
assertEquals(Resource.EMPTY_... |
@Override
public void setVerifyChecksum(boolean verifyChecksum) {
fs.setVerifyChecksum(verifyChecksum);
} | @Test
public void testVerifyChecksumPassthru() {
FileSystem mockFs = mock(FileSystem.class);
FileSystem fs = new FilterFileSystem(mockFs);
fs.setVerifyChecksum(false);
verify(mockFs).setVerifyChecksum(eq(false));
reset(mockFs);
fs.setVerifyChecksum(true);
verify(mockFs).setVerifyChecksum(... |
public static DateTime date() {
return new DateTime();
} | @Test
public void dateTest() {
//LocalDateTime ==> date
final LocalDateTime localDateTime = LocalDateTime.parse("2017-05-06T08:30:00", DateTimeFormatter.ISO_DATE_TIME);
final DateTime date = DateUtil.date(localDateTime);
assertEquals("2017-05-06 08:30:00", date.toString());
//LocalDate ==> date
final Loca... |
DateRange getRange(String dateRangeString) throws ParseException {
if (dateRangeString == null || dateRangeString.isEmpty())
return null;
String[] dateArr = dateRangeString.split("-");
if (dateArr.length > 2 || dateArr.length < 1)
return null;
// throw new Illega... | @Test
public void testToString() throws ParseException {
DateRange instance = dateRangeParser.getRange("Mar-Oct");
assertEquals("yearless:true, dayOnly:false, reverse:false, from:1970-03-01T00:00:00Z, to:1970-10-31T23:59:59Z", instance.toString());
} |
@Override
public long getCount() {
return count.sum();
} | @Test
public void startsAtZero() {
assertThat(counter.getCount())
.isZero();
} |
public String toString()
{
return toString(data);
} | @Test
public void testToString()
{
ZData data = new ZData("test".getBytes(ZMQ.CHARSET));
String string = data.toString();
assertThat(string, is("test"));
} |
public static void displayWelcomeMessage(
final int consoleWidth,
final PrintWriter writer
) {
final String[] lines = {
"",
"===========================================",
"= _ _ ____ ____ =",
"= | | _____ __ _| | _ \\| __ ) =",
... | @Test
public void shouldFlushWriterWhenOutputtingShortMessage() {
// When:
WelcomeMsgUtils.displayWelcomeMessage(10, mockPrintWriter);
// Then:
Mockito.verify(mockPrintWriter).flush();
} |
@Override
public void invoke(IN value, Context context) throws Exception {
bufferLock.lock();
try {
// TODO this implementation is not very effective,
// optimize this with MemorySegment if needed
ByteArrayOutputStream baos = new ByteArrayOutputStream();
... | @Test
void testCheckpoint() throws Exception {
functionWrapper.openFunctionWithState();
for (int i = 0; i < 2; i++) {
functionWrapper.invoke(i);
}
String version = initializeVersion();
CollectCoordinationResponse response =
functionWrapper.sendReq... |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateFileConfigMaster(Long id) {
// 校验存在
validateFileConfigExists(id);
// 更新其它为非 master
fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false));
// 更新
fileConfigMapper.updateById(new Fi... | @Test
public void testUpdateFileConfigMaster_notExists() {
// 调用, 并断言异常
assertServiceException(() -> fileConfigService.updateFileConfigMaster(randomLongId()), FILE_CONFIG_NOT_EXISTS);
} |
@Override
public double dot(SGDVector other) {
if (other.size() != elements.length) {
throw new IllegalArgumentException("Can't dot two vectors of different dimension, this = " + elements.length + ", other = " + other.size());
}
double score = 0.0;
if (other instanceof De... | @Test
public void dot() {
DenseVector a = generateVectorA();
DenseVector c = generateVectorC();
assertEquals(a.dot(c),c.dot(a),1e-10);
assertEquals(16.0, a.dot(c),1e-10);
} |
public static IOException maybeExtractIOException(
String path,
Throwable thrown,
String message) {
if (thrown == null) {
return null;
}
// walk down the chain of exceptions to find the innermost.
Throwable cause = getInnermostThrowable(thrown.getCause(), thrown);
// see i... | @Test
public void testNoConstructorExtraction() throws Throwable {
intercept(PathIOException.class, NoConstructorIOE.MESSAGE,
() -> {
throw maybeExtractIOException("p1",
sdkException("top",
sdkException("middle",
new NoConstructorIOE())), nul... |
@Override
public PullResult pull(MessageQueue mq, String subExpression, long offset, int maxNums)
throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
return this.defaultMQPullConsumerImpl.pull(queueWithNamespace(mq), subExpression, offset, maxNums);
} | @Test
public void testPullMessageAsync_Success() throws Exception {
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock mock) throws Throwable {
PullMessageRequestHeader requestHeader = mock.getArgument(1);
PullResult pullResult = c... |
@Override
public String render(String text) {
return new DefaultCommentRenderer(link, regex).render(text);
} | @Test
public void shouldRenderStringWithSpecifiedRegexAndLink() throws Exception {
TrackingTool config = new TrackingTool("http://mingle05/projects/cce/cards/${ID}", "#(\\d+)");
String result = config.render("#111: checkin message");
assertThat(result, is("<a href=\"" + "http://mingle05/pro... |
@Override
public Set<NodeHealth> readAll() {
long clusterTime = hzMember.getClusterTime();
long timeout = clusterTime - TIMEOUT_30_SECONDS;
Map<UUID, TimestampedNodeHealth> sqHealthState = readReplicatedMap();
Set<UUID> hzMemberUUIDs = hzMember.getMemberUuids();
Set<NodeHealth> existingNodeHealths... | @Test
public void readAll_returns_all_NodeHealth_in_map_sq_health_state_for_existing_client_uuids_aged_less_than_30_seconds() {
NodeHealth[] nodeHealths = IntStream.range(0, 1 + random.nextInt(6)).mapToObj(i -> randomNodeHealth()).toArray(NodeHealth[]::new);
Map<UUID, TimestampedNodeHealth> allNodeHealths = n... |
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args)
throws Throwable {
switch (method.getName()) {
case "equals":
return equals(args.length > 0 ? args[0] : null);
case "hashCode":
return hashCode();
... | @Test
public void testInvokeEquals() throws Throwable {
final Method equalsMethod = testService.getClass().getMethod("equals", Object.class);
final Boolean result = (Boolean) testSubject
.invoke(testService, equalsMethod, new Object[]{testSubject});
verify(methodHandler, times(... |
@Override
public int countWords(Note note) {
int count = 0;
String[] fields = {note.getTitle(), note.getContent()};
for (String field : fields) {
field = sanitizeTextForWordsAndCharsCount(note, field);
boolean word = false;
int endOfLine = field.length() - 1;
for (int i = 0; i < fi... | @Test
public void getChecklistWords() {
String content = CHECKED_SYM + "done\n" + UNCHECKED_SYM + "undone yet";
Note note = getNote(1L, "checklist", content);
note.setChecklist(true);
assertEquals(4, new DefaultWordCounter().countWords(note));
} |
@Override
String getInterfaceName(Invoker invoker, String prefix) {
return DubboUtils.getInterfaceName(invoker, prefix);
} | @Test
public void testDegradeAsync() throws InterruptedException {
try (MockedStatic<TimeUtil> mocked = super.mockTimeUtil()) {
setCurrentMillis(mocked, 1740000000000L);
Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne();
Invoker invoker = DubboTestUtil.g... |
protected JobMeta processLinkedJobs( JobMeta jobMeta ) {
for ( int i = 0; i < jobMeta.nrJobEntries(); i++ ) {
JobEntryCopy jec = jobMeta.getJobEntry( i );
if ( jec.getEntry() instanceof JobEntryJob ) {
JobEntryJob jej = (JobEntryJob) jec.getEntry();
ObjectLocationSpecificationMethod spec... | @Test
public void testProcessLinkedJobsWithFilename() {
JobEntryJob jobJobExecutor = spy( new JobEntryJob() );
jobJobExecutor.setFileName( "/path/to/Job1.kjb" );
jobJobExecutor.setSpecificationMethod( ObjectLocationSpecificationMethod.FILENAME );
JobEntryCopy jobEntry = mock( JobEntryCopy.class );
... |
@Override
public String builder(final String paramName, final ServerWebExchange exchange) {
return HostAddressUtils.acquireIp(exchange);
} | @Test
public void testBuilderWithAnyParamName() {
assertEquals(testHost, ipParameterData.builder(UUIDUtils.getInstance().generateShortUuid(), exchange));
} |
public static boolean isRandomPort(int port) {
return port == -1;
} | @Test
public void isRandomPort() throws Exception {
} |
@Override
public Iterable<DiscoveryNode> discoverNodes() {
try {
List<GcpAddress> gcpAddresses = gcpClient.getAddresses();
logGcpAddresses(gcpAddresses);
List<DiscoveryNode> result = new ArrayList<>();
for (GcpAddress gcpAddress : gcpAddresses) {
... | @Test
public void discoverNodes() {
// given
GcpAddress gcpInstance1 = new GcpAddress("192.168.1.15", "38.146.24.2");
GcpAddress gcpInstance2 = new GcpAddress("192.168.1.16", "38.146.28.15");
given(gcpClient.getAddresses()).willReturn(asList(gcpInstance1, gcpInstance2));
// ... |
@Override
public String generate(TokenType tokenType) {
String rawToken = generateRawToken();
return buildIdentifiablePartOfToken(tokenType) + rawToken;
} | @Test
public void generateProjectBadgeToken_nullToken_shouldNotHavePrefix() {
String token = underTest.generate(TokenType.PROJECT_BADGE_TOKEN);
assertThat(token).matches("sqb_.{40}");
} |
public String getClusterStatusReportRequestBody(Map<String, String> clusterProfile) {
JsonObject jsonObject = new JsonObject();
jsonObject.add("cluster_profile_properties", mapToJsonObject(clusterProfile));
return FORCED_EXPOSE_GSON.toJson(jsonObject);
} | @Test
public void shouldJSONizeClusterStatusReportRequestBody() throws Exception {
String actual = new ElasticAgentExtensionConverterV5().getClusterStatusReportRequestBody(Map.of("key1", "value1"));
String expected = "{" +
" \"cluster_profile_properties\":{" +
" ... |
@Override
public Expr uncheckedCastTo(Type targetType) throws AnalysisException {
if (targetType.isDateType()) {
if (type.equals(targetType)) {
return this;
}
if (targetType.isDate()) {
return new DateLiteral(this.year, this.month, this.day... | @Test
public void uncheckedCastTo() {
boolean hasException = false;
try {
DateLiteral literal = new DateLiteral("1997-10-07", Type.DATE);
Expr castToExpr = literal.uncheckedCastTo(Type.DATETIME);
Assert.assertTrue(castToExpr instanceof DateLiteral);
As... |
@Override
public void execute(Exchange exchange) throws SmppException {
DataSm dataSm = createDataSm(exchange);
if (log.isDebugEnabled()) {
log.debug("Sending a data short message for exchange id '{}'...", exchange.getExchangeId());
}
DataSmResult result;
try {
... | @Test
public void executeWithConfigurationData() throws Exception {
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND, "DataSm");
when(session.dataShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(Nu... |
@Override
public <T extends State> T state(StateNamespace namespace, StateTag<T> address) {
return workItemState.get(namespace, address, StateContexts.nullContext());
} | @Test
public void testMultimapLazyIterateHugeEntriesResult() {
// A multimap with 1 million keys with a total of 10GBs data
final String tag = "multimap";
StateTag<MultimapState<byte[], Integer>> addr =
StateTags.multimap(tag, ByteArrayCoder.of(), VarIntCoder.of());
MultimapState<byte[], Integ... |
public <T extends Tuple> DataSource<T> tupleType(Class<T> targetType) {
Preconditions.checkNotNull(targetType, "The target type class must not be null.");
if (!Tuple.class.isAssignableFrom(targetType)) {
throw new IllegalArgumentException(
"The target type must be a subcl... | @Test
void testSubClassWithPartialsInHierarchie() {
CsvReader reader = getCsvReader();
DataSource<FinalItem> sitems = reader.tupleType(FinalItem.class);
TypeInformation<?> info = sitems.getType();
assertThat(info.isTupleType()).isTrue();
assertThat(info.getTypeClass()).isEqu... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void sendGame() {
InlineKeyboardButton[] buttons = {
new InlineKeyboardButton("inline game").callbackGame("pengrad test game description"),
new InlineKeyboardButton("inline ok").callbackData("callback ok"),
new InlineKeyboardButton("cancel").callb... |
private void addBuffer(int minCapacity)
{
if (this._bufferList.peekLast() != null)
{
this._alreadyBufferedSize += this._index;
this._index = 0;
}
if (this._nextBufferSize < minCapacity)
{
this._nextBufferSize = nextPowerOf2(minCapacity);
}
// Make sure we always stay wit... | @Test
@SuppressWarnings("unchecked")
public void testAddBuffer() throws Exception
{
FastByteArrayOutputStream testStream = new FastByteArrayOutputStream();
Field bufferListField = testStream.getClass().getDeclaredField("_bufferList");
bufferListField.setAccessible(true);
// Empty linked list until... |
public void asyncAddData(T data, AddDataCallback callback, Object ctx){
if (!batchEnabled){
if (state == State.CLOSING || state == State.CLOSED){
callback.addFailed(BUFFERED_WRITER_CLOSED_EXCEPTION, ctx);
return;
}
ByteBuf byteBuf = dataSeriali... | @Test
public void testMetricsStatsThatTriggeredByMaxDelayTime() throws Exception {
SumStrDataSerializer dataSerializer = new SumStrDataSerializer();
int writeCount = 1;
int batchedWriteMaxDelayInMillis = 1000;
int expectFlushCount = 1;
int expectedTotalBytesSize = writeCount ... |
@Override
public KeyValueIterator<Windowed<K>, V> fetch(final K key) {
Objects.requireNonNull(key, "key cannot be null");
return new MeteredWindowedKeyValueIterator<>(
wrapped().fetch(keyBytes(key)),
fetchSensor,
iteratorDurationSensor,
streamsMetrics,... | @Test
public void shouldThrowNullPointerOnFetchRangeIfToIsNull() {
setUpWithoutContext();
assertThrows(NullPointerException.class, () -> store.fetch("from", null));
} |
@Override
public boolean apply(Collection<Member> members) {
if (members.size() < minimumClusterSize) {
return false;
}
int count = 0;
long timestamp = Clock.currentTimeMillis();
for (Member member : members) {
if (!isAlivePerIcmp(member)) {
... | @Test
public void testSplitBrainProtectionAbsent_whenIcmpSuspects() {
splitBrainProtectionFunction = new ProbabilisticSplitBrainProtectionFunction(splitBrainProtectionSize, 10000, 10000, 200, 100, 10);
prepareSplitBrainProtectionFunctionForIcmpFDTest(splitBrainProtectionFunction);
// heartbe... |
@Override
@SuppressWarnings("DuplicatedCode")
public Integer cleanAccessLog(Integer exceedDay, Integer deleteLimit) {
int count = 0;
LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay);
// 循环删除,直到没有满足条件的数据
for (int i = 0; i < Short.MAX_VALUE; i++) {
in... | @Test
public void testCleanJobLog() {
// mock 数据
ApiAccessLogDO log01 = randomPojo(ApiAccessLogDO.class, o -> o.setCreateTime(addTime(Duration.ofDays(-3))));
apiAccessLogMapper.insert(log01);
ApiAccessLogDO log02 = randomPojo(ApiAccessLogDO.class, o -> o.setCreateTime(addTime(Duratio... |
public StepBreakpoint addStepBreakpoint(
String workflowId,
long version,
long instanceId,
long runId,
String stepId,
long stepAttemptId,
User user) {
final String revisedWorkflowId = getRevisedWorkflowId(workflowId, stepId, true);
return withMetricLogError(
() ... | @Test
public void testAddForEachBreakpoint() {
when(workflowDao.getWorkflowDefinition(anyString(), anyString())).thenReturn(wfd);
String hashedInternalId = IdHelper.hashKey(INTERNAL_ID);
StepBreakpoint bp =
maestroStepBreakpointDao.addStepBreakpoint(
TEST_WORKFLOW_ID2,
TEST... |
public static Matcher<? super Object> hasJsonPath(String jsonPath) {
return describedAs("has json path %0",
isJson(withJsonPath(jsonPath)),
jsonPath);
} | @Test
public void shouldMatchJsonPathOnParsedJsonObject() {
Object json = Configuration.defaultConfiguration().jsonProvider().parse(BOOKS_JSON);
assertThat(json, hasJsonPath("$.store.name", equalTo("Little Shop")));
} |
public void dropDatabase(final String databaseName) {
cleanResources(databases.remove(databaseName));
} | @Test
void assertDropDatabase() {
ResourceMetaData resourceMetaData = mock(ResourceMetaData.class, RETURNS_DEEP_STUBS);
GlobalRule globalRule = mock(GlobalRule.class);
MockedDataSource dataSource = new MockedDataSource();
ShardingSphereRule databaseRule = mock(ShardingSphereRule.clas... |
public static Builder builder() {
return new Builder();
} | @Test
public void testRoundTripSerdeWithV1TableMetadata() throws Exception {
String tableMetadataJson = readTableMetadataInputFile("TableMetadataV1Valid.json");
TableMetadata v1Metadata =
TableMetadataParser.fromJson(TEST_METADATA_LOCATION, tableMetadataJson);
// Convert the TableMetadata JSON fro... |
public static Map<String, Method> getBeanPropertyReadMethods(Class cl) {
Map<String, Method> properties = new HashMap<>();
for (; cl != null; cl = cl.getSuperclass()) {
Method[] methods = cl.getDeclaredMethods();
for (Method method : methods) {
if (isBeanPropertyR... | @Test
void testGetBeanPropertyReadMethods() {
Map<String, Method> map = ReflectUtils.getBeanPropertyReadMethods(EmptyClass.class);
assertThat(map.size(), is(2));
assertThat(map, hasKey("set"));
assertThat(map, hasKey("property"));
for (Method m : map.values()) {
i... |
public int getChecksumAlg() {
return checksumAlg;
} | @Test
public void getChecksumAlgOutputZero() {
// Arrange
final LogHeader objectUnderTest = new LogHeader(0);
// Act
final int actual = objectUnderTest.getChecksumAlg();
// Assert result
Assert.assertEquals(0, actual);
} |
@Override
public int getDegree(int vertex) {
if (digraph) {
return getIndegree(vertex) + getOutdegree(vertex);
} else {
return getOutdegree(vertex);
}
} | @Test
public void testGetDegree() {
System.out.println("getDegree");
assertEquals(0, g1.getDegree(1));
assertEquals(2, g2.getDegree(1));
g2.addEdge(1, 1);
assertEquals(4, g2.getDegree(1));
assertEquals(4, g3.getDegree(1));
assertEquals(4, g3.getDegree(2));
... |
@Override
public long getNumBytesProduced() {
checkState(
subpartitionBytesByPartitionIndex.size() == numOfPartitions,
"Not all partition infos are ready");
return subpartitionBytesByPartitionIndex.values().stream()
.flatMapToLong(Arrays::stream)
... | @Test
void testGetNumBytesProducedWithIndexRange() {
PointwiseBlockingResultInfo resultInfo =
new PointwiseBlockingResultInfo(new IntermediateDataSetID(), 2, 2);
resultInfo.recordPartitionInfo(0, new ResultPartitionBytes(new long[] {32L, 64L}));
resultInfo.recordPartitionInfo... |
public SearchResponse search(IssueQuery query, SearchOptions options) {
SearchRequest requestBuilder = EsClient.prepareSearch(TYPE_ISSUE.getMainType());
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
requestBuilder.source(sourceBuilder);
configureSorting(query, sourceBuilder);
confi... | @Test
void search_exceeding_default_index_max_window() {
ComponentDto project = newPrivateProjectDto();
ComponentDto file = newFileDto(project);
List<IssueDoc> issues = new ArrayList<>();
for (int i = 0; i < 11_000; i++) {
String key = "I" + i;
issues.add(newDoc(key, project.uuid(), file))... |
public static Pod createPod(
String name,
String namespace,
Labels labels,
OwnerReference ownerReference,
PodTemplate template,
Map<String, String> defaultPodLabels,
Map<String, String> podAnnotations,
Affinity affinity,
... | @Test
public void testCreatePodWithEmptyTemplate() {
Pod pod = WorkloadUtils.createPod(
NAME,
NAMESPACE,
LABELS,
OWNER_REFERENCE,
new PodTemplate(),
Map.of("default-label", "default-value"),
Map.... |
public static <T extends Collection<E>, E extends CharSequence> T removeBlank(T collection) {
return filter(collection, StrUtil::isNotBlank);
} | @Test
public void removeBlankTest() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", null, "", " ");
final ArrayList<String> filtered = CollUtil.removeBlank(list);
// 原地过滤
assertSame(list, filtered);
assertEquals(CollUtil.newArrayList("a", "b", "c"), filtered);
} |
public static Long toLong(Object value, Long defaultValue) {
return convertQuietly(Long.class, value, defaultValue);
} | @Test
public void toLongTest() {
final String a = " 342324545435435";
final Long aLong = Convert.toLong(a);
assertEquals(Long.valueOf(342324545435435L), aLong);
final long aLong2 = ConverterRegistry.getInstance().convert(long.class, a);
assertEquals(342324545435435L, aLong2);
// 带小数测试
final String b = "... |
@Override
public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) {
ItemChangeSets changeSets = new ItemChangeSets();
if (CollectionUtils.isEmpty(baseItems) && StringUtils.isEmpty(configText)) {
return changeSets;
}
if (CollectionUtils.isEmpty(baseItems)) {
... | @Test
public void testUpdateItem(){
ItemDTO existedItem = new ItemDTO();
existedItem.setId(1000);
existedItem.setKey(ConfigConsts.CONFIG_FILE_CONTENT_KEY);
existedItem.setValue("before");
ItemChangeSets changeSets = resolver.resolve(NAMESPACE, CONFIG_TEXT,
Collections.singletonList(existe... |
public void loop() {
while (!ctx.isKilled()) {
try {
processOnce();
} catch (RpcException rpce) {
LOG.debug("Exception happened in one session(" + ctx + ").", rpce);
ctx.setKilled();
break;
} catch (Exception e) ... | @Test
public void testNullPacket() throws Exception {
ConnectContext ctx = initMockContext(mockChannel(null), GlobalStateMgr.getCurrentState());
ConnectProcessor processor = new ConnectProcessor(ctx);
processor.loop();
Assert.assertTrue(myContext.isKilled());
} |
@Override
protected int rsv(WebSocketFrame msg) {
return msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame?
msg.rsv() | WebSocketExtension.RSV1 : msg.rsv();
} | @Test
public void testCompressedFrame() {
EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false));
EmbeddedChannel decoderChannel = new EmbeddedChannel(
ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE));
// initialize
byte[] ... |
public HtmlEmail createEmail(T report) throws MalformedURLException, EmailException {
HtmlEmail email = new HtmlEmail();
setEmailSettings(email);
addReportContent(email, report);
return email;
} | @Test
public void test_email_fields() throws Exception {
BasicEmail basicEmail = new BasicEmail(Set.of("noreply@nowhere"));
when(emailSettings.getSmtpHost()).thenReturn("smtphost");
when(emailSettings.getSmtpPort()).thenReturn(25);
when(emailSettings.getFrom()).thenReturn("noreply@nowhere");
when(... |
@Override
public Map<String, String> getAddresses() {
AwsCredentials credentials = awsCredentialsProvider.credentials();
List<String> taskAddresses = emptyList();
if (!awsConfig.anyOfEc2PropertiesConfigured()) {
taskAddresses = awsEcsApi.listTaskPrivateAddresses(cluster, credenti... | @Test
public void getAddressesWithAwsConfig() {
// given
List<String> privateIps = singletonList("123.12.1.0");
Map<String, String> expectedResult = singletonMap("123.12.1.0", "1.4.6.2");
given(awsEcsApi.listTaskPrivateAddresses(CLUSTER, CREDENTIALS)).willReturn(privateIps);
... |
@Override
public List<TenantDO> getTenantListByPackageId(Long packageId) {
return tenantMapper.selectListByPackageId(packageId);
} | @Test
public void testGetTenantListByPackageId() {
// mock 数据
TenantDO dbTenant1 = randomPojo(TenantDO.class, o -> o.setPackageId(1L));
tenantMapper.insert(dbTenant1);// @Sql: 先插入出一条存在的数据
TenantDO dbTenant2 = randomPojo(TenantDO.class, o -> o.setPackageId(2L));
tenantMapper.i... |
@Override
public SQLRecognizer getInsertRecognizer(String sql, SQLStatement ast) {
return new SqlServerInsertRecognizer(sql, ast);
} | @Test
public void getInsertRecognizerTest() {
String sql = "INSERT INTO t (name) VALUES ('name1')";
SQLStatement sqlStatement = getSQLStatement(sql);
Assertions.assertNotNull(new SqlServerOperateRecognizerHolder().getInsertRecognizer(sql, sqlStatement));
} |
@Override
public LogicalSchema getSchema() {
return getSource().getSchema();
} | @Test
public void shouldExtractConstraintForMultiKeyExpressionsThatDontCoverAllKeys_tableScan() {
// Given:
when(plannerOptions.getTableScansEnabled()).thenReturn(true);
when(source.getSchema()).thenReturn(MULTI_KEY_SCHEMA);
final Expression expression = new ComparisonExpression(
Type.EQUAL,
... |
@Override
public int getQueueSize() {
// LBQ size handled by an atomic int
return taskQ.size();
} | @Test
public void getQueueSize_whenNoTasksSubmitted() {
assertEquals(0, newManagedExecutorService().getQueueSize());
} |
@Override
public String toString() {
return String.format("%s,%s,%s", getType(), beginValue, endValue);
} | @Test
void assertToString() {
assertThat(new IntegerPrimaryKeyIngestPosition(1L, 100L).toString(), is("i,1,100"));
} |
protected boolean isNodeEmpty(JsonNode json) {
if (json.isArray()) {
return isListEmpty((ArrayNode) json);
} else if (json.isObject()) {
return isObjectEmpty((ObjectNode) json);
} else {
return isEmptyText(json);
}
} | @Test
public void isNodeEmpty_arrayNodeWithTextNode() {
ArrayNode arrayNode = new ArrayNode(factory);
arrayNode.add(new TextNode(VALUE));
assertThat(expressionEvaluator.isNodeEmpty(arrayNode)).isFalse();
} |
public StatMap<K> merge(K key, int value) {
if (key.getType() == Type.LONG) {
merge(key, (long) value);
return this;
}
int oldValue = getInt(key);
int newValue = key.merge(oldValue, value);
if (newValue == 0) {
_map.remove(key);
} else {
_map.put(key, newValue);
}
... | @Test(dataProvider = "allTypeStats", expectedExceptions = IllegalArgumentException.class)
public void dynamicTypeCheckPutString(MyStats stat) {
if (stat.getType() == StatMap.Type.STRING) {
throw new SkipException("Skipping STRING test");
}
StatMap<MyStats> statMap = new StatMap<>(MyStats.class);
... |
public final void isEmpty() {
if (!checkNotNull(actual).isEmpty()) {
failWithActual(simpleFact("expected to be empty"));
}
} | @Test
public void multimapIsEmptyWithFailure() {
ImmutableMultimap<Integer, Integer> multimap = ImmutableMultimap.of(1, 5);
expectFailureWhenTestingThat(multimap).isEmpty();
assertFailureKeys("expected to be empty", "but was");
} |
public static byte[] computeHmac(final byte[] key, final String string)
throws SaslException {
Mac mac = createSha1Hmac(key);
mac.update(string.getBytes(StandardCharsets.UTF_8));
return mac.doFinal();
} | @Test
public void testComputeHmac() throws Exception
{
// Setup test fixture.
final byte[] key = StringUtils.decodeHex("1d96ee3a529b5a5f9e47c01f229a2cb8a6e15f7d"); // 'salted password' from the test vectors.
final String value = "Client Key";
// Execute system under test.
... |
@Override
public Boolean mSet(Map<byte[], byte[]> tuple) {
if (isQueueing() || isPipelined()) {
for (Entry<byte[], byte[]> entry: tuple.entrySet()) {
write(entry.getKey(), StringCodec.INSTANCE, RedisCommands.SET, entry.getKey(), entry.getValue());
}
return... | @Test
public void testMSet() {
Map<byte[], byte[]> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put(("test" + i).getBytes(), ("test" + i*100).getBytes());
}
connection.mSet(map);
for (Map.Entry<byte[], byte[]> entry : map.entrySet()) {
ass... |
@Override
public Result invoke(Invocation invocation) throws RpcException {
Result result;
String value = getUrl().getMethodParameter(
RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString())
.trim();
if (ConfigUtils.isEmpty(value)) {
... | @Test
void testMockInvokerFromOverride_Invoke_mock_false() {
URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName())
.addParameter(
REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=false"))
.addParam... |
public static VersionSet parse(ImmutableList<String> versionAndRangesList) {
checkNotNull(versionAndRangesList);
checkArgument(!versionAndRangesList.isEmpty(), "Versions and ranges list cannot be empty.");
VersionSet.Builder versionSetBuilder = VersionSet.builder();
for (String versionOrRangeString : ... | @Test
public void parse_withInvalidVersion_throwsIllegalArgumentException() {
IllegalArgumentException exception =
assertThrows(
IllegalArgumentException.class, () -> VersionSet.parse(ImmutableList.of("1,0", "abc")));
assertThat(exception)
.hasMessageThat()
.isEqualTo("Stri... |
@Deactivate
public void deactivate() {
eventDispatcher.removeSink(PiPipeconfEvent.class);
executor.shutdown();
driverAdminService.removeListener(driverListener);
pipeconfs.clear();
missingMergedDrivers.clear();
cfgService = null;
driverAdminService = null;
... | @Test
public void deactivate() {
mgr.deactivate();
assertNull("Incorrect driver admin service", mgr.driverAdminService);
assertNull("Incorrect driverAdminService service", mgr.driverAdminService);
assertNull("Incorrect configuration service", mgr.cfgService);
} |
@Override
public String generateSqlType(Dialect dialect) {
switch (dialect.getId()) {
case MsSql.ID:
return "NVARCHAR (MAX)";
case Oracle.ID, H2.ID:
return "CLOB";
case PostgreSql.ID:
return "TEXT";
default:
throw new IllegalArgumentException("Unsupported di... | @Test
public void generate_sql_type_on_postgre() {
assertThat(underTest.generateSqlType(new PostgreSql())).isEqualTo("TEXT");
} |
public static String validateIndexName(@Nullable String indexName) {
checkDbIdentifier(indexName, "Index name", INDEX_NAME_MAX_SIZE);
return indexName;
} | @Test
public void validateIndexName_throws_NPE_when_index_name_is_null() {
assertThatThrownBy(() -> validateIndexName(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Index name can't be null");
} |
public void removeFunctionListener(SAFunctionListener functionListener) {
if (mFunctionListener != null && functionListener != null) {
mFunctionListener.remove(functionListener);
}
} | @Test
public void removeFunctionListener() {
SensorsDataAPI sensorsDataAPI = SAHelper.initSensors(mApplication);
SAFunctionListener listener = new SAFunctionListener() {
@Override
public void call(String function, JSONObject args) {
Assert.fail();
... |
public static <T, K, V> MutableMap<K, V> aggregateInPlaceBy(
Iterable<T> iterable,
Function<? super T, ? extends K> groupBy,
Function0<? extends V> zeroValueFactory,
Procedure2<? super V, ? super T> mutatingAggregator)
{
return FJIterate.aggregateInPlaceBy(
... | @Test
public void aggregateInPlaceBy()
{
Procedure2<AtomicInteger, Integer> countAggregator = (aggregate, value) -> aggregate.incrementAndGet();
List<Integer> list = Interval.oneTo(2000);
MutableMap<String, AtomicInteger> aggregation =
FJIterate.aggregateInPlaceBy(list, E... |
public static String getTypeName(final int type) {
switch (type) {
case START_EVENT_V3:
return "Start_v3";
case STOP_EVENT:
return "Stop";
case QUERY_EVENT:
return "Query";
case ROTATE_EVENT:
return "... | @Test
public void getTypeNameInputPositiveOutputNotNull17() {
// Arrange
final int type = 18;
// Act
final String actual = LogEvent.getTypeName(type);
// Assert result
Assert.assertEquals("Execute_load_query", actual);
} |
@Override
public void suspend() {
switch (state()) {
case CREATED:
log.info("Suspended created");
transitionTo(State.SUSPENDED);
break;
case RUNNING:
log.info("Suspended running");
transitionTo(State.SU... | @Test
public void shouldAlwaysSuspendCreatedTasks() {
task = createStandbyTask();
assertThat(task.state(), equalTo(CREATED));
task.suspend();
assertThat(task.state(), equalTo(SUSPENDED));
} |
private CompletableFuture<Boolean> verifyTxnOwnership(TxnID txnID) {
assert ctx.executor().inEventLoop();
return service.pulsar().getTransactionMetadataStoreService()
.verifyTxnOwnership(txnID, getPrincipal())
.thenComposeAsync(isOwner -> {
if (isOwner... | @Test(timeOut = 30000)
public void sendEndTxnResponseFailed() throws Exception {
final TransactionMetadataStoreService txnStore = mock(TransactionMetadataStoreService.class);
when(txnStore.getTxnMeta(any())).thenReturn(CompletableFuture.completedFuture(mock(TxnMeta.class)));
when(txnStore.ve... |
@Converter
public static String toString(IoBuffer buffer, Exchange exchange) {
byte[] bytes = toByteArray(buffer);
// use type converter as it can handle encoding set on the Exchange
return exchange.getContext().getTypeConverter().convertTo(String.class, exchange, bytes);
} | @Test
public void testToString() throws UnsupportedEncodingException {
String in = "Hello World \u4f60\u597d";
IoBuffer bb = IoBuffer.wrap(in.getBytes(StandardCharsets.UTF_8));
Exchange exchange = new DefaultExchange(new DefaultCamelContext());
exchange.setProperty(Exchange.CHARSET_N... |
private <T> T accept(Expression<T> expr) {
return expr.accept(this);
} | @Test
public void testGroupedEvaluation() throws Exception {
// [count() >= 10 AND count() < 100 AND count() > 20] OR [count() == 101 OR count() == 402 OR [count() > 200 AND count() < 300]]
final Expression<Boolean> condition = loadCondition("condition-grouped.json");
final String ref = "co... |
public Collection<QualifiedTable> getSingleTables(final Collection<QualifiedTable> qualifiedTables) {
Collection<QualifiedTable> result = new LinkedList<>();
for (QualifiedTable each : qualifiedTables) {
Collection<DataNode> dataNodes = singleTableDataNodes.getOrDefault(each.getTableName().t... | @Test
void assertPut() {
SingleRule singleRule = new SingleRule(ruleConfig, DefaultDatabase.LOGIC_NAME, new H2DatabaseType(), dataSourceMap, Collections.singleton(mock(ShardingSphereRule.class, RETURNS_DEEP_STUBS)));
String tableName = "teacher";
String dataSourceName = "foo_ds";
sin... |
public boolean isRegisteredUser(@Nonnull final JID user, final boolean checkRemoteDomains) {
if (xmppServer.isLocal(user)) {
try {
getUser(user.getNode());
return true;
}
catch (final UserNotFoundException e) {
return false;
... | @Test
public void isRegisteredUserTrueWillReturnFalseForLocalNonUsers() {
final boolean result = userManager.isRegisteredUser(new JID("unknown-user", Fixtures.XMPP_DOMAIN, null), true);
assertThat(result, is(false));
} |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
JsonObject json = JsonParser.parseString(msg.getData()).getAsJsonObject();
String tmp;
if (msg.getOriginator().getEntityType() != EntityType.DEVICE) {
ctx.tellFailure(msg, new RuntimeException("Message originator is not a de... | @Test
public void givenExpirationTime_whenOnMsg_thenVerifyRequest() {
given(ctxMock.getRpcService()).willReturn(rpcServiceMock);
given(ctxMock.getTenantId()).willReturn(TENANT_ID);
String expirationTime = "2000000000000";
TbMsgMetaData metadata = new TbMsgMetaData();
metadat... |
@Override
public void failover(NamedNode master) {
connection.sync(RedisCommands.SENTINEL_FAILOVER, master.getName());
} | @Test
public void testFailover() throws InterruptedException {
Collection<RedisServer> masters = connection.masters();
connection.failover(masters.iterator().next());
Thread.sleep(10000);
RedisServer newMaster = connection.masters().iterator().next();
assert... |
@Override
public NodeHealth get() {
Health nodeHealth = healthChecker.checkNode();
this.nodeHealthBuilder
.clearCauses()
.setStatus(NodeHealth.Status.valueOf(nodeHealth.getStatus().name()));
nodeHealth.getCauses().forEach(this.nodeHealthBuilder::addCause);
return this.nodeHealthBuilder
... | @Test
public void get_returns_HEALTH_status_and_causes_from_HealthChecker_checkNode() {
setRequiredPropertiesForConstructor();
setStartedAt();
when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(4));
Health.Status randomStatus = Health.Status.values()[random.nextInt(Health.Status.values().l... |
@ExecuteOn(TaskExecutors.IO)
@Delete(uri = "logs/{executionId}")
@Operation(tags = {"Logs"}, summary = "Delete logs for a specific execution, taskrun or task")
public void delete(
@Parameter(description = "The execution id") @PathVariable String executionId,
@Parameter(description = "The min... | @Test
void deleteByQuery() {
LogEntry log1 = logEntry(Level.INFO);
LogEntry log2 = log1.toBuilder().message("another message").build();
LogEntry log3 = logEntry(Level.DEBUG);
logRepository.save(log1);
logRepository.save(log2);
logRepository.save(log3);
HttpRe... |
public static List<ComponentDto> sortComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest, List<MetricDto> metrics,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
List<String> sortParameters = wsRequest.getSort();
if (sortParameters == null || sor... | @Test
void sort_by_textual_metric_key_descending() {
components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure"));
ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_SORT), false, TEXT_METRIC_KEY);
List<ComponentDto> result = sor... |
@Override
public void run() {
if (processor != null) {
processor.execute();
} else {
if (!beforeHook()) {
logger.info("before-feature hook returned [false], aborting: {}", this);
} else {
scenarios.forEachRemaining(this::processScen... | @Test
void testCallJsonPath() {
run("call-jsonpath.feature");
} |
public long getStatementTimeoutMillis() {
return statementTimeoutMillis;
} | @Test
public void testEmpty() {
SqlConfig config = new SqlConfig();
assertEquals(SqlConfig.DEFAULT_STATEMENT_TIMEOUT_MILLIS, config.getStatementTimeoutMillis());
} |
public static int byteArrayToInt(byte[] b) {
if (b != null && (b.length == 2 || b.length == 4)) {
// Preserve sign on first byte
int value = b[0] << ((b.length - 1) * 8);
for (int i = 1; i < b.length; i++) {
int offset = (b.length - 1 - i) * 8;
... | @Test
public void testByteArrayToInt() throws Exception {
byte[] ba;
ba = new byte[] { 0, 0 };
assertEquals(0, TCPClientDecorator.byteArrayToInt(ba));
ba = new byte[] { 0, 15 };
assertEquals(15, TCPClientDecorator.byteArrayToInt(ba));
ba = new byte[] { 0, -1 };
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.