focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public <T> boolean isLiveObject(T instance) {
return instance instanceof RLiveObject;
} | @Test
public void testIsLiveObject() {
RLiveObjectService service = redisson.getLiveObjectService();
TestClass ts = new TestClass(new ObjectId(100));
assertFalse(service.isLiveObject(ts));
TestClass persisted = service.persist(ts);
assertFalse(service.isLiveObject(ts));
... |
@Override
public HttpResponse handle(HttpRequest request) {
final List<String> uris = circularArrayAccessLogKeeper.getUris();
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
JsonGenerator generator ... | @Test
void testOneLogLine() throws IOException {
keeper.addUri("foo");
HttpResponse response = handler.handle(null);
response.render(out);
assertEquals("{\"entries\":[{\"url\":\"foo\"}]}", out.toString());
} |
@Override
public Hotel getHotel(String id) {
return hotelRepository.findById(id).orElseThrow(
() -> new ResourceNotFoundException("Hotel no encontrado con el id: " + id)
);
} | @Test
void testGetHotel() {
// Given (Dado)
String hotelId = "1";
Hotel hotel = new Hotel(hotelId, "Hotel Test", "Info Test", "Ubicacion Test");
// Cuando se llame hotelRepository.findById con hotelId, retorna Optional.of(hotel)
when(hotelRepository.findById(hotelId)).thenRet... |
@Override
public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException {
if(containerService.isContainer(folder)) {
final S3BucketCreateService service = new S3BucketCreateService(session);
service.create(folder, StringUtils.isBlank(status.getRegion())... | @Test(expected = InteroperabilityException.class)
public void testCreateBucketInvalidName() throws Exception {
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final Path test = new Path(new DefaultHomeFinderService(session).find(), "untitled folder", EnumSet.of(Path.T... |
public static Range<Integer> integerRange(String range) {
return ofString(range, Integer::parseInt, Integer.class);
} | @Test
public void testUnboundedRangeStringIsRejected() {
PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE;
assertEquals(Range.all(), instance.integerRange("(,)"));
} |
public SearchOptions setPage(int page, int pageSize) {
checkArgument(page >= 1, "Page must be greater or equal to 1 (got " + page + ")");
setLimit(pageSize);
int lastResultIndex = page * pageSize;
checkArgument(lastResultIndex <= MAX_RETURNABLE_RESULTS, "Can return only the first %s results. %sth result... | @Test
public void fail_if_ps_is_zero() {
assertThatThrownBy(() -> new SearchOptions().setPage(1, 0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Page size must be between 1 and 500 (got 0)");
} |
public void execute(){
logger.debug("[" + getOperationName() + "] Starting execution of paged operation. maximum time: " + maxTime + ", maximum pages: " + maxPages);
long startTime = System.currentTimeMillis();
long executionTime = 0;
int i = 0;
int exceptionsSwallowedCount = 0;
int operationsCompleted =... | @Test(timeout = 1000L)
public void execute_negpage() {
CountingPageOperation op = new CountingPageOperation(-1,Long.MAX_VALUE);
op.execute();
assertEquals(0L, op.counter);
} |
@Override
public Iterable<Duplication> getDuplications(Component file) {
checkFileComponentArgument(file);
Collection<Duplication> res = this.duplications.asMap().get(file.getKey());
if (res == null) {
return Collections.emptyList();
}
return res;
} | @Test
@UseDataProvider("allComponentTypesButFile")
public void getDuplications_throws_IAE_if_Component_type_is_not_FILE(Component.Type type) {
assertThatThrownBy(() -> {
Component component = mockComponentGetType(type);
underTest.getDuplications(component);
})
.isInstanceOf(IllegalArgument... |
boolean isWriteEnclosureForFieldName( ValueMetaInterface v, String fieldName ) {
return ( isWriteEnclosed( v ) )
|| isEnclosureFixDisabledAndContainsSeparatorOrEnclosure( fieldName.getBytes() );
} | @Test
public void testWriteEnclosureForFieldNameWithEnclosureForced() {
TextFileOutputData data = new TextFileOutputData();
data.binarySeparator = new byte[1];
data.binaryEnclosure = new byte[1];
data.writer = new ByteArrayOutputStream();
TextFileOutputMeta meta = getTextFileOutputMeta();
meta... |
@Override
public Set<GrokPattern> loadAll() {
return Sets.newHashSet(store.values());
} | @Test
public void loadAll() throws Exception {
GrokPattern pattern1 = service.save(GrokPattern.create("NAME1", ".*"));
GrokPattern pattern2 = service.save(GrokPattern.create("NAME2", ".*"));
GrokPattern pattern3 = service.save(GrokPattern.create("NAME3", ".*"));
assertThat(service.l... |
public static Map<String, Object> flatten(Map<String, Object> originalMap, String parentKey, String separator) {
final Map<String, Object> result = new HashMap<>();
for (Map.Entry<String, Object> entry : originalMap.entrySet()) {
final String key = parentKey.isEmpty() ? entry.getKey() : pare... | @Test
public void flattenAddsParentKey() throws Exception {
final Map<String, Object> map = ImmutableMap.of(
"map", ImmutableMap.of(
"foo", "bar",
"baz", "qux"));
final Map<String, Object> expected = ImmutableMap.of(
"ma... |
@Override
public boolean equals(Object object) {
if (object instanceof MapUpdate) {
MapUpdate that = (MapUpdate) object;
return this.type == that.type
&& Objects.equals(this.key, that.key)
&& Objects.equals(this.value, that.value)
... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(stats1, stats1)
.addEqualityGroup(stats2)
.testEquals();
new EqualsTester()
.addEqualityGroup(stats3, stats3)
.addEqualityGroup(stats4)
... |
public Ticket addTicket(long interval, TimerHandler handler, Object... args)
{
return ticket.add(interval, handler, args);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidTicketInsertion()
{
ticker.addTicket(-1, NOOP);
} |
public static boolean checkpw(String plaintext, String hashed) {
byte hashed_bytes[];
byte try_bytes[];
try {
String try_pw = hashpw(plaintext, hashed);
hashed_bytes = hashed.getBytes("UTF-8");
try_bytes = try_pw.getBytes("UTF-8");
} catch (Unsupported... | @Test
public void testCheckpw_failure() {
System.out.print("BCrypt.checkpw w/ bad passwords: ");
for (int i = 0; i < test_vectors.length; i++) {
int broken_index = (i + 4) % test_vectors.length;
String plain = test_vectors[i][0];
String expected = te... |
public WsResponse call(WsRequest request) {
checkState(!globalMode.isMediumTest(), "No WS call should be made in medium test mode");
WsResponse response = target.wsConnector().call(request);
failIfUnauthorized(response);
checkAuthenticationWarnings(response);
return response;
} | @Test
public void call_whenTokenExpirationApproaches_shouldLogWarnings() {
WsRequest request = newRequest();
var fiveDaysLatter = LocalDateTime.now().atZone(ZoneOffset.UTC).plusDays(5);
String expirationDate = DateTimeFormatter
.ofPattern(DATETIME_FORMAT)
.format(fiveDaysLatter);
server.st... |
public static synchronized EventTimerManager getInstance() {
return SingletonHolder.mInstance;
} | @Test
public void getInstance() {
mInstance = EventTimerManager.getInstance();
Assert.assertNotNull(mInstance);
} |
@Override
public void updateReplace(Object key, Object oldValue, Object newValue) {
int keyHash = key.hashCode();
int oldValueHash = oldValue.hashCode();
int newValueHash = newValue.hashCode();
int leafOrder = MerkleTreeUtil.getLeafOrderForHash(keyHash, leafLevel);
int leafC... | @Test
public void testUpdateReplace() {
MerkleTree merkleTree = new ArrayMerkleTree(3);
merkleTree.updateAdd(1, 1);
merkleTree.updateAdd(2, 2);
merkleTree.updateAdd(3, 3);
merkleTree.updateReplace(2, 2, 4);
int expectedHash = 0;
expectedHash = MerkleTreeUtil... |
protected static boolean isDoubleQuoted(String input) {
if (input == null || input.isBlank()) {
return false;
}
return input.matches("(^" + QUOTE_CHAR + "{2}([^" + QUOTE_CHAR + "]+)" + QUOTE_CHAR + "{2})");
} | @Test
public void testEmptyDoubleQuotedNegative() {
assertFalse(isDoubleQuoted("\"\"\"\""));
} |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
FEELFnResult<BigDecimal> s = sum.invoke( list );
Function<FEELEven... | @Test
void invokeArrayWithDoubles() {
FunctionTestUtil.assertResult(meanFunction.invoke(new Object[]{10.0d, 20.0d, 30.0d}), BigDecimal.valueOf(20));
FunctionTestUtil.assertResult(meanFunction.invoke(new Object[]{10.2d, 20.2d, 30.2d}), BigDecimal.valueOf(20.2));
} |
@Override
public Object convertToPropertyType(Class<?> entityType, String[] propertyPath, String value) {
IndexValueFieldDescriptor fieldDescriptor = getValueFieldDescriptor(entityType, propertyPath);
if (fieldDescriptor == null) {
return super.convertToPropertyType(entityType, propertyPath, val... | @Test
public void testConvertFloatProperty() {
assertThat(convertToPropertyType(TestEntity.class, "f", "42.0")).isEqualTo(42.0F);
} |
public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password) {
return getAccessTokenPasswordGrantAsync(username, password,
(OAuthAsyncRequestCallback<OAuth2AccessToken>) null);
} | @Test
public void shouldProduceCorrectRequestAsync() throws ExecutionException, InterruptedException, IOException {
final OAuth20Service service = new ServiceBuilder("your_api_key")
.apiSecret("your_api_secret")
.build(new OAuth20ApiUnit());
final OAuth2AccessToken t... |
@Override
public void report(SortedMap<MetricName, Gauge> gauges,
SortedMap<MetricName, Counter> counters,
SortedMap<MetricName, Histogram> histograms,
SortedMap<MetricName, Meter> meters,
SortedMap<MetricName, Timer> timers... | @Test
public void reportsTimerValuesAtError() throws Exception {
final Timer timer = mock(Timer.class);
when(timer.getCount()).thenReturn(1L);
when(timer.getMeanRate()).thenReturn(2.0);
when(timer.getOneMinuteRate()).thenReturn(3.0);
when(timer.getFiveMinuteRate()).thenRetur... |
@Override
// TODO(yimin) integrate this method with load() method
public void cacheData(String ufsPath, long length, long pos, boolean isAsync)
throws IOException {
List<CompletableFuture<Void>> futures = new ArrayList<>();
// TODO(yimin) To implement the sync data caching.
alluxio.grpc.FileInfo f... | @Test
public void testCacheDataPartial() throws Exception {
int numPages = 10;
long length = mPageSize * numPages;
String ufsPath = mTestFolder.newFile("test").getAbsolutePath();
byte[] buffer = BufferUtils.getIncreasingByteArray((int) length);
BufferUtils.writeBufferToFile(ufsPath, buffer);
... |
@Override
public void open() {
super.open();
for (String propertyKey : properties.stringPropertyNames()) {
LOGGER.debug("propertyKey: {}", propertyKey);
String[] keyValue = propertyKey.split("\\.", 2);
if (2 == keyValue.length) {
LOGGER.debug("key: {}, value: {}", keyValue[0], keyVal... | @Test
void testDBPrefixProhibited() throws IOException, InterpreterException {
Properties properties = new Properties();
properties.setProperty("common.max_count", "1000");
properties.setProperty("common.max_retry", "3");
properties.setProperty("default.driver", "org.h2.Driver");
properties.setPro... |
public NioAsyncSocketBuilder setWriteQueueCapacity(int writeQueueCapacity) {
verifyNotBuilt();
this.writeQueueCapacity = checkPositive(writeQueueCapacity, "writeQueueCapacity");
return this;
} | @Test
public void test_setWriteQueueCapacity() {
Reactor reactor = newReactor();
NioAsyncSocketBuilder builder = (NioAsyncSocketBuilder) reactor.newAsyncSocketBuilder();
builder.setWriteQueueCapacity(16384);
assertEquals(16384, builder.writeQueueCapacity);
} |
Mono<ImmutableMap<String, String>> resolve(List<SchemaReference> refs) {
return resolveReferences(refs, new Resolving(ImmutableMap.of(), ImmutableSet.of()))
.map(Resolving::resolved);
} | @Test
void resolvesRefsUsingSrClient() {
mockSrCall("sub1", 1,
new SchemaSubject()
.schema("schema1"));
mockSrCall("sub2", 1,
new SchemaSubject()
.schema("schema2")
.references(
List.of(
new SchemaReference().name("ref2_1... |
public static HttpAsyncClientBuilder custom(MetricRegistry metricRegistry) {
return custom(metricRegistry, METHOD_ONLY);
} | @Test
public void registersExpectedExceptionMetrics() throws Exception {
client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build();
client.start();
final CountDownLatch countDownLatch = new CountDownLatch(1);
final SimpleHttpR... |
@Override
public Double dist(V firstMember, V secondMember, GeoUnit geoUnit) {
return get(distAsync(firstMember, secondMember, geoUnit));
} | @Test
public void testDistEmpty() {
RGeo<String> geo = redisson.getGeo("test");
assertThat(geo.dist("Palermo", "Catania", GeoUnit.METERS)).isNull();
} |
public <T> void addClientLevelMutableMetric(final String name,
final String description,
final RecordingLevel recordingLevel,
final Gauge<T> valueProvider) {
final Metr... | @Test
public void shouldAddClientLevelMutableMetric() {
final Metrics metrics = mock(Metrics.class);
final RecordingLevel recordingLevel = RecordingLevel.INFO;
final MetricConfig metricConfig = new MetricConfig().recordLevel(recordingLevel);
final Gauge<String> valueProvider = (confi... |
@Override
public V move(Duration timeout, DequeMoveArgs args) {
return get(moveAsync(timeout, args));
} | @Test
public void testMove() {
RBlockingDeque<Integer> deque1 = redisson.getBlockingDeque("deque1");
RBlockingDeque<Integer> deque2 = redisson.getBlockingDeque("deque2");
deque2.add(4);
deque2.add(5);
deque2.add(6);
Executors.newSingleThreadScheduledExecutor().sched... |
@VisibleForTesting
public RequestInterceptorChainWrapper getInterceptorChain()
throws IOException {
String user = UserGroupInformation.getCurrentUser().getUserName();
RequestInterceptorChainWrapper chain = userPipelineMap.get(user);
if (chain != null && chain.getRootInterceptor() != null) {
re... | @Test
public void testClientPipelineConcurrent() throws InterruptedException {
final String user = "test1";
/*
* ClientTestThread is a thread to simulate a client request to get a
* ClientRequestInterceptor for the user.
*/
class ClientTestThread extends Thread {
private ClientReques... |
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
// Do not allow framing; OF-997
... | @Test
public void nonExcludedUrlWillNotErrorWhenListsEmpty() throws Exception {
// Setup test fixture.
AuthCheckFilter.SERVLET_REQUEST_AUTHENTICATOR.setValue(AdminUserServletAuthenticatorClass.class);
final AuthCheckFilter filter = new AuthCheckFilter(adminManager, loginLimitManager);
... |
@Override
public void authenticate(
final JsonObject authInfo,
final Handler<AsyncResult<User>> resultHandler
) {
final String username = authInfo.getString("username");
if (username == null) {
resultHandler.handle(Future.failedFuture("authInfo missing 'username' field"));
return;
... | @Test
public void shouldAuthenticateWithWildcardAllowedRole() throws Exception {
// Given:
givenAllowedRoles("**");
givenUserRoles();
// When:
authProvider.authenticate(authInfo, userHandler);
// Then:
verifyAuthorizedSuccessfulLogin();
} |
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
ConfigServer[] configServers = getConfigServers();
int[] zookeeperIds = getConfigServerZookeeperIds();
if (configServers.length != zookeeperIds.length) {
throw new IllegalArgumentException(String.format("Nu... | @Test
void zookeeperConfig_uneven_number_of_config_servers_and_zk_ids() {
assertThrows(IllegalArgumentException.class, () -> {
TestOptions testOptions = createTestOptions(List.of("cfg1", "localhost", "cfg3"), List.of(1));
getConfig(ZookeeperServerConfig.class, testOptions);
}... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testTheatreOfBloodNoPb()
{
when(client.getVarbitValue(Varbits.THEATRE_OF_BLOOD_ORB1)).thenReturn(1);
ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "",
"Wave 'The Final Challenge' (Normal Mode) complete!<br>" +
"Duration: <col=ff0000>2:42</col><br>" +
"Theatre of Blood ... |
@Override
public UltraLogLog applyAggregatedValue(UltraLogLog value, UltraLogLog aggregatedValue) {
value.add(aggregatedValue);
return value;
} | @Test
public void applyAggregatedValueShouldUnion() {
UltraLogLog input1 = UltraLogLog.create(12);
IntStream.range(0, 1000).mapToObj(UltraLogLogUtils::hashObject).forEach(h -> h.ifPresent(input1::add));
UltraLogLog input2 = UltraLogLog.create(12);
IntStream.range(0, 1000).mapToObj(UltraLogLogUtils::ha... |
@PUT
@Path("/{connector}/topics/reset")
@Operation(summary = "Reset the list of topics actively used by the specified connector")
public Response resetConnectorActiveTopics(final @PathParam("connector") String connector, final @Context HttpHeaders headers) {
if (isTopicTrackingDisabled) {
... | @Test
public void testResetConnectorActiveTopicsWithTopicTrackingEnabled() {
when(serverConfig.topicTrackingEnabled()).thenReturn(true);
when(serverConfig.topicTrackingResetEnabled()).thenReturn(false);
HttpHeaders headers = mock(HttpHeaders.class);
connectorsResource = new Connector... |
public void validateReadPermission(String serverUrl, String personalAccessToken) {
HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/repos");
doGet(personalAccessToken, url, body -> buildGson().fromJson(body, RepositoryList.class));
} | @Test
public void fail_validate_url_on_text_result_log_the_returned_payload() {
server.enqueue(new MockResponse()
.setResponseCode(500)
.setBody("this is a text payload"));
String serverUrl = server.url("/").toString();
assertThatThrownBy(() -> underTest.validateReadPermission(serverUrl, "tok... |
public Map<Integer, Schema> schemasById() {
return schemasById;
} | @Test
public void testParseSchemaIdentifierFields() throws Exception {
String data = readTableMetadataInputFile("TableMetadataV2Valid.json");
TableMetadata parsed = TableMetadataParser.fromJson(data);
assertThat(parsed.schemasById().get(0).identifierFieldIds()).isEmpty();
assertThat(parsed.schemasById... |
public DropSourceCommand create(final DropStream statement) {
return create(
statement.getName(),
statement.getIfExists(),
statement.isDeleteTopic(),
DataSourceType.KSTREAM
);
} | @Test
public void shouldCreateCommandForDropStream() {
// Given:
final DropStream ddlStatement = new DropStream(SOME_NAME, true, true);
// When:
final DdlCommand result = dropSourceFactory.create(ddlStatement);
// Then:
assertThat(result, instanceOf(DropSourceCommand.class));
} |
@Override public boolean supports( ConnectionType type ) {
return type == WEBSPHERE;
} | @Test
public void onlySupportsWebsphere() {
assertTrue( jmsProvider.supports( WEBSPHERE ) );
assertFalse( jmsProvider.supports( ACTIVEMQ ) );
} |
@Bean
public CircuitBreakerRegistry circuitBreakerRegistry(
EventConsumerRegistry<CircuitBreakerEvent> eventConsumerRegistry,
RegistryEventConsumer<CircuitBreaker> circuitBreakerRegistryEventConsumer,
@Qualifier("compositeCircuitBreakerCustomizer") CompositeCustomizer<CircuitBreakerConfigCus... | @Test
public void testCreateCircuitBreakerRegistryWithSharedConfigs() {
InstanceProperties defaultProperties = new InstanceProperties();
defaultProperties.setSlidingWindowSize(1000);
defaultProperties.setPermittedNumberOfCallsInHalfOpenState(100);
InstanceProperties sharedProperties ... |
public List<ContextPropagator> getContextPropagators() {
return Collections.unmodifiableList(this.contextPropagators);
} | @Test
public void testConfigs() {
assertThat(schedulerService.getCorePoolSize()).isEqualTo(20);
assertThat(schedulerService.getThreadFactory()).isInstanceOf(NamingThreadFactory.class);
assertThat(schedulerService.getContextPropagators()).hasSize(1)
.hasOnlyElementsOfTypes(TestCon... |
public Map<Periodical, ScheduledFuture> getFutures() {
return Maps.newHashMap(futures);
} | @Test
public void testGetFutures() throws Exception {
periodicals.registerAndStart(periodical);
assertTrue("missing periodical in future Map", periodicals.getFutures().containsKey(periodical));
assertEquals(1, periodicals.getFutures().size());
} |
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testStaticMemberRejoinsWithNewSubscribedTopics() {
String groupId = "fooup";
// Use a static member id as it makes the test easier.
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
String member2RejoinId = Uui... |
@VisibleForTesting
SmsTemplateDO validateSmsTemplate(String templateCode) {
// 获得短信模板。考虑到效率,从缓存中获取
SmsTemplateDO template = smsTemplateService.getSmsTemplateByCodeFromCache(templateCode);
// 短信模板不存在
if (template == null) {
throw exception(SMS_SEND_TEMPLATE_NOT_EXISTS);
... | @Test
public void testCheckSmsTemplateValid_notExists() {
// 准备参数
String templateCode = randomString();
// mock 方法
// 调用,并断言异常
assertServiceException(() -> smsSendService.validateSmsTemplate(templateCode),
SMS_SEND_TEMPLATE_NOT_EXISTS);
} |
@Override
public Collection<CompressionProvider> getCompressionProviders() {
Collection<CompressionProvider> providerClasses = new ArrayList<CompressionProvider>();
List<PluginInterface> providers = getPlugins();
if ( providers != null ) {
for ( PluginInterface plugin : providers ) {
try {
... | @Test
public void getCoreProviders() {
@SuppressWarnings( "serial" )
final HashMap<String, Boolean> foundProvider = new HashMap<String, Boolean>() {
{
put( "None", false );
put( "Zip", false );
put( "GZip", false );
put( "Snappy", false );
put( "Hadoop-snappy", fa... |
public void checkOin(String entityId, String oin) {
Pattern pattern = Pattern.compile("urn:nl-eid-gdi:1.0:\\w+:" + oin + ":entities:\\d+");
Matcher matcher = pattern.matcher(entityId);
if (!matcher.matches()) {
throw new MetadataParseException("OIN certificate does not match entityI... | @Test
public void checkOinTest() {
metadataProcessorServiceMock.checkOin("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS", "SSSSSSSSSSSSSSSSSSSS");
metadataProcessorServiceMock.checkOin("urn:nl-eid-gdi:1:0:DV:00000008888888888001:entities:0001", "SSSSSSSSSSSSSSSSSSSS");
} |
@PUT
@Path("/{logger}")
@Operation(summary = "Set the log level for the specified logger")
@SuppressWarnings("fallthrough")
public Response setLevel(final @PathParam("logger") String namespace,
final Map<String, String> levelMap,
@DefaultValue("w... | @Test
public void setLevelWithInvalidArgTest() {
for (String scope : Arrays.asList("worker", "cluster", "N/A", null)) {
assertThrows(
NotFoundException.class,
() -> loggingResource.setLevel(
"@root",
... |
@VisibleForTesting
static Document buildQuery(TupleDomain<ColumnHandle> tupleDomain)
{
Document query = new Document();
if (tupleDomain.getDomains().isPresent()) {
for (Map.Entry<ColumnHandle, Domain> entry : tupleDomain.getDomains().get().entrySet()) {
MongoColumnHan... | @Test
public void testBuildQueryIn()
{
TupleDomain<ColumnHandle> tupleDomain = TupleDomain.withColumnDomains(ImmutableMap.of(
COL2, Domain.create(ValueSet.ofRanges(equal(createUnboundedVarcharType(), utf8Slice("hello")), equal(createUnboundedVarcharType(), utf8Slice("world"))), false)));... |
public GithubAppConfiguration validate(AlmSettingDto almSettingDto) {
return validate(almSettingDto.getAppId(), almSettingDto.getClientId(), almSettingDto.getClientSecret(), almSettingDto.getPrivateKey(), almSettingDto.getUrl());
} | @Test
public void github_global_settings_validation() {
AlmSettingDto almSettingDto = createNewGithubDto("clientId", "clientSecret", EXAMPLE_APP_ID, EXAMPLE_PRIVATE_KEY);
when(encryption.isEncrypted(any())).thenReturn(false);
GithubAppConfiguration configuration = underTest.validate(almSettingDto);
... |
public SmppMessage createSmppMessage(CamelContext camelContext, AlertNotification alertNotification) {
SmppMessage smppMessage = new SmppMessage(camelContext, alertNotification, configuration);
smppMessage.setHeader(SmppConstants.MESSAGE_TYPE, SmppMessageType.AlertNotification.toString());
smpp... | @Test
void deliverSmWithEmptyBodyAndPayloadInOptionalParameter() throws Exception {
DeliverSm deliverSm = new DeliverSm();
String payload = "Hellö SMPP wörld!";
deliverSm.setShortMessage(new byte[] {});
deliverSm.setDataCoding(new GeneralDataCoding(Alphabet.ALPHA_DEFAULT).toByte());
... |
static MultiLineString buildMultiLineString(TDWay outerWay, List<TDWay> innerWays) {
List<LineString> lineStrings = new ArrayList<>();
// outer way geometry
lineStrings.add(buildLineString(outerWay));
// inner strings
if (innerWays != null) {
for (TDWay innerWay : in... | @Test
public void testBuildNonSimpleMultiLineString() {
String testfile = "non-simple-multilinestring.wkt";
List<TDWay> ways = MockingUtils.wktMultiLineStringToWays(testfile);
MultiLineString mls = JTSUtils.buildMultiLineString(ways.get(0), ways.subList(1, ways.size()));
Geometry ex... |
public ConfigTransformerResult transform(Map<String, String> configs) {
Map<String, Map<String, Set<String>>> keysByProvider = new HashMap<>();
Map<String, Map<String, Map<String, String>>> lookupsByProvider = new HashMap<>();
// Collect the variables from the given configs that need transforma... | @Test
public void testSingleLevelOfIndirection() {
ConfigTransformerResult result = configTransformer.transform(Collections.singletonMap(MY_KEY, "${test:testPath:testIndirection}"));
Map<String, String> data = result.data();
assertEquals("${test:testPath:testResult}", data.get(MY_KEY));
... |
public static boolean isJCacheAvailable(ClassLoader classLoader) {
return isJCacheAvailable((className) -> ClassLoaderUtil.isClassAvailable(classLoader, className));
} | @Test
public void testIsJCacheAvailable_withCorrectVersion_withLogger() {
JCacheDetector.ClassAvailabilityChecker classAvailabilityChecker = className -> true;
assertTrue(isJCacheAvailable(logger, classAvailabilityChecker));
} |
public CsvData read() throws IORuntimeException {
return read(this.reader, false);
} | @Test
@Disabled
public void readTest3() {
final CsvReadConfig csvReadConfig = CsvReadConfig.defaultConfig();
csvReadConfig.setContainsHeader(true);
final CsvReader reader = CsvUtil.getReader(csvReadConfig);
final CsvData read = reader.read(FileUtil.file("d:/test/ceshi.csv"));
for (CsvRow row : read) {
Co... |
@Override
@SneakyThrows
public WxJsapiSignature createWxMpJsapiSignature(Integer userType, String url) {
WxMpService service = getWxMpService(userType);
return service.createJsapiSignature(url);
} | @Test
public void testCreateWxMpJsapiSignature() throws WxErrorException {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
String url = randomString();
// mock 方法
WxJsapiSignature signature = randomPojo(WxJsapiSignature.class);
when(wxMpService.c... |
@Override
public ConnectionType getConnectionType() {
return ConnectionType.GRPC;
} | @Test
void testGetConnectionType() {
assertEquals(ConnectionType.GRPC, grpcClient.getConnectionType());
} |
public ConnectionDetails getConnectionDetails( IMetaStore metaStore, String key, String name ) {
ConnectionProvider<? extends ConnectionDetails> connectionProvider = getConnectionProvider( key );
if ( connectionProvider != null ) {
Class<? extends ConnectionDetails> clazz = connectionProvider.getClassType... | @Test
public void testBaRolesNotNull() {
addOne();
TestConnectionWithBucketsDetails connectionDetails =
(TestConnectionWithBucketsDetails) connectionManager.getConnectionDetails( CONNECTION_NAME );
assertNotNull( connectionDetails );
assertNotNull( connectionDetails.getBaRoles() );
} |
public static NotificationDispatcherMetadata newMetadata() {
return METADATA;
} | @Test
public void qgChange_notification_is_enable_at_global_level() {
NotificationDispatcherMetadata metadata = QGChangeNotificationHandler.newMetadata();
assertThat(metadata.getProperty(GLOBAL_NOTIFICATION)).isEqualTo("true");
} |
@Override
public void fail(Throwable t) {
currentExecutions.values().forEach(e -> e.fail(t));
} | @Test
void testFail() throws Exception {
final SpeculativeExecutionVertex ev = createSpeculativeExecutionVertex();
final Execution e1 = ev.getCurrentExecutionAttempt();
final Execution e2 = ev.createNewSpeculativeExecution(System.currentTimeMillis());
ev.fail(new Exception("Forced t... |
@Override
public Collection<PiPacketOperation> mapOutboundPacket(OutboundPacket packet)
throws PiInterpreterException {
DeviceId deviceId = packet.sendThrough();
TrafficTreatment treatment = packet.treatment();
// fabric.p4 supports only OUTPUT instructions.
List<Instruc... | @Test
public void testMapOutboundPacketWithoutForwarding()
throws Exception {
PortNumber outputPort = PortNumber.portNumber(1);
TrafficTreatment outputTreatment = DefaultTrafficTreatment.builder()
.setOutput(outputPort)
.build();
ByteBuffer data = ... |
@Override
public synchronized Set<InternalNode> getCatalogServers()
{
return catalogServers;
} | @Test
public void testGetCatalogServers()
{
DiscoveryNodeManager manager = new DiscoveryNodeManager(selector, workerNodeInfo, new NoOpFailureDetector(), Optional.of(host -> false), expectedVersion, testHttpClient, new TestingDriftClient<>(), internalCommunicationConfig);
try {
assert... |
public static List<Integer> buildQueryWithINClauseStrings(Configuration conf, List<String> queries, StringBuilder prefix,
StringBuilder suffix, List<String> inList, String inColumn, boolean addParens, boolean notIn) {
// Get configuration parameters
int maxQueryLength = MetastoreConf.getIntVar(conf, ConfV... | @Test(expected = IllegalArgumentException.class)
public void testBuildQueryWithNOTINClauseFailure() throws Exception {
MetastoreConf.setLongVar(conf, ConfVars.DIRECT_SQL_MAX_QUERY_LENGTH, 10);
MetastoreConf.setLongVar(conf, ConfVars.DIRECT_SQL_MAX_ELEMENTS_IN_CLAUSE, 100);
MetastoreConf.setLongVar(conf, C... |
public LocationIndex prepareIndex() {
return prepareIndex(EdgeFilter.ALL_EDGES);
} | @Test
public void testFindingWayGeometry() {
BaseGraph g = new BaseGraph.Builder(encodingManager).create();
NodeAccess na = g.getNodeAccess();
na.setNode(10, 51.2492152, 9.4317166);
na.setNode(20, 52, 9);
na.setNode(30, 51.2, 9.4);
na.setNode(50, 49, 10);
g.ed... |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) {
return invoke(n, BigDecimal.ZERO);
} | @Test
void invokeNull() {
FunctionTestUtil.assertResultError(roundUpFunction.invoke(null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(roundUpFunction.invoke((BigDecimal) null, null),
InvalidParametersEvent.class);
FunctionTest... |
@Override
public void doLimitForModifyRequest(ModifyRequest modifyRequest) throws SQLException {
if (null == modifyRequest || !enabledLimit) {
return;
}
doLimit(modifyRequest.getSql());
} | @Test
void testDoLimitForModifyRequestForDmlInvalid() throws SQLException {
ModifyRequest insert = new ModifyRequest("insert into test(id,name) values(1,'test')");
ModifyRequest invalid = new ModifyRequest("CALL SALES.TOTAL_REVENUES()");
List<ModifyRequest> modifyRequests = new LinkedList<>(... |
long findLogStartOffset(TopicIdPartition topicIdPartition, UnifiedLog log) throws RemoteStorageException {
Optional<Long> logStartOffset = Optional.empty();
Option<LeaderEpochFileCache> maybeLeaderEpochFileCache = log.leaderEpochCache();
if (maybeLeaderEpochFileCache.isDefined()) {
L... | @Test
public void testFindLogStartOffsetFallbackToLocalLogStartOffsetWhenRemoteIsEmpty() throws RemoteStorageException, IOException {
List<EpochEntry> epochEntries = new ArrayList<>();
epochEntries.add(new EpochEntry(1, 250L));
epochEntries.add(new EpochEntry(2, 550L));
checkpoint.wr... |
public static String toCamelCase(CharSequence name) {
return toCamelCase(name, CharUtil.UNDERLINE);
} | @Test
public void toCamelCaseFromDashedTest() {
Dict.create()
.set("Table-Test-Of-day","tableTestOfDay")
.forEach((key, value) -> assertEquals(value, NamingCase.toCamelCase(key, CharUtil.DASHED)));
} |
@Around(SYNC_UPDATE_CONFIG_ALL)
public Object aroundSyncUpdateConfigAll(ProceedingJoinPoint pjp, HttpServletRequest request,
HttpServletResponse response, String dataId, String group, String content, String appName, String srcUser,
String tenant, String tag) throws Throwable {
if (!P... | @Test
void testAroundSyncUpdateConfigAllForInsertAspect1() throws Throwable {
//test with insert
//condition:
// 1. has tenant: true
// 2. capacity limit check: true
// 3. over cluster quota: true
when(PropertyUtil.isManageCapacity()).thenReturn(true);
when... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (!(statement.getStatement() instanceof CreateSource)
&& !(statement.getStatement() instanceof CreateAsSelect)) {
return statement;
}
t... | @Test
public void shouldReturnStatementUnchangedIfCsasDoesnotHaveSchemaId() {
// Given:
givenKeyAndValueInferenceSupported();
// When:
final ConfiguredStatement<?> result = injector.inject(csasStatement);
// Then:
assertThat(result, is(sameInstance(csasStatement)));
} |
@Override
public int incrementAndGet(int key) {
return addAndGet(key, 1);
} | @Test
public void testSingleThreadV2() {
final IntHashCounter intMap = new AtomicIntHashCounter(16);
for (int i = 1; i < 1024; i++) {
intMap.incrementAndGet(i);
}
System.out.println(intMap);
} |
public long periodBarriersCrossed(long start, long end) {
if (start > end)
throw new IllegalArgumentException("Start cannot come before end");
long startFloored = getStartOfCurrentPeriodWithGMTOffsetCorrection(start, getTimeZone());
long endFloored = getStartOfCurrentPeriodWithGMTOf... | @Test
public void testPeriodBarriersCrossedWhenLeavingDaylightSaving() {
RollingCalendar rc = new RollingCalendar(dailyPattern, TimeZone.getTimeZone("CET"), Locale.US);
// Sun Oct 29 00:02:03 CEST 2017, GMT offset = -2h
long start = 1509228123333L;// 1490482923333L+217*CoreConstants.MILLIS_I... |
public static byte[] readFileBytes(File file) {
if (file.exists()) {
String result = readFile(file);
if (result != null) {
return ByteUtils.toBytes(result);
}
}
return null;
} | @Test
void testReadFileBytesWithPath() {
assertNotNull(DiskUtils.readFileBytes(testFile.getParent(), testFile.getName()));
} |
public int getCurrentCount(String ip) {
int index = 0;
if (ip != null) {
index = ip.hashCode() % slotCount;
}
if (index < 0) {
index = -index;
}
return data[index].get();
} | @Test
void testGetCurrentCount() {
SimpleIpFlowData simpleIpFlowData = new SimpleIpFlowData(3, 10000);
simpleIpFlowData.incrementAndGet("127.0.0.1");
simpleIpFlowData.incrementAndGet("127.0.0.1");
simpleIpFlowData.incrementAndGet("127.0.0.1");
assertEquals(3, simpleIpFlowData... |
@Override
public void initialize(String inputName, Map<String, String> properties) {
this.catalogProperties = ImmutableMap.copyOf(properties);
this.name = inputName;
if (conf == null) {
LOG.warn("No Hadoop Configuration was set, using the default environment Configuration");
this.conf = new Co... | @Test
public void testInitialize() {
assertThatNoException()
.isThrownBy(
() -> {
HiveCatalog hiveCatalog = new HiveCatalog();
hiveCatalog.initialize("hive", Maps.newHashMap());
});
} |
public void incGroupGetNums(final String group, final String topic, final int incValue) {
final String statsKey = buildStatsKey(topic, group);
this.statsTable.get(Stats.GROUP_GET_NUMS).addValue(statsKey, incValue, 1);
} | @Test
public void testIncGroupGetNums() {
brokerStatsManager.incGroupGetNums(GROUP_NAME, TOPIC, 1);
String statsKey = brokerStatsManager.buildStatsKey(TOPIC, GROUP_NAME);
assertThat(brokerStatsManager.getStatsItem(GROUP_GET_NUMS, statsKey).getValue().doubleValue()).isEqualTo(1L);
} |
public String createRetrievalToken() throws IOException {
File retrievalToken =
new File(
resource.baseDirectory,
"retrieval_token_" + UUID.randomUUID().toString() + ".json");
if (retrievalToken.createNewFile()) {
final DataOutp... | @Test
void testCreateRetrievalToken() throws Exception {
PythonDependencyInfo dependencyInfo =
new PythonDependencyInfo(new HashMap<>(), null, null, new HashMap<>(), "python");
Map<String, String> sysEnv = new HashMap<>();
sysEnv.put("FLINK_HOME", "/flink");
try (Pro... |
@Override
public void onRestRequest(RestRequest req, RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<RestRequest, RestResponse> nextFilter)
{
try
{
if (_requestContentEncoding.hasCompressor())
{
if (_helper.... | @Test(dataProvider = "requestCompressionData")
public void testRequestCompressionRules(CompressionConfig requestCompressionConfig,
CompressionOption requestCompressionOverride, boolean headerShouldBePresent)
throws CompressionException, URISyntaxException
{
Client... |
@Override
public void apply(IntentOperationContext<FlowObjectiveIntent> intentOperationContext) {
Objects.requireNonNull(intentOperationContext);
Optional<IntentData> toUninstall = intentOperationContext.toUninstall();
Optional<IntentData> toInstall = intentOperationContext.toInstall();
... | @Test
public void testGroupInstallationFailedErrorUnderThreshold() {
// group install failed, and retry two times.
intentInstallCoordinator = new TestIntentInstallCoordinator();
installer.intentInstallCoordinator = intentInstallCoordinator;
errors = ImmutableList.of(GROUPINSTALLATION... |
@Override
public PageResult<MailAccountDO> getMailAccountPage(MailAccountPageReqVO pageReqVO) {
return mailAccountMapper.selectPage(pageReqVO);
} | @Test
public void testGetMailAccountPage() {
// mock 数据
MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class, o -> { // 等会查询到
o.setMail("768@qq.com");
o.setUsername("yunai");
});
mailAccountMapper.insert(dbMailAccount);
// 测试 mail 不匹配
m... |
@Override
public GatewayFilter apply(RequestSizeGatewayFilterFactory.RequestSizeConfig requestSizeConfig) {
requestSizeConfig.validate();
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest... | @Test
public void toStringFormat() {
RequestSizeConfig config = new RequestSizeConfig();
config.setMaxSize(DataSize.ofBytes(1000L));
GatewayFilter filter = new RequestSizeGatewayFilterFactory().apply(config);
assertThat(filter.toString()).contains("max").contains("1000");
} |
@Override
public Code issueCode(Session session, IdTokenJWS idTokenJWS) {
var code = IdGenerator.generateID();
var value =
new Code(
code,
clock.instant(),
clock.instant().plus(TTL),
session.redirectUri(),
session.nonce(),
session... | @Test
void issueCode_propagatesValues() {
var issuer = URI.create("https://idp.example.com");
var keyStore = mock(KeyStore.class);
var codeRepo = mock(CodeRepo.class);
var sut = new TokenIssuerImpl(issuer, keyStore, codeRepo);
var nonce = UUID.randomUUID().toString();
var redirectUri = URI.c... |
@Override
public void updateProject(GoViewProjectUpdateReqVO updateReqVO) {
// 校验存在
validateProjectExists(updateReqVO.getId());
// 更新
GoViewProjectDO updateObj = GoViewProjectConvert.INSTANCE.convert(updateReqVO);
goViewProjectMapper.updateById(updateObj);
} | @Test
public void testUpdateProject_success() {
// mock 数据
GoViewProjectDO dbGoViewProject = randomPojo(GoViewProjectDO.class);
goViewProjectMapper.insert(dbGoViewProject);// @Sql: 先插入出一条存在的数据
// 准备参数
GoViewProjectUpdateReqVO reqVO = randomPojo(GoViewProjectUpdateReqVO.class,... |
@Override public final String path() {
return delegate.getRequestURI();
} | @Test void path_doesntCrashOnNullUrl() {
assertThat(wrapper.path())
.isNull();
} |
@Override
public void validate(CruiseConfig cruiseConfig) {
String newServerId = cruiseConfig.server().getServerId();
if (initialIdHolder.compareAndSet(null, newServerId)) {
return;
}
String initialId = initialIdHolder.get();
if (!Objects.equals(initialId, newSer... | @Test
public void shouldBeValidWhenServerIdIsUpdatedFromNull() {
validator.validate(cruiseConfig);
cruiseConfig.server().ensureServerIdExists();
validator.validate(cruiseConfig);
validator.validate(cruiseConfig);
} |
@Override
public Registry getRegistry(URL url) {
if (registryManager == null) {
throw new IllegalStateException("Unable to fetch RegistryManager from ApplicationModel BeanFactory. "
+ "Please check if `setApplicationModel` has been override.");
}
Registry def... | @Test
void testRegistryFactoryCache() {
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":2233");
Registry registry1 = registryFactory.getRegistry(url);
Registry registry2 = registryFactory.getRegistry(url);
Assertions.assertEquals(registry1, registry... |
public Object getProperty( Object root, String propName ) throws Exception {
List<Integer> extractedIndexes = new ArrayList<>();
BeanInjectionInfo.Property prop = info.getProperties().get( propName );
if ( prop == null ) {
throw new RuntimeException( "Property not found" );
}
Object obj = ro... | @Test
public void getProperty_Found() {
BeanInjector bi = new BeanInjector(null );
BeanInjectionInfo bii = new BeanInjectionInfo( MetaBeanLevel1.class );
BeanInjectionInfo.Property actualProperty = bi.getProperty( bii, "SEPARATOR" );
assertNotNull(actualProperty);
assertEquals("SEPARATOR", actual... |
@Udf
public String rpad(
@UdfParameter(description = "String to be padded") final String input,
@UdfParameter(description = "Target length") final Integer targetLen,
@UdfParameter(description = "Padding string") final String padding) {
if (input == null) {
return null;
}
if (paddi... | @Test
public void shouldReturnEmptyByteBufferForZeroLength() {
final ByteBuffer result = udf.rpad(BYTES_123, 0, BYTES_45);
assertThat(result, is(EMPTY_BYTES));
} |
public static Boolean isMultiInstance() {
return isMultiInstance;
} | @Test
void testIsMultiInstance2() throws InvocationTargetException, IllegalAccessException {
System.setProperty("isMultiInstance", "true");
initMethod.invoke(JvmUtil.class);
Boolean multiInstance = JvmUtil.isMultiInstance();
assertTrue(multiInstance);
} |
public static Activity getActivityOfView(Context context, View view) {
Activity activity = null;
try {
if (context != null) {
if (context instanceof Activity) {
activity = (Activity) context;
} else if (context instanceof ContextWrapper) {
... | @Test
public void getActivityOfView() {
TextView textView1 = new TextView(mApplication);
textView1.setText("child1");
Assert.assertNull(SAViewUtils.getActivityOfView(mApplication, textView1));
} |
@Override
public void reportFailedMsgs(FailedMsgs failedMsgs) {
logger.info(String.format(LOG_PREFIX + "reportFailedMsgs: %s", failedMsgs));
} | @Test
public void testReportFailedMsgs() {
FailedMsgs failedMsgs = new FailedMsgs();
failedMsgs.setTopic("unit-test");
failedMsgs.setConsumerGroup("default-consumer");
failedMsgs.setFailedMsgsTotalRecently(2);
defaultMonitorListener.reportFailedMsgs(failedMsgs);
} |
@Override
public final boolean offer(int ordinal, @Nonnull Object item) {
if (ordinal == -1) {
return offerInternal(allEdges, item);
} else {
if (ordinal == bucketCount()) {
// ordinal beyond bucketCount will add to snapshot queue, which we don't allow through... | @Test
public void when_sameItemOfferedTwice_then_success() {
String item = "foo";
assertTrue(outbox.offer(item));
assertTrue(outbox.offer(item));
} |
@Override
public Bytes key(final Bytes cacheKey) {
return Bytes.wrap(bytesFromCacheKey(cacheKey));
} | @Test
public void key() {
assertThat(
cacheFunction.key(THE_CACHE_KEY),
equalTo(THE_KEY)
);
} |
public XAttrFeature(List<XAttr> xAttrs) {
if (xAttrs != null && !xAttrs.isEmpty()) {
List<XAttr> toPack = new ArrayList<XAttr>();
ImmutableList.Builder<XAttr> b = null;
for (XAttr attr : xAttrs) {
if (attr.getValue() == null ||
attr.getValue().length <= PACK_THRESHOLD) {
... | @Test
public void testXAttrFeature() throws Exception {
List<XAttr> xAttrs = new ArrayList<>();
XAttrFeature feature = new XAttrFeature(xAttrs);
// no XAttrs in the feature
assertTrue(feature.getXAttrs().isEmpty());
// one XAttr in the feature
XAttr a1 = XAttrHelper.buildXAttr(name1, value1)... |
public RowExpression extract(PlanNode node)
{
return node.accept(new Visitor(domainTranslator, functionAndTypeManager), null);
} | @Test
public void testLeftJoin()
{
ImmutableList.Builder<EquiJoinClause> criteriaBuilder = ImmutableList.builder();
criteriaBuilder.add(new EquiJoinClause(AV, DV));
criteriaBuilder.add(new EquiJoinClause(BV, EV));
List<EquiJoinClause> criteria = criteriaBuilder.build();
... |
public Optional<DateTime> nextTime(JobTriggerDto trigger) {
return nextTime(trigger, trigger.nextTime());
} | @Test
public void emptyNextTimeCron() {
final JobTriggerDto trigger = JobTriggerDto.builderWithClock(clock)
.jobDefinitionId("abc-123")
.jobDefinitionType("event-processor-execution-v1")
.schedule(CronJobSchedule.builder()
// At every h... |
@Override
public Object executeOnKey(K key, com.hazelcast.map.EntryProcessor entryProcessor) {
return map.executeOnKey(key, entryProcessor);
} | @Test
public void testExecuteOnKey() {
map.put(23, "value-23");
map.put(42, "value-42");
String result = (String) adapter.executeOnKey(23, new IMapReplaceEntryProcessor("value", "newValue"));
assertEquals("newValue-23", result);
assertEquals("newValue-23", map.get(23));
... |
public void setRequestTarget(String requestTarget) {
this.requestTarget = requestTarget;
} | @Test
void testSetRequestTarget() {
assertNull(basicContext.getRequestTarget());
basicContext.setRequestTarget("POST /v2/ns/instance");
assertEquals("POST /v2/ns/instance", basicContext.getRequestTarget());
basicContext.setRequestTarget(InstanceRequest.class.getSimpleName());
... |
@Override
public ByteBuf asReadOnly() {
return this;
} | @Test
public void asReadOnly() {
ByteBuf buf = buffer(1);
ByteBuf readOnly = buf.asReadOnly();
assertTrue(readOnly.isReadOnly());
assertSame(readOnly, readOnly.asReadOnly());
readOnly.release();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.