focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public double interpolate(double... x) {
if (x.length != this.x[0].length) {
throw new IllegalArgumentException(String.format("Invalid input vector size: %d, expected: %d", x.length, this.x[0].length));
}
double sum = 0.0, sumw = 0.0;
for (int i = 0; i < this.x.length; i++) ... | @Test
public void testInterpolate() {
System.out.println("interpolate");
double[][] x = {{0, 0}, {1, 1}};
double[] y = {0, 1};
RBFInterpolation instance = new RBFInterpolation(x, y, new GaussianRadialBasis());
double[] x1 = {0.5, 0.5};
assertEquals(0, instance.interpo... |
public static GlobalLockConfig setAndReturnPrevious(GlobalLockConfig config) {
GlobalLockConfig previous = holder.get();
holder.set(config);
return previous;
} | @Test
void setAndReturnPrevious() {
GlobalLockConfig config1 = new GlobalLockConfig();
assertNull(GlobalLockConfigHolder.setAndReturnPrevious(config1), "should return null");
assertSame(config1, GlobalLockConfigHolder.getCurrentGlobalLockConfig(), "holder fail to store config");
Glo... |
@Override
public ScheduledFuture<?> scheduleWithRepetition(Runnable command, long initialDelay, long period, TimeUnit unit) {
return internalExecutor.scheduleAtFixedRate(command, initialDelay, period, unit);
} | @Test
public void testScheduleWithRepetition() {
TestRunnable runnable = new TestRunnable(5);
ScheduledFuture<?> future = executionService.scheduleWithRepetition(runnable, 0, 100, MILLISECONDS);
runnable.await();
boolean result = future.cancel(true);
assertTrue(result);
... |
public static SchemeHandler get() {
return new SchemeHandlerFactory().create();
} | @Test
public void testGet() {
assertNotNull(SchemeHandlerFactory.get());
} |
static List<RawMetric> constructMetricsList(ObjectName jmxMetric,
MBeanAttributeInfo[] attributes,
Object[] attrValues) {
String domain = fixIllegalChars(jmxMetric.getDomain());
LinkedHashMap<String, String> labels = get... | @Test
void convertsJmxMetricsAccordingToJmxExporterFormat() throws Exception {
List<RawMetric> metrics = JmxMetricsFormatter.constructMetricsList(
new ObjectName(
"kafka.server:type=Some.BrokerTopic-Metrics,name=BytesOutPer-Sec,topic=test,some-lbl=123"),
new MBeanAttributeInfo[] {
... |
public List<Address> getWatchedAddresses() {
keyChainGroupLock.lock();
try {
List<Address> addresses = new LinkedList<>();
for (Script script : watchedScripts)
if (ScriptPattern.isP2PKH(script))
addresses.add(script.getToAddress(network));
... | @Test
public void getWatchedAddresses() {
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, TESTNET);
wallet.addWatchedAddress(watchedAddress);
List<Address> watchedAddresses = wallet.getWatchedAddresses();
assertEquals(1, watchedAddresses.size());
assertEquals... |
@Async
@Transactional
public SamlMetadataProcessResult startCollectMetadata(Connection con, Map<String, String> map) {
SamlMetadataProcessResult result = new SamlMetadataProcessResult(con.getId());
EntitiesDescriptor descriptor;
try {
String metadataXML = getMetadataFromConn... | @Test
public void startCollectMetadataWithUnknownServiceEntityIDTest() throws IOException {
Connection connection = newConnection();
when(httpClientMock.execute(any(HttpGet.class))).thenReturn(httpResponseMock);
when(httpResponseMock.getEntity()).thenReturn(httpEntityMock);
when(htt... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
EntityType originatorEntityType = msg.getOriginator().getEntityType();
if (!EntityType.DEVICE.equals(originatorEntityType)) {
ctx.tellFailure(msg, new IllegalArgumentException(
"Unsupported originator entity type... | @Test
public void givenMetadataDoesNotContainTs_whenOnMsg_thenMsgTsIsUsedAsEventTs() {
// GIVEN
given(ctxMock.getDeviceStateNodeRateLimitConfig()).willReturn("1:1");
try {
initNode(TbMsgType.ACTIVITY_EVENT);
} catch (TbNodeException e) {
fail("Node failed to i... |
public static String encode(String s) {
return encode(s, UTF_8);
} | @Test
public void testEncodeDecode2() {
String origin = null;
String encode1 = UrlUtils.encode(origin);
assertThat(encode1).isNull();
origin = "";
encode1 = UrlUtils.encode(origin);
assertThat(encode1).isEqualTo(origin);
} |
public MetricsBuilder exportServicePort(Integer exportServicePort) {
this.exportServicePort = exportServicePort;
return getThis();
} | @Test
void exportServicePort() {
MetricsBuilder builder = MetricsBuilder.newBuilder();
builder.exportServicePort(2999);
Assertions.assertEquals(2999, builder.build().getExportServicePort());
} |
@Override
public SarifSchema210 deserialize(Path reportPath) {
try {
return mapper
.enable(JsonParser.Feature.INCLUDE_SOURCE_IN_LOCATION)
.addHandler(new DeserializationProblemHandler() {
@Override
public Object handleInstantiationProblem(DeserializationContext ctxt, Clas... | @Test
public void deserialize_shouldFail_whenSarifVersionIsNotSupported() throws URISyntaxException {
URL sarifResource = requireNonNull(getClass().getResource("unsupported-sarif-version-abc.json"));
Path sarif = Paths.get(sarifResource.toURI());
assertThatThrownBy(() -> serializer.deserialize(sarif))
... |
@Override
public int updateAllNotifyMessageRead(Long userId, Integer userType) {
return notifyMessageMapper.updateListRead(userId, userType);
} | @Test
public void testUpdateAllNotifyMessageRead() {
// mock 数据
NotifyMessageDO dbNotifyMessage = randomPojo(NotifyMessageDO.class, o -> { // 等会查询到
o.setUserId(1L);
o.setUserType(UserTypeEnum.ADMIN.getValue());
o.setReadStatus(false);
o.setReadTime(nul... |
public boolean hasProjectSubscribersForTypes(String projectUuid, Set<Class<? extends Notification>> notificationTypes) {
Set<String> dispatcherKeys = handlers.stream()
.filter(handler -> notificationTypes.stream().anyMatch(notificationType -> handler.getNotificationClass() == notificationType))
.map(Not... | @Test
public void hasProjectSubscribersForType_returns_false_if_there_are_no_handler() {
String projectUuid = randomAlphabetic(7);
NotificationService underTest = new NotificationService(dbClient);
assertThat(underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of(Notification1.class))).isFa... |
@Override
public String getDistinctId() {
return null;
} | @Test
public void getDistinctId() {
Assert.assertNull(mSensorsAPI.getDistinctId());
} |
public static JSONObject parseObj(String jsonStr) {
return new JSONObject(jsonStr);
} | @Test
public void parseObjTest() {
// 测试转义
final JSONObject jsonObject = JSONUtil.parseObj("{\n" +
" \"test\": \"\\\\地库地库\",\n" +
"}");
assertEquals("\\地库地库", jsonObject.getObj("test"));
} |
public List<Class<?>> getAllCommandClass() {
final Set<String> commandList =
frameworkModel.getExtensionLoader(BaseCommand.class).getSupportedExtensions();
final List<Class<?>> classes = new ArrayList<>();
for (String commandName : commandList) {
BaseCommand command ... | @Test
void testGetAllCommandClass() {
List<Class<?>> classes = commandHelper.getAllCommandClass();
// update this list when introduce a new command
List<Class<?>> expectedClasses = new LinkedList<>();
expectedClasses.add(GreetingCommand.class);
expectedClasses.add(Help.class... |
static LinkedHashMap<String, Double> getFixedProbabilityMap(final LinkedHashMap<String, Double> probabilityResultMap) {
LinkedHashMap<String, Double> toReturn = new LinkedHashMap<>();
String[] resultMapKeys = probabilityResultMap.keySet().toArray(new String[0]);
AtomicReference<Double> sumCounte... | @Test
void getFixedProbabilityMap() {
double initialTotalProbability = 0.99;
AtomicReference<Double> totalReference = new AtomicReference<>(initialTotalProbability);
Random rand = new Random();
List<Double> doubles = IntStream.range(0, 3).mapToDouble(value -> {
double rem... |
@Override
public ObjectNode queryService(String namespaceId, String serviceName) throws NacosException {
Service service = getServiceFromGroupedServiceName(namespaceId, serviceName, true);
if (!ServiceManager.getInstance().containSingleton(service)) {
throw new NacosApiException(NacosExc... | @Test
void testQueryService() throws NacosException {
ClusterMetadata clusterMetadata = new ClusterMetadata();
Map<String, ClusterMetadata> clusterMetadataMap = new HashMap<>(2);
clusterMetadataMap.put("D", clusterMetadata);
ServiceMetadata metadata = new ServiceMetadata();
m... |
@GwtIncompatible("java.util.regex.Pattern")
public void doesNotContainMatch(@Nullable Pattern regex) {
checkNotNull(regex);
if (actual == null) {
failWithActual("expected a string that does not contain a match for", regex);
return;
}
Matcher matcher = regex.matcher(actual);
if (matcher... | @Test
public void stringDoesNotContainMatchStringUsesFind() {
expectFailureWhenTestingThat("aba").doesNotContainMatch("[b]");
assertFailureValue("expected not to contain a match for", "[b]");
} |
public static String rtrim( String source ) {
if ( source == null ) {
return null;
}
int max = source.length();
while ( max > 0 && isSpace( source.charAt( max - 1 ) ) ) {
max--;
}
return source.substring( 0, max );
} | @Test
public void testRtrim() {
assertEquals( null, Const.rtrim( null ) );
assertEquals( "", Const.rtrim( "" ) );
assertEquals( "", Const.rtrim( " " ) );
assertEquals( "test", Const.rtrim( "test " ) );
assertEquals( "test ", Const.ltrim( " test " ) );
} |
@Override
public SendResult send(
Message msg) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
msg.setTopic(withNamespace(msg.getTopic()));
if (this.getAutoBatch() && !(msg instanceof MessageBatch)) {
return sendByAccumulator(msg, null, null... | @Test
public void testSendMessageSync_Success() throws RemotingException, InterruptedException, MQBrokerException, MQClientException {
when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createTopicRoute());
SendResult sendResult = producer.send(message);
... |
@Override
public ConfigErrors errors() {
return errors;
} | @Test
public void shouldValidateMissingLabel() {
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(null);
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), is(PipelineConfig.BLANK_LABEL_TEMPLATE_ERROR_MESSAGE));
pipelineConfig = createAndValidatePipelineLabe... |
public boolean hasSameNameAs(Header header) {
AssertParameter.notNull(header, Header.class);
return this.name.equalsIgnoreCase(header.getName());
} | @Test
public void header_has_same_name_as_expected() {
final Header header1 = new Header("foo", "bar");
final Header header2 = new Header("Foo", "baz");
assertThat(header2.hasSameNameAs(header1)).isTrue();
} |
public static ServiceListResponse buildSuccessResponse(int count, List<String> serviceNames) {
return new ServiceListResponse(count, serviceNames, "success");
} | @Test
void testSerializeSuccessResponse() throws JsonProcessingException {
ServiceListResponse response = ServiceListResponse.buildSuccessResponse(10, Collections.singletonList("a"));
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"count\":10"));
assert... |
@Override
public byte[] get(byte[] key) {
return read(key, ByteArrayCodec.INSTANCE, RedisCommands.GET, key);
} | @Test
public void testGeo() {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson));
redisTemplate.afterPropertiesSet();
String key = "test_geo_key";
Point point = new Point(116.401001... |
public static StreamedRow toRowFromDelimited(final Buffer buff) {
try {
final QueryResponseMetadata metadata = deserialize(buff, QueryResponseMetadata.class);
return StreamedRow.header(new QueryId(Strings.nullToEmpty(metadata.queryId)),
createSchema(metadata));
} catch (KsqlRestClientExcepti... | @Test
public void shouldParseRow() {
// When:
final StreamedRow row = KsqlTargetUtil.toRowFromDelimited(Buffer.buffer(
"[3467362496,5.5]"));
// Then:
assertThat(row.getRow().isPresent(), is(true));
assertThat(row.getRow().get().getColumns().size(), is(2));
assertThat(row.getRow().get(... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldNotChooseSpecificWhenTrickyVarArgLoop() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING, INT),
function("two", 0, STRING_VARARGS)
);
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> udfIndex.getFunction(Immutab... |
public synchronized void releaseWriteLock() {
status = 0;
} | @Test
public void releaseWriteLockTest() {
SimpleReadWriteLock simpleReadWriteLock = new SimpleReadWriteLock();
simpleReadWriteLock.tryWriteLock();
simpleReadWriteLock.releaseWriteLock();
boolean result = simpleReadWriteLock.tryReadLock();
Assert.isTrue(result);
} |
@VisibleForTesting
static String toString(@Nullable TaskManagerLocation location) {
// '(unassigned)' being the default value is added to support backward-compatibility for the
// deprecated fields
return location != null ? location.getEndpoint() : "(unassigned)";
} | @Test
void testArchivedTaskManagerLocationFallbackHandling() {
assertThat(
JobExceptionsHandler.toString(
(ExceptionHistoryEntry.ArchivedTaskManagerLocation) null))
.isNull();
} |
String zone(String podName) {
String nodeUrlString = String.format("%s/api/v1/nodes/%s", kubernetesMaster, nodeName(podName));
return extractZone(callGet(nodeUrlString));
} | @Test
public void zone() throws JsonProcessingException {
// given
String podName = "pod-name";
stub(String.format("/api/v1/namespaces/%s/pods/%s", NAMESPACE, podName), pod("hazelcast-0", NAMESPACE, "node-name"));
//language=JSON
String nodeResponse = """
{
... |
@Override
public TableScan appendsBetween(long fromSnapshotId, long toSnapshotId) {
validateSnapshotIdsRefinement(fromSnapshotId, toSnapshotId);
return new IncrementalDataTableScan(
table(),
schema(),
context().fromSnapshotIdExclusive(fromSnapshotId).toSnapshotId(toSnapshotId));
} | @TestTemplate
public void testInvalidScans() {
add(table.newAppend(), files("A"));
assertThatThrownBy(() -> appendsBetweenScan(1, 1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("from and to snapshot ids cannot be the same");
add(table.newAppend(), files("B"));
add(table... |
@Override
public List<QualityProfile> load(String projectKey) {
StringBuilder url = new StringBuilder(WS_URL + "?project=").append(encodeForUrl(projectKey));
return handleErrors(url, () -> String.format("Failed to load the quality profiles of project '%s'", projectKey), true);
} | @Test
public void load_tries_default_if_no_profiles_found_for_project() throws IOException {
HttpException e = new HttpException("", 404, "{\"errors\":[{\"msg\":\"No project found with key 'foo'\"}]}");
WsTestUtil.mockException(wsClient, "/api/qualityprofiles/search.protobuf?project=foo", e);
WsTestUtil.m... |
@SuppressWarnings("checkstyle:NestedIfDepth")
@Nullable
public PartitioningStrategy getPartitioningStrategy(
String mapName,
PartitioningStrategyConfig config,
final List<PartitioningAttributeConfig> attributeConfigs
) {
if (attributeConfigs != null && !attributeC... | @Test
public void whenStrategyInstantiationThrowsException_getPartitioningStrategy_rethrowsException() {
PartitioningStrategyConfig cfg = new PartitioningStrategyConfig();
cfg.setPartitioningStrategyClass("NonExistentPartitioningStrategy");
// while attempting to get partitioning strategy, ... |
@Override
protected IMetaStoreClient newClient() {
try {
try {
return GET_CLIENT.invoke(
hiveConf, (HiveMetaHookLoader) tbl -> null, HiveMetaStoreClient.class.getName());
} catch (RuntimeException e) {
// any MetaException would be wrapped into RuntimeException during refle... | @Test
public void testGetTablesFailsForNonReconnectableException() throws Exception {
HiveMetaStoreClient hmsClient = Mockito.mock(HiveMetaStoreClient.class);
Mockito.doReturn(hmsClient).when(clients).newClient();
Mockito.doThrow(new MetaException("Another meta exception"))
.when(hmsClient)
... |
@Override
public Mono<List<ListedAuthProvider>> listAll() {
return client.list(AuthProvider.class, provider ->
provider.getMetadata().getDeletionTimestamp() == null,
defaultComparator()
)
.map(this::convertTo)
.collectList()
... | @Test
@WithMockUser(username = "admin")
void listAll() {
AuthProvider github = createAuthProvider("github");
github.getSpec().setBindingUrl("fake-binding-url");
AuthProvider gitlab = createAuthProvider("gitlab");
gitlab.getSpec().setBindingUrl("fake-binding-url");
AuthP... |
@Override
protected Map get(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
return (Map) rs.getObject(position);
} | @Test
public void test() {
doInJPA(entityManager -> {
Book book = new Book();
book.setIsbn("978-9730228236");
book.getProperties().put("title", "High-Performance Java Persistence");
book.getProperties().put("author", "Vlad Mihalcea");
book.getProp... |
@Override
public Http2AllocationStrategy copy() {
return new Http2AllocationStrategy(this);
} | @Test
void copy() {
builder.maxConcurrentStreams(2).maxConnections(2).minConnections(1);
Http2AllocationStrategy strategy = builder.build();
Http2AllocationStrategy copy = strategy.copy();
assertThat(copy.maxConcurrentStreams()).isEqualTo(strategy.maxConcurrentStreams());
assertThat(copy.permitMaximum()).isE... |
public static ExecutionEnvironment createBatchExecutionEnvironment(FlinkPipelineOptions options) {
return createBatchExecutionEnvironment(
options,
MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()),
options.getFlinkConfDir());
} | @Test
public void useDefaultParallelismFromContextBatch() {
FlinkPipelineOptions options = getDefaultPipelineOptions();
options.setRunner(TestFlinkRunner.class);
ExecutionEnvironment bev = FlinkExecutionEnvironments.createBatchExecutionEnvironment(options);
assertThat(bev, instanceOf(LocalEnvironmen... |
public Set<Analysis.AliasedDataSource> extractDataSources(final AstNode node) {
new Visitor().process(node, null);
return getAllSources();
} | @Test
public void shouldExtractUnaliasedDataSources() {
// Given:
final AstNode stmt = givenQuery("SELECT * FROM TEST1;");
// When:
extractor.extractDataSources(stmt);
// Then:
assertContainsAlias(TEST1);
} |
public static <T> NavigableSet<Point<T>> fastKNearestPoints(SortedSet<Point<T>> points, Instant time, int k) {
checkNotNull(points, "The input SortedSet of Points cannot be null");
checkNotNull(time, "The input time cannot be null");
checkArgument(k >= 0, "k (" + k + ") must be non-negative");
... | @Test
public void testFastKNearestPoints_3() {
NavigableSet<Point<String>> knn = fastKNearestPoints(points, EPOCH.plusMillis(5), 3);
assertEquals(3, knn.size());
Point one = knn.pollFirst();
Point two = knn.pollFirst();
Point three = knn.pollFirst();
assertFalse(one =... |
public static <T> PTransform<PCollection<T>, PCollection<T>> intersectAll(
PCollection<T> rightCollection) {
checkNotNull(rightCollection, "rightCollection argument is null");
return new SetImpl<>(rightCollection, intersectAll());
} | @Test
@Category(NeedsRunner.class)
public void testIntersectionAll() {
PAssert.that(first.apply("strings", Sets.intersectAll(second)))
.containsInAnyOrder("a", "a", "b", "b", "c", "d", "d");
PCollection<Row> results = firstRows.apply("rows", Sets.intersectAll(secondRows));
PAssert.that(result... |
@Override
public void checkBeforeUpdate(final AlterEncryptRuleStatement sqlStatement) {
checkToBeAlteredRules(sqlStatement);
checkColumnNames(sqlStatement);
checkToBeAlteredEncryptors(sqlStatement);
} | @Test
void assertCheckSQLStatementWithConflictColumnNames() {
EncryptRule rule = mock(EncryptRule.class);
when(rule.getAllTableNames()).thenReturn(Collections.singleton("t_encrypt"));
executor.setRule(rule);
assertThrows(InvalidRuleConfigurationException.class, () -> executor.checkBe... |
@Override
public ElasticAgentPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
String pluginId = descriptor.id();
PluggableInstanceSettings pluggableInstanceSettings = null;
if (!extension.supportsClusterProfiles(pluginId)) {
pluggableInstanceSettings = getPluginSettings... | @Test
public void shouldGetCapabilitiesForAPlugin() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
when(pluginManager.resolveExtensionVersion("plugin1", ELASTIC_AGENT_EXTENSION, SUPPORTED_VERSIONS)).thenReturn("2.0");
Capabilities capabilities = new Ca... |
static String toDatabaseName(Namespace namespace, boolean skipNameValidation) {
if (!skipNameValidation) {
validateNamespace(namespace);
}
return namespace.level(0);
} | @Test
public void testSkipNamespaceValidation() {
List<Namespace> acceptableNames =
Lists.newArrayList(Namespace.of("db-1"), Namespace.of("db-1-1-1"));
for (Namespace name : acceptableNames) {
assertThat(IcebergToGlueConverter.toDatabaseName(name, true)).isEqualTo(name.toString());
}
} |
public <T> List<T> toList(Class<T> elementType) {
return JSONConverter.toList(this, elementType);
} | @Test
public void toListTest() {
String jsonStr = FileUtil.readString("exam_test.json", CharsetUtil.CHARSET_UTF_8);
JSONArray array = JSONUtil.parseArray(jsonStr);
List<Exam> list = array.toList(Exam.class);
assertFalse(list.isEmpty());
assertSame(Exam.class, list.get(0).getClass());
} |
public TExecPlanFragmentParams plan(TUniqueId loadId) throws UserException {
boolean isPrimaryKey = destTable.getKeysType() == KeysType.PRIMARY_KEYS;
resetAnalyzer();
// construct tuple descriptor, used for scanNode and dataSink
TupleDescriptor tupleDesc = descTable.createTupleDescriptor... | @Test
public void testPartialUpdatePlan() throws UserException {
List<Column> columns = Lists.newArrayList();
Column c1 = new Column("c1", Type.BIGINT, false);
columns.add(c1);
Column c2 = new Column("c2", Type.BIGINT, true);
columns.add(c2);
new Expectations() {
... |
@Override
public void close() throws IOException {
super.close();
try {
final Reply response = this.getStatus();
if(response != null) {
if(log.isDebugEnabled()) {
log.debug(String.format("Closed stream %s with response value %s", this, resp... | @Test(expected = IOException.class)
public void testClose() throws Exception {
try {
new HttpResponseOutputStream<Void>(NullOutputStream.NULL_OUTPUT_STREAM, new VoidAttributesAdapter(), new TransferStatus()) {
@Override
public Void getStatus() throws BackgroundExc... |
public void shutdown() {
DefaultMetricsSystem.shutdown();
} | @Test(timeout = 300000)
public void testTransactionSinceLastCheckpointMetrics() throws Exception {
Random random = new Random();
int retryCount = 0;
while (retryCount < 5) {
try {
int basePort = 10060 + random.nextInt(100) * 2;
MiniDFSNNTopology topology = new MiniDFSNNTopology()
... |
public boolean isMatch(boolean input) {
for (BoolMatch boolMatch : oneof) {
if (boolMatch.isMatch(input)) {
return true;
}
}
return false;
} | @Test
void isMatch() {
ListBoolMatch listBoolMatch = new ListBoolMatch();
List<BoolMatch> oneof = new ArrayList<>();
BoolMatch boolMatch1 = new BoolMatch();
boolMatch1.setExact(true);
oneof.add(boolMatch1);
listBoolMatch.setOneof(oneof);
assertTrue(listBoolM... |
@Override
public void e(String tag, String message, Object... args) {
Log.e(tag, formatString(message, args));
} | @Test
public void errorWithThrowableLoggedCorrectly() {
String expectedMessage = "Hello World";
Throwable t = new Throwable("Test Throwable");
logger.e(t, tag, "Hello %s", "World");
assertLogged(ERROR, tag, expectedMessage, t);
} |
public Builder asBuilder() {
return new Builder(columns);
} | @Test
public void shouldDetectDuplicateKeysViaAsBuilder() {
// Given:
final Builder builder = SOME_SCHEMA.asBuilder();
// When:
assertThrows(
KsqlException.class,
() -> builder.keyColumn(K0, STRING)
);
} |
@Override
public int expireEntries(Set<K> keys, Duration ttl) {
return get(expireEntriesAsync(keys, ttl));
} | @Test
public void testExpireEntries() {
RMapCacheNative<String, String> testMap = redisson.getMapCacheNative("map");
testMap.put("key1", "value");
testMap.put("key2", "value");
testMap.expireEntries(new HashSet<>(Arrays.asList("key1", "key2")), Duration.ofMillis(20000));
asse... |
public static Protocol parse(File file) throws IOException {
try (JsonParser jsonParser = Schema.FACTORY.createParser(file)) {
return parse(jsonParser);
}
} | @Test
void normalization() {
final String schema = "{\n" + " \"type\":\"record\", \"name\": \"Main\", " + " \"fields\":[\n"
+ " { \"name\":\"f1\", \"type\":\"Sub\" },\n" // use Sub
+ " { \"name\":\"f2\", " + " \"type\":{\n" + " \"type\":\"enum\", \"name\":\"Sub\",\n" // de... |
public static <T> Write<T> write() {
return new AutoValue_XmlIO_Write.Builder<T>().setCharset(StandardCharsets.UTF_8.name()).build();
} | @Test
public void testWriteDisplayData() {
XmlIO.Write<Integer> write =
XmlIO.<Integer>write().withRootElement("bird").withRecordClass(Integer.class);
DisplayData displayData = DisplayData.from(write);
assertThat(displayData, hasDisplayItem("rootElement", "bird"));
assertThat(displayData, has... |
public SendResult sendMessage(
final String addr,
final String brokerName,
final Message msg,
final SendMessageRequestHeader requestHeader,
final long timeoutMillis,
final CommunicationMode communicationMode,
final SendMessageContext context,
final Default... | @Test
public void testSendMessageAsync_WithException() throws RemotingException, InterruptedException, MQBrokerException {
doThrow(new RemotingTimeoutException("Remoting Exception in Test")).when(remotingClient)
.invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any(InvokeCallback.... |
public ProcessContinuation run(
PartitionRecord partitionRecord,
RestrictionTracker<StreamProgress, StreamProgress> tracker,
OutputReceiver<KV<ByteString, ChangeStreamRecord>> receiver,
ManualWatermarkEstimator<Instant> watermarkEstimator)
throws IOException {
BytesThroughputEstimator<... | @Test
public void testLockingRowSucceed() throws IOException {
final ServerStream<ChangeStreamRecord> responses = mock(ServerStream.class);
final Iterator<ChangeStreamRecord> responseIterator = mock(Iterator.class);
when(responses.iterator()).thenReturn(responseIterator);
Heartbeat mockHeartBeat = Mo... |
@Override
public void createNode(OpenstackNode osNode) {
checkNotNull(osNode, ERR_NULL_NODE);
OpenstackNode updatedNode;
if (osNode.intgBridge() == null && osNode.type() != CONTROLLER) {
String deviceIdStr = genDpid(deviceIdCounter.incrementAndGet());
checkNotNull(d... | @Test(expected = IllegalArgumentException.class)
public void testCreateNodeWithDuplicateIntgBridge() {
target.createNode(COMPUTE_1);
target.createNode(COMPUTE_1_DUP_INT);
} |
public void container(Action<? super ContainerParameters> action) {
action.execute(container);
} | @Test
public void testContainer() {
assertThat(testJibExtension.getContainer().getJvmFlags()).isEmpty();
assertThat(testJibExtension.getContainer().getEnvironment()).isEmpty();
assertThat(testJibExtension.getContainer().getExtraClasspath()).isEmpty();
assertThat(testJibExtension.getContainer().getExpa... |
@Override
public Object getValue() {
return lazyMetric == null ? null : lazyMetric.getValue();
} | @Test
public void getValue() {
//Long
LazyDelegatingGauge gauge = new LazyDelegatingGauge("bar", 99l);
assertThat(gauge.getValue()).isEqualTo(99l);
assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_NUMBER);
//Double
gauge = new LazyDelegatingGauge("bar", 99.0);
... |
public static String addQuery(String url, String... parameters) {
if (parameters.length % 2 != 0)
throw new IllegalArgumentException("Expected an even number of parameters.");
var result = new StringBuilder(url);
var printedParams = 0;
for (var i = 0; i < parameters.length; ... | @Test
public void testQuery() throws Exception {
var url = "http://localhost/api/foo";
assertThat(UrlUtil.addQuery(url, "a", "1", "b", null, "c", "b\ta/r"))
.isEqualTo("http://localhost/api/foo?a=1&c=b%09a/r");
} |
public CompletionStage<Void> migrate(MigrationSet set) {
InterProcessLock lock = new InterProcessSemaphoreMutex(client.unwrap(), ZKPaths.makePath(lockPath, set.id()));
CompletionStage<Void> lockStage = lockAsync(lock, lockMax.toMillis(), TimeUnit.MILLISECONDS, executor);
return lockStage.thenCom... | @Test
public void testChecksumDataError() {
CuratorOp op1 = client.transactionOp().create().forPath("/test");
CuratorOp op2 = client.transactionOp().create().forPath("/test/bar", "first".getBytes());
Migration migration = () -> Arrays.asList(op1, op2);
MigrationSet migrationSet = Mig... |
@Override
public void doClean() {
long currentTime = System.currentTimeMillis();
for (ExpiredMetadataInfo each : metadataManager.getExpiredMetadataInfos()) {
if (currentTime - each.getCreateTime() > GlobalConfig.getExpiredMetadataExpiredTime()) {
removeExpiredMetadata(eac... | @Test
void testDoClean() {
expiredMetadataCleaner.doClean();
verify(metadataManagerMock).getExpiredMetadataInfos();
verify(metadataOperateServiceMock).deleteServiceMetadata(expiredMetadataInfoMock.getService());
} |
static <E extends Enum<E>> String enumName(final E state)
{
return null == state ? "null" : state.name();
} | @Test
void stateNameReturnsNameOfTheEnumConstant()
{
final ChronoUnit state = ChronoUnit.CENTURIES;
assertEquals(state.name(), enumName(state));
} |
public static void setProtectedFieldValue(String protectedField, Object object, Object newValue) {
try {
// acgegi would silently fail to write to final fields
// FieldUtils.writeField(Object, field, true) only sets accessible on *non* public fields
// and then fails with Ill... | @Test
public void setProtectedFieldValue_Should_Succeed() {
InnerClassWithProtectedField sut = new InnerClassWithProtectedField();
FieldUtils.setProtectedFieldValue("myProtectedField", sut, "test");
assertEquals("test", sut.getMyNonFinalField());
} |
void doSubmit(final Runnable action) {
CONTINUATION.get().submit(action);
} | @Test
public void testRecursiveOrder() {
final Continuations CONT = new Continuations();
final StringBuilder result = new StringBuilder();
CONT.doSubmit(() -> {
result.append("BEGIN{");
recursivePostOrder(CONT, result, "root", 0);
});
CONT.doSubmit(() -> {
result.append("}END");
... |
public static String[] splitIPPortStr(String address) {
if (StringUtils.isBlank(address)) {
throw new IllegalArgumentException("ip and port string cannot be empty!");
}
if (address.charAt(0) == '[') {
address = removeBrackets(address);
}
String[] serverAdd... | @Test
public void testSplitIPPortStr() {
String[] ipPort = new String[]{"127.0.0.1","8080"};
assertThat(NetUtil.splitIPPortStr("127.0.0.1:8080")).isEqualTo(ipPort);
ipPort = new String[]{"::","8080"};
assertThat(NetUtil.splitIPPortStr("[::]:8080")).isEqualTo(ipPort);
ipPort =... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testCreateTableAsColumns()
{
// TODO: validate output
analyze("CREATE TABLE test(a) AS SELECT 123");
analyze("CREATE TABLE test(a, b) AS SELECT 1, 2");
analyze("CREATE TABLE test(a) AS (VALUES 1)");
assertFails(COLUMN_NAME_NOT_SPECIFIED, "CREATE TABLE t... |
static boolean containsIn(CloneGroup first, CloneGroup second) {
if (first.getCloneUnitLength() > second.getCloneUnitLength()) {
return false;
}
List<ClonePart> firstParts = first.getCloneParts();
List<ClonePart> secondParts = second.getCloneParts();
return SortedListsUtils.contains(secondPart... | @Test
public void length_of_C1_bigger_than_length_of_C2() {
CloneGroup c1 = spy(newCloneGroup(3,
newClonePart("a", 0)));
CloneGroup c2 = spy(newCloneGroup(1,
newClonePart("a", 0)));
assertThat(Filter.containsIn(c1, c2), is(false));
// containsIn method should check only origin and len... |
@Override
public boolean execute(Workflow workflow, Task task, WorkflowExecutor executor) {
Map<String, Task> taskMap = TaskHelper.getTaskMap(workflow);
Optional<Task.Status> done = executeJoin(task, taskMap);
if (done.isPresent() && confirmDone(workflow, task)) { // update task status if it is done
... | @Test
public void testExecuteDone() {
StepRuntimeState state = new StepRuntimeState();
state.setStatus(StepInstance.Status.COMPLETED_WITH_ERROR);
when(stepInstanceDao.getStepStates(anyString(), anyLong(), anyLong(), anyList()))
.thenReturn(Collections.singletonMap("job1", state));
assertTrue(... |
@Override
public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances) {
throw new UnsupportedOperationException(
"Do not support persistent instances to perform batch de registration methods.");
} | @Test
void testBatchDeregisterService() {
assertThrows(UnsupportedOperationException.class, () -> {
clientProxy.batchDeregisterService("a", "b", null);
});
} |
public static synchronized String getEcosystem(String vendor, String product, String identifiedEcosystem) {
final Pair<String, String> key = new Pair<>(vendor, product);
final String current = cache.get(key);
String result = null;
if (current == null) {
if (!StringUtils.isBla... | @Test
public void testGetEcosystem() {
Pair<String, String> key = new Pair<>("apache", "zookeeper");
Map<Pair<String, String>, String> map = new HashMap<>();
map.put(key, "java");
CpeEcosystemCache.setCache(map);
String expected = "java";
String result = CpeEcosystem... |
public static Find find(String regex) {
return find(regex, 0);
} | @Test
@Category(NeedsRunner.class)
public void testFindNameNone() {
PCollection<String> output =
p.apply(Create.of("a", "b", "c", "d"))
.apply(Regex.find("(?<namedgroup>[xyz])", "namedgroup"));
PAssert.that(output).empty();
p.run();
} |
@Override
public List<String> listPartitionNamesByValue(String databaseName, String tableName,
List<Optional<String>> partitionValues) {
List<Partition> partitions = get(partitionCache, OdpsTableName.of(databaseName, tableName));
ImmutableList.Builde... | @Test
public void testListPartitionNamesByValue() {
List<String> partitions = odpsMetadata.listPartitionNamesByValue("project", "tableName",
ImmutableList.of(Optional.of("a"), Optional.empty()));
Assert.assertEquals(Collections.singletonList("p1=a/p2=b"), partitions);
partit... |
public static <K, V> Reshuffle<K, V> of() {
return new Reshuffle<>();
} | @Test
public void testRequestOldUpdateCompatibility() {
pipeline.enableAbandonedNodeEnforcement(false);
pipeline.getOptions().as(StreamingOptions.class).setUpdateCompatibilityVersion("2.53.0");
pipeline.apply(Create.of(KV.of("arbitrary", "kv"))).apply(Reshuffle.of());
OldTransformSeeker seeker = new ... |
public static TypeDescriptor javaTypeForFieldType(FieldType fieldType) {
switch (fieldType.getTypeName()) {
case LOGICAL_TYPE:
// TODO: shouldn't we handle this differently?
return javaTypeForFieldType(fieldType.getLogicalType().getBaseType());
case ARRAY:
return TypeDescriptors.... | @Test
public void testMapTypeToJavaType() {
assertEquals(
TypeDescriptors.maps(TypeDescriptors.strings(), TypeDescriptors.longs()),
FieldTypeDescriptors.javaTypeForFieldType(
FieldType.map(FieldType.STRING, FieldType.INT64)));
assertEquals(
TypeDescriptors.maps(
... |
public TopicConnection topicConnection(TopicConnection connection) {
// It is common to implement both interfaces
if (connection instanceof XATopicConnection) {
return xaTopicConnection((XATopicConnection) connection);
}
return TracingConnection.create(connection, this);
} | @Test void topicConnection_doesntDoubleWrap() {
TopicConnection wrapped = jmsTracing.topicConnection(mock(TopicConnection.class));
assertThat(jmsTracing.topicConnection(wrapped))
.isSameAs(wrapped);
} |
@Override
public int deleteById(final String userId) {
final User user = loadById(userId);
if (user == null) {
return 0;
}
DBObject query = new BasicDBObject();
query.put("_id", new ObjectId(userId));
final int deleteCount = destroy(query, UserImpl.COLLECT... | @Test
@MongoDBFixtures("UserServiceImplTest.json")
public void testDeleteById() throws Exception {
assertThat(userService.deleteById("54e3deadbeefdeadbeef0001")).isEqualTo(1);
assertThat(userService.deleteById("54e3deadbeefdeadbeef0003")).isEqualTo(1);
assertThat(userService.deleteById("... |
public String getClientLatency() {
if (!enabled) {
return null;
}
Instant trackerStart = Instant.now();
String latencyDetails = queue.poll(); // non-blocking pop
if (LOG.isDebugEnabled()) {
Instant stop = Instant.now();
long elapsed = Duration.between(trackerStart, stop).toMillis... | @Test
public void verifyGettingLatencyRecordsIsCheapWhenEnabled() throws Exception {
final double maxLatencyWhenDisabledMs = 5000;
final double minLatencyWhenDisabledMs = 0;
final long numTasks = 1000;
long aggregateLatency = 0;
AbfsPerfTracker abfsPerfTracker = new AbfsPerfTracker(accountName, fi... |
@Override
public String format(final Schema schema) {
final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema);
return options.contains(Option.AS_COLUMN_LIST)
? stripTopLevelStruct(converted)
: converted;
} | @Test
public void shouldFormatRequiredStructAsColumns() {
// Given:
final Schema structSchema = SchemaBuilder.struct()
.field("COL1", Schema.OPTIONAL_STRING_SCHEMA)
.field("COL4", SchemaBuilder
.array(Schema.OPTIONAL_FLOAT64_SCHEMA)
.optional()
.build())
... |
public Histogram(BinScheme binScheme) {
this.hist = new float[binScheme.bins()];
this.count = 0.0f;
this.binScheme = binScheme;
} | @Test
public void testHistogram() {
BinScheme scheme = new ConstantBinScheme(10, -5, 5);
Histogram hist = new Histogram(scheme);
for (int i = -5; i < 5; i++)
hist.record(i);
for (int i = 0; i < 10; i++)
assertEquals(scheme.fromBin(i), hist.value(i / 10.0 + EPS... |
public List<String> getTaintRepositories() {
return taintRepositories;
} | @Test
public void test_getTaintRepositories_withExtraReposFromConfiguration() {
when(configuration.hasKey(EXTRA_TAINT_REPOSITORIES)).thenReturn(true);
when(configuration.getStringArray(EXTRA_TAINT_REPOSITORIES)).thenReturn(new String[]{"extra-1", "extra-2"});
TaintChecker underTest = new TaintChecker(conf... |
@Override
public double rand() {
if (rng == null) {
rng = new RejectionLogLogistic();
}
return rng.rand();
} | @Test
public void testSd() {
System.out.println("sd");
BetaDistribution instance = new BetaDistribution(2, 5);
instance.rand();
assertEquals(0.1597191, instance.sd(), 1E-7);
} |
static long getNodeHashRangeOnLevel(int level) {
int nodesOnLevel = getNodesOnLevel(level);
return INT_RANGE / nodesOnLevel;
} | @Test
public void testGetHashStepForLevel() {
assertEquals(1L << 32, MerkleTreeUtil.getNodeHashRangeOnLevel(0));
assertEquals(1L << 31, MerkleTreeUtil.getNodeHashRangeOnLevel(1));
assertEquals(1L << 30, MerkleTreeUtil.getNodeHashRangeOnLevel(2));
assertEquals(1L << 29, MerkleTreeUtil... |
static long deleteObsoleteJRobinFiles(String application) {
final Calendar nowMinusThreeMonthsAndADay = Calendar.getInstance();
nowMinusThreeMonthsAndADay.add(Calendar.DAY_OF_YEAR, -getObsoleteGraphsDays());
nowMinusThreeMonthsAndADay.add(Calendar.DAY_OF_YEAR, -1);
final long timestamp = Util.getTimestamp(nowMi... | @Test
public void testDeleteObsoleteJRobinFiles() {
JRobin.deleteObsoleteJRobinFiles(TEST_APPLICATION);
Utils.setProperty(Parameter.OBSOLETE_GRAPHS_DAYS, "1");
JRobin.deleteObsoleteJRobinFiles(TEST_APPLICATION);
} |
public Optional<ScimGroupDto> findByGroupUuid(DbSession dbSession, String groupUuid) {
return Optional.ofNullable(mapper(dbSession).findByGroupUuid(groupUuid));
} | @Test
void findByGroupUuid_whenScimUuidFound_shouldReturnDto() {
ScimGroupDto scimGroupDto = db.users().insertScimGroup(db.users().insertGroup());
db.users().insertScimGroup(db.users().insertGroup());
ScimGroupDto underTest = scimGroupDao.findByGroupUuid(db.getSession(), scimGroupDto.getGroupUuid())
... |
public boolean shouldRestartTask(TaskStatus status) {
return includeTasks && (!onlyFailed || status.state() == AbstractStatus.State.FAILED);
} | @Test
public void doNotRestartTasks() {
RestartRequest restartRequest = new RestartRequest(CONNECTOR_NAME, false, false);
assertFalse(restartRequest.shouldRestartTask(createTaskStatus(AbstractStatus.State.FAILED)));
assertFalse(restartRequest.shouldRestartTask(createTaskStatus(AbstractStatus... |
@Operation(summary = "get", description = "GET_WORKFLOWS_NOTES")
@GetMapping(value = "/{code}")
@ResponseStatus(HttpStatus.OK)
@ApiException(QUERY_PROCESS_DEFINITION_LIST)
public Result<ProcessDefinition> getWorkflow(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginU... | @Test
public void testGetWorkflow() {
Mockito.when(processDefinitionService.getProcessDefinition(user, 1L))
.thenReturn(this.getProcessDefinition(name));
Result<ProcessDefinition> resourceResponse = workflowV2Controller.getWorkflow(user, 1L);
Assertions.assertEquals(this.getP... |
public List<String> toPrefix(String in) {
List<String> tokens = buildTokens(alignINClause(in));
List<String> output = new ArrayList<>();
List<String> stack = new ArrayList<>();
for (String token : tokens) {
if (isOperand(token)) {
if (token.equals(")")) {
... | @Test
public void testComplexStatementWithGreaterAndEquals() {
String s = "age>=5 AND ((( active = true ) AND (age = 23 )) OR age > 40) AND( salary>10 ) OR age=10";
List<String> list = parser.toPrefix(s);
assertEquals(Arrays.asList("age", "5", ">=", "active", "true", "=", "age", "23", "=", "... |
@Override
@Deprecated
public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNul... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowBadTransformerSupplierOnFlatTransformWithNamedAndStores() {
final org.apache.kafka.streams.kstream.Transformer<String, String, Iterable<KeyValue<String, String>>> transformer = flatTransformerSupplier.get();
final IllegalArgumentEx... |
@VisibleForTesting
protected void copyFromHost(MapHost host) throws IOException {
// reset retryStartTime for a new host
retryStartTime = 0;
// Get completed maps on 'host'
List<TaskAttemptID> maps = scheduler.getMapsForHost(host);
// Sanity check to catch hosts with only 'OBSOLETE' maps,
... | @SuppressWarnings("unchecked")
@Test(timeout=10000)
public void testCopyFromHostCompressFailure() throws Exception {
InMemoryMapOutput<Text, Text> immo = mock(InMemoryMapOutput.class);
Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm,
r, metrics, except, key, connection);
... |
public void setPrefix(String prefix) {
this.prefix = prefix;
} | @Test
public void customMetricsPrefix() throws Exception {
iqtp.setPrefix(PREFIX);
iqtp.start();
assertThat(metricRegistry.getNames())
.overridingErrorMessage("Custom metrics prefix doesn't match")
.allSatisfy(name -> assertThat(name).startsWith(PREFIX));
... |
public TrackingResult track(Component component, Input<DefaultIssue> rawInput, @Nullable Input<DefaultIssue> targetInput) {
if (analysisMetadataHolder.isPullRequest()) {
return standardResult(pullRequestTracker.track(component, rawInput, targetInput));
}
if (isFirstAnalysisSecondaryBranch()) {
... | @Test
public void delegate_pull_request_tracker() {
Branch branch = mock(Branch.class);
when(branch.getType()).thenReturn(BranchType.PULL_REQUEST);
when(analysisMetadataHolder.getBranch()).thenReturn(mock(Branch.class));
when(analysisMetadataHolder.isPullRequest()).thenReturn(true);
underTest.tra... |
public static Permission getPermission(String name, String serviceName, String... actions) {
PermissionFactory permissionFactory = PERMISSION_FACTORY_MAP.get(serviceName);
if (permissionFactory == null) {
throw new IllegalArgumentException("No permissions found for service: " + serviceName);... | @Test
public void getPermission_Semaphore() {
Permission permission = ActionConstants.getPermission("foo", SemaphoreServiceUtil.SERVICE_NAME);
assertNotNull(permission);
assertTrue(permission instanceof SemaphorePermission);
} |
static boolean isProviderEnabled(Configuration configuration, String serviceName) {
return SecurityOptions.forProvider(configuration, serviceName)
.get(DELEGATION_TOKEN_PROVIDER_ENABLED);
} | @Test
public void isProviderEnabledMustGiveBackFalseWhenDisabled() {
Configuration configuration = new Configuration();
configuration.setBoolean(CONFIG_PREFIX + ".test.enabled", false);
assertFalse(DefaultDelegationTokenManager.isProviderEnabled(configuration, "test"));
} |
@Override
public <T> void register(Class<T> remoteInterface, T object) {
register(remoteInterface, object, 1);
} | @Test
public void testNoAckWithResultInvocations() throws InterruptedException {
RedissonClient server = createInstance();
RedissonClient client = createInstance();
try {
server.getRemoteService().register(RemoteInterface.class, new RemoteImpl());
// no ack but an ex... |
@Override
public Mono<GetUnversionedProfileResponse> getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated t... | @Test
void getUnversionedProfileExpiredGroupSendEndorsement() throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
// Expirations must be on a day boundary; pick one in the recent past
final Instant expiration = Instant.now().truncatedTo(ChronoUnit... |
public RuleData obtainRuleData(final String pluginName, final String path) {
final Map<String, RuleData> lruMap = RULE_DATA_MAP.get(pluginName);
return Optional.ofNullable(lruMap).orElse(Maps.newHashMap()).get(path);
} | @Test
public void testObtainRuleData() throws NoSuchFieldException, IllegalAccessException {
RuleData cacheRuleData = RuleData.builder().id("1").pluginName(mockPluginName1).sort(1).build();
ConcurrentHashMap<String, WindowTinyLFUMap<String, RuleData>> ruleMap = getFieldByName(ruleMapStr);
ru... |
public static BadRequestException accessKeyNotExists() {
return new BadRequestException("accessKey not exist.");
} | @Test
public void testAccessKeyNotExists(){
BadRequestException accessKeyNotExists = BadRequestException.accessKeyNotExists();
assertEquals("accessKey not exist.", accessKeyNotExists.getMessage());
} |
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) {
FunctionConfig mergedConfig = existingConfig.toBuilder().build();
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "isRegexPattern for input topic test-input cannot be altered")
public void testMergeDifferentInputSpecWithRegexChange() {
FunctionConfig functionConfig = createFunctionConfig();
Map<String, ConsumerConfig> i... |
static String encodeNumeric(NumericType numericType) {
byte[] rawValue = toByteArray(numericType);
byte paddingValue = getPaddingValue(numericType);
byte[] paddedRawValue = new byte[MAX_BYTE_LENGTH];
if (paddingValue != 0) {
for (int i = 0; i < paddedRawValue.length; i++) {
... | @Test
public void testIntEncode() {
Int zero8 = new Int8(BigInteger.ZERO);
assertEquals(
TypeEncoder.encodeNumeric(zero8),
("0000000000000000000000000000000000000000000000000000000000000000"));
Int max8 = new Int8(BigInteger.valueOf(127));
assertEqual... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.