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.class.getName());
}
return new DataTypes(transferDataTypes);
}
|
@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 DataTypesAction(registry, new Monitor() {
});
GetDataTypes request = mock(GetDataTypes.class);
DataTypes actual = dataTypesAction.handle(request);
assertEquals(actual.getDataTypes(), dataTypes);
}
|
public ClientSession toClientSession()
{
return new ClientSession(
parseServer(server),
user,
source,
Optional.empty(),
parseClientTags(clientTags),
clientInfo,
catalog,
schema,
TimeZone.getDefault().getID(),
Locale.getDefault(),
toResourceEstimates(resourceEstimates),
toProperties(sessionProperties),
emptyMap(),
emptyMap(),
toExtraCredentials(extraCredentials),
null,
clientRequestTimeout,
disableCompression,
emptyMap(),
emptyMap(),
validateNextUriSource);
}
|
@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> inboundServerObserver =
TestStreams.<BeamFnApi.InstructionResponse>withOnNext(
response -> fail(String.format("Unexpected Response %s", response)))
.withOnError(error::add)
.build();
Endpoints.ApiServiceDescriptor apiServiceDescriptor =
Endpoints.ApiServiceDescriptor.newBuilder()
.setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString())
.build();
Server server =
InProcessServerBuilder.forName(apiServiceDescriptor.getUrl())
.addService(
new BeamFnControlGrpc.BeamFnControlImplBase() {
@Override
public StreamObserver<BeamFnApi.InstructionResponse> control(
StreamObserver<BeamFnApi.InstructionRequest> outboundObserver) {
Uninterruptibles.putUninterruptibly(outboundServerObservers, outboundObserver);
return inboundServerObserver;
}
})
.build();
server.start();
try {
EnumMap<
BeamFnApi.InstructionRequest.RequestCase,
ThrowingFunction<BeamFnApi.InstructionRequest, BeamFnApi.InstructionResponse.Builder>>
handlers = new EnumMap<>(BeamFnApi.InstructionRequest.RequestCase.class);
handlers.put(
BeamFnApi.InstructionRequest.RequestCase.REGISTER,
value -> {
assertEquals(value.getInstructionId(), BeamFnLoggingMDC.getInstructionId());
throw new Error("Test Error");
});
ExecutorService executor = Executors.newCachedThreadPool();
BeamFnControlClient client =
new BeamFnControlClient(
apiServiceDescriptor,
ManagedChannelFactory.createInProcess(),
OutboundObserverFactory.trivial(),
executor,
handlers);
// Get the connected client and attempt to send and receive an instruction
StreamObserver<BeamFnApi.InstructionRequest> outboundServerObserver =
outboundServerObservers.take();
// Ensure that all exceptions are caught and translated to failures
outboundServerObserver.onNext(
InstructionRequest.newBuilder()
.setInstructionId("0")
.setRegister(RegisterRequest.getDefaultInstance())
.build());
// There should be an error reported to the StreamObserver.
assertThat(error.take(), not(nullValue()));
// Ensure that the client shuts down when an Error is thrown from the harness
try {
client.terminationFuture().get();
throw new IllegalStateException("The future should have terminated with an error");
} catch (ExecutionException errorWrapper) {
assertThat(errorWrapper.getCause().getMessage(), containsString("Test Error"));
}
} finally {
server.shutdownNow();
}
}
|
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.getEdgeKeys());
assertEquals(1, result.getTotalComponents());
assertEquals(1, result.getComponents().size());
assertTrue(result.getSingleEdgeComponents().isEmpty());
assertEquals(result.getComponents().get(0), result.getBiggestComponent());
assertEquals(IntArrayList.from(1, 3, 2, 0), result.getComponents().get(0));
}
|
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.hasOption(CliFrontendOptions.HELP)) {
HelpFormatter formatter = new HelpFormatter();
formatter.setLeftPadding(4);
formatter.setWidth(80);
formatter.printHelp(" ", cliOptions);
return;
}
// Create executor and execute the pipeline
PipelineExecution.ExecutionInfo result = createExecutor(commandLine).run();
// Print execution result
printExecutionInfo(result);
}
|
@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.getAsLong());
logger.trace("Updated lag for {} to {}", tp, l.getAsLong());
} else {
fetchedLags.remove(tp);
}
}
}
}
|
@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, OptionalLong.empty()),
getValueSensor(metrics, lastLatenessValue),
enforcedProcessingSensor,
10L
);
hasNoFetchedLag(group, partition1);
lags.put(partition1, OptionalLong.of(5));
hasNoFetchedLag(group, partition1);
group.updateLags();
hasNonZeroFetchedLag(group, partition1, 5);
lags.put(partition1, OptionalLong.of(0));
group.updateLags();
hasZeroFetchedLag(group, partition1);
lags.remove(partition1);
hasZeroFetchedLag(group, partition1);
group.updateLags();
hasNoFetchedLag(group, partition1);
}
|
@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));// 等会查询到
fileConfigMapper.insert(dbFileConfig);
// 测试 name 不匹配
fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setName("源码")));
// 测试 storage 不匹配
fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setStorage(FileStorageEnum.DB.getStorage())));
// 测试 createTime 不匹配
fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setCreateTime(LocalDateTimeUtil.parse("2020-11-23", DatePattern.NORM_DATE_PATTERN))));
// 准备参数
FileConfigPageReqVO reqVO = new FileConfigPageReqVO();
reqVO.setName("芋道");
reqVO.setStorage(FileStorageEnum.LOCAL.getStorage());
reqVO.setCreateTime((new LocalDateTime[]{buildTime(2020, 1, 1),
buildTime(2020, 1, 24)}));
// 调用
PageResult<FileConfigDO> pageResult = fileConfigService.getFileConfigPage(reqVO);
// 断言
assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size());
assertPojoEquals(dbFileConfig, pageResult.getList().get(0));
}
|
@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) {
plainKey = pb.plainKey;
} else if (pb.encryptedKey != null) {
encryptedKey = pb.encryptedKey;
} else {
throw new IllegalArgumentException("no encryptedKey in EncryptionKeyPB for NormalKey id:" + id);
}
}
|
@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, mgr);
});
}
|
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[]{(byte) (value >> 32), (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8),
(byte) value};
}
|
@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("azure.upload.snapshot")) {
session.getClient().getContainerReference(containerService.getContainer(file).getName())
.getBlobReferenceFromServer(containerService.getKey(file)).createSnapshot();
}
if(status.isAppend()) {
// Existing append blob type
blob = session.getClient().getContainerReference(containerService.getContainer(file).getName())
.getAppendBlobReference(containerService.getKey(file));
}
else {
// Existing block blob type
final PathAttributes attr = new AzureAttributesFinderFeature(session, context).find(file);
if(BlobType.APPEND_BLOB == BlobType.valueOf(attr.getCustom().get(AzureAttributesFinderFeature.KEY_BLOB_TYPE))) {
blob = session.getClient().getContainerReference(containerService.getContainer(file).getName())
.getAppendBlobReference(containerService.getKey(file));
}
else {
blob = session.getClient().getContainerReference(containerService.getContainer(file).getName())
.getBlockBlobReference(containerService.getKey(file));
}
}
}
else {
// Create new blob with default type set in defaults
switch(blobType) {
case APPEND_BLOB:
blob = session.getClient().getContainerReference(containerService.getContainer(file).getName())
.getAppendBlobReference(containerService.getKey(file));
break;
default:
blob = session.getClient().getContainerReference(containerService.getContainer(file).getName())
.getBlockBlobReference(containerService.getKey(file));
}
}
if(StringUtils.isNotBlank(status.getMime())) {
blob.getProperties().setContentType(status.getMime());
}
// Add previous metadata when overwriting file
final HashMap<String, String> headers = new HashMap<>(status.getMetadata());
blob.setMetadata(headers);
// Remove additional headers not allowed in metadata and move to properties
if(headers.containsKey(HttpHeaders.CACHE_CONTROL)) {
blob.getProperties().setCacheControl(headers.get(HttpHeaders.CACHE_CONTROL));
headers.remove(HttpHeaders.CACHE_CONTROL);
}
if(headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
blob.getProperties().setContentType(headers.get(HttpHeaders.CONTENT_TYPE));
headers.remove(HttpHeaders.CONTENT_TYPE);
}
final Checksum checksum = status.getChecksum();
if(Checksum.NONE != checksum) {
switch(checksum.algorithm) {
case md5:
headers.remove(HttpHeaders.CONTENT_MD5);
blob.getProperties().setContentMD5(status.getChecksum().base64);
break;
}
}
final BlobRequestOptions options = new BlobRequestOptions();
options.setConcurrentRequestCount(1);
options.setStoreBlobContentMD5(new HostPreferences(session.getHost()).getBoolean("azure.upload.md5"));
final BlobOutputStream out;
if(status.isAppend()) {
options.setStoreBlobContentMD5(false);
if(blob instanceof CloudAppendBlob) {
out = ((CloudAppendBlob) blob).openWriteExisting(AccessCondition.generateEmptyCondition(), options, context);
}
else {
throw new NotfoundException(String.format("Unexpected blob type for %s", blob.getName()));
}
}
else {
if(blob instanceof CloudAppendBlob) {
out = ((CloudAppendBlob) blob).openWriteNew(AccessCondition.generateEmptyCondition(), options, context);
}
else {
out = ((CloudBlockBlob) blob).openOutputStream(AccessCondition.generateEmptyCondition(), options, context);
}
}
return new VoidStatusOutputStream(out) {
@Override
protected void handleIOException(final IOException e) throws IOException {
if(StringUtils.equals(SR.STREAM_CLOSED, e.getMessage())) {
log.warn(String.format("Ignore failure %s", e));
return;
}
final Throwable cause = ExceptionUtils.getRootCause(e);
if(cause instanceof StorageException) {
throw new IOException(e.getMessage(), new AzureExceptionMappingService().map((StorageException) cause));
}
throw e;
}
};
}
catch(StorageException e) {
throw new AzureExceptionMappingService().map("Upload {0} failed", e, file);
}
catch(URISyntaxException e) {
throw new NotfoundException(e.getMessage(), e);
}
}
|
@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);
status.setLength(content.length);
status.setChecksum(new MD5ChecksumCompute().compute(new ByteArrayInputStream(content), new TransferStatus().withLength(content.length)));
status.setMetadata(Collections.singletonMap("Cache-Control", "public,max-age=86400"));
final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final OutputStream out = new AzureWriteFeature(session, BlobType.BLOCK_BLOB, context).write(test, status, new DisabledConnectionCallback());
assertNotNull(out);
new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), out);
assertTrue(new AzureFindFeature(session, context).find(test));
final PathAttributes attributes = new AzureAttributesFinderFeature(session, context).find(test);
assertEquals(content.length, attributes.getSize());
final Map<String, String> metadata = new AzureMetadataFeature(session, context).getMetadata(test);
assertEquals("text/plain", metadata.get("Content-Type"));
assertEquals("public,max-age=86400", metadata.get("Cache-Control"));
final byte[] buffer = new byte[content.length];
final InputStream in = new AzureReadFeature(session, context).read(test, new TransferStatus(), new DisabledConnectionCallback());
IOUtils.readFully(in, buffer);
in.close();
assertArrayEquals(content, buffer);
final OutputStream overwrite = new AzureWriteFeature(session, context).write(test, new TransferStatus().exists(true)
.withLength("overwrite".getBytes(StandardCharsets.UTF_8).length).withMetadata(Collections.singletonMap("Content-Type", "text/plain")), new DisabledConnectionCallback());
new StreamCopier(new TransferStatus(), new TransferStatus())
.transfer(new ByteArrayInputStream("overwrite".getBytes(StandardCharsets.UTF_8)), overwrite);
overwrite.close();
// Test double close
overwrite.close();
assertEquals("overwrite".getBytes(StandardCharsets.UTF_8).length, new AzureAttributesFinderFeature(session, context).find(test).getSize());
new AzureDeleteFeature(session, context).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
|
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 not a subclass of " + targetClassType.getName());
}
return (Class<? extends T>) clazz;
} catch (ClassNotFoundException e) {
throw new ConfigParseException("Class not found: " + className, e);
}
}
|
@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"),
Basic.of("key2", 3, "value3"),
Basic.of("key2", 4, "value4")))
.apply(Group.byFieldNames("field1"));
Schema keySchema = Schema.builder().addStringField("field1").build();
Schema outputSchema =
Schema.builder()
.addRowField("key", keySchema)
.addIterableField("value", FieldType.row(BASIC_SCHEMA))
.build();
SerializableFunction<Basic, Row> toRow =
pipeline.getSchemaRegistry().getToRowFunction(Basic.class);
List<Row> expected =
ImmutableList.of(
Row.withSchema(outputSchema)
.addValue(Row.withSchema(keySchema).addValue("key1").build())
.addIterable(
ImmutableList.of(
toRow.apply(Basic.of("key1", 1L, "value1")),
toRow.apply(Basic.of("key1", 2L, "value2"))))
.build(),
Row.withSchema(outputSchema)
.addValue(Row.withSchema(keySchema).addValue("key2").build())
.addIterable(
ImmutableList.of(
toRow.apply(Basic.of("key2", 3L, "value3")),
toRow.apply(Basic.of("key2", 4L, "value4"))))
.build());
PAssert.that(grouped).satisfies(actual -> containsKIterableVs(expected, actual));
pipeline.run();
}
|
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 = parser.parse(query);
final ParsedQuery.Builder builder = ParsedQuery.builder().query(query);
builder.tokensBuilder().addAll(parser.getTokens());
final TermCollectingQueryVisitor visitor = new TermCollectingQueryVisitor(ANALYZER, parser.getTokenLookup());
parsed.visit(visitor);
builder.termsBuilder().addAll(visitor.getParsedTerms());
return builder.build();
}
|
@Test
void testLeadingWildcardsParsingDependsOnParserSettings() throws ParseException {
assertThatThrownBy(() -> parser.parse("foo:*bar"))
.isInstanceOf(ParseException.class);
assertThatThrownBy(() -> parser.parse("foo:?bar"))
.isInstanceOf(ParseException.class);
final LuceneQueryParser leadingWildcardsTolerantParser = new LuceneQueryParser(true);
assertThat(leadingWildcardsTolerantParser.parse("foo:*bar"))
.isNotNull();
assertThat(leadingWildcardsTolerantParser.parse("foo:?bar"))
.isNotNull();
}
|
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.4729730f};
Matrix a = Matrix.of(A);
Matrix.QR qr = a.qr();
double[] x2 = qr.solve(b);
assertEquals(x.length, x2.length);
for (int i = 0; i < x.length; i++) {
assertEquals(x[i], x2[i], 1E-7);
}
double[][] B = {
{0.5, 0.2f},
{0.5, 0.8f},
{0.5, 0.3f}
};
double[][] X = {
{-0.2027027, -1.2837838f},
{ 0.8783784, 2.2297297f},
{ 0.4729730, 0.6621622f}
};
Matrix X2 = Matrix.of(B);
qr.solve(X2);
for (int i = 0; i < X.length; i++) {
for (int j = 0; j < X[i].length; j++) {
assertEquals(X[i][j], X2.get(i, j), 1E-7);
}
}
}
|
@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.
} else if (localRowCount == OVER_MAX_ROW_COUNT
|| globalRowCount + localRowCount > maxRowCount) {
// The received local filter is over-max-row-count, mark the global filter as
// over-max-row-count.
globalRowCount = OVER_MAX_ROW_COUNT;
serializedGlobalFilter = null;
} else {
// merge the local filter
byte[] serializedLocalFilter = rowData.getBinary(1);
if (serializedGlobalFilter == null) {
serializedGlobalFilter = serializedLocalFilter.clone();
} else {
BloomFilter.mergeSerializedBloomFilters(
serializedGlobalFilter, serializedLocalFilter);
}
globalRowCount += localRowCount;
}
}
|
@Test
void testOverMaxRowCountInput() throws Exception {
try (StreamTaskMailboxTestHarness<RowData> testHarness =
createGlobalRuntimeFilterBuilderOperatorHarness(10)) {
// process elements
testHarness.processElement(
new StreamRecord<RowData>(
GenericRowData.of(5, BloomFilter.toBytes(createBloomFilter1()))));
testHarness.processElement(
new StreamRecord<RowData>(GenericRowData.of(OVER_MAX_ROW_COUNT, null)));
testHarness.processEvent(new EndOfData(StopMode.DRAIN), 0);
// test the output
Queue<Object> outputs = testHarness.getOutput();
assertThat(outputs.size()).isEqualTo(1);
RowData outputRowData = ((StreamRecord<RowData>) outputs.poll()).getValue();
assertThat(outputRowData.getArity()).isEqualTo(2);
int globalCount = outputRowData.getInt(0);
assertThat(globalCount).isEqualTo(OVER_MAX_ROW_COUNT);
assertThat(outputRowData.isNullAt(1)).isTrue();
}
}
|
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(configForEdit);
config = preprocessAndValidate(configForEdit);
return new GoConfigHolder(config, configForEdit);
}
|
@Test
void shouldAllowOnlyOneTimerOnAPipeline() {
String content = configWithPipeline(
"""
<pipeline name='pipeline1'>
<timer>1 1 1 * * ? *</timer>
<timer>2 2 2 * * ? *</timer>
<materials>
<svn url ='svnurl'/>
</materials>
<stage name='mingle'>
<jobs>
<job name='cardlist'><tasks><exec command='echo'><runif status='passed' /></exec></tasks></job>
</jobs>
</stage>
</pipeline>""", CONFIG_SCHEMA_VERSION);
assertThatThrownBy(() -> xmlLoader.loadConfigHolder(content))
.as("XSD should not allow duplicate timer in pipeline")
.hasMessageContaining("Invalid content was found starting with element 'timer'.");
}
|
@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);
if (parser == null) {
Loggers.AUTH.warn("Can't find Grpc request resourceParser for type {}", type);
return useSpecifiedParserToParse(secured, request);
}
return parser.parse(request, secured);
}
|
@Test
@Secured(signType = "non-exist")
void testParseResourceWithNonExistType() throws NoSuchMethodException {
Secured secured = getMethodSecure("testParseResourceWithNonExistType");
Resource actual = protocolAuthService.parseResource(namingRequest, secured);
assertEquals(Resource.EMPTY_RESOURCE, actual);
}
|
@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(eq(true));
}
|
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 LocalDate localDate = localDateTime.toLocalDate();
final DateTime date2 = DateUtil.date(localDate);
assertEquals("2017-05-06",
DateUtil.format(date2, DatePattern.NORM_DATE_PATTERN));
}
|
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 IllegalArgumentException("Only Strings containing two Date separated by a '-' or a single Date are allowed");
ParsedCalendar from = parseDateString(dateArr[0]);
ParsedCalendar to;
if (dateArr.length == 2)
to = parseDateString(dateArr[1]);
else
// faster and safe?
// to = new ParsedCalendar(from.parseType, (Calendar) from.parsedCalendar.clone());
to = parseDateString(dateArr[0]);
try {
return new DateRange(from, to);
} catch (IllegalArgumentException ex) {
return null;
}
}
|
@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 = {
"",
"===========================================",
"= _ _ ____ ____ =",
"= | | _____ __ _| | _ \\| __ ) =",
"= | |/ / __|/ _` | | | | | _ \\ =",
"= | <\\__ \\ (_| | | |_| | |_) | =",
"= |_|\\_\\___/\\__, |_|____/|____/ =",
"= |_| =",
"= The Database purpose-built =",
"= for stream processing apps =",
"==========================================="
};
final String copyrightMsg = "Copyright 2017-2022 Confluent Inc.";
final Integer logoWidth = Arrays.stream(lines)
.map(String::length)
.reduce(0, Math::max);
// Don't want to display the logo if it'll just end up getting wrapped and looking hideous
if (consoleWidth < logoWidth) {
writer.println("ksqlDB, " + copyrightMsg);
} else {
final int paddingChars = (consoleWidth - logoWidth) / 2;
final String leftPadding = IntStream.range(0, paddingChars)
.mapToObj(idx -> " ")
.collect(Collectors.joining());
Arrays.stream(lines)
.forEach(line -> writer.println(leftPadding + line));
writer.println();
writer.println(copyrightMsg);
}
writer.println();
writer.flush();
}
|
@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();
DataOutputViewStreamWrapper wrapper = new DataOutputViewStreamWrapper(baos);
serializer.serialize(value, wrapper);
invokingRecordBytes = baos.size();
if (invokingRecordBytes > maxBytesPerBatch) {
throw new RuntimeException(
"Record size is too large for CollectSinkFunction. Record size is "
+ invokingRecordBytes
+ " bytes, "
+ "but max bytes per batch is only "
+ maxBytesPerBatch
+ " bytes. "
+ "Please consider increasing max bytes per batch value by setting "
+ CollectSinkOperatorFactory.MAX_BATCH_SIZE.key());
}
if (currentBufferBytes + invokingRecordBytes > bufferSizeLimitBytes) {
bufferCanAddNextResultCondition.await();
}
buffer.add(baos.toByteArray());
currentBufferBytes += baos.size();
} finally {
bufferLock.unlock();
}
}
|
@Test
void testCheckpoint() throws Exception {
functionWrapper.openFunctionWithState();
for (int i = 0; i < 2; i++) {
functionWrapper.invoke(i);
}
String version = initializeVersion();
CollectCoordinationResponse response =
functionWrapper.sendRequestAndGetResponse(version, 0);
assertResponseEquals(response, version, 0, Arrays.asList(0, 1));
for (int i = 2; i < 6; i++) {
functionWrapper.invoke(i);
}
response = functionWrapper.sendRequestAndGetResponse(version, 3);
assertResponseEquals(response, version, 0, Arrays.asList(3, 4, 5));
functionWrapper.checkpointFunction(1);
// checkpoint hasn't finished yet
response = functionWrapper.sendRequestAndGetResponse(version, 4);
assertResponseEquals(response, version, 0, Arrays.asList(4, 5));
functionWrapper.checkpointComplete(1);
// checkpoint finished
response = functionWrapper.sendRequestAndGetResponse(version, 4);
assertResponseEquals(response, version, 3, Arrays.asList(4, 5));
functionWrapper.closeFunctionNormally();
}
|
@Override
@Transactional(rollbackFor = Exception.class)
public void updateFileConfigMaster(Long id) {
// 校验存在
validateFileConfigExists(id);
// 更新其它为非 master
fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false));
// 更新
fileConfigMapper.updateById(new FileConfigDO().setId(id).setMaster(true));
// 清空缓存
clearCache(null, true);
}
|
@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 DenseVector) {
for (int i = 0; i < elements.length; i++) {
score += get(i) * other.get(i);
}
} else {
// else must be sparse
for (VectorTuple tuple : other) {
score += get(tuple.index) * tuple.value;
}
}
return score;
}
|
@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 if this is an http channel exception
HttpChannelEOFException channelException =
maybeExtractChannelException(path, message, cause);
if (channelException != null) {
return channelException;
}
// not a channel exception, not an IOE.
if (!(cause instanceof IOException)) {
return null;
}
// the cause can be extracted to an IOE.
// rather than just return it, we try to preserve the stack trace
// of the outer exception.
// as a new instance is created through reflection, the
// class of the returned instance will be that of the innermost,
// unless no suitable constructor is available.
final IOException ioe = (IOException) cause;
return wrapWithInnerIOE(path, message, thrown, ioe);
}
|
@Test
public void testNoConstructorExtraction() throws Throwable {
intercept(PathIOException.class, NoConstructorIOE.MESSAGE,
() -> {
throw maybeExtractIOException("p1",
sdkException("top",
sdkException("middle",
new NoConstructorIOE())), null);
});
}
|
@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 = createPullResult(requestHeader, PullStatus.FOUND, Collections.singletonList(new MessageExt()));
PullCallback pullCallback = mock.getArgument(4);
pullCallback.onSuccess(pullResult);
return null;
}
}).when(mQClientAPIImpl).pullMessage(anyString(), any(PullMessageRequestHeader.class), anyLong(), any(CommunicationMode.class), nullable(PullCallback.class));
MessageQueue messageQueue = new MessageQueue(topic, brokerName, 0);
pullConsumer.pull(messageQueue, "*", 1024, 3, new PullCallback() {
@Override
public void onSuccess(PullResult pullResult) {
assertThat(pullResult).isNotNull();
assertThat(pullResult.getPullStatus()).isEqualTo(PullStatus.FOUND);
assertThat(pullResult.getNextBeginOffset()).isEqualTo(1024 + 1);
assertThat(pullResult.getMinOffset()).isEqualTo(123);
assertThat(pullResult.getMaxOffset()).isEqualTo(2048);
assertThat(pullResult.getMsgFoundList()).isEqualTo(new ArrayList<>());
}
@Override
public void onException(Throwable e) {
}
});
}
|
@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/projects/cce/cards/111\" target=\"story_tracker\">#111</a>: checkin message"));
}
|
@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 = sqHealthState.entrySet().stream()
.filter(outOfDate(timeout))
.filter(ofNonExistentMember(hzMemberUUIDs))
.map(entry -> entry.getValue().getNodeHealth())
.collect(Collectors.toSet());
if (LOG.isTraceEnabled()) {
LOG.trace("Reading {} and keeping {}", new HashMap<>(sqHealthState), existingNodeHealths);
}
return ImmutableSet.copyOf(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 = new HashMap<>();
Map<UUID, NodeHealth> expected = new HashMap<>();
for (NodeHealth nodeHealth : nodeHealths) {
UUID memberUuid = UUID.randomUUID();
TimestampedNodeHealth timestampedNodeHealth = new TimestampedNodeHealth(nodeHealth, clusterTime - random.nextInt(30 * 1000));
allNodeHealths.put(memberUuid, timestampedNodeHealth);
if (random.nextBoolean()) {
expected.put(memberUuid, nodeHealth);
}
}
doReturn(allNodeHealths).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE);
when(hazelcastMember.getMemberUuids()).thenReturn(expected.keySet());
when(hazelcastMember.getClusterTime()).thenReturn(clusterTime);
assertThat(underTest.readAll())
.containsOnly(expected.values().toArray(new NodeHealth[0]));
assertThat(logging.getLogs()).isEmpty();
}
|
@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();
case "toString":
return toString();
default:
break;
}
return decoratedDispatch.get(method).apply(args);
}
|
@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(0)).invoke(any());
assertThat(feignDecorator.isCalled())
.describedAs("FeignDecorator is called")
.isTrue();
assertThat(result)
.describedAs("Return of invocation")
.isTrue();
}
|
@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 < field.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(field.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before, counter goes up.
} else if (!Character.isLetter(field.charAt(i)) && word) {
count++;
word = false;
// last word of String; if it doesn't end with a non letter, it wouldn't count without this.
} else if (Character.isLetter(field.charAt(i)) && i == endOfLine) {
count++;
}
}
}
return count;
}
|
@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.getDefaultMockInvoker();
when(invocation.getAttachment(ASYNC_KEY)).thenReturn(Boolean.TRUE.toString());
initDegradeRule(DubboUtils.getInterfaceName(invoker));
Result result = invokeDubboRpc(false, invoker, invocation);
verifyInvocationStructureForCallFinish(invoker, invocation);
assertEquals("normal", result.getValue());
// inc the clusterNode's exception to trigger the fallback
for (int i = 0; i < 5; i++) {
invokeDubboRpc(true, invoker, invocation);
verifyInvocationStructureForCallFinish(invoker, invocation);
}
Result result2 = invokeDubboRpc(false, invoker, invocation);
assertEquals("fallback", result2.getValue());
// sleeping 1000 ms to reset exception
sleep(mocked, 1000);
Result result3 = invokeDubboRpc(false, invoker, invocation);
assertEquals("normal", result3.getValue());
Context context = ContextUtil.getContext();
assertNull(context);
}
}
|
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 specMethod = jej.getSpecificationMethod();
// If the reference is by filename, change it to Repository By Name. Otherwise it's fine so leave it alone
if ( specMethod == ObjectLocationSpecificationMethod.FILENAME ) {
jej.setSpecificationMethod( ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME );
String filename = jej.getFilename();
// if the filename is a missing variable name, it will not contain a slash - we don't want to fail
// ungracefully in this case, simply set the job name to the whole filename value and let the run-time
// handle any exceptions that arise from this
if ( filename != null ) {
if ( filename.indexOf( "/" ) > -1 ) {
String jobname = filename.substring( filename.lastIndexOf( "/" ) + 1, filename.lastIndexOf( '.' ) );
String directory = filename.substring( 0, filename.lastIndexOf( "/" ) );
jej.setJobName( jobname );
jej.setDirectory( directory );
} else {
jej.setJobName( filename );
}
}
jobMeta.setJobEntry( i, jec );
}
}
}
return jobMeta;
}
|
@Test
public void testProcessLinkedJobsWithFilename() {
JobEntryJob jobJobExecutor = spy( new JobEntryJob() );
jobJobExecutor.setFileName( "/path/to/Job1.kjb" );
jobJobExecutor.setSpecificationMethod( ObjectLocationSpecificationMethod.FILENAME );
JobEntryCopy jobEntry = mock( JobEntryCopy.class );
when( jobEntry.getEntry() ).thenReturn( jobJobExecutor );
JobMeta parent = mock( JobMeta.class );
when( parent.nrJobEntries() ).thenReturn( 1 );
when( parent.getJobEntry( 0 ) ).thenReturn( jobEntry );
JobMeta result = jobFileListener.processLinkedJobs( parent );
JobEntryCopy meta = result.getJobEntry( 0 );
assertNotNull( meta );
JobEntryJob resultExecMeta = (JobEntryJob) meta.getEntry();
assertEquals( ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME, resultExecMeta.getSpecificationMethod() );
assertEquals( resultExecMeta.getDirectory(), "/path/to" );
assertEquals( resultExecMeta.getJobName(), "Job1" );
}
|
@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) {
for (int port = portRange.getFromPort(); port <= portRange.getToPort(); port++) {
result.add(createDiscoveryNode(gcpAddress, port));
}
}
return result;
} catch (Exception e) {
LOGGER.warning("Cannot discover nodes, returning empty list", e);
return Collections.emptyList();
}
}
|
@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));
// when
Iterable<DiscoveryNode> nodes = gcpDiscoveryStrategy.discoverNodes();
// then
Iterator<DiscoveryNode> iter = nodes.iterator();
DiscoveryNode node1 = iter.next();
assertEquals(gcpInstance1.getPrivateAddress(), node1.getPrivateAddress().getHost());
assertEquals(gcpInstance1.getPublicAddress(), node1.getPublicAddress().getHost());
assertEquals(PORT1, node1.getPrivateAddress().getPort());
DiscoveryNode node2 = iter.next();
assertEquals(gcpInstance1.getPrivateAddress(), node2.getPrivateAddress().getHost());
assertEquals(gcpInstance1.getPublicAddress(), node2.getPublicAddress().getHost());
assertEquals(PORT2, node2.getPrivateAddress().getPort());
DiscoveryNode node3 = iter.next();
assertEquals(gcpInstance2.getPrivateAddress(), node3.getPrivateAddress().getHost());
assertEquals(gcpInstance2.getPublicAddress(), node3.getPublicAddress().getHost());
assertEquals(PORT1, node3.getPrivateAddress().getPort());
DiscoveryNode node4 = iter.next();
assertEquals(gcpInstance2.getPrivateAddress(), node4.getPrivateAddress().getHost());
assertEquals(gcpInstance2.getPublicAddress(), node4.getPublicAddress().getHost());
assertEquals(PORT2, node4.getPrivateAddress().getPort());
}
|
@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\":{" +
" \"key1\":\"value1\"" +
" }" +
"}";
assertThatJson(expected).isEqualTo(actual);
}
|
@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);
} else if (targetType.isDatetime()) {
return new DateLiteral(this.year, this.month, this.day, this.hour, this.minute, this.second,
this.microsecond);
} else {
throw new AnalysisException("Error date literal type : " + type);
}
} else if (targetType.isStringType()) {
return new StringLiteral(getStringValue());
} else if (Type.isImplicitlyCastable(this.type, targetType, true)) {
return new CastExpr(targetType, this);
}
Preconditions.checkState(false);
return this;
}
|
@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);
Assert.assertEquals(castToExpr.type, Type.DATETIME);
DateLiteral literal2 = new DateLiteral("1997-10-07 12:23:23", Type.DATETIME);
Expr castToExpr2 = literal2.uncheckedCastTo(Type.DATETIME);
Assert.assertTrue(castToExpr2 instanceof DateLiteral);
} catch (AnalysisException e) {
e.printStackTrace();
hasException = true;
}
Assert.assertFalse(hasException);
}
|
@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 {
result = session.dataShortMessage(
dataSm.getServiceType(),
TypeOfNumber.valueOf(dataSm.getSourceAddrTon()),
NumberingPlanIndicator.valueOf(dataSm.getSourceAddrNpi()),
dataSm.getSourceAddr(),
TypeOfNumber.valueOf(dataSm.getDestAddrTon()),
NumberingPlanIndicator.valueOf(dataSm.getDestAddrNpi()),
dataSm.getDestAddress(),
new ESMClass(dataSm.getEsmClass()),
new RegisteredDelivery(dataSm.getRegisteredDelivery()),
DataCodings.newInstance(dataSm.getDataCoding()),
dataSm.getOptionalParameters());
} catch (Exception e) {
throw new SmppException(e);
}
if (log.isDebugEnabled()) {
log.debug("Sent a data short message for exchange id '{}' and message id '{}'",
exchange.getExchangeId(), result.getMessageId());
}
Message message = ExchangeHelper.getResultMessage(exchange);
message.setHeader(SmppConstants.ID, result.getMessageId());
message.setHeader(SmppConstants.OPTIONAL_PARAMETERS, createOptionalParameterByName(result.getOptionalParameters()));
message.setHeader(SmppConstants.OPTIONAL_PARAMETER, createOptionalParameterByCode(result.getOptionalParameters()));
}
|
@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(NumberingPlanIndicator.UNKNOWN), eq("1616"),
eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()),
eq(new RegisteredDelivery((byte) 1)), eq(DataCodings.newInstance((byte) 0))))
.thenReturn(new DataSmResult(new MessageId("1"), null));
command.execute(exchange);
assertEquals("1", exchange.getMessage().getHeader(SmppConstants.ID));
assertNull(exchange.getMessage().getHeader(SmppConstants.OPTIONAL_PARAMETERS));
}
|
@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[], Integer> multimapState = underTest.state(NAMESPACE, addr);
SettableFuture<Iterable<Map.Entry<ByteString, Iterable<Integer>>>> entriesFuture =
SettableFuture.create();
when(mockReader.multimapFetchAllFuture(
false, key(NAMESPACE, tag), STATE_FAMILY, VarIntCoder.of()))
.thenReturn(entriesFuture);
waitAndSet(
entriesFuture,
() ->
new Iterator<Map.Entry<ByteString, Iterable<Integer>>>() {
final int targetEntries = 1_000_000; // return 1 million entries, which is 10 GBs
final byte[] entryKey = new byte[10_000]; // each key is 10KB
final Random rand = new Random();
int returnedEntries = 0;
@Override
public boolean hasNext() {
return returnedEntries < targetEntries;
}
@Override
public Map.Entry<ByteString, Iterable<Integer>> next() {
returnedEntries++;
rand.nextBytes(entryKey);
return multimapEntry(entryKey, 1);
}
},
200);
Iterable<Map.Entry<byte[], Integer>> entries = multimapState.entries().read();
assertEquals(1_000_000, Iterables.size(entries));
}
|
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 subclass of " + Tuple.class.getName());
}
@SuppressWarnings("unchecked")
TupleTypeInfo<T> typeInfo = (TupleTypeInfo<T>) TypeExtractor.createTypeInfo(targetType);
CsvInputFormat<T> inputFormat =
new TupleCsvInputFormat<T>(
path, this.lineDelimiter, this.fieldDelimiter, typeInfo, this.includedMask);
Class<?>[] classes = new Class<?>[typeInfo.getArity()];
for (int i = 0; i < typeInfo.getArity(); i++) {
classes[i] = typeInfo.getTypeAt(i).getTypeClass();
}
configureInputFormat(inputFormat);
return new DataSource<T>(
executionContext, inputFormat, typeInfo, Utils.getCallLocationName());
}
|
@Test
void testSubClassWithPartialsInHierarchie() {
CsvReader reader = getCsvReader();
DataSource<FinalItem> sitems = reader.tupleType(FinalItem.class);
TypeInformation<?> info = sitems.getType();
assertThat(info.isTupleType()).isTrue();
assertThat(info.getTypeClass()).isEqualTo(FinalItem.class);
@SuppressWarnings("unchecked")
TupleTypeInfo<SubItem> tinfo = (TupleTypeInfo<SubItem>) info;
assertThat(tinfo.getTypeAt(0)).isEqualTo(BasicTypeInfo.INT_TYPE_INFO);
assertThat(tinfo.getTypeAt(1)).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO);
assertThat(tinfo.getTypeAt(2)).isEqualTo(BasicTypeInfo.DOUBLE_TYPE_INFO);
assertThat(tinfo.getTypeAt(3).getClass()).isEqualTo(ValueTypeInfo.class);
assertThat(tinfo.getTypeAt(4).getClass()).isEqualTo(ValueTypeInfo.class);
assertThat((tinfo.getTypeAt(3)).getTypeClass()).isEqualTo(StringValue.class);
assertThat((tinfo.getTypeAt(4)).getTypeClass()).isEqualTo(LongValue.class);
CsvInputFormat<?> inputFormat = (CsvInputFormat<?>) sitems.getInputFormat();
assertThat(inputFormat.getFieldTypes())
.containsExactly(
Integer.class,
String.class,
Double.class,
StringValue.class,
LongValue.class);
}
|
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").callbackData("callback cancel"),
new InlineKeyboardButton("url").url(someUrl),
new InlineKeyboardButton("switch inline").switchInlineQuery("query"),
new InlineKeyboardButton("switch inline current").switchInlineQueryCurrentChat("query"),
};
InlineKeyboardButton[][] inlineKeyboard = new InlineKeyboardButton[1][];
inlineKeyboard[0] = buttons;
InlineKeyboardMarkup keyboardMarkup = new InlineKeyboardMarkup(inlineKeyboard);
String desc = "pengrad_test_game";
Message message = bot.execute(new SendGame(chatId, desc).replyMarkup(keyboardMarkup)).message();
MessageTest.checkMessage(message);
Game game = message.game();
GameTest.check(game);
assertEquals(desc, game.description());
InlineKeyboardButton[] actualButtons = message.replyMarkup().inlineKeyboard()[0];
assertEquals(buttons.length, actualButtons.length);
assertNotNull(actualButtons[0].callbackGame());
for (int i = 1; i < buttons.length; i++) {
assertEquals(buttons[i].text(), actualButtons[i].text());
assertFalse(buttons[i].isPay());
}
assertEquals(buttons[1].callbackData(), actualButtons[1].callbackData());
assertEquals(buttons[2].callbackData(), actualButtons[2].callbackData());
assertEquals(buttons[3].url(), actualButtons[3].url());
assertEquals(buttons[4].switchInlineQuery(), actualButtons[4].switchInlineQuery());
assertEquals(buttons[5].switchInlineQueryCurrentChat(), actualButtons[5].switchInlineQueryCurrentChat());
}
|
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 within maximum stream size.
if (this._nextBufferSize > MAX_STREAM_SIZE - size())
{
this._nextBufferSize = MAX_STREAM_SIZE - size();
}
this._bufferList.add(new byte[this._nextBufferSize]);
this._nextBufferSize *= 2;
}
|
@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 the first write.
Assert.assertEquals(((LinkedList<byte[]>) bufferListField.get(testStream)).size(), 0);
testStream.write(1);
Assert.assertEquals(((LinkedList<byte[]>) bufferListField.get(testStream)).size(), 1);
Field defaultSizeField = FastByteArrayOutputStream.class.getDeclaredField("DEFAULT_BUFFER_SIZE");
defaultSizeField.setAccessible(true);
int defaultSize = (int) defaultSizeField.get(null);
byte[] testArray = new byte[defaultSize];
testStream.write(testArray, 0, testArray.length);
// Exceed the capacity of DEFAULT_BUFFER_SIZE and the second buffer is added.
Assert.assertEquals(((LinkedList<byte[]>) bufferListField.get(testStream)).size(), 2);
Assert.assertEquals(testStream.toByteArray().length, defaultSize + 1);
}
|
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 = dataSerializer.serialize(data);
managedLedger.asyncAddEntry(byteBuf, DisabledBatchCallback.INSTANCE,
AsyncAddArgs.newInstance(callback, ctx, System.currentTimeMillis(), byteBuf));
return;
}
CompletableFuture
.runAsync(
() -> internalAsyncAddData(data, callback, ctx), singleThreadExecutorForWrite)
.exceptionally(e -> {
log.warn("Execute 'internalAsyncAddData' fail", e);
return null;
});
}
|
@Test
public void testMetricsStatsThatTriggeredByMaxDelayTime() throws Exception {
SumStrDataSerializer dataSerializer = new SumStrDataSerializer();
int writeCount = 1;
int batchedWriteMaxDelayInMillis = 1000;
int expectFlushCount = 1;
int expectedTotalBytesSize = writeCount * dataSerializer.getSizePerData();
var callbackWithCounter = createCallBackWithCounter();
// Create TxnLogBufferedWriter.
var txnLogBufferedWriterContext =
createTxnBufferedWriterContextWithMetrics(dataSerializer, Integer.MAX_VALUE,
Integer.MAX_VALUE, batchedWriteMaxDelayInMillis);
var txnLogBufferedWriter = txnLogBufferedWriterContext.txnLogBufferedWriter;
// Add one data.
txnLogBufferedWriter.asyncAddData(1, callbackWithCounter.callback, "");
// Wait for all write finish.
Awaitility.await().atMost(2, TimeUnit.SECONDS).until(
() -> callbackWithCounter.finishCounter.get() + callbackWithCounter.failureCounter.get() == writeCount
);
assertEquals(callbackWithCounter.failureCounter.get(), 0);
int actualBatchFlushCount = txnLogBufferedWriterContext.mockedManagedLedger.writeCounter.get();
assertEquals(actualBatchFlushCount, expectFlushCount);
verifyTheCounterMetrics(0,0, actualBatchFlushCount,0);
verifyTheHistogramMetrics(actualBatchFlushCount, writeCount, expectedTotalBytesSize);
// cleanup.
releaseTxnLogBufferedWriterContext(txnLogBufferedWriterContext);
// after close, verify the metrics change to 0.
verifyTheCounterMetrics(0,0,0,0);
verifyTheHistogramMetrics(0,0,0);
}
|
@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,
serdes::keyFrom,
serdes::valueFrom,
time,
numOpenIterators,
openIterators);
}
|
@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)) {
continue;
}
if (member.localMember() || failureDetector.isAlive(member, timestamp)) {
count++;
}
}
return count >= minimumClusterSize;
}
|
@Test
public void testSplitBrainProtectionAbsent_whenIcmpSuspects() {
splitBrainProtectionFunction = new ProbabilisticSplitBrainProtectionFunction(splitBrainProtectionSize, 10000, 10000, 200, 100, 10);
prepareSplitBrainProtectionFunctionForIcmpFDTest(splitBrainProtectionFunction);
// heartbeat each second for all members for 5 seconds
heartbeat(5, 1000);
pingFailure();
assertFalse(splitBrainProtectionFunction.apply(Arrays.asList(members)));
}
|
@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++) {
int deleteCount = apiAccessLogMapper.deleteByCreateTimeLt(expireDate, deleteLimit);
count += deleteCount;
// 达到删除预期条数,说明到底了
if (deleteCount < deleteLimit) {
break;
}
}
return count;
}
|
@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(Duration.ofDays(-1))));
apiAccessLogMapper.insert(log02);
// 准备参数
Integer exceedDay = 2;
Integer deleteLimit = 1;
// 调用
Integer count = apiAccessLogService.cleanAccessLog(exceedDay, deleteLimit);
// 断言
assertEquals(1, count);
List<ApiAccessLogDO> logs = apiAccessLogMapper.selectList();
assertEquals(1, logs.size());
assertEquals(log02, logs.get(0));
}
|
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(
() ->
withRetryableTransaction(
conn -> {
try (PreparedStatement stmt = conn.prepareStatement(ADD_STEP_BREAKPOINT)) {
int idx = 0;
stmt.setString(++idx, revisedWorkflowId);
stmt.setLong(++idx, version);
stmt.setLong(++idx, instanceId);
stmt.setLong(++idx, runId);
stmt.setString(++idx, stepId);
stmt.setLong(++idx, stepAttemptId);
stmt.setString(++idx, toJson(user));
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return stepBreakpointFromResultSet(rs);
} else {
throw new MaestroBadRequestException(
Collections.emptyList(),
"Breakpoint could not be set with identifier [%s][%d][%d][%d][%s][%d]",
workflowId,
version,
instanceId,
runId,
stepId,
stepAttemptId);
}
}
}
}),
"addStepBreakpointForStepIdentifier",
"Failed to addStepBreakpointForStepIdentifier [{}][{}][{}][{}][{}][{}]",
workflowId,
version,
instanceId,
runId,
stepId,
stepAttemptId);
}
|
@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_WORKFLOW_VERSION1,
TEST_WORKFLOW_INSTANCE1,
Constants.MATCH_ALL_RUNS,
TEST_FOREACH_STEP_ID4,
Constants.MATCH_ALL_STEP_ATTEMPTS,
TEST_USER);
assertEquals(
String.format("%s_%s_", Constants.FOREACH_INLINE_WORKFLOW_PREFIX, hashedInternalId),
bp.getWorkflowId());
assertEquals(TEST_FOREACH_STEP_ID4, bp.getStepId());
assertEquals(TEST_WORKFLOW_INSTANCE1, bp.getWorkflowInstanceId().longValue());
assertEquals(TEST_WORKFLOW_VERSION1, bp.getWorkflowVersionId().longValue());
assertNull(bp.getWorkflowRunId());
assertNull(bp.getStepAttemptId());
}
|
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.class);
when(databaseRule.getAttributes()).thenReturn(new RuleAttributes());
ShardingSphereMetaData metaData = new ShardingSphereMetaData(new HashMap<>(Collections.singletonMap("foo_db", mockDatabase(resourceMetaData, dataSource, databaseRule))),
mock(ResourceMetaData.class), new RuleMetaData(Collections.singleton(globalRule)), new ConfigurationProperties(new Properties()));
metaData.dropDatabase("foo_db");
assertTrue(metaData.getDatabases().isEmpty());
Awaitility.await().pollDelay(10L, TimeUnit.MILLISECONDS).until(dataSource::isClosed);
assertTrue(dataSource.isClosed());
verify(globalRule).refresh(metaData.getDatabases(), GlobalRuleChangedType.DATABASE_CHANGED);
}
|
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 from the file to an object and then back to JSON so that
// missing fields
// are filled in with their default values.
String json =
String.format(
"{\"metadata-location\":\"%s\",\"metadata\":%s,\"config\":{\"foo\":\"bar\"}}",
TEST_METADATA_LOCATION, TableMetadataParser.toJson(v1Metadata));
LoadTableResponse resp =
LoadTableResponse.builder().withTableMetadata(v1Metadata).addAllConfig(CONFIG).build();
assertRoundTripSerializesEquallyFrom(json, resp);
}
|
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 (isBeanPropertyReadMethod(method)) {
method.setAccessible(true);
String property = getPropertyNameFromBeanReadMethod(method);
properties.put(property, method);
}
}
}
return properties;
}
|
@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()) {
if (!m.isAccessible()) {
fail();
}
}
}
|
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));
assertEquals(4, g3.getDegree(3));
assertEquals(2, g4.getDegree(4));
assertEquals(0, g5.getDegree(1));
assertEquals(1, g6.getDegree(1));
g6.addEdge(1, 1);
assertEquals(2, g6.getDegree(1));
assertEquals(2, g7.getDegree(1));
assertEquals(2, g7.getDegree(2));
assertEquals(2, g7.getDegree(3));
assertEquals(2, g8.getDegree(4));
}
|
@Override
public long getNumBytesProduced() {
checkState(
subpartitionBytesByPartitionIndex.size() == numOfPartitions,
"Not all partition infos are ready");
return subpartitionBytesByPartitionIndex.values().stream()
.flatMapToLong(Arrays::stream)
.reduce(0L, Long::sum);
}
|
@Test
void testGetNumBytesProducedWithIndexRange() {
PointwiseBlockingResultInfo resultInfo =
new PointwiseBlockingResultInfo(new IntermediateDataSetID(), 2, 2);
resultInfo.recordPartitionInfo(0, new ResultPartitionBytes(new long[] {32L, 64L}));
resultInfo.recordPartitionInfo(1, new ResultPartitionBytes(new long[] {128L, 256L}));
IndexRange partitionIndexRange = new IndexRange(0, 0);
IndexRange subpartitionIndexRange = new IndexRange(0, 1);
assertThat(resultInfo.getNumBytesProduced(partitionIndexRange, subpartitionIndexRange))
.isEqualTo(96L);
}
|
public SearchResponse search(IssueQuery query, SearchOptions options) {
SearchRequest requestBuilder = EsClient.prepareSearch(TYPE_ISSUE.getMainType());
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
requestBuilder.source(sourceBuilder);
configureSorting(query, sourceBuilder);
configurePagination(options, sourceBuilder);
configureRouting(query, options, requestBuilder);
AllFilters allFilters = createAllFilters(query);
RequestFiltersComputer filterComputer = newFilterComputer(options, allFilters);
configureTopAggregations(query, options, sourceBuilder, allFilters, filterComputer);
configureQuery(sourceBuilder, filterComputer);
configureTopFilters(sourceBuilder, filterComputer);
sourceBuilder.fetchSource(false)
.trackTotalHits(true);
return client.search(requestBuilder);
}
|
@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));
}
indexIssues(issues.toArray(new IssueDoc[]{}));
IssueQuery.Builder query = IssueQuery.builder();
SearchResponse result = underTest.search(query.build(), new SearchOptions().setLimit(500));
assertThat(result.getHits().getHits()).hasSize(SearchOptions.MAX_PAGE_SIZE);
assertThat(result.getHits().getTotalHits().value).isEqualTo(11_000L);
assertThat(result.getHits().getTotalHits().relation).isEqualTo(Relation.EQUAL_TO);
}
|
public static Pod createPod(
String name,
String namespace,
Labels labels,
OwnerReference ownerReference,
PodTemplate template,
Map<String, String> defaultPodLabels,
Map<String, String> podAnnotations,
Affinity affinity,
List<Container> initContainers,
List<Container> containers,
List<Volume> volumes,
List<LocalObjectReference> defaultImagePullSecrets,
PodSecurityContext podSecurityContext
) {
return new PodBuilder()
.withNewMetadata()
.withName(name)
.withLabels(labels.withAdditionalLabels(Util.mergeLabelsOrAnnotations(defaultPodLabels, TemplateUtils.labels(template))).toMap())
.withNamespace(namespace)
.withAnnotations(Util.mergeLabelsOrAnnotations(podAnnotations, TemplateUtils.annotations(template)))
.withOwnerReferences(ownerReference)
.endMetadata()
.withNewSpec()
.withRestartPolicy("Never")
.withServiceAccountName(name)
.withEnableServiceLinks(template != null ? template.getEnableServiceLinks() : null)
.withAffinity(affinity)
.withInitContainers(initContainers)
.withContainers(containers)
.withVolumes(volumes)
.withTolerations(template != null && template.getTolerations() != null ? template.getTolerations() : null)
.withTerminationGracePeriodSeconds(template != null ? (long) template.getTerminationGracePeriodSeconds() : 30L)
.withImagePullSecrets(imagePullSecrets(template, defaultImagePullSecrets))
.withSecurityContext(podSecurityContext)
.withPriorityClassName(template != null ? template.getPriorityClassName() : null)
.withSchedulerName(template != null && template.getSchedulerName() != null ? template.getSchedulerName() : "default-scheduler")
.withHostAliases(template != null ? template.getHostAliases() : null)
.withTopologySpreadConstraints(template != null ? template.getTopologySpreadConstraints() : null)
.endSpec()
.build();
}
|
@Test
public void testCreatePodWithEmptyTemplate() {
Pod pod = WorkloadUtils.createPod(
NAME,
NAMESPACE,
LABELS,
OWNER_REFERENCE,
new PodTemplate(),
Map.of("default-label", "default-value"),
Map.of("extra", "annotations"),
DEFAULT_AFFINITY,
List.of(new ContainerBuilder().withName("init-container").build()),
List.of(new ContainerBuilder().withName("container").build()),
VolumeUtils.createPodSetVolumes(NAME + "-0", DEFAULT_STORAGE, false),
List.of(new LocalObjectReference("some-pull-secret")),
DEFAULT_POD_SECURITY_CONTEXT
);
assertThat(pod.getMetadata().getName(), is(NAME));
assertThat(pod.getMetadata().getNamespace(), is(NAMESPACE));
assertThat(pod.getMetadata().getLabels(), is(LABELS.withAdditionalLabels(Map.of("default-label", "default-value")).toMap()));
assertThat(pod.getMetadata().getAnnotations(), is(Map.of("extra", "annotations")));
assertThat(pod.getSpec().getRestartPolicy(), is("Never"));
assertThat(pod.getSpec().getServiceAccountName(), is(NAME));
assertThat(pod.getSpec().getEnableServiceLinks(), is(nullValue()));
assertThat(pod.getSpec().getAffinity(), is(DEFAULT_AFFINITY));
assertThat(pod.getSpec().getInitContainers().size(), is(1));
assertThat(pod.getSpec().getInitContainers().get(0).getName(), is("init-container"));
assertThat(pod.getSpec().getContainers().size(), is(1));
assertThat(pod.getSpec().getContainers().get(0).getName(), is("container"));
assertThat(pod.getSpec().getVolumes(), is(VolumeUtils.createPodSetVolumes(NAME + "-0", DEFAULT_STORAGE, false)));
assertThat(pod.getSpec().getTolerations(), is(nullValue()));
assertThat(pod.getSpec().getTerminationGracePeriodSeconds(), is(30L));
assertThat(pod.getSpec().getImagePullSecrets(), is(List.of(new LocalObjectReference("some-pull-secret"))));
assertThat(pod.getSpec().getSecurityContext(), is(DEFAULT_POD_SECURITY_CONTEXT));
assertThat(pod.getSpec().getPriorityClassName(), is(nullValue()));
assertThat(pod.getSpec().getSchedulerName(), is("default-scheduler"));
assertThat(pod.getSpec().getHostAliases(), is(nullValue()));
assertThat(pod.getSpec().getTopologySpreadConstraints(), is(nullValue()));
}
|
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 = " 342324545435435.245435435";
final Long bLong = Convert.toLong(b);
assertEquals(Long.valueOf(342324545435435L), bLong);
final long bLong2 = ConverterRegistry.getInstance().convert(long.class, b);
assertEquals(342324545435435L, bLong2);
// boolean测试
final boolean c = true;
final Long cLong = Convert.toLong(c);
assertEquals(Long.valueOf(1), cLong);
final long cLong2 = ConverterRegistry.getInstance().convert(long.class, c);
assertEquals(1, cLong2);
// boolean测试
final String d = "08";
final Long dLong = Convert.toLong(d);
assertEquals(Long.valueOf(8), dLong);
final long dLong2 = ConverterRegistry.getInstance().convert(long.class, d);
assertEquals(8, dLong2);
}
|
@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)) {
changeSets.addCreateItem(createItem(namespaceId, 0, configText));
} else {
ItemDTO beforeItem = baseItems.get(0);
if (!configText.equals(beforeItem.getValue())) {//update
changeSets.addUpdateItem(createItem(namespaceId, beforeItem.getId(), configText));
}
}
return changeSets;
}
|
@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(existedItem));
Assert.assertEquals(0, changeSets.getCreateItems().size());
Assert.assertEquals(1, changeSets.getUpdateItems().size());
Assert.assertEquals(0, changeSets.getDeleteItems().size());
ItemDTO updatedItem = changeSets.getUpdateItems().get(0);
Assert.assertEquals(CONFIG_TEXT, updatedItem.getValue());
}
|
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) {
// TODO(zhaochun): something wrong
LOG.warn("Exception happened in one seesion(" + ctx + ").", e);
ctx.setKilled();
break;
}
}
}
|
@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[] payload = new byte[300];
random.nextBytes(payload);
BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true,
WebSocketExtension.RSV3, Unpooled.wrappedBuffer(payload));
// execute
assertTrue(encoderChannel.writeOutbound(frame));
BinaryWebSocketFrame compressedFrame = encoderChannel.readOutbound();
// test
assertNotNull(compressedFrame);
assertNotNull(compressedFrame.content());
assertEquals(WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedFrame.rsv());
assertTrue(decoderChannel.writeInbound(compressedFrame.content()));
assertTrue(decoderChannel.writeInbound(DeflateDecoder.FRAME_TAIL.duplicate()));
ByteBuf uncompressedPayload = decoderChannel.readInbound();
assertEquals(300, uncompressedPayload.readableBytes());
byte[] finalPayload = new byte[300];
uncompressedPayload.readBytes(finalPayload);
assertArrayEquals(finalPayload, payload);
uncompressedPayload.release();
}
|
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(emailSettings.getFromName()).thenReturn("My SonarQube");
when(emailSettings.getPrefix()).thenReturn("[SONAR]");
when(emailSettings.getSmtpUsername()).thenReturn("");
when(emailSettings.getSmtpPassword()).thenReturn("");
MultiPartEmail email = sender.createEmail(basicEmail);
assertThat(email.getHostName()).isEqualTo("smtphost");
assertThat(email.getSmtpPort()).isEqualTo("25");
assertThat(email.getSubject()).isEqualTo("Email Subject");
assertThat(email.getFromAddress()).hasToString("My SonarQube <noreply@nowhere>");
assertThat(email.getToAddresses()).isEmpty();
assertThat(email.getCcAddresses()).isEmpty();
assertThat(email.isSSLOnConnect()).isFalse();
assertThat(email.isStartTLSEnabled()).isFalse();
assertThat(email.isStartTLSRequired()).isFalse();
}
|
@Override
public Map<String, String> getAddresses() {
AwsCredentials credentials = awsCredentialsProvider.credentials();
List<String> taskAddresses = emptyList();
if (!awsConfig.anyOfEc2PropertiesConfigured()) {
taskAddresses = awsEcsApi.listTaskPrivateAddresses(cluster, credentials);
LOGGER.fine("AWS ECS DescribeTasks found the following addresses: %s", taskAddresses);
}
if (!taskAddresses.isEmpty()) {
return awsEc2Api.describeNetworkInterfaces(taskAddresses, credentials);
} else if (DiscoveryMode.Client == awsConfig.getDiscoveryMode() && !awsConfig.anyOfEcsPropertiesConfigured()) {
LOGGER.fine("No tasks found in ECS cluster: '%s'. Trying AWS EC2 Discovery.", cluster);
return awsEc2Api.describeInstances(credentials);
}
return emptyMap();
}
|
@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);
given(awsEc2Api.describeNetworkInterfaces(privateIps, CREDENTIALS)).willReturn(expectedResult);
// when
Map<String, String> result = awsEcsClient.getAddresses();
// then
assertEquals(expectedResult, result);
}
|
@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.insert(dbTenant2);// @Sql: 先插入出一条存在的数据
// 调用
List<TenantDO> result = tenantService.getTenantListByPackageId(1L);
assertEquals(1, result.size());
assertPojoEquals(dbTenant1, result.get(0));
}
|
@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,
new UnqualifiedColumnReferenceExp(ColumnName.of("K1")),
new IntegerLiteral(1)
);
// Then:
expectTableScan(expression, false);
}
|
@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);
}
return this;
}
|
@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);
statMap.merge(stat, "foo");
}
|
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.
final byte[] result = ScramUtils.computeHmac(key, value);
// Verify results.
assertArrayEquals(StringUtils.decodeHex("e234c47bf6c36696dd6d852b99aaa2ba26555728"), result); // test against 'client key' from the test vectors.
}
|
@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 true;
}
CommandBatchService es = new CommandBatchService(executorService);
for (Entry<byte[], byte[]> entry: tuple.entrySet()) {
es.writeAsync(entry.getKey(), StringCodec.INSTANCE, RedisCommands.SET, entry.getKey(), entry.getValue());
}
es.execute();
return true;
}
|
@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()) {
assertThat(connection.get(entry.getKey())).isEqualTo(entry.getValue());
}
}
|
@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)) {
// no mock
result = this.invoker.invoke(invocation);
} else if (value.startsWith(FORCE_KEY)) {
if (logger.isWarnEnabled()) {
logger.warn(
CLUSTER_FAILED_MOCK_REQUEST,
"force mock",
"",
"force-mock: " + RpcUtils.getMethodName(invocation) + " force-mock enabled , url : "
+ getUrl());
}
// force:direct mock
result = doMockInvoke(invocation, null);
} else {
// fail-mock
try {
result = this.invoker.invoke(invocation);
// fix:#4585
if (result.getException() != null && result.getException() instanceof RpcException) {
RpcException rpcException = (RpcException) result.getException();
if (rpcException.isBiz()) {
throw rpcException;
} else {
result = doMockInvoke(invocation, rpcException);
}
}
} catch (RpcException e) {
if (e.isBiz()) {
throw e;
}
if (logger.isWarnEnabled()) {
logger.warn(
CLUSTER_FAILED_MOCK_REQUEST,
"failed to mock invoke",
"",
"fail-mock: " + RpcUtils.getMethodName(invocation) + " fail-mock enabled , url : "
+ getUrl(),
e);
}
result = doMockInvoke(invocation, e);
}
}
return result;
}
|
@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"))
.addParameter("invoke_return_error", "true");
Invoker<IHelloService> cluster = getClusterInvoker(url);
// Configured with mock
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getBoolean2");
try {
cluster.invoke(invocation);
Assertions.fail();
} catch (RpcException e) {
Assertions.assertTrue(e.isTimeout());
}
}
|
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 : versionAndRangesList) {
if (isDiscreteVersion(versionOrRangeString)) {
versionSetBuilder.addVersion(Version.fromString(versionOrRangeString));
} else if (VersionRange.isValidVersionRange(versionOrRangeString)) {
versionSetBuilder.addVersionRange(VersionRange.parse(versionOrRangeString));
} else {
throw new IllegalArgumentException(
String.format(
"String '%s' is neither a discrete string nor a version range.",
versionOrRangeString));
}
}
return versionSetBuilder.build();
}
|
@Test
public void parse_withInvalidVersion_throwsIllegalArgumentException() {
IllegalArgumentException exception =
assertThrows(
IllegalArgumentException.class, () -> VersionSet.parse(ImmutableList.of("1,0", "abc")));
assertThat(exception)
.hasMessageThat()
.isEqualTo("String '1,0' is neither a discrete string nor a version range.");
}
|
@Deactivate
public void deactivate() {
eventDispatcher.removeSink(PiPipeconfEvent.class);
executor.shutdown();
driverAdminService.removeListener(driverListener);
pipeconfs.clear();
missingMergedDrivers.clear();
cfgService = null;
driverAdminService = null;
log.info("Stopped");
}
|
@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 dialect id " + dialect.getId());
}
}
|
@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();
}
};
sensorsDataAPI.addFunctionListener(listener);
sensorsDataAPI.removeFunctionListener(listener);
sensorsDataAPI.track("AppTest");
}
|
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(
iterable,
groupBy,
zeroValueFactory,
mutatingAggregator,
FJIterate.DEFAULT_MIN_FORK_SIZE);
}
|
@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, EVEN_OR_ODD, ATOMIC_INTEGER_NEW, countAggregator);
assertEquals(1000, aggregation.get("Even").intValue());
assertEquals(1000, aggregation.get("Odd").intValue());
FJIterate.aggregateInPlaceBy(list, EVEN_OR_ODD, ATOMIC_INTEGER_NEW, countAggregator, aggregation);
assertEquals(2000, aggregation.get("Even").intValue());
assertEquals(2000, aggregation.get("Odd").intValue());
}
|
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 "Rotate";
case INTVAR_EVENT:
return "Intvar";
case LOAD_EVENT:
return "Load";
case NEW_LOAD_EVENT:
return "New_load";
case SLAVE_EVENT:
return "Slave";
case CREATE_FILE_EVENT:
return "Create_file";
case APPEND_BLOCK_EVENT:
return "Append_block";
case DELETE_FILE_EVENT:
return "Delete_file";
case EXEC_LOAD_EVENT:
return "Exec_load";
case RAND_EVENT:
return "RAND";
case XID_EVENT:
return "Xid";
case USER_VAR_EVENT:
return "User var";
case FORMAT_DESCRIPTION_EVENT:
return "Format_desc";
case TABLE_MAP_EVENT:
return "Table_map";
case PRE_GA_WRITE_ROWS_EVENT:
return "Write_rows_event_old";
case PRE_GA_UPDATE_ROWS_EVENT:
return "Update_rows_event_old";
case PRE_GA_DELETE_ROWS_EVENT:
return "Delete_rows_event_old";
case WRITE_ROWS_EVENT_V1:
return "Write_rows_v1";
case UPDATE_ROWS_EVENT_V1:
return "Update_rows_v1";
case DELETE_ROWS_EVENT_V1:
return "Delete_rows_v1";
case BEGIN_LOAD_QUERY_EVENT:
return "Begin_load_query";
case EXECUTE_LOAD_QUERY_EVENT:
return "Execute_load_query";
case INCIDENT_EVENT:
return "Incident";
case HEARTBEAT_LOG_EVENT:
case HEARTBEAT_LOG_EVENT_V2:
return "Heartbeat";
case IGNORABLE_LOG_EVENT:
return "Ignorable";
case ROWS_QUERY_LOG_EVENT:
return "Rows_query";
case WRITE_ROWS_EVENT:
return "Write_rows";
case UPDATE_ROWS_EVENT:
return "Update_rows";
case DELETE_ROWS_EVENT:
return "Delete_rows";
case GTID_LOG_EVENT:
return "Gtid";
case ANONYMOUS_GTID_LOG_EVENT:
return "Anonymous_Gtid";
case PREVIOUS_GTIDS_LOG_EVENT:
return "Previous_gtids";
case PARTIAL_UPDATE_ROWS_EVENT:
return "Update_rows_partial";
case TRANSACTION_CONTEXT_EVENT :
return "Transaction_context";
case VIEW_CHANGE_EVENT :
return "view_change";
case XA_PREPARE_LOG_EVENT :
return "Xa_prepare";
case TRANSACTION_PAYLOAD_EVENT :
return "transaction_payload";
default:
return "Unknown type:" + type;
}
}
|
@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.SUSPENDED);
break;
case SUSPENDED:
log.info("Skip suspending since state is {}", state());
break;
case RESTORING:
case CLOSED:
throw new IllegalStateException("Illegal state " + state() + " while suspending standby task " + id);
default:
throw new IllegalStateException("Unknown state " + state() + " while suspending standby task " + id);
}
}
|
@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) {
return CompletableFuture.completedFuture(true);
}
if (service.isAuthenticationEnabled() && service.isAuthorizationEnabled()) {
return isSuperUser();
} else {
return CompletableFuture.completedFuture(false);
}
}, ctx.executor());
}
|
@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.verifyTxnOwnership(any(), any())).thenReturn(CompletableFuture.completedFuture(true));
when(txnStore.endTransaction(any(TxnID.class), anyInt(), anyBoolean()))
.thenReturn(CompletableFuture.failedFuture(new RuntimeException("server error")));
when(pulsar.getTransactionMetadataStoreService()).thenReturn(txnStore);
svcConfig.setTransactionCoordinatorEnabled(true);
resetChannel();
setChannelConnected();
ByteBuf clientCommand = Commands.serializeWithSize(Commands.newEndTxn(89L, 1L, 12L,
TxnAction.COMMIT));
channel.writeInbound(clientCommand);
CommandEndTxnResponse response = (CommandEndTxnResponse) getResponse();
assertEquals(response.getRequestId(), 89L);
assertEquals(response.getTxnidLeastBits(), 1L);
assertEquals(response.getTxnidMostBits(), 12L);
assertEquals(response.getError().getValue(), 0);
assertEquals(response.getMessage(), "server error");
channel.finish();
}
|
@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_NAME, "UTF-8");
String out = MinaConverter.toString(bb, exchange);
assertEquals("Hello World \u4f60\u597d", out);
}
|
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 = "count-";
assertThat(condition.accept(new BooleanNumberConditionsVisitor(Collections.singletonMap(ref, 42d)))).isTrue();
assertThat(condition.accept(new BooleanNumberConditionsVisitor(Collections.singletonMap(ref, 8d)))).isFalse();
assertThat(condition.accept(new BooleanNumberConditionsVisitor(Collections.singletonMap(ref, 402d)))).isTrue();
assertThat(condition.accept(new BooleanNumberConditionsVisitor(Collections.singletonMap(ref, 403d)))).isFalse();
assertThat(condition.accept(new BooleanNumberConditionsVisitor(Collections.singletonMap(ref, 250d)))).isTrue();
assertThat(condition.accept(new BooleanNumberConditionsVisitor(Collections.singletonMap(ref, 300d)))).isFalse();
}
|
public Collection<QualifiedTable> getSingleTables(final Collection<QualifiedTable> qualifiedTables) {
Collection<QualifiedTable> result = new LinkedList<>();
for (QualifiedTable each : qualifiedTables) {
Collection<DataNode> dataNodes = singleTableDataNodes.getOrDefault(each.getTableName().toLowerCase(), new LinkedList<>());
if (!dataNodes.isEmpty() && containsDataNode(each, dataNodes)) {
result.add(each);
}
}
return result;
}
|
@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";
singleRule.getAttributes().getAttribute(MutableDataNodeRuleAttribute.class).put(dataSourceName, DefaultDatabase.LOGIC_NAME, tableName);
Collection<QualifiedTable> tableNames = new LinkedList<>();
tableNames.add(new QualifiedTable(DefaultDatabase.LOGIC_NAME, "teacher"));
assertThat(singleRule.getSingleTables(tableNames).iterator().next().getSchemaName(), is(DefaultDatabase.LOGIC_NAME));
assertThat(singleRule.getSingleTables(tableNames).iterator().next().getTableName(), is("teacher"));
assertTrue(singleRule.getAttributes().getAttribute(TableMapperRuleAttribute.class).getLogicTableNames().contains("employee"));
assertTrue(singleRule.getAttributes().getAttribute(TableMapperRuleAttribute.class).getLogicTableNames().contains("student"));
assertTrue(singleRule.getAttributes().getAttribute(TableMapperRuleAttribute.class).getLogicTableNames().contains("t_order_0"));
assertTrue(singleRule.getAttributes().getAttribute(TableMapperRuleAttribute.class).getLogicTableNames().contains("t_order_1"));
assertTrue(singleRule.getAttributes().getAttribute(TableMapperRuleAttribute.class).getLogicTableNames().contains("teacher"));
}
|
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;
}
}
else if (!checkRemoteDomains) {
return false;
} else {
// Look up in the cache using the full JID
Boolean isRegistered = remoteUsersCache.get(user.toString());
if (isRegistered == null) {
// Check if the bare JID of the user is cached
isRegistered = remoteUsersCache.get(user.toBareJID());
if (isRegistered == null) {
// No information is cached so check user identity and cache it
// A disco#info is going to be sent to the bare JID of the user. This packet
// is going to be handled by the remote server.
final IQ iq = new IQ(IQ.Type.get);
iq.setFrom(xmppServer.getServerInfo().getXMPPDomain());
iq.setTo(user.toBareJID());
iq.setChildElement("query", "http://jabber.org/protocol/disco#info");
final Semaphore completionSemaphore = new Semaphore(0);
// Send the disco#info request to the remote server.
final IQRouter iqRouter = xmppServer.getIQRouter();
final long timeoutInMillis = REMOTE_DISCO_INFO_TIMEOUT.getValue().toMillis();
iqRouter.addIQResultListener(iq.getID(), new IQResultListener() {
@Override
public void receivedAnswer(final IQ packet) {
final JID from = packet.getFrom();
// Assume that the user is not a registered user
Boolean isRegistered = Boolean.FALSE;
// Analyze the disco result packet
if (IQ.Type.result == packet.getType()) {
final Element child = packet.getChildElement();
if (child != null) {
for (final Iterator it = child.elementIterator("identity"); it.hasNext();) {
final Element identity = (Element) it.next();
final String accountType = identity.attributeValue("type");
if ("registered".equals(accountType) || "admin".equals(accountType)) {
isRegistered = Boolean.TRUE;
break;
}
}
}
}
// Update cache of remote registered users
remoteUsersCache.put(from.toBareJID(), isRegistered);
completionSemaphore.release();
}
@Override
public void answerTimeout(final String packetId) {
Log.warn("The result from the disco#info request was never received. request: {}", iq);
completionSemaphore.release();
}
}, timeoutInMillis);
// Send the request
iqRouter.route(iq);
// Wait for the response
try {
completionSemaphore.tryAcquire(timeoutInMillis, TimeUnit.MILLISECONDS);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
Log.warn("Interrupted whilst waiting for response from remote server", e);
}
isRegistered = remoteUsersCache.computeIfAbsent(user.toBareJID(), ignored -> Boolean.FALSE);
}
}
return isRegistered;
}
}
|
@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 device entity!"));
} else if (!json.has("method")) {
ctx.tellFailure(msg, new RuntimeException("Method is not present in the message!"));
} else if (!json.has("params")) {
ctx.tellFailure(msg, new RuntimeException("Params are not present in the message!"));
} else {
int requestId = json.has("requestId") ? json.get("requestId").getAsInt() : random.nextInt();
boolean restApiCall = msg.isTypeOf(TbMsgType.RPC_CALL_FROM_SERVER_TO_DEVICE);
tmp = msg.getMetaData().getValue("oneway");
boolean oneway = !StringUtils.isEmpty(tmp) && Boolean.parseBoolean(tmp);
tmp = msg.getMetaData().getValue(DataConstants.PERSISTENT);
boolean persisted = !StringUtils.isEmpty(tmp) && Boolean.parseBoolean(tmp);
tmp = msg.getMetaData().getValue("requestUUID");
UUID requestUUID = !StringUtils.isEmpty(tmp) ? UUID.fromString(tmp) : Uuids.timeBased();
tmp = msg.getMetaData().getValue("originServiceId");
String originServiceId = !StringUtils.isEmpty(tmp) ? tmp : null;
tmp = msg.getMetaData().getValue(DataConstants.EXPIRATION_TIME);
long expirationTime = !StringUtils.isEmpty(tmp) ? Long.parseLong(tmp) : (System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(config.getTimeoutInSeconds()));
tmp = msg.getMetaData().getValue(DataConstants.RETRIES);
Integer retries = !StringUtils.isEmpty(tmp) ? Integer.parseInt(tmp) : null;
String params = parseJsonData(json.get("params"));
String additionalInfo = parseJsonData(json.get(DataConstants.ADDITIONAL_INFO));
RuleEngineDeviceRpcRequest request = RuleEngineDeviceRpcRequest.builder()
.oneway(oneway)
.method(json.get("method").getAsString())
.body(params)
.tenantId(ctx.getTenantId())
.deviceId(new DeviceId(msg.getOriginator().getId()))
.requestId(requestId)
.requestUUID(requestUUID)
.originServiceId(originServiceId)
.expirationTime(expirationTime)
.retries(retries)
.restApiCall(restApiCall)
.persisted(persisted)
.additionalInfo(additionalInfo)
.build();
ctx.getRpcService().sendRpcRequestToDevice(request, ruleEngineDeviceRpcResponse -> {
if (ruleEngineDeviceRpcResponse.getError().isEmpty()) {
TbMsg next = ctx.newMsg(msg.getQueueName(), msg.getType(), msg.getOriginator(), msg.getCustomerId(), msg.getMetaData(), ruleEngineDeviceRpcResponse.getResponse().orElse(TbMsg.EMPTY_JSON_OBJECT));
ctx.enqueueForTellNext(next, TbNodeConnectionType.SUCCESS);
} else {
TbMsg next = ctx.newMsg(msg.getQueueName(), msg.getType(), msg.getOriginator(), msg.getCustomerId(), msg.getMetaData(), wrap("error", ruleEngineDeviceRpcResponse.getError().get().name()));
ctx.enqueueForTellFailure(next, ruleEngineDeviceRpcResponse.getError().get().name());
}
});
ctx.ack(msg);
}
}
|
@Test
public void givenExpirationTime_whenOnMsg_thenVerifyRequest() {
given(ctxMock.getRpcService()).willReturn(rpcServiceMock);
given(ctxMock.getTenantId()).willReturn(TENANT_ID);
String expirationTime = "2000000000000";
TbMsgMetaData metadata = new TbMsgMetaData();
metadata.putValue(DataConstants.EXPIRATION_TIME, expirationTime);
TbMsg msg = TbMsg.newMsg(TbMsgType.RPC_CALL_FROM_SERVER_TO_DEVICE, DEVICE_ID, metadata, MSG_DATA);
node.onMsg(ctxMock, msg);
ArgumentCaptor<RuleEngineDeviceRpcRequest> requestCaptor = captureRequest();
assertThat(requestCaptor.getValue().getExpirationTime()).isEqualTo(Long.parseLong(expirationTime));
}
|
@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();
assertThat(masters.iterator().next().getPort()).isNotEqualTo(newMaster.getPort());
}
|
@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
.setDetails(nodeDetails)
.build();
}
|
@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().length)];
String[] expected = IntStream.range(0, random.nextInt(4)).mapToObj(s -> randomAlphabetic(55)).toArray(String[]::new);
Health.Builder healthBuilder = Health.builder()
.setStatus(randomStatus);
Arrays.stream(expected).forEach(healthBuilder::addCause);
when(healthChecker.checkNode()).thenReturn(healthBuilder.build());
NodeHealthProviderImpl underTest = new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils);
NodeHealth nodeHealth = underTest.get();
assertThat(nodeHealth.getStatus().name()).isEqualTo(randomStatus.name());
assertThat(nodeHealth.getCauses()).containsOnly(expected);
}
|
@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 log level filter") @Nullable @QueryValue Level minLevel,
@Parameter(description = "The taskrun id") @Nullable @QueryValue String taskRunId,
@Parameter(description = "The task id") @Nullable @QueryValue String taskId,
@Parameter(description = "The attempt number") @Nullable @QueryValue Integer attempt
) {
logRepository.deleteByQuery(tenantService.resolveTenant(), executionId, taskId, taskRunId, minLevel, attempt);
}
|
@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);
HttpResponse<?> delete = client.toBlocking().exchange(
HttpRequest.DELETE("/api/v1/logs/" + log1.getNamespace() + "/" + log1.getFlowId())
);
assertThat(delete.getStatus(), is(HttpStatus.OK));
List<LogEntry> logs = client.toBlocking().retrieve(
HttpRequest.GET("/api/v1/logs/" + log1.getExecutionId()),
Argument.of(List.class, LogEntry.class)
);
assertThat(logs.size(), is(0));
}
|
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 || sortParameters.isEmpty()) {
return components;
}
boolean isAscending = wsRequest.getAsc();
Map<String, Ordering<ComponentDto>> orderingsBySortField = ImmutableMap.<String, Ordering<ComponentDto>>builder()
.put(NAME_SORT, componentNameOrdering(isAscending))
.put(QUALIFIER_SORT, componentQualifierOrdering(isAscending))
.put(PATH_SORT, componentPathOrdering(isAscending))
.put(METRIC_SORT, metricValueOrdering(wsRequest, metrics, measuresByComponentUuidAndMetric))
.put(METRIC_PERIOD_SORT, metricPeriodOrdering(wsRequest, metrics, measuresByComponentUuidAndMetric))
.build();
String firstSortParameter = sortParameters.get(0);
Ordering<ComponentDto> primaryOrdering = orderingsBySortField.get(firstSortParameter);
if (sortParameters.size() > 1) {
for (int i = 1; i < sortParameters.size(); i++) {
String secondarySortParameter = sortParameters.get(i);
Ordering<ComponentDto> secondaryOrdering = orderingsBySortField.get(secondarySortParameter);
primaryOrdering = primaryOrdering.compound(secondaryOrdering);
}
}
primaryOrdering = primaryOrdering.compound(componentNameOrdering(true));
return primaryOrdering.immutableSortedCopy(components);
}
|
@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 = sortComponents(wsRequest);
assertThat(result).extracting("path")
.containsExactly("path-9", "path-8", "path-7", "path-6", "path-5", "path-4", "path-3", "path-2", "path-1", "path-without-measure");
}
|
@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::processScenario);
}
afterFeature();
}
}
|
@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;
value += (b[i] & 0xFF) << offset;
}
return value;
} else {
throw new IllegalArgumentException(
"Byte array is null or invalid length.");
}
}
|
@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 };
assertEquals(255, TCPClientDecorator.byteArrayToInt(ba));
ba = new byte[] { 1, 0 };
assertEquals(256, TCPClientDecorator.byteArrayToInt(ba));
ba = new byte[] { -1, -1 };
assertEquals(-1, TCPClientDecorator.byteArrayToInt(ba));
ba = new byte[] { 0, 0, -1, -1 };
assertEquals(65535, TCPClientDecorator.byteArrayToInt(ba));
ba = new byte[] { 0, 1, 0, 0 };
assertEquals(65536, TCPClientDecorator.byteArrayToInt(ba));
ba = new byte[] { 0, 0, 0, 0 };
assertEquals(0, TCPClientDecorator.byteArrayToInt(ba));
ba = new byte[] { -128, 0, 0, 0 };
assertEquals(Integer.MIN_VALUE, TCPClientDecorator.byteArrayToInt(ba));
ba = new byte[] { 127, -1, -1, -1 };
assertEquals(Integer.MAX_VALUE, TCPClientDecorator.byteArrayToInt(ba));
// test invalid byte arrays
try {
TCPClientDecorator.byteArrayToInt(null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected){
// ignored
}
try {
TCPClientDecorator.byteArrayToInt(new byte[]{});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected){
// ignored
}
try {
TCPClientDecorator.byteArrayToInt(new byte[]{0});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected){
// ignored
}
try {
TCPClientDecorator.byteArrayToInt(new byte[]{0,0,0});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected){
// ignored
}
try {
TCPClientDecorator.byteArrayToInt(new byte[]{0,0,0});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected){
// ignored
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.