focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload,
final ConnectionSession connectionSession) {
switch (commandPacketType) {
case COM_QUIT:
return new MySQLCom... | @Test
void assertNewInstanceWithComResetConnectionPacket() {
assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_RESET_CONNECTION, payload, connectionSession), instanceOf(MySQLComResetConnectionPacket.class));
} |
public SearchResults<ProjectBindingInformation> findProjectBindingsByRequest(ProjectBindingsSearchRequest request) {
ProjectAlmSettingQuery query = buildProjectAlmSettingQuery(request);
try (DbSession session = dbClient.openSession(false)) {
int total = dbClient.projectAlmSettingDao().countProjectAlmSetti... | @Test
void findProjectBindingsByRequest_whenPageSize0_returnsOnlyTotal() {
when(dbClient.projectAlmSettingDao().countProjectAlmSettings(eq(dbSession), any()))
.thenReturn(12);
ProjectBindingsSearchRequest request = new ProjectBindingsSearchRequest(null, null, 42, 0);
SearchResults<ProjectBindingInf... |
@Override
protected CompletableFuture<R> handleRequest(
@Nonnull HandlerRequest<EmptyRequestBody> request, @Nonnull RestfulGateway gateway)
throws RestHandlerException {
JobID jobId = request.getPathParameter(JobIDPathParameter.class);
try {
return checkpointStat... | @Test
void testRetrieveSnapshotFromCache() throws Exception {
GatewayRetriever<RestfulGateway> leaderRetriever =
() -> CompletableFuture.completedFuture(null);
CheckpointingStatistics checkpointingStatistics = getTestCheckpointingStatistics();
CheckpointStatsSnapshot checkpoi... |
@NonNull
@Override
public FileName toProviderFileName( @NonNull ConnectionFileName pvfsFileName, @NonNull T details )
throws KettleException {
StringBuilder providerUriBuilder = new StringBuilder();
appendProviderUriConnectionRoot( providerUriBuilder, details );
// Examples:
// providerUriBu... | @Test
public void testToProviderFileNameHandlesFolders() throws Exception {
ConnectionFileName pvfsFileName = mockPvfsFileNameWithPath( "/rest/path/" );
FileName providerFileName = transformer.toProviderFileName( pvfsFileName, details1 );
assertEquals( "scheme1://rest/path", providerFileName.getURI() )... |
public static CompositeData parseComposite(URI uri) throws URISyntaxException {
CompositeData rc = new CompositeData();
rc.scheme = uri.getScheme();
String ssp = stripPrefix(uri.getRawSchemeSpecificPart().trim(), "//").trim();
parseComposite(uri, rc, ssp);
rc.fragment = uri.ge... | @Test
public void testEmptyCompositePath() throws Exception {
CompositeData data = URISupport.parseComposite(new URI("broker:()/localhost?persistent=false"));
assertEquals(0, data.getComponents().length);
} |
@Override
public boolean isOperational() {
if (nodeOperational) {
return true;
}
boolean flag = false;
try {
flag = checkOperational();
} catch (InterruptedException e) {
LOG.trace("Interrupted while checking ES node is operational", e);
Thread.currentThread().interrupt();... | @Test
public void isOperational_should_return_true_if_Elasticsearch_is_GREEN() {
EsConnector esConnector = mock(EsConnector.class);
when(esConnector.getClusterHealthStatus()).thenReturn(Optional.of(ClusterHealthStatus.GREEN));
EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), ProcessI... |
@Override
public void set(File file, String view, String attribute, Object value, boolean create) {
if (attribute.equals("acl")) {
checkNotCreate(view, attribute, create);
file.setAttribute("acl", "acl", toAcl(checkType(view, attribute, value, List.class)));
}
} | @Test
public void testSet() {
assertSetAndGetSucceeds("acl", ImmutableList.of());
assertSetFailsOnCreate("acl", ImmutableList.of());
assertSetFails("acl", ImmutableSet.of());
assertSetFails("acl", ImmutableList.of("hello"));
} |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldAnonymizeCreateStreamQueryCorrectly() {
final String output = anon.anonymize(
"CREATE STREAM my_stream (profileId VARCHAR, latitude DOUBLE, longitude DOUBLE)\n"
+ "WITH (kafka_topic='locations', value_format='json', partitions=1);");
Approvals.verify(output);
} |
public static Read read() {
return new AutoValue_HCatalogIO_Read.Builder()
.setDatabase(DEFAULT_DATABASE)
.setPartitionCols(new ArrayList<>())
.build();
} | @Test
@NeedsTestData
public void testReadFromSource() throws Exception {
ReaderContext context = getReaderContext(getConfigPropertiesAsMap(service.getHiveConf()));
HCatalogIO.Read spec =
HCatalogIO.read()
.withConfigProperties(getConfigPropertiesAsMap(service.getHiveConf()))
... |
public ReliableTopicConfig addMessageListenerConfig(ListenerConfig listenerConfig) {
checkNotNull(listenerConfig, "listenerConfig can't be null");
listenerConfigs.add(listenerConfig);
return this;
} | @Test(expected = NullPointerException.class)
public void addMessageListenerConfig_whenNull() {
ReliableTopicConfig config = new ReliableTopicConfig("foo");
config.addMessageListenerConfig(null);
} |
@Deprecated
public static boolean isEmpty( String val ) {
return Utils.isEmpty( val );
} | @Test
public void testIsEmptyObjectArray() {
assertTrue( Const.isEmpty( (Object[]) null ) );
assertTrue( Const.isEmpty( new Object[] {} ) );
assertFalse( Const.isEmpty( new Object[] { "test" } ) );
} |
@Override
public void collectAndOverwriteTimestamp(OUT record, long timestamp) {
setTimestamp(timestamp);
output.collect(reuse.replace(record));
} | @Test
void testCollectAndOverwriteTimestamp() {
List<StreamElement> list = new ArrayList<>();
CollectorOutput<Integer> collectorOutput = new CollectorOutput<>(list);
OutputCollector<Integer> collector = new OutputCollector<>(collectorOutput);
collector.collectAndOverwriteTimestamp(1,... |
@Override
public boolean isEmpty() {
return data.isEmpty();
} | @Test(dataProvider = "caches")
@CacheSpec(compute = Compute.SYNC, population = Population.EMPTY, maximumSize = Maximum.FULL)
public void drain_blocksOrderedMap(BoundedLocalCache<Int, Int> cache,
CacheContext context, Eviction<Int, Int> eviction) {
checkDrainBlocks(cache, () -> {
var results = evicti... |
public static String toJson(TableIdentifier identifier) {
return toJson(identifier, false);
} | @Test
public void testTableIdentifierToJson() {
String json = "{\"namespace\":[\"accounting\",\"tax\"],\"name\":\"paid\"}";
TableIdentifier identifier = TableIdentifier.of(Namespace.of("accounting", "tax"), "paid");
assertThat(TableIdentifierParser.toJson(identifier))
.as("Should be able to serial... |
@Override
public AnalyticsPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
Capabilities capabilities = capabilities(descriptor.id());
PluggableInstanceSettings pluginSettingsAndView = getPluginSettingsAndView(descriptor, extension);
Image image = image(descriptor.id());
re... | @Test
public void shouldBuildPluginInfoWithCapabilities() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
Capabilities capabilities = new Capabilities(Collections.emptyList());
when(extension.getCapabilities(descriptor.id())).thenReturn(capabilities);
... |
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
for (String pool : POOLS) {
for (int i = 0; i < ATTRIBUTES.length; i++) {
final String attribute = ATTRIBUTES[i];
final String name = NAMES[i];
... | @Test
public void includesAGaugeForMappedMemoryUsed() throws Exception {
final Gauge gauge = (Gauge) buffers.getMetrics().get("mapped.used");
when(mBeanServer.getAttribute(mapped, "MemoryUsed")).thenReturn(100);
assertThat(gauge.getValue())
.isEqualTo(100);
} |
@Override
public synchronized void putConnectorConfig(String connName,
final Map<String, String> config,
boolean allowReplace,
final Callback<Created<ConnectorInfo>> callba... | @Test
public void testCorruptConfig() {
initialize(false);
Map<String, String> config = new HashMap<>();
config.put(ConnectorConfig.NAME_CONFIG, CONNECTOR_NAME);
config.put(ConnectorConfig.CONNECTOR_CLASS_CONFIG, BogusSinkConnector.class.getName());
config.put(SinkConnectorCo... |
@Udf(description = "Returns a new string encoded using the outputEncoding ")
public String encode(
@UdfParameter(
description = "The source string. If null, then function returns null.") final String str,
@UdfParameter(
description = "The input encoding."
+ " If null, the... | @Test(expected = KsqlFunctionException.class)
public void shouldThrowIfUnsupportedEncodingTypes() {
udf.encode("4578616d706C6521", "hex", "hex");
udf.encode("Ελλάδα", "utf8", "utf8");
udf.encode("1 + 1 = 1", "ascii", "ascii");
udf.encode("w5xiZXJtZW5zY2g=", "base64", "base64");
} |
@Override
public int run(String[] args) throws Exception {
if (args.length != 2) {
return usage(args);
}
String action = args[0];
String name = args[1];
int result;
if (A_LOAD.equals(action)) {
result = loadClass(name);
} else if (A_CREATE.equals(action)) {
//first load t... | @Test
public void testCreateFailsInStaticInit() throws Throwable {
run(FindClass.E_LOAD_FAILED,
FindClass.A_CREATE,
"org.apache.hadoop.util.TestFindClass$FailInStaticInit");
} |
@Override
public void execute(Context context) {
if (analysisMetadataHolder.isPullRequest() && targetInputFactory.hasTargetBranchAnalysis()) {
int fixedIssuesCount = pullRequestFixedIssueRepository.getFixedIssues().size();
measureRepository.add(treeRootHolder.getRoot(), metricRepository.getByKey(CoreM... | @Test
public void execute_whenComponentIsNotPullRequest_shouldNotCreateMeasure() {
when(analysisMetadataHolder.isPullRequest()).thenReturn(false);
underTest.execute(new TestComputationStepContext());
assertThat(measureRepository.getAddedRawMeasures(ROOT_REF)).isEmpty();
} |
@Override
public boolean exceedsRateLimitPerFrequency(Task task, TaskDef taskDef) {
int rateLimit =
taskDef == null ? task.getRateLimitPerFrequency() : taskDef.getRateLimitPerFrequency();
if (rateLimit <= 0) {
return false;
}
int bucketSize =
taskDef == null
? task.ge... | @Test
public void testExceedsRateLimitWhenNoRateLimitSet() {
TaskDef taskDef = createTaskDef(0, 0);
Task task = createRunningTestTask(TEST_TASK_ID_1);
assertFalse(dao.exceedsRateLimitPerFrequency(task, taskDef));
} |
public static Set<String> verifyTopologyOptimizationConfigs(final String config) {
final List<String> configs = Arrays.asList(config.split("\\s*,\\s*"));
final Set<String> verifiedConfigs = new HashSet<>();
// Verify it doesn't contain none or all plus a list of optimizations
if (configs... | @Test
public void shouldNotEnableAnyOptimizationsWithNoOptimizationConfig() {
final Set<String> configs = StreamsConfig.verifyTopologyOptimizationConfigs(StreamsConfig.NO_OPTIMIZATION);
assertEquals(0, configs.size());
} |
@Override
public String getGroupKeyColumnName(int groupKeyColumnIndex) {
throw new AssertionError("No group key column name for aggregation results");
} | @Test(expectedExceptions = AssertionError.class)
public void testGetGroupKeyColumnName() {
_aggregationResultSetUnderTest.getGroupKeyColumnName(0);
} |
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) {
if (null == source) {
return null;
}
T target = ReflectUtil.newInstanceIfPossible(tClass);
copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties));
return target;
} | @Test
public void beanToBeanOverlayFieldTest() {
final SubPersonWithOverlayTransientField source = new SubPersonWithOverlayTransientField();
source.setName("zhangsan");
source.setAge(20);
source.setOpenid("1");
final SubPersonWithOverlayTransientField dest = new SubPersonWithOverlayTransientField();
BeanUt... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final CountDownLatch signal = new CountDownLatch(1);
final AtomicReference<BackgroundException> failure = new AtomicReference<>();
final Sc... | @Test(expected = NotfoundException.class)
public void testDeleteNotFound() throws Exception {
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new DropboxBatchDeleteFeature(session).delete(Collection... |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
PointList pointList = way.getTag("point_list", null);
if (pointList != null) {
if (pointList.isEmpty() || !pointList.is3D()) {
if (maxSlopeEnc != null)
... | @Test
public void testMaxSlopeLargerThanMaxStorableDecimal() {
PointList pointList = new PointList(5, true);
pointList.add(47.7281561, 11.9993135, 1163.0);
pointList.add(47.7282782, 11.9991944, 1163.0);
pointList.add(47.7283135, 11.9991135, 1178.0);
ReaderWay way = new Reader... |
static EndTransactionMarker deserializeValue(ControlRecordType type, ByteBuffer value) {
ensureTransactionMarkerControlType(type);
if (value.remaining() < CURRENT_END_TXN_MARKER_VALUE_SIZE)
throw new InvalidRecordException("Invalid value size found for end transaction marker. Must have " +
... | @Test
public void testNotEnoughBytes() {
assertThrows(InvalidRecordException.class,
() -> EndTransactionMarker.deserializeValue(ControlRecordType.COMMIT, ByteBuffer.wrap(new byte[0])));
} |
public boolean matchStage(StageConfigIdentifier stageIdentifier, StageEvent event) {
return this.event.include(event) && appliesTo(stageIdentifier.getPipelineName(), stageIdentifier.getStageName());
} | @Test
void anyStageShouldNotMatchWithinADifferentPipeline() {
NotificationFilter filter = new NotificationFilter("cruise", GoConstants.ANY_STAGE, StageEvent.Breaks, false);
assertThat(filter.matchStage(new StageConfigIdentifier("cruise2", "dev"), StageEvent.Breaks)).isFalse();
} |
@Override
public Object convertFromSourceToTargetDataType( int sourceValueMetaType, int targetValueMetaType, Object value )
throws ValueMetaConversionException {
if ( value == null ) {
return null;
}
switch ( sourceValueMetaType ) {
case ValueMetaInterface.TYPE_INET:
return conver... | @Test
public void convertFromSourceToTargetDataTypeTest() throws Exception {
//"-", "Number", "String", "Date", "Boolean", "Integer", "BigNumber", "Serializable", "Binary", "Timestamp",
// "Internet Address", }
DateFormat dateFormat = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss.SSS" );
Date date1 = ( ... |
@Override
public String getHeader(String name) {
// The browser javascript WebSocket client couldn't add the auth param to the request header, use the
// query param `token` to transport the auth token for the browser javascript WebSocket client.
if (name.equals(HTTP_HEADER_NAME)
... | @Test
public void testTokenParamWithBearerPrefix() {
UpgradeHttpServletRequest httpServletRequest = Mockito.mock(UpgradeHttpServletRequest.class);
Mockito.when(httpServletRequest.getParameter(WebSocketHttpServletRequestWrapper.TOKEN))
.thenReturn(BEARER_TOKEN);
WebSocketHttp... |
public static JsonMapper validateJsonMapper(JsonMapper jsonMapper) {
try {
final String serializedJob = jsonMapper.serialize(getJobForTesting());
testTimeFields(serializedJob);
testUseFieldsNotMethods(serializedJob);
testUsePolymorphism(serializedJob);
... | @Test
void testValidJsonBJsonMapper() {
assertThatCode(() -> validateJsonMapper(new JsonbJsonMapper())).doesNotThrowAnyException();
} |
@Override
public String command() {
return TYPE;
} | @Test
public void shouldShowCommandName() {
assertThat(new RakeTask().command(), is("rake"));
} |
public static void mergeMap(boolean decrypt, Map<String, Object> config) {
merge(decrypt, config);
} | @Test
public void testMap_valueCastToDouble() {
Map<String, Object> testMap = new HashMap<>();
testMap.put("key", "${TEST.double: 1.1}");
CentralizedManagement.mergeMap(true, testMap);
Assert.assertTrue(testMap.get("key") instanceof Double);
} |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testGroupByWithQualifiedName3()
{
// TODO: verify output
analyze("SELECT * FROM t1 GROUP BY t1.a, t1.b, t1.c, t1.d");
} |
public static AsyncArchiveService startAsyncArchiveIfEnabled(BaseHoodieWriteClient writeClient) {
HoodieWriteConfig config = writeClient.getConfig();
if (!config.isAutoArchive() || !config.isAsyncArchive()) {
LOG.info("The HoodieWriteClient is not configured to auto & async archive. Async archive service ... | @Test
void startAsyncArchiveReturnsNullWhenAutoArchiveDisabled() {
when(config.isAutoArchive()).thenReturn(false);
when(writeClient.getConfig()).thenReturn(config);
assertNull(AsyncArchiveService.startAsyncArchiveIfEnabled(writeClient));
} |
@Override
public RouteContext route(final RouteContext routeContext, final BroadcastRule broadcastRule) {
RouteMapper dataSourceMapper = getDataSourceRouteMapper(broadcastRule.getDataSourceNames());
routeContext.getRouteUnits().add(new RouteUnit(dataSourceMapper, createTableRouteMappers()));
... | @Test
void assertRoute() {
SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class);
Collection<String> logicTables = Collections.singleton("t_address");
ConnectionContext connectionContext = mock(ConnectionContext.class);
BroadcastUnicastRoutingEngine engine = new B... |
@Override
public boolean supportsNamedParameters() {
return false;
} | @Test
void assertSupportsNamedParameters() {
assertFalse(metaData.supportsNamedParameters());
} |
public Environment addAll(@NonNull Map<String, String> map) {
map.forEach((key, value) -> this.props.setProperty(key, value));
return this;
} | @Test
public void testAddAll() {
Environment environment = Environment.empty();
Properties prop = new Properties();
prop.setProperty("a", "1");
environment.addAll(prop);
assertEquals(1, environment.size());
Map<String, String> map = Collections.singletonMap("aa", "... |
ByteBuffer packDecimal() {
ByteBuffer buffer = ByteBuffer.allocate(type.getTypeSize());
buffer.order(ByteOrder.LITTLE_ENDIAN);
int scale = ((ScalarType) type).getScalarScale();
BigDecimal scaledValue = value.multiply(SCALE_FACTOR[scale]);
switch (type.getPrimitiveType()) {
... | @Test
public void testPackDecimal() {
BigInteger[] bigIntegers = new BigInteger[] {
BigInteger.ZERO,
BigInteger.ONE,
BigInteger.ONE.shiftLeft(31).subtract(BigInteger.ONE),
BigInteger.ONE.shiftLeft(31).negate(),
BigInteger.ONE.sh... |
public List<CodegenColumnDO> buildColumns(Long tableId, List<TableField> tableFields) {
List<CodegenColumnDO> columns = CodegenConvert.INSTANCE.convertList(tableFields);
int index = 1;
for (CodegenColumnDO column : columns) {
column.setTableId(tableId);
column.setOrdinalP... | @Test
public void testBuildColumns() {
// 准备参数
Long tableId = randomLongId();
TableField tableField = mock(TableField.class);
List<TableField> tableFields = Collections.singletonList(tableField);
// mock 方法
TableField.MetaInfo metaInfo = mock(TableField.MetaInfo.class... |
public static byte[] toJsonBytes(Slime slime) throws IOException {
return toJsonBytes(slime.get());
} | @Test
public void test_slime_to_json() throws IOException {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString("foo", "foobie");
root.setObject("bar");
String json = Utf8.toString(SlimeUtils.toJsonBytes(slime));
assertEquals("{\"foo\":\"foobie\... |
@Override
public boolean isEnabled() {
return branchFeatureExtension != null && branchFeatureExtension.isAvailable();
} | @Test
public void return_true_when_extension_returns_ftrue() {
when(branchFeatureExtension.isAvailable()).thenReturn(true);
assertThat(new BranchFeatureProxyImpl(branchFeatureExtension).isEnabled()).isTrue();
} |
public static byte[] adjustParity(byte[] data) {
for (int i = 0; i < data.length; i++) {
// Mask with fe to get first 7 bits
int b = data[i] & 0xfe;
data[i] = (byte) (b | ((Integer.bitCount(b) & 1) ^ 1));
}
return data;
} | @Test
public void adjustParity() {
assertArrayEquals(Hex.decode("010102020404070708080b0b0d0d0e0e101013131515161619191a1a1c1c1f1f"),
CryptoUtils.adjustParity(
Hex.decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
)
);
assertArr... |
@Override
public boolean supportsStatementPooling() {
return false;
} | @Test
void assertSupportsStatementPooling() {
assertFalse(metaData.supportsStatementPooling());
} |
@Override
public void checkBeforeUpdate(final CreateEncryptRuleStatement sqlStatement) {
if (!sqlStatement.isIfNotExists()) {
checkDuplicateRuleNames(sqlStatement);
}
checkColumnNames(sqlStatement);
checkAlgorithmTypes(sqlStatement);
checkToBeCreatedEncryptors(sql... | @Test
void assertCreateAESEncryptRuleWithPropertiesNotExists() {
CreateEncryptRuleStatement sqlStatement = createWrongAESEncryptorSQLStatement();
EncryptRule rule = mock(EncryptRule.class);
when(rule.getConfiguration()).thenReturn(getCurrentRuleConfiguration());
executor.setRule(rule... |
public static String buildGlueExpression(Map<Column, Domain> partitionPredicates)
{
List<String> perColumnExpressions = new ArrayList<>();
int expressionLength = 0;
for (Map.Entry<Column, Domain> partitionPredicate : partitionPredicates.entrySet()) {
String columnName = partition... | @Test
public void testBuildGlueExpressionMaxLengthOneColumn()
{
Map<Column, Domain> predicates = new PartitionFilterBuilder(HIVE_TYPE_TRANSLATOR)
.addStringValues("col1", Strings.repeat("x", GLUE_EXPRESSION_CHAR_LIMIT))
.addStringValues("col2", Strings.repeat("x", 5))
... |
public Object execute(ProceedingJoinPoint proceedingJoinPoint, Method method, String fallbackMethodValue, CheckedSupplier<Object> primaryFunction) throws Throwable {
String fallbackMethodName = spelResolver.resolve(method, proceedingJoinPoint.getArgs(), fallbackMethodValue);
FallbackMethod fallbackMeth... | @Test
public void testPrimaryMethodExecutionWithFallback() throws Throwable {
Method method = this.getClass().getMethod("getName", String.class);
final CheckedSupplier<Object> primaryFunction = () -> getName("Name");
final String fallbackMethodValue = "getNameValidFallback";
when(pr... |
public static Map<TopicPartition, Long> parseSinkConnectorOffsets(Map<Map<String, ?>, Map<String, ?>> partitionOffsets) {
Map<TopicPartition, Long> parsedOffsetMap = new HashMap<>();
for (Map.Entry<Map<String, ?>, Map<String, ?>> partitionOffset : partitionOffsets.entrySet()) {
Map<String, ... | @Test
public void testValidateAndParseIntegerPartitionValue() {
Map<Map<String, ?>, Map<String, ?>> partitionOffsets = createPartitionOffsetMap("topic", 10, "100");
Map<TopicPartition, Long> parsedOffsets = SinkUtils.parseSinkConnectorOffsets(partitionOffsets);
assertEquals(1, parsedOffsets.... |
@Operation(summary= "Abort current session from digid")
@PostMapping(value = "abort", consumes = "application/json", produces = "application/json")
public Map<String, String> abort(@Valid @RequestBody AppRequest request) {
RdaSession session = findSession(request, null);
if (session != null) {
... | @Test
public void testAbortRestService() {
AppRequest appRequest = new AppRequest();
appRequest.setSessionId("sessionId");
RdaSession session = new RdaSession();
session.setId("sessionId");
mockSession(session);
Map<String, String> responseData = controller.abort(app... |
@Override
public SearchVersion convertFrom(String value) {
try {
// only major version - we know it's elasticsearch
final int majorVersion = Integer.parseInt(value);
return SearchVersion.elasticsearch(majorVersion, 0, 0);
} catch (NumberFormatException nfe) {
... | @Test
void convertEncodedValue() {
final SearchVersion version = converter.convertFrom("OPENSEARCH:1.2.0");
assertThat(version).isEqualTo(SearchVersion.create(SearchVersion.Distribution.OPENSEARCH, Version.parse("1.2.0")));
} |
@InvokeOnHeader(Web3jConstants.DB_GET_STRING)
void dbGetString(Message message) throws IOException {
String databaseName = message.getHeader(Web3jConstants.DATABASE_NAME, configuration::getDatabaseName, String.class);
String keyName = message.getHeader(Web3jConstants.KEY_NAME, configuration::getKeyN... | @Test
public void dbGetStringTest() throws Exception {
DbGetString response = Mockito.mock(DbGetString.class);
Mockito.when(mockWeb3j.dbGetString(any(), any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getStoredValue()).thenReturn(... |
public void and(BitmapValue other) {
switch (other.bitmapType) {
case EMPTY:
clear();
break;
case SINGLE_VALUE:
switch (this.bitmapType) {
case EMPTY:
break;
case SINGLE_VALUE:... | @Test
public void testBitmapValueAnd() throws IOException {
// empty and empty
BitmapValue bitmap = new BitmapValue(emptyBitmap);
bitmap.and(emptyBitmap);
checkBitmap(bitmap, BitmapValue.EMPTY, 0, 0);
// empty and single
bitmap = new BitmapValue(emptyBitmap);
... |
public static Options options() {
return new Options("/tmp", 100, SorterType.HADOOP);
} | @Test
public void testZeroMemory() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("memoryMB must be greater than zero");
BufferedExternalSorter.Options options = BufferedExternalSorter.options();
options.withMemoryMB(0);
} |
@Override
public void handleFetchError(String key, Exception e) {
log.error("Failed retrieving rate for " + key + ", will create new rate", e);
} | @Test
public void testHandleFetchErrorShouldNotThrowException() {
target.handleFetchError("key", new Exception());
} |
public static InetSocketAddress createUnresolved(String hostname, int port) {
return createInetSocketAddress(hostname, port, false);
} | @Test
void createUnresolvedBadValues() {
assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> AddressUtils.createUnresolved(null, 0))
.withMessage("hostname");
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> AddressUtils.createUnresolved("hostname", -1))
... |
public void loadFromSnapshot(ConcurrentMap<String, IpPortBasedClient> clients) {
ConcurrentMap<String, IpPortBasedClient> oldClients = this.clients;
this.clients = clients;
oldClients.clear();
} | @Test
void testLoadFromSnapshot() {
ConcurrentMap<String, IpPortBasedClient> snapshotClients = new ConcurrentHashMap<>();
snapshotClients.put(snapshotClientId, snapshotClient);
persistentIpPortClientManager.loadFromSnapshot(snapshotClients);
Collection<String> allClientIds = persiste... |
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to validate internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final ValidationResult validationResult... | @Test
public void shouldOnlyRetryDescribeConfigsWhenDescribeConfigsThrowsLeaderNotAvailableExceptionDuringValidation() {
final AdminClient admin = mock(AdminClient.class);
final InternalTopicManager topicManager = new InternalTopicManager(
time,
admin,
new Streams... |
@Config("resource-groups.config-file")
public FileResourceGroupConfig setConfigFile(String configFile)
{
this.configFile = configFile;
return this;
} | @Test
public void testDefaults()
{
assertRecordedDefaults(ConfigAssertions.recordDefaults(FileResourceGroupConfig.class)
.setConfigFile(null));
} |
protected static SimpleDateFormat getLog4j2Appender() {
Optional<Appender> log4j2xmlAppender =
configuration.getAppenders().values().stream()
.filter( a -> a.getName().equalsIgnoreCase( log4J2Appender ) ).findFirst();
if ( log4j2xmlAppender.isPresent() ) {
ArrayList<String> matchesArray = ne... | @Test
public void testGetLog4j2UsingAppender11() {
// Testing adding TimeZone GMT-5
KettleLogLayout.log4J2Appender = "pdi-execution-appender-test-11";
Assert.assertEquals( "HH:mm:ss",
KettleLogLayout.getLog4j2Appender().toPattern() );
} |
@Override
public String getSerializableForm(boolean includeConfidence) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < names.length; i++) {
builder.append(names[i]);
builder.append('=');
builder.append(values[i]);
if (includeConfiden... | @Test
public void getsCorrectSerializableForm() {
Regressor mr = new Regressor(
new String[]{"a", "b", "c"},
new double[]{1d, 2d, 3d}
);
assertEquals("a=1.0,b=2.0,c=3.0", mr.getSerializableForm(false));
// Should be the same for includeConfidence eithe... |
@Operation(summary = "Check if credentials are valid.", tags = { SwaggerConfig.ACTIVATE_WEBSITE, SwaggerConfig.ACTIVATE_SMS, SwaggerConfig.ACTIVATE_LETTER, SwaggerConfig.ACTIVATE_RDA }, operationId = "auth",
parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter... | @Test
void validateIfCorrectProcessesAreCalledAuthenticate() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException {
ActivationUsernamePasswordRequest activationUsernamePasswordRequest = new ActivationUsernamePasswordRequest();
... |
public synchronized void executePeriodically(final Runnable task, long period) {
TimerTask existing = timerTasks.get(task);
if (existing != null) {
LOG.debug("Task {} already scheduled, cancelling and rescheduling", task);
cancel(task);
}
TimerTask timerTask = new... | @Test
public void testExecutePeriodically() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
scheduler.executePeriodically(new CountDownRunnable(latch), 10);
assertTrue(latch.await(5000, TimeUnit.MILLISECONDS));
} |
@Nonnull
@Override
public Result addChunk(ByteBuf buffer) {
final byte[] readable = new byte[buffer.readableBytes()];
buffer.readBytes(readable, buffer.readerIndex(), buffer.readableBytes());
final GELFMessage msg = new GELFMessage(readable);
final ByteBuf aggregatedBuffer;
... | @Test
public void tooManyChunks() {
final ByteBuf[] chunks = createChunkedMessage(129 * 1024, 1024);
int i = 1;
for (final ByteBuf chunk : chunks) {
final CodecAggregator.Result result = aggregator.addChunk(chunk);
if (i == 129) {
assertFalse("Message ... |
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) {
Objects.requireNonNull(metric);
if (batchMeasure == null) {
return Optional.empty();
}
Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder();
switch (metric.getType().getValueType()) {
... | @Test
public void toMeasure_returns_long_part_of_value_in_dto_for_Long_Metric() {
Optional<Measure> measure = underTest.toMeasure(ScannerReport.Measure.newBuilder().setLongValue(LongValue.newBuilder().setValue(15L)).build(), SOME_LONG_METRIC);
assertThat(measure).isPresent();
assertThat(measure.get().get... |
public Map<String, Integer> getNotAnalysedFilesByLanguage() {
return ImmutableMap.copyOf(notAnalysedFilesByLanguage);
} | @Test
public void stores_not_analysed_cpp_file_count_in_sq_community_edition() {
when(sonarRuntime.getEdition()).thenReturn(SonarEdition.COMMUNITY);
InputComponentStoreTester underTest = new InputComponentStoreTester(sonarRuntime);
String mod1Key = "mod1";
underTest.addFile(mod1Key, "src/main/java/Foo... |
@Cacheable(value = CACHE_LATEST_EXTENSION_VERSION, keyGenerator = GENERATOR_LATEST_EXTENSION_VERSION)
public ExtensionVersion getLatest(List<ExtensionVersion> versions, boolean groupedByTargetPlatform) {
return getLatest(versions, groupedByTargetPlatform, false);
} | @Test
public void testGetLatestPreRelease() {
var release = new ExtensionVersion();
release.setTargetPlatform(TargetPlatform.NAME_UNIVERSAL);
release.setPreRelease(false);
release.setVersion("1.0.0");
var minor = new ExtensionVersion();
minor.setTargetPlatform(Target... |
public URI getUri() {
return _uri;
} | @Test
public void testCreateGcsUriUsingADifferentScheme() {
URI uri = URI.create("file://bucket/file");
GcsUri gcsUri = new GcsUri(uri);
assertEquals(gcsUri.getUri().getScheme(), SCHEME);
} |
@Override
public V put(K key, V value, Duration ttl) {
return get(putAsync(key, value, ttl));
} | @Test
public void testReadAllValuesTTL() {
final RMapCacheNative<String, String> map = redisson.getMapCacheNative("testRMapCacheAllValues");
map.put("1234", "5678", Duration.ofMinutes(1));
assertThat(map.readAllValues()).containsOnly("5678");
map.destroy();
} |
@Udf(description = "Returns the base 10 logarithm of an INT value.")
public Double log(
@UdfParameter(
value = "value",
description = "the value get the base 10 logarithm of."
) final Integer value
) {
return log(value == null ? null : value.doubleValue())... | @Test
public void shouldHandleNull() {
assertThat(udf.log((Integer)null), is(nullValue()));
assertThat(udf.log((Long)null), is(nullValue()));
assertThat(udf.log((Double)null), is(nullValue()));
assertThat(udf.log(null, 13), is(nullValue()));
assertThat(udf.log(null, 13L), is(nullValue()));
ass... |
@Override
public Num calculate(Position position, int currentIndex) {
return this.calculate(position);
} | @Test
public void calculateOpenSellPosition() {
// Calculate the transaction costs of an open position
int currentIndex = 4;
Position position = new Position(Trade.TradeType.BUY, transactionModel, new ZeroCostModel());
position.operate(0, DoubleNum.valueOf(100), DoubleNum.valueOf(1))... |
@Override
public boolean exists(Env targetEnv) {
return addresses.containsKey(targetEnv);
} | @Test
public void testExists() {
assertTrue(databasePortalMetaServerProvider.exists(Env.DEV));
assertFalse(databasePortalMetaServerProvider.exists(Env.PRO));
assertTrue(databasePortalMetaServerProvider.exists(Env.addEnvironment("nothing")));
} |
public static DisplayData from(HasDisplayData component) {
checkNotNull(component, "component argument cannot be null");
InternalBuilder builder = new InternalBuilder();
builder.include(Path.root(), component);
return builder.build();
} | @Test
public void testIncludeNullPath() {
thrown.expectCause(isA(NullPointerException.class));
DisplayData.from(
new HasDisplayData() {
@Override
public void populateDisplayData(DisplayData.Builder builder) {
builder.include(null, new NoopDisplayData());
}
... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testNodeNotReady() {
final long producerId = 123456L;
time = new MockTime(10);
client = new MockClient(time, metadata);
TransactionManager transactionManager = new TransactionManager(new LogContext(), "testNodeNotReady",
60000, 100L, new ApiVersions... |
public PlanNode plan(Analysis analysis)
{
return planStatement(analysis, analysis.getStatement());
} | @Test
public void testRedundantTopNNodeRemoval()
{
Session exploitConstraints = Session.builder(this.getQueryRunner().getDefaultSession())
.setSystemProperty(EXPLOIT_CONSTRAINTS, Boolean.toString(true))
.build();
String query = "SELECT count(*) FROM orders ORDER ... |
public synchronized <K> KeyQueryMetadata getKeyQueryMetadataForKey(final String storeName,
final K key,
final Serializer<K> keySerializer) {
Objects.requireNonNull(keySer... | @Test
public void shouldGetQueryMetadataForGlobalStoreWithKeyAndPartitioner() {
final KeyQueryMetadata metadata = metadataState.getKeyQueryMetadataForKey(globalTable, "key", partitioner);
assertEquals(hostOne, metadata.activeHost());
assertTrue(metadata.standbyHosts().isEmpty());
} |
List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder) {
return decorateTextWithHtml(text, decorationDataHolder, null, null);
} | @Test
public void should_close_tags_at_end_of_file() {
String classDeclarationSample =
"/*" + LF_END_OF_LINE +
" * Header" + LF_END_OF_LINE +
" */" + LF_END_OF_LINE +
LF_END_OF_LINE +
"public class HelloWorld {" + LF_END_OF_LINE +
"}";
DecorationDataHolder decor... |
public static long estimateSize(StructType tableSchema, long totalRecords) {
if (totalRecords == Long.MAX_VALUE) {
return totalRecords;
}
long result;
try {
result = LongMath.checkedMultiply(tableSchema.defaultSize(), totalRecords);
} catch (ArithmeticException e) {
result = Long.... | @Test
public void testEstimateSize() throws IOException {
long tableSize = SparkSchemaUtil.estimateSize(SparkSchemaUtil.convert(TEST_SCHEMA), 1);
Assert.assertEquals("estimateSize matches with expected approximation", 24, tableSize);
} |
@VisibleForTesting
Pair<String, SearchQueryOperator> extractOperator(String value, SearchQueryOperator defaultOperator) {
if (value.length() >= 3) {
final String substring2 = value.substring(0, 2);
switch (substring2) {
case ">=":
return Pair.of(v... | @Test
void extractOperator() {
final SearchQueryParser parser = new SearchQueryParser("defaultfield",
ImmutableMap.of(
"id", SearchQueryField.create("real_id"),
"date", SearchQueryField.create("created_at", SearchQueryField.Type.DATE),
... |
public static String Lpad( String valueToPad, String filler, int size ) {
if ( ( size == 0 ) || ( valueToPad == null ) || ( filler == null ) ) {
return valueToPad;
}
int vSize = valueToPad.length();
int fSize = filler.length();
// This next if ensures previous behavior, but prevents infinite l... | @Test
public void testLpad() {
final String s = "pad me";
assertEquals( s, Const.Lpad( s, "-", 0 ) );
assertEquals( s, Const.Lpad( s, "-", 3 ) );
assertEquals( "--" + s, Const.Lpad( s, "-", 8 ) );
// add in some edge cases
assertEquals( s, Const.Lpad( s, null, 15 ) ); // No NPE
assertEqual... |
@Override
public String toString() {
return toStringHelper(getClass())
.toString();
// TODO: need to handle options
} | @Test
public void testToStringRS() throws Exception {
RouterSolicitation rs = deserializer.deserialize(bytePacket, 0, bytePacket.length);
String str = rs.toString();
// TODO: need to handle Options
} |
public static int getPid() {
return PID;
} | @Test
public void testGetPid() {
assertThat(UtilAll.getPid()).isGreaterThan(0);
} |
public static DateTime parse(CharSequence dateStr, DateFormat dateFormat) {
return new DateTime(dateStr, dateFormat);
} | @Test
public void parseSingleMonthAndDayTest() {
DateTime parse = DateUtil.parse("2021-1-1");
assertNotNull(parse);
assertEquals("2021-01-01 00:00:00", parse.toString());
parse = DateUtil.parse("2021-1-22 00:00:00");
assertNotNull(parse);
assertEquals("2021-01-22 00:00:00", parse.toString());
} |
@Override
public Set<Map.Entry> entrySet() {
return null;
} | @Test
public void testEntrySet() throws Exception {
assertNull(NULL_QUERY_CACHE.entrySet());
} |
@Override
public SelArray assignOps(SelOp op, SelType rhs) {
if (op == SelOp.ASSIGN) {
SelTypeUtil.checkTypeMatch(this.type(), rhs.type());
this.val = ((SelArray) rhs).val; // direct assignment
return this;
}
throw new UnsupportedOperationException(
this.type() + " DO NOT support... | @Test(expected = UnsupportedOperationException.class)
public void testInvalidAssignOp() {
one.assignOps(SelOp.ADD_ASSIGN, another);
} |
@Override
@CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
allEntries = true) // allEntries 清空所有缓存,因为 permission 如果变更,涉及到新老两个 permission。直接清理,简单有效
public void updateMenu(MenuSaveVO updateReqVO) {
// 校验更新的菜单是否存在
if (menuMapper.selectById(updateReqVO.getId()) == null) {
... | @Test
public void testUpdateMenu_sonIdNotExist() {
// 准备参数
MenuSaveVO reqVO = randomPojo(MenuSaveVO.class);
// 调用,并断言异常
assertServiceException(() -> menuService.updateMenu(reqVO), MENU_NOT_EXISTS);
} |
@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
MetaData.Builder metaData = new MetaData.Builder(sanit... | @Test
public void reportsBooleanGauges() throws Exception {
reporter.report(
map("gauge", () -> true),
map(),
map(),
map(),
map());
assertThat(nextValues(receiver)).containsExactly(1d);
reporter.report(
... |
void resolveSelectors(EngineDiscoveryRequest request, CucumberEngineDescriptor engineDescriptor) {
Predicate<String> packageFilter = buildPackageFilter(request);
resolve(request, engineDescriptor, packageFilter);
filter(engineDescriptor, packageFilter);
pruneTree(engineDescriptor);
} | @Test
void resolveRequestWithClasspathResourceSelectorAndWithSpaceInFilename() {
DiscoverySelector resource = selectClasspathResource("io/cucumber/junit/platform/engine/with space.feature");
EngineDiscoveryRequest discoveryRequest = new SelectorRequest(resource);
resolver.resolveSelectors(di... |
@RequiresApi(Build.VERSION_CODES.R)
@Override
public boolean onInlineSuggestionsResponse(@NonNull InlineSuggestionsResponse response) {
final List<InlineSuggestion> inlineSuggestions = response.getInlineSuggestions();
if (inlineSuggestions.size() > 0) {
mInlineSuggestionAction.onNewSuggestions(inline... | @Test
public void testActionStripAddedForUnknown() {
simulateOnStartInputFlow();
mAnySoftKeyboardUnderTest.onInlineSuggestionsResponse(
mockResponse(
new String[] {"I", "do", "not", "know"}, Mockito.mock(InlineContentView.class)));
ImageView icon =
mAnySoftKeyboardUnderTest
... |
@Override
public HttpHeaders filter(HttpHeaders headers, ServerWebExchange exchange) {
HttpHeaders updated = new HttpHeaders();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
updated.addAll(entry.getKey(), entry.getValue());
}
// https://datatracker.ietf.org/doc/html/rfc7540#section-8.... | @Test
public void shouldIncludeTrailersHeaderIfGRPC() {
MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost:8080/get")
.header(HttpHeaders.CONTENT_TYPE, "application/grpc")
.build();
GRPCRequestHeadersFilter filter = new GRPCRequestHeadersFilter();
HttpHeaders headers = filter.fil... |
public void initCustomSigners() {
String[] customSigners = ownerConf.getTrimmedStrings(CUSTOM_SIGNERS);
if (customSigners == null || customSigners.length == 0) {
// No custom signers specified, nothing to do.
LOG.debug("No custom signers specified");
return;
}
for (String customSigner... | @Test
public void testCustomSignerFailureIfNotRegistered() throws Exception {
Configuration config = new Configuration();
config.set(CUSTOM_SIGNERS, "testsignerUnregistered");
SignerManager signerManager = new SignerManager("dontcare", null, config,
UserGroupInformation.getCurrentUser());
// M... |
@Override public List<RunConfiguration> load() {
List<RunConfiguration> runConfigurations = new ArrayList<>();
for ( RunConfigurationProvider runConfigurationProvider : getRunConfigurationProviders() ) {
runConfigurations.addAll( runConfigurationProvider.load() );
}
Collections.sort( runConfigurat... | @Test
public void testLoad() {
List<RunConfiguration> runConfigurations = executionConfigurationManager.load();
assertEquals( 2, runConfigurations.size() ); //Includes default
} |
public static String sanitizeDefaultPort(String url) {
int afterSchemeIndex = url.indexOf("://");
if(afterSchemeIndex < 0) {
return url;
}
String scheme = url.substring(0, afterSchemeIndex);
int fromIndex = scheme.length() + 3;
//Let's see if it is an IPv6 Add... | @Test
public void testSanitizeDefaultPort() {
String url = "http://127.0.0.1:80";
assertThat(CorsUtil.sanitizeDefaultPort(url), is("http://127.0.0.1"));
url = "http://127.0.0.1";
assertThat(CorsUtil.sanitizeDefaultPort(url), is("http://127.0.0.1"));
url = "http://127.0.0.1:44... |
public Map<String, Parameter> getAllParams(
Step stepDefinition, WorkflowSummary workflowSummary, StepRuntimeSummary runtimeSummary) {
return paramsManager.generateMergedStepParams(
workflowSummary, stepDefinition, getStepRuntime(stepDefinition.getType()), runtimeSummary);
} | @Test
public void testMergeNestedParamMap() {
when(this.defaultParamManager.getDefaultStepParams())
.thenReturn(
ImmutableMap.of(
"nested-default-new",
MapParamDefinition.builder()
.name("nested-default-new")
.value(
... |
public static int read(final AtomicBuffer buffer, final EntryConsumer entryConsumer)
{
final int capacity = buffer.capacity();
int recordsRead = 0;
int offset = 0;
while (offset < capacity)
{
final long observationCount = buffer.getLongVolatile(offset + OBSERVAT... | @Test
void shouldReadNoEntriesInEmptyReport()
{
assertEquals(0, LossReportReader.read(buffer, entryConsumer));
verifyNoInteractions(entryConsumer);
} |
@Override
public boolean needsInitializationOrRestoration() {
return task.needsInitializationOrRestoration();
} | @Test
public void shouldDelegateNeedsInitializationOrRestoration() {
final ReadOnlyTask readOnlyTask = new ReadOnlyTask(task);
readOnlyTask.needsInitializationOrRestoration();
verify(task).needsInitializationOrRestoration();
} |
public static AccessTokenRetriever create(Map<String, ?> configs, Map<String, Object> jaasConfig) {
return create(configs, null, jaasConfig);
} | @Test
public void testConfigureRefreshingFileAccessTokenRetrieverWithInvalidDirectory() {
// Should fail because the parent path doesn't exist.
Map<String, ?> configs = getSaslConfigs(SASL_OAUTHBEARER_TOKEN_ENDPOINT_URL, new File("/tmp/this-directory-does-not-exist/foo.json").toURI().toString());
... |
@Override
public PageResult<DictDataDO> getDictDataPage(DictDataPageReqVO pageReqVO) {
return dictDataMapper.selectPage(pageReqVO);
} | @Test
public void testGetDictDataPage() {
// mock 数据
DictDataDO dbDictData = randomPojo(DictDataDO.class, o -> { // 等会查询到
o.setLabel("芋艿");
o.setDictType("yunai");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
});
dictDataMapper.insert(dbDictDa... |
private static void convertToTelemetry(JsonElement jsonElement, long systemTs, Map<Long, List<KvEntry>> result, PostTelemetryMsg.Builder builder) {
if (jsonElement.isJsonObject()) {
parseObject(systemTs, result, builder, jsonElement.getAsJsonObject());
} else if (jsonElement.isJsonArray()) {... | @Test
public void testParseAsLong() {
var result = JsonConverter.convertToTelemetry(JsonParser.parseString("{\"meterReadingDelta\": 11}"), 0L);
Assertions.assertEquals(11L, result.get(0L).get(0).getLongValue().get().longValue());
} |
public SmppCommand createSmppCommand(SMPPSession session, Exchange exchange) {
SmppCommandType commandType = SmppCommandType.fromExchange(exchange);
return commandType.createCommand(session, configuration);
} | @Test
public void createSmppSubmitMultiCommand() {
SMPPSession session = new SMPPSession();
Exchange exchange = new DefaultExchange(new DefaultCamelContext());
exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitMulti");
SmppCommand command = binding.createSmppCommand(session, ... |
@Override
public ObjectName createName(String type, String domain, MetricName metricName) {
String name = metricName.getKey();
try {
ObjectName objectName = new ObjectName(domain, "name", name);
if (objectName.isPattern()) {
objectName = new ObjectName(domain, "name", ObjectName.quote(name));
}
... | @Test
public void createsObjectNameWithNameAsKeyPropertyName() {
DefaultObjectNameFactory f = new DefaultObjectNameFactory();
ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.dots"));
assertThat(on.getKeyProperty("name")).isEqualTo("something.with.dots");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.