focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@Override
public long arrayAppend(String path, Object... values) {
return get(arrayAppendAsync(path, values));
} | @Test
public void testArrayAppend() {
RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class));
TestType t = new TestType();
NestedType nt = new NestedType();
nt.setValues(Arrays.asList("t1", "t2"));
t.setType(nt);
al.set(t);
long s1 = al.arrayAppend("$.type.values", "t3", "t4");
assertThat(s1).isEqualTo(4);
List<String> n = al.get(new JacksonCodec<>(new TypeReference<List<String>>() {}), "type.values");
assertThat(n).containsExactly("t1", "t2", "t3", "t4");
List<Long> s2 = al.arrayAppendMulti("$.type.values", "t5", "t6");
assertThat(s2).containsExactly(6L);
List<String> n2 = al.get(new JacksonCodec<>(new TypeReference<List<String>>() {}), "type.values");
assertThat(n2).containsExactly("t1", "t2", "t3", "t4", "t5", "t6");
} |
@Override
public PageResult<CouponTemplateDO> getCouponTemplatePage(CouponTemplatePageReqVO pageReqVO) {
return couponTemplateMapper.selectPage(pageReqVO);
} | @Test
public void testGetCouponTemplatePage() {
// mock 数据
CouponTemplateDO dbCouponTemplate = randomPojo(CouponTemplateDO.class, o -> { // 等会查询到
o.setName("芋艿");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
o.setDiscountType(PromotionDiscountTypeEnum.PERCENT.getType());
o.setCreateTime(buildTime(2022, 2, 2));
});
couponTemplateMapper.insert(dbCouponTemplate);
// 测试 name 不匹配
couponTemplateMapper.insert(cloneIgnoreId(dbCouponTemplate, o -> o.setName("土豆")));
// 测试 status 不匹配
couponTemplateMapper.insert(cloneIgnoreId(dbCouponTemplate, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
// 测试 type 不匹配
couponTemplateMapper.insert(cloneIgnoreId(dbCouponTemplate, o -> o.setDiscountType(PromotionDiscountTypeEnum.PRICE.getType())));
// 测试 createTime 不匹配
couponTemplateMapper.insert(cloneIgnoreId(dbCouponTemplate, o -> o.setCreateTime(buildTime(2022, 1, 1))));
// 准备参数
CouponTemplatePageReqVO reqVO = new CouponTemplatePageReqVO();
reqVO.setName("芋艿");
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
reqVO.setDiscountType(PromotionDiscountTypeEnum.PERCENT.getType());
reqVO.setCreateTime((new LocalDateTime[]{buildTime(2022, 2, 1), buildTime(2022, 2, 3)}));
// 调用
PageResult<CouponTemplateDO> pageResult = couponTemplateService.getCouponTemplatePage(reqVO);
// 断言
assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size());
assertPojoEquals(dbCouponTemplate, pageResult.getList().get(0));
} |
@Override
public void validate(final Analysis analysis) {
try {
RULES.forEach(rule -> rule.check(analysis));
} catch (final KsqlException e) {
throw new KsqlException(e.getMessage() + PULL_QUERY_SYNTAX_HELP, e);
}
QueryValidatorUtil.validateNoUserColumnsWithSameNameAsPseudoColumns(analysis);
} | @Test
public void shouldThrowOnPartitionBy() {
// Given:
when(analysis.getPartitionBy()).thenReturn(Optional.of(new PartitionBy(
Optional.empty(),
ImmutableList.of(AN_EXPRESSION)
)));
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> validator.validate(analysis)
);
// Then:
assertThat(e.getMessage(), containsString("Pull queries don't support PARTITION BY clauses."));
} |
Object getFromStep(String stepId, String paramName) {
try {
return executor
.submit(() -> fromStep(stepId, paramName))
.get(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new MaestroInternalError(
e, "getFromStep throws an exception for stepId=[%s], paramName=[%s]", stepId, paramName);
}
} | @Test
public void testGetFromStep() throws Exception {
StepRuntimeSummary summary = loadObject(TEST_STEP_RUNTIME_SUMMARY, StepRuntimeSummary.class);
when(allStepOutputData.get("step1"))
.thenReturn(Collections.singletonMap("maestro_step_runtime_summary", summary));
assertEquals("foo", paramExtension.getFromStep("step1", "param1"));
assertEquals("SUCCEEDED", paramExtension.getFromStep("step1", Constants.STEP_STATUS_PARAM));
assertEquals(
1608171805401L, paramExtension.getFromStep("step1", Constants.STEP_END_TIME_PARAM));
} |
public static <T> T head(final T[] elements) {
checkNotNull(elements);
if (elements.length == 0) {
return null;
}
return elements[0];
} | @Test
public void should_get_head() {
assertThat(Iterables.head(new Integer[]{1, 2}), is(1));
assertThat(Iterables.head(new Integer[]{1}), is(1));
assertThat(Iterables.head(new Integer[0]), nullValue());
assertThrows(NullPointerException.class, () -> Iterables.head(null));
} |
@Override
public boolean hasDesiredResources() {
final Collection<? extends SlotInfo> freeSlots =
declarativeSlotPool.getFreeSlotTracker().getFreeSlotsInformation();
return hasDesiredResources(desiredResources, freeSlots);
} | @Test
void testHasEnoughResourcesReturnsTrueIfSatisfied() {
final ResourceCounter resourceRequirement =
ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1);
final Collection<TestingSlot> freeSlots =
createSlotsForResourceRequirements(resourceRequirement);
assertThat(AdaptiveScheduler.hasDesiredResources(resourceRequirement, freeSlots)).isTrue();
} |
public static <K, V> Read<K, V> read() {
return new AutoValue_CdapIO_Read.Builder<K, V>().build();
} | @Test
public void testReadObjectCreationFailsIfPullFrequencySecIsNull() {
assertThrows(
IllegalArgumentException.class,
() -> CdapIO.<String, String>read().withPullFrequencySec(null));
} |
@Override
public void handle(CommitterEvent event) {
try {
eventQueue.put(event);
} catch (InterruptedException e) {
throw new YarnRuntimeException(e);
}
} | @Test
public void testBasic() throws Exception {
AppContext mockContext = mock(AppContext.class);
OutputCommitter mockCommitter = mock(OutputCommitter.class);
Clock mockClock = mock(Clock.class);
CommitterEventHandler handler = new CommitterEventHandler(mockContext,
mockCommitter, new TestingRMHeartbeatHandler());
YarnConfiguration conf = new YarnConfiguration();
conf.set(MRJobConfig.MR_AM_STAGING_DIR, stagingDir);
JobContext mockJobContext = mock(JobContext.class);
ApplicationAttemptId attemptid = ApplicationAttemptId.fromString(
"appattempt_1234567890000_0001_0");
JobId jobId = TypeConverter.toYarn(
TypeConverter.fromYarn(attemptid.getApplicationId()));
WaitForItHandler waitForItHandler = new WaitForItHandler();
when(mockContext.getApplicationID()).thenReturn(attemptid.getApplicationId());
when(mockContext.getApplicationAttemptId()).thenReturn(attemptid);
when(mockContext.getEventHandler()).thenReturn(waitForItHandler);
when(mockContext.getClock()).thenReturn(mockClock);
handler.init(conf);
handler.start();
try {
handler.handle(new CommitterJobCommitEvent(jobId, mockJobContext));
String user = UserGroupInformation.getCurrentUser().getShortUserName();
Path startCommitFile = MRApps.getStartJobCommitFile(conf, user, jobId);
Path endCommitSuccessFile = MRApps.getEndJobCommitSuccessFile(conf, user,
jobId);
Path endCommitFailureFile = MRApps.getEndJobCommitFailureFile(conf, user,
jobId);
Event e = waitForItHandler.getAndClearEvent();
assertNotNull(e);
assertTrue(e instanceof JobCommitCompletedEvent);
FileSystem fs = FileSystem.get(conf);
assertTrue(startCommitFile.toString(), fs.exists(startCommitFile));
assertTrue(endCommitSuccessFile.toString(), fs.exists(endCommitSuccessFile));
assertFalse(endCommitFailureFile.toString(), fs.exists(endCommitFailureFile));
verify(mockCommitter).commitJob(any(JobContext.class));
} finally {
handler.stop();
}
} |
@Override
public Optional<Map<String, EncryptionInformation>> getReadEncryptionInformation(
ConnectorSession session,
Table table,
Optional<Set<HiveColumnHandle>> requestedColumns,
Map<String, Partition> partitions)
{
Optional<DwrfTableEncryptionProperties> encryptionProperties = getTableEncryptionProperties(table);
if (!encryptionProperties.isPresent()) {
return Optional.empty();
}
Optional<Map<String, String>> fieldToKeyReference = getFieldToKeyReference(encryptionProperties.get(), requestedColumns);
if (!fieldToKeyReference.isPresent()) {
return Optional.empty();
}
return Optional.of(getReadEncryptionInformationInternal(session, table, requestedColumns, partitions, fieldToKeyReference.get(), encryptionProperties.get()));
} | @Test
public void testGetReadEncryptionInformationForPartitionedTableWithTableLevelEncryption()
{
Table table = createTable(DWRF, Optional.of(forTable("table_level_key", "algo", "provider")), true);
Optional<Map<String, EncryptionInformation>> encryptionInformation = encryptionInformationSource.getReadEncryptionInformation(
SESSION,
table,
Optional.of(ImmutableSet.of(
// hiveColumnIndex value does not matter in this test
new HiveColumnHandle("col_bigint", HIVE_LONG, HIVE_LONG.getTypeSignature(), 0, REGULAR, Optional.empty(), Optional.empty()),
new HiveColumnHandle(
"col_struct",
STRUCT_TYPE,
STRUCT_TYPE.getTypeSignature(),
0,
REGULAR,
Optional.empty(),
ImmutableList.of(new Subfield("col_struct.a"), new Subfield("col_struct.b.b2")),
Optional.empty()))),
ImmutableMap.of(
"ds=2020-01-01", new Partition("dbName", "tableName", ImmutableList.of("2020-01-01"), table.getStorage(), table.getDataColumns(), ImmutableMap.of(), Optional.empty(), false, true, 0, 0, Optional.empty()),
"ds=2020-01-02", new Partition("dbName", "tableName", ImmutableList.of("2020-01-02"), table.getStorage(), table.getDataColumns(), ImmutableMap.of(), Optional.empty(), false, true, 0, 0, Optional.empty())));
assertTrue(encryptionInformation.isPresent());
assertEquals(
encryptionInformation.get(),
ImmutableMap.of(
"ds=2020-01-01", EncryptionInformation.fromEncryptionMetadata(DwrfEncryptionMetadata.forTable("table_level_key".getBytes(), ImmutableMap.of(TEST_EXTRA_METADATA, "ds=2020-01-01"), "algo", "provider")),
"ds=2020-01-02", EncryptionInformation.fromEncryptionMetadata(DwrfEncryptionMetadata.forTable("table_level_key".getBytes(), ImmutableMap.of(TEST_EXTRA_METADATA, "ds=2020-01-02"), "algo", "provider"))));
} |
@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
response.setHeader("X-Frame-Options", JiveGlobals.getProperty("adminConsole.frame-options", "SAMEORIGIN"));
// Reset the defaultLoginPage variable
String loginPage = defaultLoginPage;
if (loginPage == null) {
loginPage = request.getContextPath() + (AuthFactory.isOneTimeAccessTokenEnabled() ? "/loginToken.jsp" : "/login.jsp" );
}
// Get the page we're on:
String url = request.getRequestURI().substring(1);
if (url.startsWith("plugins/")) {
url = url.substring("plugins/".length());
}
// See if it's contained in the exclude list. If so, skip filter execution
boolean doExclude = false;
for (String exclude : excludes) {
if (testURLPassesExclude(url, exclude)) {
doExclude = true;
break;
}
}
if (!doExclude || IP_ACCESS_IGNORE_EXCLUDES.getValue()) {
if (!passesBlocklist(req) || !passesAllowList(req)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
if (!doExclude) {
WebManager manager = new WebManager();
manager.init(request, response, request.getSession(), context);
boolean haveOneTimeToken = manager.getAuthToken() instanceof AuthToken.OneTimeAuthToken;
User loggedUser = manager.getUser();
boolean loggedAdmin = loggedUser == null ? false : adminManager.isUserAdmin(loggedUser.getUsername(), true);
if (!haveOneTimeToken && !loggedAdmin && !authUserFromRequest(request)) {
response.sendRedirect(getRedirectURL(request, loginPage, null));
return;
}
}
chain.doFilter(req, res);
} | @Test
public void willRedirectARequestIfTheServletRequestAuthenticatorReturnsAnUnauthorisedUser() throws Exception {
AuthCheckFilter.SERVLET_REQUEST_AUTHENTICATOR.setValue(NormalUserServletAuthenticatorClass.class);
final AuthCheckFilter filter = new AuthCheckFilter(adminManager, loginLimitManager);
filter.doFilter(request, response, filterChain);
verify(response).sendRedirect(anyString());
} |
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isEmpty(args)) {
return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})";
}
Channel channel = commandContext.getRemote();
String service = channel.attr(ChangeTelnet.SERVICE_KEY) != null
? channel.attr(ChangeTelnet.SERVICE_KEY).get()
: null;
String message = args[0];
int i = message.indexOf("(");
if (i < 0 || !message.endsWith(")")) {
return "Invalid parameters, format: service.method(args)";
}
String method = message.substring(0, i).trim();
String param = message.substring(i + 1, message.length() - 1).trim();
i = method.lastIndexOf(".");
if (i >= 0) {
service = method.substring(0, i).trim();
method = method.substring(i + 1).trim();
}
if (StringUtils.isEmpty(service)) {
return "If you want to invoke like [invoke sayHello(\"xxxx\")], please execute cd command first,"
+ " or you can execute it like [invoke IHelloService.sayHello(\"xxxx\")]";
}
List<Object> list;
try {
list = JsonUtils.toJavaList("[" + param + "]", Object.class);
} catch (Throwable t) {
return "Invalid json argument, cause: " + t.getMessage();
}
StringBuilder buf = new StringBuilder();
Method invokeMethod = null;
ProviderModel selectedProvider = null;
if (isInvokedSelectCommand(channel)) {
selectedProvider = channel.attr(INVOKE_METHOD_PROVIDER_KEY).get();
invokeMethod = channel.attr(SelectTelnet.SELECT_METHOD_KEY).get();
} else {
for (ProviderModel provider : frameworkModel.getServiceRepository().allProviderModels()) {
if (!isServiceMatch(service, provider)) {
continue;
}
selectedProvider = provider;
List<Method> methodList = findSameSignatureMethod(provider.getAllMethods(), method, list);
if (CollectionUtils.isEmpty(methodList)) {
break;
}
if (methodList.size() == 1) {
invokeMethod = methodList.get(0);
} else {
List<Method> matchMethods = findMatchMethods(methodList, list);
if (CollectionUtils.isEmpty(matchMethods)) {
break;
}
if (matchMethods.size() == 1) {
invokeMethod = matchMethods.get(0);
} else { // exist overridden method
channel.attr(INVOKE_METHOD_PROVIDER_KEY).set(provider);
channel.attr(INVOKE_METHOD_LIST_KEY).set(matchMethods);
channel.attr(INVOKE_MESSAGE_KEY).set(message);
printSelectMessage(buf, matchMethods);
return buf.toString();
}
}
break;
}
}
if (!StringUtils.isEmpty(service)) {
buf.append("Use default service ").append(service).append('.');
}
if (selectedProvider == null) {
buf.append("\r\nNo such service ").append(service);
return buf.toString();
}
if (invokeMethod == null) {
buf.append("\r\nNo such method ")
.append(method)
.append(" in service ")
.append(service);
return buf.toString();
}
try {
Object[] array =
realize(list.toArray(), invokeMethod.getParameterTypes(), invokeMethod.getGenericParameterTypes());
long start = System.currentTimeMillis();
AppResponse result = new AppResponse();
try {
Object o = invokeMethod.invoke(selectedProvider.getServiceInstance(), array);
boolean setValueDone = false;
if (RpcContext.getServerAttachment().isAsyncStarted()) {
AsyncContext asyncContext = RpcContext.getServerAttachment().getAsyncContext();
if (asyncContext instanceof AsyncContextImpl) {
CompletableFuture<Object> internalFuture =
((AsyncContextImpl) asyncContext).getInternalFuture();
result.setValue(internalFuture.get());
setValueDone = true;
}
}
if (!setValueDone) {
result.setValue(o);
}
} catch (Throwable t) {
result.setException(t);
if (t instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
} finally {
RpcContext.removeContext();
}
long end = System.currentTimeMillis();
buf.append("\r\nresult: ");
buf.append(JsonUtils.toJson(result.recreate()));
buf.append("\r\nelapsed: ");
buf.append(end - start);
buf.append(" ms.");
} catch (Throwable t) {
return "Failed to invoke method " + invokeMethod.getName() + ", cause: " + StringUtils.toString(t);
}
return buf.toString();
} | @Test
void testInvalidMessage() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null);
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY));
given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY));
String result = invoke.execute(mockCommandContext, new String[] {"("});
assertEquals("Invalid parameters, format: service.method(args)", result);
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove();
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove();
} |
@Override
public ValidationResult validate(Object value) {
ValidationResult result = super.validate(value);
if (result instanceof ValidationResult.ValidationPassed) {
final String sValue = (String)value;
if (sValue.length() < minLength || sValue.length() > maxLength) {
result = new ValidationResult.ValidationFailed("Value is not between " + minLength + " and " + maxLength + " in length!");
}
}
return result;
} | @Test
public void testValidateEmptyValue() {
assertThat(new LimitedStringValidator(1, 1).validate(""))
.isInstanceOf(ValidationResult.ValidationFailed.class);
} |
@Override
public void destroy() {
ManagedExecutorService asyncExecutor = getMapStoreExecutor();
asyncExecutor.submit(() -> {
awaitInitFinished();
// Instance is not shutting down.
// Only GenericMapLoader is being closed
if (instance.isRunning()) {
dropMapping(mappingName);
}
});
} | @Test
public void whenMapLoaderDestroyOnMaster_thenDropMapping() {
objectProvider.createObject(mapName, false);
mapLoader = createMapLoader();
assertMappingCreated();
mapLoader.destroy();
assertMappingDestroyed();
} |
@Override
public Health check(Set<NodeHealth> nodeHealths) {
Set<NodeHealth> appNodes = nodeHealths.stream()
.filter(s -> s.getDetails().getType() == NodeDetails.Type.APPLICATION)
.collect(Collectors.toSet());
return Arrays.stream(AppNodeClusterHealthSubChecks.values())
.map(s -> s.check(appNodes))
.reduce(Health.GREEN, HealthReducer::merge);
} | @Test
public void status_YELLOW_when_single_YELLOW_application_node() {
Set<NodeHealth> nodeHealths = nodeHealths(YELLOW).collect(toSet());
Health check = underTest.check(nodeHealths);
assertThat(check)
.forInput(nodeHealths)
.hasStatus(Health.Status.YELLOW)
.andCauses(
"Status of all application nodes is YELLOW",
"There should be at least two application nodes");
} |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
void testInputMismatchWithRawFuntion() {
MapFunction<?, ?> function = new MapWithResultTypeQueryable();
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(
(MapFunction) function, BasicTypeInfo.INT_TYPE_INFO);
assertThat(ti).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO);
} |
public static Document loadXMLFrom( String xml ) throws SAXException, IOException {
return loadXMLFrom( new ByteArrayInputStream( xml.getBytes() ) );
} | @Test
public void whenLoadingLegalXmlFromStringNotNullDocumentIsReturned() throws Exception {
final String trans = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<transformation>"
+ "</transformation>";
assertNotNull( PDIImportUtil.loadXMLFrom( trans ) );
} |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));
return query;
} | @Test
public void filter_on_projectUuids_if_projectUuid_is_empty_and_criteria_non_empty() {
ProjectMeasuresQuery query = newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue("10").build()),
emptySet());
assertThat(query.getProjectUuids()).isPresent();
} |
public Object set(final String property, final Object value) {
Objects.requireNonNull(value, "value");
final Object parsed = parser.parse(property, value);
return props.put(property, parsed);
} | @Test(expected = IllegalArgumentException.class)
public void shouldNotAllowUnknownConsumerPropertyToBeSet() {
realProps.set(StreamsConfig.CONSUMER_PREFIX + "some.unknown.prop", "some.value");
} |
@Nullable public Span currentSpan() {
TraceContext context = currentTraceContext.get();
if (context == null) return null;
// Returns a lazy span to reduce overhead when tracer.currentSpan() is invoked just to see if
// one exists, or when the result is never used.
return new LazySpan(this, context);
} | @Test void currentSpan_defaultsToNull() {
assertThat(tracer.currentSpan()).isNull();
} |
public Set<FlowRule> flowtable() {
JsonNode ents = object.path(ENTRIES);
if (!ents.isArray()) {
return ImmutableSet.of();
}
ArrayNode entries = (ArrayNode) ents;
Builder<FlowRule> builder = ImmutableSet.builder();
entries.forEach(entry -> builder.add(decode(entry, FlowRule.class)));
return builder.build();
} | @Test
public void writeTest() throws JsonProcessingException, IOException {
FlowTableConfig w = new FlowTableConfig();
w.init(DID, FlowTableConfig.CONFIG_KEY, mapper.createObjectNode(), mapper, noopDelegate);
Set<FlowRule> table = ImmutableSet.of(FLOW_RULE);
w.flowtable(table);
assertEquals(cfgnode, w.node());
} |
@Override
public String formatNotifyTemplateContent(String content, Map<String, Object> params) {
return StrUtil.format(content, params);
} | @Test
public void testFormatNotifyTemplateContent() {
// 准备参数
Map<String, Object> params = new HashMap<>();
params.put("name", "小红");
params.put("what", "饭");
// 调用,并断言
assertEquals("小红,你好,饭吃了吗?",
notifyTemplateService.formatNotifyTemplateContent("{name},你好,{what}吃了吗?", params));
} |
Timer.Context getTimerContextFromExchange(Exchange exchange, String propertyName) {
return exchange.getProperty(propertyName, Timer.Context.class);
} | @Test
public void testGetTimerContextFromExchange() {
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(context);
assertThat(producer.getTimerContextFromExchange(exchange, PROPERTY_NAME), is(context));
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
inOrder.verifyNoMoreInteractions();
} |
@ApiOperation(value = "Create a user", tags = { "Users" }, code = 201)
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Indicates the user was created."),
@ApiResponse(code = 400, message = "Indicates the id of the user was missing.")
})
@PostMapping(value = "/identity/users", produces = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public UserResponse createUser(@RequestBody UserRequest userRequest) {
if (userRequest.getId() == null) {
throw new FlowableIllegalArgumentException("Id cannot be null.");
}
if (restApiInterceptor != null) {
restApiInterceptor.createUser(userRequest);
}
// Check if a user with the given ID already exists so we return a CONFLICT
if (identityService.createUserQuery().userId(userRequest.getId()).count() > 0) {
throw new FlowableConflictException("A user with id '" + userRequest.getId() + "' already exists.");
}
User created = identityService.newUser(userRequest.getId());
created.setEmail(userRequest.getEmail());
created.setFirstName(userRequest.getFirstName());
created.setLastName(userRequest.getLastName());
created.setDisplayName(userRequest.getDisplayName());
created.setPassword(userRequest.getPassword());
created.setTenantId(userRequest.getTenantId());
identityService.saveUser(created);
return restResponseFactory.createUserResponse(created, true);
} | @Test
public void testCreateUser() throws Exception {
try {
ObjectNode requestNode = objectMapper.createObjectNode();
requestNode.put("id", "testuser");
requestNode.put("firstName", "Frederik");
requestNode.put("lastName", "Heremans");
requestNode.put("displayName", "Frederik Heremans");
requestNode.put("password", "test");
requestNode.put("email", "no-reply@flowable.org");
HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER_COLLECTION, "testuser"));
httpPost.setEntity(new StringEntity(requestNode.toString()));
CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
closeResponse(response);
assertThat(responseNode).isNotNull();
assertThatJson(responseNode)
.when(Option.IGNORING_EXTRA_FIELDS)
.isEqualTo("{"
+ "id: 'testuser',"
+ "firstName: 'Frederik',"
+ "lastName: 'Heremans',"
+ "displayName: 'Frederik Heremans',"
+ "email: 'no-reply@flowable.org',"
+ "url: '" + SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER, "testuser") + "'"
+ "}");
User createdUser = identityService.createUserQuery().userId("testuser").singleResult();
assertThat(createdUser).isNotNull();
assertThat(createdUser.getFirstName()).isEqualTo("Frederik");
assertThat(createdUser.getLastName()).isEqualTo("Heremans");
assertThat(createdUser.getDisplayName()).isEqualTo("Frederik Heremans");
assertThat(createdUser.getPassword()).isEqualTo("test");
assertThat(createdUser.getEmail()).isEqualTo("no-reply@flowable.org");
} finally {
try {
identityService.deleteUser("testuser");
} catch (Throwable t) {
// Ignore, user might not have been created by test
}
}
} |
@Override
public Optional<Customer> findByName(String name) throws SQLException {
var sql = "select * from CUSTOMERS where name = ?;";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, name);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
return Optional.of(
Customer.builder()
.name(rs.getString("name"))
.money(Money.of(USD, rs.getBigDecimal("money")))
.customerDao(this)
.build());
} else {
return Optional.empty();
}
}
} | @Test
void shouldFindCustomerByName() throws SQLException {
var customer = customerDao.findByName("customer");
assertTrue(customer.isEmpty());
TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource);
customer = customerDao.findByName("customer");
assertTrue(customer.isPresent());
assertEquals("customer", customer.get().getName());
assertEquals(Money.of(USD, 100), customer.get().getMoney());
} |
@Override
public ScalarOperator visitBinaryPredicate(BinaryPredicateOperator predicate, Void context) {
return shuttleIfUpdate(predicate);
} | @Test
void testBinaryOperator() {
BinaryPredicateOperator operator = new BinaryPredicateOperator(BinaryType.EQ,
new ColumnRefOperator(1, INT, "id", true), ConstantOperator.createInt(1));
{
ScalarOperator newOperator = shuttle.visitBinaryPredicate(operator, null);
assertEquals(operator, newOperator);
}
{
ScalarOperator newOperator = shuttle2.visitBinaryPredicate(operator, null);
assertEquals(operator, newOperator);
}
} |
public static void checkKeyParam(String dataId, String group) throws NacosException {
if (StringUtils.isBlank(dataId) || !ParamUtils.isValid(dataId)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, DATAID_INVALID_MSG);
}
if (StringUtils.isBlank(group) || !ParamUtils.isValid(group)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, GROUP_INVALID_MSG);
}
} | @Test
void testCheckKeyParam1() throws NacosException {
String dataId = "b";
String group = "c";
ParamUtils.checkKeyParam(dataId, group);
try {
dataId = "";
group = "c";
ParamUtils.checkKeyParam(dataId, group);
fail();
} catch (NacosException e) {
assertEquals("dataId invalid", e.getMessage());
}
try {
dataId = "b";
group = "";
ParamUtils.checkKeyParam(dataId, group);
fail();
} catch (NacosException e) {
assertEquals("group invalid", e.getMessage());
}
} |
public void checkWritePermission(String gitlabUrl, String personalAccessToken) {
String url = format("%s/markdown", gitlabUrl);
LOG.debug("verify write permission by formating some markdown : [{}]", url);
Request.Builder builder = new Request.Builder()
.url(url)
.addHeader(PRIVATE_TOKEN, personalAccessToken)
.addHeader("Content-Type", MediaTypes.JSON)
.post(RequestBody.create("{\"text\":\"validating write permission\"}".getBytes(UTF_8)));
Request request = builder.build();
String errorMessage = "Could not validate GitLab write permission. Got an unexpected answer.";
try (Response response = client.newCall(request).execute()) {
checkResponseIsSuccessful(response, errorMessage);
GsonMarkdown.parseOne(response.body().string());
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException("Could not parse GitLab answer to verify write permission. Got a non-json payload as result.");
} catch (IOException e) {
logException(url, e);
throw new IllegalArgumentException(errorMessage);
}
} | @Test
public void fail_check_write_permission_with_unexpected_io_exception_with_detailed_log() throws IOException {
server.shutdown();
assertThatThrownBy(() -> underTest.checkWritePermission(gitlabUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not validate GitLab write permission. Got an unexpected answer.");
assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("/markdown") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
} |
public static <T> T createInstance(String userClassName,
Class<T> xface,
ClassLoader classLoader) {
Class<?> theCls;
try {
theCls = Class.forName(userClassName, true, classLoader);
} catch (ClassNotFoundException | NoClassDefFoundError cnfe) {
throw new RuntimeException("User class must be in class path", cnfe);
}
if (!xface.isAssignableFrom(theCls)) {
throw new RuntimeException(userClassName + " does not implement " + xface.getName());
}
Class<T> tCls = (Class<T>) theCls.asSubclass(xface);
T result;
try {
Constructor<T> meth = (Constructor<T>) constructorCache.get(theCls);
if (null == meth) {
meth = tCls.getDeclaredConstructor();
meth.setAccessible(true);
constructorCache.put(theCls, meth);
}
result = meth.newInstance();
} catch (InstantiationException ie) {
throw new RuntimeException("User class must be concrete", ie);
} catch (NoSuchMethodException e) {
throw new RuntimeException("User class must have a no-arg constructor", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("User class must have a public constructor", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("User class constructor throws exception", e);
}
return result;
} | @Test
public void testCreateTypedInstanceAbstractClass() {
try {
createInstance(AbstractClass.class.getName(), aInterface.class, classLoader);
fail("Should fail to load abstract class");
} catch (RuntimeException re) {
assertTrue(re.getCause() instanceof InstantiationException);
}
} |
@Udf
public Long trunc(@UdfParameter final Long val) {
return val;
} | @Test
public void shouldTruncateDoubleWithDecimalPlacesPositive() {
assertThat(udf.trunc(0d, 0), is(0d));
assertThat(udf.trunc(1.0d, 0), is(1.0d));
assertThat(udf.trunc(1.1d, 0), is(1.0d));
assertThat(udf.trunc(1.5d, 0), is(1.0d));
assertThat(udf.trunc(1.75d, 0), is(1.0d));
assertThat(udf.trunc(100.1d, 0), is(100.0d));
assertThat(udf.trunc(100.5d, 0), is(100.0d));
assertThat(udf.trunc(100.75d, 0), is(100.0d));
assertThat(udf.trunc(100.10d, 1), is(100.1d));
assertThat(udf.trunc(100.11d, 1), is(100.1d));
assertThat(udf.trunc(100.15d, 1), is(100.1d));
assertThat(udf.trunc(100.17d, 1), is(100.1d));
assertThat(udf.trunc(100.110d, 2), is(100.11d));
assertThat(udf.trunc(100.111d, 2), is(100.11d));
assertThat(udf.trunc(100.115d, 2), is(100.11d));
assertThat(udf.trunc(100.117d, 2), is(100.11d));
assertThat(udf.trunc(100.1110d, 3), is(100.111d));
assertThat(udf.trunc(100.1111d, 3), is(100.111d));
assertThat(udf.trunc(100.1115d, 3), is(100.111d));
assertThat(udf.trunc(100.1117d, 3), is(100.111d));
assertThat(udf.trunc(1.0d, 3), is(1.0d));
assertThat(udf.trunc(1.1d, 3), is(1.1d));
assertThat(udf.trunc(1.5d, 3), is(1.5d));
assertThat(udf.trunc(1.7d, 3), is(1.7d));
assertThat(udf.trunc(12345.67d, -1), is(12340d));
assertThat(udf.trunc(12345.67d, -2), is(12300d));
assertThat(udf.trunc(12345.67d, -3), is(12000d));
assertThat(udf.trunc(12345.67d, -4), is(10000d));
assertThat(udf.trunc(12345.67d, -5), is(0d));
} |
public void validateSamlRequest(SamlRequest samlRequest, Signature signature) throws SamlValidationException {
try {
SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
profileValidator.validate(signature);
} catch (SignatureException e) {
throw new SamlValidationException("Request check signature handler exception", e);
}
List<Credential> credentials = retrieveServiceProviderCredentials(samlRequest.getConnectionEntity());
boolean canValidateWithOneOfTheCredentails = credentials.stream().anyMatch(credential -> {
try {
SignatureValidator.validate(signature, credential);
return true;
} catch (SignatureException e) {
return false;
}
});
if (!canValidateWithOneOfTheCredentails)
throw new SamlValidationException("Request check signature handler exception");
} | @Test
public void verifyRequestSignatureValid() throws SamlValidationException {
assertDoesNotThrow(() -> signatureService.validateSamlRequest(null, null));
} |
public List<InterpreterResultMessage> message() {
return msg;
} | @Test
void testTextType() {
InterpreterResult result = new InterpreterResult(InterpreterResult.Code.SUCCESS,
"this is a TEXT type");
assertEquals(InterpreterResult.Type.TEXT, result.message().get(0).getType(), "No magic");
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%this is a TEXT type");
assertEquals(InterpreterResult.Type.TEXT, result.message().get(0).getType(), "No magic");
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%\n");
assertEquals(0, result.message().size());
} |
@Override
public void init(final InternalProcessorContext<KIn, VIn> context) {
// It is important to first create the sensor before calling init on the
// parent object. Otherwise due to backwards compatibility an empty sensor
// without parent is created with the same name.
// Once the backwards compatibility is not needed anymore it might be possible to
// change this.
processAtSourceSensor = ProcessorNodeMetrics.processAtSourceSensor(
Thread.currentThread().getName(),
context.taskId().toString(),
context.currentNode().name(),
context.metrics()
);
super.init(context);
this.context = context;
try {
keyDeserializer = prepareKeyDeserializer(keyDeserializer, context, name());
} catch (final ConfigException | StreamsException e) {
throw new StreamsException(String.format("Failed to initialize key serdes for source node %s", name()), e, context.taskId());
}
try {
valDeserializer = prepareValueDeserializer(valDeserializer, context, name());
} catch (final ConfigException | StreamsException e) {
throw new StreamsException(String.format("Failed to initialize value serdes for source node %s", name()), e, context.taskId());
}
} | @Test
public void shouldThrowStreamsExceptionOnUndefinedKeySerde() {
final InternalMockProcessorContext<String, String> context = new InternalMockProcessorContext<>();
final SourceNode<String, String> node =
new SourceNode<>(context.currentNode().name(), new TheDeserializer(), new TheDeserializer());
utilsMock.when(() -> WrappingNullableUtils.prepareKeyDeserializer(any(), any(), any()))
.thenThrow(new ConfigException("Please set StreamsConfig#DEFAULT_KEY_SERDE_CLASS_CONFIG"));
final Throwable exception = assertThrows(StreamsException.class, () -> node.init(context));
assertThat(
exception.getMessage(),
equalTo("Failed to initialize key serdes for source node TESTING_NODE")
);
assertThat(
exception.getCause().getMessage(),
equalTo("Please set StreamsConfig#DEFAULT_KEY_SERDE_CLASS_CONFIG")
);
} |
@Override
public <T> List<ExtensionWrapper<T>> find(Class<T> type) {
log.debug("Finding extensions of extension point '{}'", type.getName());
Map<String, Set<String>> entries = getEntries();
List<ExtensionWrapper<T>> result = new ArrayList<>();
// add extensions found in classpath and plugins
for (String pluginId : entries.keySet()) {
// classpath's extensions <=> pluginId = null
List<ExtensionWrapper<T>> pluginExtensions = find(type, pluginId);
result.addAll(pluginExtensions);
}
if (result.isEmpty()) {
log.debug("No extensions found for extension point '{}'", type.getName());
} else {
log.debug("Found {} extensions for extension point '{}'", result.size(), type.getName());
}
// sort by "ordinal" property
Collections.sort(result);
return result;
} | @Test
public void testFindFromClasspath() {
ExtensionFinder instance = new AbstractExtensionFinder(pluginManager) {
@Override
public Map<String, Set<String>> readPluginsStorages() {
return Collections.emptyMap();
}
@Override
public Map<String, Set<String>> readClasspathStorages() {
Map<String, Set<String>> entries = new LinkedHashMap<>();
Set<String> bucket = new HashSet<>();
bucket.add("org.pf4j.test.TestExtension");
entries.put(null, bucket);
return entries;
}
};
List<ExtensionWrapper<TestExtensionPoint>> list = instance.find(TestExtensionPoint.class);
assertEquals(1, list.size());
} |
@Override
public void doPublishConfig(final String dataId, final Object data) {
this.apolloClient.createOrUpdateItem(dataId, data, "create config data");
this.apolloClient.publishNamespace("publish config data", "");
} | @Test
public void testPublishConfig() {
doNothing().when(apolloClient)
.createOrUpdateItem(Mockito.any(), Mockito.<Object>any(), Mockito.any());
doNothing().when(apolloClient).publishNamespace(Mockito.any(), Mockito.any());
apolloDataChangedListener.doPublishConfig("42", "Data");
verify(apolloClient).createOrUpdateItem(Mockito.any(), Mockito.<Object>any(), Mockito.any());
verify(apolloClient).publishNamespace(Mockito.any(), Mockito.any());
} |
@Override
public void createNamespace(Namespace namespace, Map<String, String> metadata) {
if (namespaceExists(namespace)) {
throw new AlreadyExistsException("Namespace already exists: %s", namespace);
}
Map<String, String> createMetadata;
if (metadata == null || metadata.isEmpty()) {
createMetadata = ImmutableMap.of(NAMESPACE_EXISTS_PROPERTY, "true");
} else {
createMetadata =
ImmutableMap.<String, String>builder()
.putAll(metadata)
.put(NAMESPACE_EXISTS_PROPERTY, "true")
.buildOrThrow();
}
insertProperties(namespace, createMetadata);
} | @Test
public void testCreateNamespace() {
Namespace testNamespace = Namespace.of("testDb", "ns1", "ns2");
assertThat(catalog.namespaceExists(testNamespace)).isFalse();
assertThat(catalog.namespaceExists(Namespace.of("testDb", "ns1"))).isFalse();
catalog.createNamespace(testNamespace);
assertThat(catalog.namespaceExists(testNamespace)).isTrue();
assertThat(catalog.namespaceExists(Namespace.of("testDb"))).isTrue();
assertThat(catalog.namespaceExists(Namespace.of("testDb", "ns1"))).isTrue();
assertThat(catalog.namespaceExists(Namespace.of("testDb", "ns1", "ns2"))).isTrue();
assertThat(catalog.namespaceExists(Namespace.of("ns1", "ns2"))).isFalse();
assertThat(catalog.namespaceExists(Namespace.of("testDb", "ns%"))).isFalse();
assertThat(catalog.namespaceExists(Namespace.of("testDb", "ns_"))).isFalse();
assertThat(catalog.namespaceExists(Namespace.of("testDb", "ns1", "ns2", "ns3"))).isFalse();
} |
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) {
final Fetch<K, V> fetch = Fetch.empty();
final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>();
int recordsRemaining = fetchConfig.maxPollRecords;
try {
while (recordsRemaining > 0) {
final CompletedFetch nextInLineFetch = fetchBuffer.nextInLineFetch();
if (nextInLineFetch == null || nextInLineFetch.isConsumed()) {
final CompletedFetch completedFetch = fetchBuffer.peek();
if (completedFetch == null)
break;
if (!completedFetch.isInitialized()) {
try {
fetchBuffer.setNextInLineFetch(initialize(completedFetch));
} catch (Exception e) {
// Remove a completedFetch upon a parse with exception if (1) it contains no completedFetch, and
// (2) there are no fetched completedFetch with actual content preceding this exception.
// The first condition ensures that the completedFetches is not stuck with the same completedFetch
// in cases such as the TopicAuthorizationException, and the second condition ensures that no
// potential data loss due to an exception in a following record.
if (fetch.isEmpty() && FetchResponse.recordsOrFail(completedFetch.partitionData).sizeInBytes() == 0)
fetchBuffer.poll();
throw e;
}
} else {
fetchBuffer.setNextInLineFetch(completedFetch);
}
fetchBuffer.poll();
} else if (subscriptions.isPaused(nextInLineFetch.partition)) {
// when the partition is paused we add the records back to the completedFetches queue instead of draining
// them so that they can be returned on a subsequent poll if the partition is resumed at that time
log.debug("Skipping fetching records for assigned partition {} because it is paused", nextInLineFetch.partition);
pausedCompletedFetches.add(nextInLineFetch);
fetchBuffer.setNextInLineFetch(null);
} else {
final Fetch<K, V> nextFetch = fetchRecords(nextInLineFetch, recordsRemaining);
recordsRemaining -= nextFetch.numRecords();
fetch.add(nextFetch);
}
}
} catch (KafkaException e) {
if (fetch.isEmpty())
throw e;
} finally {
// add any polled completed fetches for paused partitions back to the completed fetches queue to be
// re-evaluated in the next poll
fetchBuffer.addAll(pausedCompletedFetches);
}
return fetch;
} | @Test
public void testFetchWithTopicAuthorizationFailed() {
buildDependencies();
assignAndSeek(topicAPartition0);
// Try to data and validate that we get an empty Fetch back.
CompletedFetch completedFetch = completedFetchBuilder
.error(Errors.TOPIC_AUTHORIZATION_FAILED)
.build();
fetchBuffer.add(completedFetch);
assertThrows(TopicAuthorizationException.class, () -> fetchCollector.collectFetch(fetchBuffer));
} |
public static String bytesToString(List<?> bytesList) {
byte[] bytes = bytesFromList(bytesList);
return new String(bytes);
} | @Test
public void bytesFromList_SpecSymbol() {
List<String> listHex = new ArrayList<>(Arrays.asList("1D", "0x1D", "1F", "0x1F", "0x20", "0x20"));
byte[] expectedBytes = new byte[]{29, 29, 31, 31, 32, 32};
String actualStr = TbUtils.bytesToString(listHex);
byte[] actualBytes = actualStr.getBytes();
Assertions.assertArrayEquals(expectedBytes, actualBytes);
Assertions.assertTrue(actualStr.isBlank());
listHex = new ArrayList<>(Arrays.asList("0x21", "0x21"));
expectedBytes = new byte[]{33, 33};
actualStr = TbUtils.bytesToString(listHex);
actualBytes = actualStr.getBytes();
Assertions.assertArrayEquals(expectedBytes, actualBytes);
Assertions.assertFalse(actualStr.isBlank());
Assertions.assertEquals("!!", actualStr);
listHex = new ArrayList<>(Arrays.asList("21", "0x21"));
expectedBytes = new byte[]{21, 33};
actualStr = TbUtils.bytesToString(listHex);
actualBytes = actualStr.getBytes();
Assertions.assertArrayEquals(expectedBytes, actualBytes);
Assertions.assertFalse(actualStr.isBlank());
Assertions.assertEquals("!", actualStr.substring(1));
Assertions.assertEquals('\u0015', actualStr.charAt(0));
Assertions.assertEquals(21, actualStr.charAt(0));
} |
public static Schema fromTableSchema(TableSchema tableSchema) {
return fromTableSchema(tableSchema, SchemaConversionOptions.builder().build());
} | @Test
public void testFromTableSchema_enum() {
Schema beamSchema = BigQueryUtils.fromTableSchema(BQ_ENUM_TYPE);
assertEquals(ENUM_STRING_TYPE, beamSchema);
} |
@Override
public boolean isTrusted(Address address) {
if (address == null) {
return false;
}
if (trustedInterfaces.isEmpty()) {
return true;
}
String host = address.getHost();
if (matchAnyInterface(host, trustedInterfaces)) {
return true;
} else {
if (logger.isFineEnabled()) {
logger.fine(
"Address %s doesn't match any trusted interface", host);
}
return false;
}
} | @Test
public void givenInterfaceRangeIsConfigured_whenMessageWithMatchingHost_thenTrust() throws UnknownHostException {
AddressCheckerImpl joinMessageTrustChecker = new AddressCheckerImpl(singleton("127.0.0.1-100"), logger);
Address address = createAddress("127.0.0.2");
assertTrue(joinMessageTrustChecker.isTrusted(address));
} |
public void schedule(final ScheduledHealthCheck check, final boolean healthy) {
unschedule(check.getName());
final Duration interval;
if (healthy) {
interval = check.getSchedule().getCheckInterval();
} else {
interval = check.getSchedule().getDowntimeInterval();
}
schedule(check, interval, interval);
} | @Test
void shouldRescheduleCheckForUnhealthyDependency() {
final String name = "test";
final Schedule schedule = new Schedule();
final ScheduledFuture future = mock(ScheduledFuture.class);
when(future.cancel(true)).thenReturn(true);
final ScheduledHealthCheck check = mock(ScheduledHealthCheck.class);
when(check.getName()).thenReturn(name);
when(check.getSchedule()).thenReturn(schedule);
when(executor.scheduleWithFixedDelay(
eq(check),
or(eq(schedule.getCheckInterval().toMilliseconds()), eq(schedule.getDowntimeInterval().toMilliseconds())),
or(eq(schedule.getCheckInterval().toMilliseconds()), eq(schedule.getDowntimeInterval().toMilliseconds())),
eq(TimeUnit.MILLISECONDS))
)
.thenReturn(future);
scheduler.schedule(check, true);
scheduler.schedule(check, false);
verify(executor, times(2)).scheduleWithFixedDelay(
eq(check),
or(eq(schedule.getCheckInterval().toMilliseconds()), eq(schedule.getDowntimeInterval().toMilliseconds())),
or(eq(schedule.getCheckInterval().toMilliseconds()), eq(schedule.getDowntimeInterval().toMilliseconds())),
eq(TimeUnit.MILLISECONDS));
verify(future).cancel(true);
} |
@Bean("Configuration")
public Configuration provide(Settings settings) {
return new ServerConfigurationAdapter(settings);
} | @Test
@UseDataProvider("emptyFields2")
public void getStringArray_on_unknown_or_non_multivalue_properties_ignores_empty_fields_differently_from_settings(String emptyFields, String[] expected) {
settings.setProperty(nonDeclaredKey, emptyFields);
settings.setProperty(nonMultivalueKey, emptyFields);
Configuration configuration = underTest.provide(settings);
getStringArrayBehaviorDiffers(configuration, nonDeclaredKey, expected);
getStringArrayBehaviorDiffers(configuration, nonMultivalueKey, expected);
} |
@Override
public boolean processData(DistroData distroData) {
switch (distroData.getType()) {
case ADD:
case CHANGE:
ClientSyncData clientSyncData = ApplicationUtils.getBean(Serializer.class)
.deserialize(distroData.getContent(), ClientSyncData.class);
handlerClientSyncData(clientSyncData);
return true;
case DELETE:
String deleteClientId = distroData.getDistroKey().getResourceKey();
Loggers.DISTRO.info("[Client-Delete] Received distro client sync data {}", deleteClientId);
clientManager.clientDisconnected(deleteClientId);
return true;
default:
return false;
}
} | @Test
void testProcessDataForDeleteClient() {
distroData.setType(DataOperation.DELETE);
distroClientDataProcessor.processData(distroData);
verify(clientManager).clientDisconnected(CLIENT_ID);
} |
@Override
public void addPartitions(String dbName, String tableName, List<HivePartitionWithStats> partitions) {
List<org.apache.hadoop.hive.metastore.api.Partition> hivePartitions = partitions.stream()
.map(HiveMetastoreApiConverter::toMetastoreApiPartition)
.collect(Collectors.toList());
client.addPartitions(dbName, tableName, hivePartitions);
// TODO(stephen): add partition column statistics
} | @Test
public void testAddPartitions() {
HiveMetaClient client = new MockedHiveMetaClient();
HiveMetastore metastore = new HiveMetastore(client, "hive_catalog", MetastoreType.HMS);
HivePartition hivePartition = HivePartition.builder()
.setColumns(Lists.newArrayList(new Column("c1", Type.INT)))
.setStorageFormat(HiveStorageFormat.PARQUET)
.setDatabaseName("db")
.setTableName("table")
.setLocation("location")
.setValues(Lists.newArrayList("p1=1"))
.setParameters(new HashMap<>()).build();
HivePartitionStats hivePartitionStats = HivePartitionStats.empty();
HivePartitionWithStats hivePartitionWithStats = new HivePartitionWithStats("p1=1", hivePartition, hivePartitionStats);
metastore.addPartitions("db", "table", Lists.newArrayList(hivePartitionWithStats));
} |
public void defineDocStringType(DocStringType docStringType) {
DocStringType existing = lookupByContentTypeAndType(docStringType.getContentType(), docStringType.getType());
if (existing != null) {
throw createDuplicateTypeException(existing, docStringType);
}
Map<Type, DocStringType> map = docStringTypes.computeIfAbsent(docStringType.getContentType(),
s -> new HashMap<>());
map.put(docStringType.getType(), docStringType);
docStringTypes.put(docStringType.getContentType(), map);
} | @Test
void anonymous_doc_string_is_predefined() {
DocStringType docStringType = new DocStringType(
String.class,
DEFAULT_CONTENT_TYPE,
(String s) -> s);
CucumberDocStringException actualThrown = assertThrows(
CucumberDocStringException.class, () -> registry.defineDocStringType(docStringType));
assertThat(actualThrown.getMessage(), is(equalTo(
"There is already docstring type registered for '[anonymous]' and java.lang.String.\n" +
"You are trying to add '[anonymous]' and java.lang.String")));
} |
public List<String> getChildren(final String key) {
try {
return client.getChildren().forPath(key);
} catch (Exception e) {
LOGGER.error("zookeeper get child error=", e);
return Collections.emptyList();
}
} | @Test
void getChildren() throws Exception {
assertTrue(client.getChildren("/test").isEmpty());
GetChildrenBuilder getChildrenBuilder = mock(GetChildrenBuilder.class);
when(curatorFramework.getChildren()).thenReturn(getChildrenBuilder);
when(getChildrenBuilder.forPath(anyString())).thenReturn(new ArrayList<>());
List<String> children = client.getChildren("/test");
assertEquals(0, children.size());
} |
public List<CommentSimpleResponse> findAllWithPaging(final Long boardId, final Long memberId, final Long commentId, final int pageSize) {
return jpaQueryFactory.select(constructor(CommentSimpleResponse.class,
comment.id,
comment.content,
member.id,
member.id.eq(memberId),
member.nickname,
comment.createdAt
)).from(comment)
.where(
ltCommentId(commentId),
comment.boardId.eq(boardId)
)
.orderBy(comment.id.desc())
.leftJoin(member).on(comment.writerId.eq(member.id))
.limit(pageSize)
.fetch();
} | @Test
void no_offset_페이징_첫_조회() {
// given
for (long i = 1L; i <= 20L; i++) {
commentRepository.save(Comment.builder()
.id(i)
.boardId(board.getId())
.content("comment")
.writerId(member.getId())
.build()
);
}
// when
List<CommentSimpleResponse> result = commentQueryRepository.findAllWithPaging(1L, member.getId(), null, 10);
// then
assertSoftly(softly -> {
softly.assertThat(result).hasSize(10);
softly.assertThat(result.get(0).id()).isEqualTo(20L);
softly.assertThat(result.get(9).id()).isEqualTo(11L);
});
} |
@Override
public void close() throws IOException {
close(true);
} | @Test
public void testMultipleClose() throws IOException {
S3OutputStream stream = new S3OutputStream(s3, randomURI(), properties, nullMetrics());
stream.close();
stream.close();
} |
public static List<ArtifactPlan> toArtifactPlans(ArtifactTypeConfigs artifactConfigs) {
List<ArtifactPlan> artifactPlans = new ArrayList<>();
for (ArtifactTypeConfig artifactTypeConfig : artifactConfigs) {
artifactPlans.add(new ArtifactPlan(artifactTypeConfig));
}
return artifactPlans;
} | @Test
public void toArtifactPlans_shouldConvertArtifactConfigsToArtifactPlanList() {
final PluggableArtifactConfig artifactConfig = new PluggableArtifactConfig("id", "storeId", create("Foo", true, "Bar"));
final ArtifactTypeConfigs artifactTypeConfigs = new ArtifactTypeConfigs(Arrays.asList(
new BuildArtifactConfig("source", "destination"),
new TestArtifactConfig("test-source", "test-destination"),
artifactConfig
));
final List<ArtifactPlan> artifactPlans = ArtifactPlan.toArtifactPlans(artifactTypeConfigs);
assertThat(artifactPlans).containsExactlyInAnyOrder(
new ArtifactPlan(ArtifactPlanType.file, "source", "destination"),
new ArtifactPlan(ArtifactPlanType.unit, "test-source", "test-destination"),
new ArtifactPlan(artifactConfig.toJSON())
);
} |
@Override
public void ping() {
try {
if (sslInfrastructureService.isRegistered()) {
AgentIdentifier agent = agentIdentifier();
LOG.trace("{} is pinging server [{}]", agent, client);
getAgentRuntimeInfo().refreshUsableSpace();
agentInstruction = client.ping(getAgentRuntimeInfo());
pingSuccess();
LOG.trace("{} pinged server [{}]", agent, client);
}
} catch (Throwable e) {
LOG.error("Error occurred when agent tried to ping server: ", e);
}
} | @Test
void shouldPingIfAfterRegistered() {
when(agentRegistry.uuid()).thenReturn(agentUuid);
when(sslInfrastructureService.isRegistered()).thenReturn(true);
agentController = createAgentController();
agentController.init();
agentController.ping();
verify(sslInfrastructureService).createSslInfrastructure();
verify(loopServer).ping(any(AgentRuntimeInfo.class));
} |
public static Function.FunctionMetaData incrMetadataVersion(Function.FunctionMetaData existingMetaData,
Function.FunctionMetaData updatedMetaData) {
long version = 0;
if (existingMetaData != null) {
version = existingMetaData.getVersion() + 1;
}
return updatedMetaData.toBuilder()
.setVersion(version)
.build();
} | @Test
public void testUpdate() {
long version = 5;
Function.FunctionMetaData existingMetaData = Function.FunctionMetaData.newBuilder().setFunctionDetails(
Function.FunctionDetails.newBuilder().setName("func-1").setParallelism(2)).setVersion(version).build();
Function.FunctionMetaData updatedMetaData = Function.FunctionMetaData.newBuilder().setFunctionDetails(
Function.FunctionDetails.newBuilder().setName("func-1").setParallelism(3)).setVersion(version).build();
Function.FunctionMetaData newMetaData = FunctionMetaDataUtils.incrMetadataVersion(existingMetaData, updatedMetaData);
Assert.assertEquals(newMetaData.getVersion(), version + 1);
Assert.assertEquals(newMetaData.getFunctionDetails().getParallelism(), 3);
newMetaData = FunctionMetaDataUtils.incrMetadataVersion(null, newMetaData);
Assert.assertEquals(newMetaData.getVersion(), 0);
} |
@Transactional
public void deleteChecklistById(User user, long id) {
Checklist checklist = checklistRepository.getById(id);
validateChecklistOwnership(user, checklist);
checklistQuestionRepository.deleteAllByChecklistId(checklist.getId());
checklistOptionRepository.deleteAllByChecklistId(checklist.getId());
checklistMaintenanceRepository.deleteAllByChecklistId(checklist.getId());
checklistRepository.deleteById(id);
roomRepository.deleteById(checklist.getRoom().getId());
} | @DisplayName("체크리스트 삭제 실패 : 체크리스트 작성 유저와 삭제하려는 유저가 다른 경우")
@Test
void deleteChecklistById_notOwnedByUser_exception() {
// given
roomRepository.save(RoomFixture.ROOM_1);
Checklist checklist = checklistRepository.save(ChecklistFixture.CHECKLIST1_USER1);
// when & then
assertThatThrownBy(
() -> checklistService.deleteChecklistById(UserFixture.USER2, checklist.getId())
)
.isInstanceOf(BangggoodException.class)
.hasMessage(ExceptionCode.CHECKLIST_NOT_OWNED_BY_USER.getMessage());
} |
public static String padLeft(String s, int n) {
return String.format("%1$" + n + "s", s);
} | @Test
public void testPadLeft(){
String a = "hello";
String b = StringKit.padLeft(a, 10);
Assert.assertEquals(" hello", b);
} |
public synchronized Topology addStateStore(final StoreBuilder<?> storeBuilder,
final String... processorNames) {
internalTopologyBuilder.addStateStore(storeBuilder, processorNames);
return this;
} | @Test
public void shouldNotAddNullStateStoreSupplier() {
assertThrows(NullPointerException.class, () -> topology.addStateStore(null));
} |
public static ShenyuPluginLoader getInstance() {
if (null == pluginLoader) {
synchronized (ShenyuPluginLoader.class) {
if (null == pluginLoader) {
pluginLoader = new ShenyuPluginLoader();
}
}
}
return pluginLoader;
} | @Test
public void testGetInstance() {
assertThat(shenyuPluginLoader, is(ShenyuPluginLoader.getInstance()));
} |
public static String fix(final String raw) {
if ( raw == null || "".equals( raw.trim() )) {
return raw;
}
MacroProcessor macroProcessor = new MacroProcessor();
macroProcessor.setMacros( macros );
return macroProcessor.parse( raw );
} | @Test
public void testAdd__Handle__Simple() {
String result = KnowledgeHelperFixerTest.fixer.fix( "update(myObject );" );
assertEqualsIgnoreWhitespace( "drools.update(myObject );",
result );
result = KnowledgeHelperFixerTest.fixer.fix( "update ( myObject );" );
assertEqualsIgnoreWhitespace( "drools.update( myObject );",
result );
} |
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> loadedClass = findLoadedClass(name);
if (loadedClass != null) {
return loadedClass;
}
if (isClosed) {
throw new ClassNotFoundException("This ClassLoader is closed");
}
if (config.shouldAcquire(name)) {
loadedClass =
PerfStatsCollector.getInstance()
.measure("load sandboxed class", () -> maybeInstrumentClass(name));
} else {
loadedClass = getParent().loadClass(name);
}
if (resolve) {
resolveClass(loadedClass);
}
return loadedClass;
}
} | @Test
public void callingNormalMethodReturningIntegerShouldInvokeClassHandler() throws Exception {
Class<?> exampleClass = loadClass(AClassWithMethodReturningInteger.class);
classHandler.valueToReturn = 456;
Method normalMethod = exampleClass.getMethod("normalMethodReturningInteger", int.class);
Object exampleInstance = exampleClass.getDeclaredConstructor().newInstance();
assertEquals(456, normalMethod.invoke(exampleInstance, 123));
assertThat(transcript)
.containsExactly(
"methodInvoked: AClassWithMethodReturningInteger.__constructor__()",
"methodInvoked: AClassWithMethodReturningInteger.normalMethodReturningInteger(int"
+ " 123)");
} |
@Override
public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException {
if(workdir.isRoot()) {
final AttributedList<Path> result = new AttributedList<>();
final AttributedList<Path> buckets = new GoogleStorageBucketListService(session).list(workdir, listener);
for(Path bucket : buckets) {
result.addAll(filter(regex, new GoogleStorageObjectListService(session).list(bucket, listener, null)));
}
result.addAll(filter(regex, buckets));
return result;
}
try {
return filter(regex, new GoogleStorageObjectListService(session).list(workdir, listener, null));
}
catch(NotfoundException e) {
return AttributedList.emptyList();
}
} | @Test
public void testSearchInDirectory() throws Exception {
final Path bucket = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final String name = new AlphanumericRandomStringService().random();
final Path file = new GoogleStorageTouchFeature(session).touch(new Path(bucket, name, EnumSet.of(Path.Type.file)), new TransferStatus());
final GoogleStorageSearchFeature feature = new GoogleStorageSearchFeature(session);
assertTrue(feature.search(bucket, new SearchFilter(name), new DisabledListProgressListener()).contains(file));
assertTrue(feature.search(bucket, new SearchFilter(StringUtils.substring(name, 2)), new DisabledListProgressListener()).contains(file));
{
final AttributedList<Path> result = feature.search(bucket, new SearchFilter(StringUtils.substring(name, 0, name.length() - 2)), new DisabledListProgressListener());
assertTrue(result.contains(file));
}
assertFalse(feature.search(new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new SearchFilter(name), new DisabledListProgressListener()).contains(file));
final Path subdir = new GoogleStorageDirectoryFeature(session).mkdir(new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus());
assertFalse(feature.search(subdir, new SearchFilter(name), new DisabledListProgressListener()).contains(file));
final Path filesubdir = new GoogleStorageTouchFeature(session).touch(new Path(subdir, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
{
final AttributedList<Path> result = feature.search(bucket, new SearchFilter(filesubdir.getName()), new DisabledListProgressListener());
assertNotNull(result.find(new SimplePathPredicate(filesubdir)));
assertEquals(subdir, result.find(new SimplePathPredicate(filesubdir)).getParent());
}
new GoogleStorageDeleteFeature(session).delete(Arrays.asList(file, filesubdir, subdir), new DisabledLoginCallback(), new Delete.DisabledCallback());
} |
@Override
public Object evaluate(final ProcessingDTO processingDTO) {
return commonEvaluate(getValue(), dataType);
} | @Test
void evaluate() {
Object value = 234.45;
final KiePMMLConstant kiePMMLConstant1 = new KiePMMLConstant("NAME", Collections.emptyList(), value, null);
ProcessingDTO processingDTO = new ProcessingDTO(Collections.emptyList(), Collections.emptyList(),
Collections.emptyList(), Collections.emptyList(),
Collections.emptyList(), Collections.emptyList(),
Collections.emptyList());
Object retrieved = kiePMMLConstant1.evaluate(processingDTO);
assertThat(retrieved).isEqualTo(value);
final KiePMMLConstant kiePMMLConstant2 = new KiePMMLConstant("NAME", Collections.emptyList(), value,
DATA_TYPE.STRING);
processingDTO = new ProcessingDTO(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(),
Collections.emptyList(), Collections.emptyList(), Collections.emptyList(),
Collections.emptyList());
retrieved = kiePMMLConstant2.evaluate(processingDTO);
assertThat(retrieved).isEqualTo("234.45");
} |
public String getClusterProfileChangedRequestBody(ClusterProfilesChangedStatus status, Map<String, String> oldClusterProfile, Map<String, String> newClusterProfile) {
return switch (status) {
case CREATED -> getClusterCreatedRequestBody(newClusterProfile);
case UPDATED -> getClusterUpdatedRequestBody(oldClusterProfile, newClusterProfile);
case DELETED -> getClusterDeletedRequestBody(oldClusterProfile);
};
} | @Test
public void shouldGetClusterProfilesChangedRequestBodyWhenClusterProfileIsUpdated() {
ClusterProfilesChangedStatus status = ClusterProfilesChangedStatus.UPDATED;
Map<String, String> oldClusterProfile = Map.of("old_key1", "old_key2");
Map<String, String> newClusterProfile = Map.of("key1", "key2");
String json = new ElasticAgentExtensionConverterV5().getClusterProfileChangedRequestBody(status, oldClusterProfile, newClusterProfile);
assertThatJson(json).isEqualTo("{" +
" \"status\":\"updated\"," +
" \"old_cluster_profiles_properties\":{" +
" \"old_key1\":\"old_key2\"" +
" }," +
" \"cluster_profiles_properties\":{" +
" \"key1\":\"key2\"" +
" }" +
"}");
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void sendSpoilerMessage() {
SendResponse response = bot.execute(new SendMessage(chatId, "ok this is spoiler ha-ha-ha")
.entities(new MessageEntity(MessageEntity.Type.spoiler, 19, 8)));
MessageEntity entity = response.message().entities()[0];
assertEquals(MessageEntity.Type.spoiler, entity.type());
assertEquals((Integer) 19, entity.offset());
assertEquals((Integer) 8, entity.length());
} |
public File pathToFile(Path path) {
return ((RawLocalFileSystem)fs).pathToFile(path);
} | @Test
public void testFileStatusPipeFile() throws Exception {
RawLocalFileSystem origFs = new RawLocalFileSystem();
RawLocalFileSystem fs = spy(origFs);
Configuration conf = mock(Configuration.class);
fs.setConf(conf);
RawLocalFileSystem.setUseDeprecatedFileStatus(false);
Path path = new Path("/foo");
File pipe = mock(File.class);
when(pipe.isFile()).thenReturn(false);
when(pipe.isDirectory()).thenReturn(false);
when(pipe.exists()).thenReturn(true);
FileStatus stat = mock(FileStatus.class);
doReturn(pipe).when(fs).pathToFile(path);
doReturn(stat).when(fs).getFileStatus(path);
FileStatus[] stats = fs.listStatus(path);
assertTrue(stats != null && stats.length == 1 && stats[0] == stat);
} |
public static <E> List<E> ensureImmutable(List<E> list) {
if (list.isEmpty()) return Collections.emptyList();
// Faster to make a copy than check the type to see if it is already a singleton list
if (list.size() == 1) return Collections.singletonList(list.get(0));
if (isImmutable(list)) return list;
return Collections.unmodifiableList(new ArrayList<E>(list));
} | @Test void ensureImmutable_returnsEmptyList() {
List<Object> list = Collections.emptyList();
assertThat(Lists.ensureImmutable(list))
.isSameAs(list);
} |
public static TrieRouter createRoute() {
return new TrieRouter();
} | @Test
public void testRouteMatch() {
PathKit.TrieRouter trieRouter = PathKit.createRoute();
trieRouter.addRoute("/static/**");
trieRouter.addRoute("/users/:userId");
trieRouter.addRoute("/users/**");
trieRouter.addRoute("/users/bg/**");
trieRouter.addRoute("/login");
System.out.println(
trieRouter.matchRoute("/users/123")
);
Assert.assertTrue(trieRouter.match("/static/123"));
Assert.assertTrue(trieRouter.match("/static/abcd/123"));
Assert.assertTrue(trieRouter.match("/static"));
Assert.assertTrue(trieRouter.match("/static/"));
Assert.assertTrue(trieRouter.match("/users/123"));
Assert.assertTrue(trieRouter.match("/users/bg/123"));
Assert.assertTrue(trieRouter.match("/users/bg/123/456"));
Assert.assertTrue(trieRouter.match("/login"));
} |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
try {
try {
final HttpHead request = new HttpHead(new DAVPathEncoder().encode(file));
for(Header header : this.headers()) {
request.addHeader(header);
}
return session.getClient().execute(request, new ExistsResponseHandler());
}
catch(SardineException e) {
throw new DAVExceptionMappingService().map("Failure to read attributes of {0}", e, file);
}
catch(IOException e) {
throw new HttpExceptionMappingService().map(e, file);
}
}
catch(AccessDeniedException | InteroperabilityException e) {
// 400 Multiple choices
return new DefaultFindFeature(session).find(file, listener);
}
}
catch(AccessDeniedException e) {
// Parent directory may not be accessible. Issue #5662
return true;
}
catch(LoginFailureException | NotfoundException e) {
return false;
}
} | @Test
public void testFindNotFound() throws Exception {
assertFalse(new DAVFindFeature(session).find(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory))));
assertFalse(new DAVFindFeature(session).find(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file))));
} |
@Override
public void store(Measure newMeasure) {
saveMeasure(newMeasure.inputComponent(), (DefaultMeasure<?>) newMeasure);
} | @Test
public void store_whenAdhocRuleIsSpecifiedWithOptionalFieldEmpty_shouldWriteAdhocRuleWithDefaultImpactsToReport() {
underTest.store(new DefaultAdHocRule().ruleId("ruleId").engineId("engineId")
.name("name")
.description("description"));
try (CloseableIterator<ScannerReport.AdHocRule> adhocRuleIt = reportReader.readAdHocRules()) {
ScannerReport.AdHocRule adhocRule = adhocRuleIt.next();
assertThat(adhocRule).extracting(ScannerReport.AdHocRule::getSeverity, ScannerReport.AdHocRule::getType)
.containsExactlyInAnyOrder(Constants.Severity.UNSET_SEVERITY, ScannerReport.IssueType.UNSET);
assertThat(adhocRule.getDefaultImpactsList()).extracting(ScannerReport.Impact::getSoftwareQuality, ScannerReport.Impact::getSeverity)
.containsExactlyInAnyOrder(Tuple.tuple(SoftwareQuality.MAINTAINABILITY.name(), Severity.MEDIUM.name()));
assertThat(adhocRule.getCleanCodeAttribute()).isEqualTo(CleanCodeAttribute.CONVENTIONAL.name());
}
} |
@Override public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException {
if ( dbMetaData == null ) {
throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" ) );
}
if ( rsMetaData == null ) {
throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoRSMetaDataException" ) );
}
try {
return rsMetaData.getColumnLabel( index );
} catch ( Exception e ) {
throw new KettleDatabaseException( String.format( "%s: %s", BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameException" ), e.getMessage() ), e );
}
} | @Test
public void testGetLegacyColumnNameFieldDB() throws Exception {
assertEquals( "DB", new MariaDBDatabaseMeta().getLegacyColumnName( mock( DatabaseMetaData.class ), getResultSetMetaData(), 5 ) );
} |
static List<ProviderInfo> convertInstancesToProviders(List<Instance> allInstances) {
List<ProviderInfo> providerInfos = new ArrayList<ProviderInfo>();
if (CommonUtils.isEmpty(allInstances)) {
return providerInfos;
}
for (Instance instance : allInstances) {
String url = convertInstanceToUrl(instance);
ProviderInfo providerInfo = ProviderHelper.toProviderInfo(url);
// Nacos的默认权重为1.0
// 当Nacos默认权重传入1.0,根据代码逻辑计算结果为100,与sofa-rpc默认权重一致
// 因为是接口级别,如果不同的服务具有不同的权重也不会出现被覆盖或者冲突的情况
long weight = Math.round(providerInfo.getWeight() * instance.getWeight());
providerInfo.setWeight(Math.round(weight));
providerInfos.add(providerInfo);
}
return providerInfos;
} | @Test
public void testNacosWeightWith0() {
Instance instance = new Instance();
instance.setClusterName(NacosRegistryHelper.DEFAULT_CLUSTER);
instance.setIp("1.1.1.1");
instance.setPort(12200);
instance.setServiceName("com.alipay.xxx.TestService");
instance.setWeight(0.0D);
List<ProviderInfo> providerInfos = NacosRegistryHelper
.convertInstancesToProviders(Lists.newArrayList(instance));
assertNotNull(providerInfos);
assertEquals(1, providerInfos.size());
ProviderInfo providerInfo = providerInfos.get(0);
assertNotNull(providerInfo);
assertEquals(0, providerInfo.getWeight());
} |
public static boolean validateExecuteBitPresentIfReadOrWrite(FsAction perms) {
if ((perms == FsAction.READ) || (perms == FsAction.WRITE)
|| (perms == FsAction.READ_WRITE)) {
return false;
}
return true;
} | @Test
public void testExecutePermissionsCheck() {
Assert.assertTrue(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.ALL));
Assert.assertTrue(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.NONE));
Assert.assertTrue(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.EXECUTE));
Assert.assertTrue(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.READ_EXECUTE));
Assert.assertTrue(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.WRITE_EXECUTE));
Assert.assertFalse(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.READ));
Assert.assertFalse(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.WRITE));
Assert.assertFalse(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.READ_WRITE));
} |
Future<RecordMetadata> send(final ProducerRecord<byte[], byte[]> record,
final Callback callback) {
maybeBeginTransaction();
try {
return producer.send(record, callback);
} catch (final KafkaException uncaughtException) {
if (isRecoverable(uncaughtException)) {
// producer.send() call may throw a KafkaException which wraps a FencedException,
// in this case we should throw its wrapped inner cause so that it can be
// captured and re-wrapped as TaskMigratedException
throw new TaskMigratedException(
formatException("Producer got fenced trying to send a record"),
uncaughtException.getCause()
);
} else {
throw new StreamsException(
formatException(String.format("Error encountered trying to send record to topic %s", record.topic())),
uncaughtException
);
}
}
} | @Test
public void shouldFailOnEosAbortTxFatal() {
eosAlphaMockProducer.abortTransactionException = new RuntimeException("KABOOM!");
// call `send()` to start a transaction
eosAlphaStreamsProducer.send(record, null);
final RuntimeException thrown = assertThrows(RuntimeException.class, eosAlphaStreamsProducer::abortTransaction);
assertThat(thrown.getMessage(), is("KABOOM!"));
} |
@Override
public ByteBuf setIndex(int readerIndex, int writerIndex) {
if (checkBounds) {
checkIndexBounds(readerIndex, writerIndex, capacity());
}
setIndex0(readerIndex, writerIndex);
return this;
} | @Test
public void setIndexBoundaryCheck1() {
assertThrows(IndexOutOfBoundsException.class, new Executable() {
@Override
public void execute() {
buffer.setIndex(-1, CAPACITY);
}
});
} |
@Override
public List<?> deserialize(final String topic, final byte[] bytes) {
if (bytes == null) {
return null;
}
try {
final String recordCsvString = new String(bytes, StandardCharsets.UTF_8);
final List<CSVRecord> csvRecords = CSVParser.parse(recordCsvString, csvFormat)
.getRecords();
if (csvRecords.isEmpty()) {
throw new SerializationException("No fields in record");
}
final CSVRecord csvRecord = csvRecords.get(0);
if (csvRecord == null || csvRecord.size() == 0) {
throw new SerializationException("No fields in record.");
}
SerdeUtils.throwOnColumnCountMismatch(parsers.size(), csvRecord.size(), false, topic);
final List<Object> values = new ArrayList<>(parsers.size());
final Iterator<Parser> pIt = parsers.iterator();
for (int i = 0; i < csvRecord.size(); i++) {
final String value = csvRecord.get(i);
final Parser parser = pIt.next();
final Object parsed = value == null || value.isEmpty()
? null
: parser.parse(value);
values.add(parsed);
}
return values;
} catch (final Exception e) {
throw new SerializationException("Error deserializing delimited", e);
}
} | @Test
public void shouldDeserializeJsonCorrectlyWithEmptyFields() {
// Given:
final byte[] bytes = "1511897796092,1,item_1,,,,,,\r\n".getBytes(StandardCharsets.UTF_8);
// When:
final List<?> result = deserializer.deserialize("", bytes);
// Then:
assertThat(result, contains(1511897796092L, 1L, "item_1", null, null, null, null, null, null));
} |
@Udf
public String extractHost(
@UdfParameter(description = "a valid URL") final String input) {
return UrlParser.extract(input, URI::getHost);
} | @Test
public void shouldExtractHostIfPresent() {
assertThat(extractUdf.extractHost("https://docs.confluent.io:8080/current/ksql/docs/syntax-reference.html#scalar-functions"), equalTo("docs.confluent.io"));
} |
public static void writeBinaryCodedLengthBytes(byte[] data, ByteArrayOutputStream out) throws IOException {
// 1. write length byte/bytes
if (data.length < 252) {
out.write((byte) data.length);
} else if (data.length < (1 << 16L)) {
out.write((byte) 252);
writeUnsignedShortLittleEndian(data.length, out);
} else if (data.length < (1 << 24L)) {
out.write((byte) 253);
writeUnsignedMediumLittleEndian(data.length, out);
} else {
out.write((byte) 254);
writeUnsignedIntLittleEndian(data.length, out);
}
// 2. write real data followed length byte/bytes
out.write(data);
} | @Test
public void testWriteBinaryCodedLengthBytes1() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteHelper.writeBinaryCodedLengthBytes(new byte[] {2, 4}, out);
Assert.assertArrayEquals(new byte[] {2, 2, 4}, (out.toByteArray()));
} |
public AggregateAnalysisResult analyze(
final ImmutableAnalysis analysis,
final List<SelectExpression> finalProjection
) {
if (!analysis.getGroupBy().isPresent()) {
throw new IllegalArgumentException("Not an aggregate query");
}
final AggAnalyzer aggAnalyzer = new AggAnalyzer(analysis, functionRegistry);
aggAnalyzer.process(finalProjection);
return aggAnalyzer.result();
} | @Test
public void shouldThrowOnGroupByAggregateFunction() {
// Given:
givenGroupByExpressions(AGG_FUNCTION_CALL);
// When:
final KsqlException e = assertThrows(KsqlException.class,
() -> analyzer.analyze(analysis, selects));
// Then:
assertThat(e.getMessage(), containsString(
"GROUP BY does not support aggregate functions: MAX is an aggregate function."));
} |
Method findMethod(ProceedingJoinPoint pjp) {
Class<?> clazz = pjp.getTarget().getClass();
Signature pjpSignature = pjp.getSignature();
String methodName = pjp.getSignature().getName();
Class[] parameterTypes = null;
if (pjpSignature instanceof MethodSignature) {
parameterTypes = ((MethodSignature) pjpSignature).getParameterTypes();
}
try {
Method method = ReflectUtils.findDeclaredMethod(clazz, methodName, parameterTypes);
return method;
} catch (NoSuchMethodException e) {
return null;
}
} | @Test
public void testFindMethod() throws NoSuchMethodException {
ProceedingJoinPoint mockPJP = mock(ProceedingJoinPoint.class);
MockAuditClass mockAuditClass = new MockAuditClass();
MethodSignature signature = mock(MethodSignature.class);
Method method = MockAuditClass.class.getMethod("mockAuditMethod", Object.class, Object.class);
Method sameNameMethod = MockAuditClass.class.getMethod("mockAuditMethod", Object.class);
{
when(mockPJP.getTarget()).thenReturn(mockAuditClass);
when(mockPJP.getSignature()).thenReturn(signature);
when(signature.getName()).thenReturn("mockAuditMethod");
when(signature.getParameterTypes()).thenReturn(new Class[]{Object.class, Object.class});
}
Method methodFounded = aspect.findMethod(mockPJP);
assertEquals(method, methodFounded);
assertNotEquals(sameNameMethod, methodFounded);
} |
public boolean isCheckpointingEnabled() {
if (snapshotSettings == null) {
return false;
}
return snapshotSettings.getCheckpointCoordinatorConfiguration().isCheckpointingEnabled();
} | @Test
public void checkpointingIsDisabledIfIntervalIsMaxValue() {
final JobGraph jobGraph =
JobGraphBuilder.newStreamingJobGraphBuilder()
.setJobCheckpointingSettings(
createCheckpointSettingsWithInterval(Long.MAX_VALUE))
.build();
assertFalse(jobGraph.isCheckpointingEnabled());
} |
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
// Skip if processed before, prevent duplicated execution in Hierarchical ApplicationContext
if (processed.get()) {
return;
}
/**
* Gets Logger After LoggingSystem configuration ready
* @see LoggingApplicationListener
*/
final Logger logger = LoggerFactory.getLogger(getClass());
String bannerText = buildBannerText();
if (logger.isInfoEnabled()) {
logger.info(bannerText);
} else {
System.out.print(bannerText);
}
// mark processed to be true
processed.compareAndSet(false, true);
} | @Test
public void testOnApplicationEvent() {
Assert.assertNotNull(welcomeLogoApplicationListener.buildBannerText());
} |
@Override
public Collection<SlotOffer> offerSlots(
Collection<? extends SlotOffer> offers,
TaskManagerLocation taskManagerLocation,
TaskManagerGateway taskManagerGateway,
long currentTime) {
log.debug("Received {} slot offers from TaskExecutor {}.", offers, taskManagerLocation);
return internalOfferSlots(
offers,
taskManagerLocation,
taskManagerGateway,
currentTime,
this::matchWithOutstandingRequirement);
} | @TestTemplate
void testOfferSlots() throws InterruptedException {
final NewSlotsService notifyNewSlots = new NewSlotsService();
final DefaultDeclarativeSlotPool slotPool =
createDefaultDeclarativeSlotPoolWithNewSlotsListener(notifyNewSlots);
final ResourceCounter resourceRequirements = createResourceRequirements();
slotPool.increaseResourceRequirementsBy(resourceRequirements);
slotPool.tryWaitSlotRequestIsDone();
Collection<SlotOffer> slotOffers =
createSlotOffersForResourceRequirements(resourceRequirements);
final Collection<SlotOffer> acceptedSlots =
SlotPoolTestUtils.offerSlots(slotPool, slotOffers);
assertThat(acceptedSlots).containsExactlyInAnyOrderElementsOf(slotOffers);
final Map<AllocationID, PhysicalSlot> newSlotsById =
drainNewSlotService(notifyNewSlots).stream()
.collect(
Collectors.toMap(
PhysicalSlot::getAllocationId, Function.identity()));
assertThat(slotOffers)
.hasSize(newSlotsById.size())
.allSatisfy(
slotOffer -> {
PhysicalSlot slot = newSlotsById.get(slotOffer.getAllocationId());
assertThat(slot).isNotNull();
assertThat(slotOffer.getAllocationId())
.isEqualTo(slot.getAllocationId());
assertThat(slotOffer.getSlotIndex())
.isEqualTo(slot.getPhysicalSlotNumber());
assertThat(slotOffer.getResourceProfile())
.isEqualTo(slot.getResourceProfile());
});
assertThat(slotPool.getAllSlotsInformation())
.hasSize(newSlotsById.size())
.allSatisfy(
slotInfo -> {
PhysicalSlot slot = newSlotsById.get(slotInfo.getAllocationId());
assertThat(slot).isNotNull();
assertThat(slotInfo.getAllocationId())
.isEqualTo(slot.getAllocationId());
assertThat(slotInfo.getPhysicalSlotNumber())
.isEqualTo(slot.getPhysicalSlotNumber());
assertThat(slotInfo.getResourceProfile())
.isEqualTo(slot.getResourceProfile());
assertThat(slotInfo.getTaskManagerLocation())
.isEqualTo(slot.getTaskManagerLocation());
});
} |
@Operation(summary = "countCommandState", description = "COUNT_COMMAND_STATE_NOTES")
@GetMapping(value = "/command-state-count")
@ResponseStatus(HttpStatus.OK)
@ApiException(COMMAND_STATE_COUNT_ERROR)
public Result<List<CommandStateCount>> countCommandState(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser) {
List<CommandStateCount> commandStateCounts = dataAnalysisService.countCommandState(loginUser);
return Result.success(commandStateCounts);
} | @Test
public void testCountCommandState() throws Exception {
MvcResult mvcResult = mockMvc.perform(get("/projects/analysis/command-state-count")
.header("sessionId", sessionId))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class);
assertThat(result.getCode().intValue()).isEqualTo(Status.SUCCESS.getCode());
logger.info(mvcResult.getResponse().getContentAsString());
} |
public static PeriodDuration analyzeDataCachePartitionDuration(Map<String, String> properties) throws AnalysisException {
String text = properties.get(PROPERTIES_DATACACHE_PARTITION_DURATION);
if (text == null) {
return null;
}
properties.remove(PROPERTIES_DATACACHE_PARTITION_DURATION);
try {
return TimeUtils.parseHumanReadablePeriodOrDuration(text);
} catch (DateTimeParseException ex) {
throw new AnalysisException(ex.getMessage());
}
} | @Test
public void testAnalyzeDataCachePartitionDuration() {
Map<String, String> properties = new HashMap<>();
properties.put(PropertyAnalyzer.PROPERTIES_DATACACHE_PARTITION_DURATION, "7 day");
try {
PropertyAnalyzer.analyzeDataCachePartitionDuration(properties);
} catch (AnalysisException e) {
Assert.assertTrue(false);
}
Assert.assertTrue(properties.size() == 0);
properties.put(PropertyAnalyzer.PROPERTIES_DATACACHE_PARTITION_DURATION, "abcd");
try {
PropertyAnalyzer.analyzeDataCachePartitionDuration(properties);
Assert.assertTrue(false);
} catch (AnalysisException e) {
Assert.assertEquals("Cannot parse text to Duration", e.getMessage());
}
} |
public static <T> T checkNotNull(T reference,
String errorMessageTemplate,
Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(
format(errorMessageTemplate, errorMessageArgs));
}
return reference;
} | @Test
void checkNotNullInputZeroNotNull0OutputZero() {
// Arrange
final Object reference = 0;
final String errorMessageTemplate = " ";
final Object[] errorMessageArgs = {};
// Act
final Object retval = Util.checkNotNull(reference, errorMessageTemplate, errorMessageArgs);
// Assert result
assertThat(retval).isEqualTo(0);
} |
public List<Upstream> findUpstreamListBySelectorId(final String selectorId) {
return task.getHealthyUpstream().get(selectorId);
} | @Test
@Order(4)
public void findUpstreamListBySelectorIdTest() {
final UpstreamCacheManager upstreamCacheManager = UpstreamCacheManager.getInstance();
Assertions.assertNull(upstreamCacheManager.findUpstreamListBySelectorId(SELECTOR_ID));
} |
public static String replaceTokens(String template, Pattern pattern,
Map<String, String> replacements) {
StringBuffer sb = new StringBuffer();
Matcher matcher = pattern.matcher(template);
while (matcher.find()) {
String replacement = replacements.get(matcher.group(1));
if (replacement == null) {
replacement = "";
}
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
}
matcher.appendTail(sb);
return sb.toString();
} | @Test (timeout = 5000)
public void testReplaceTokensWinEnvVars() {
Pattern pattern = StringUtils.WIN_ENV_VAR_PATTERN;
Map<String, String> replacements = new HashMap<String, String>();
replacements.put("foo", "zoo");
replacements.put("baz", "zaz");
assertEquals("zoo", StringUtils.replaceTokens("%foo%", pattern,
replacements));
assertEquals("zaz", StringUtils.replaceTokens("%baz%", pattern,
replacements));
assertEquals("", StringUtils.replaceTokens("%bar%", pattern,
replacements));
assertEquals("", StringUtils.replaceTokens("", pattern, replacements));
assertEquals("zoo__zaz", StringUtils.replaceTokens("%foo%_%bar%_%baz%",
pattern, replacements));
assertEquals("begin zoo__zaz end", StringUtils.replaceTokens(
"begin %foo%_%bar%_%baz% end", pattern, replacements));
} |
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
public KDiag(Configuration conf,
PrintWriter out,
File keytab,
String principal,
long minKeyLength,
boolean securityRequired) {
super(conf);
this.keytab = keytab;
this.principal = principal;
this.out = out;
this.minKeyLength = minKeyLength;
this.securityRequired = securityRequired;
} | @Test
public void testKeytabAndPrincipal() throws Throwable {
kdiag(ARG_KEYLEN, KEYLEN,
ARG_KEYTAB, keytab.getAbsolutePath(),
ARG_PRINCIPAL, "foo@EXAMPLE.COM");
} |
@Override
public Cursor<byte[]> scan(RedisClusterNode node, ScanOptions options) {
return new ScanCursor<byte[]>(0, options) {
private RedisClient client = getEntry(node);
@Override
protected ScanIteration<byte[]> doScan(long cursorId, ScanOptions options) {
if (isQueueing() || isPipelined()) {
throw new UnsupportedOperationException("'SSCAN' cannot be called in pipeline / transaction mode.");
}
if (client == null) {
return null;
}
List<Object> args = new ArrayList<Object>();
if (cursorId == 101010101010101010L) {
cursorId = 0;
}
args.add(Long.toUnsignedString(cursorId));
if (options.getPattern() != null) {
args.add("MATCH");
args.add(options.getPattern());
}
if (options.getCount() != null) {
args.add("COUNT");
args.add(options.getCount());
}
RFuture<ListScanResult<byte[]>> f = executorService.readAsync(client, ByteArrayCodec.INSTANCE, RedisCommands.SCAN, args.toArray());
ListScanResult<byte[]> res = syncFuture(f);
String pos = res.getPos();
client = res.getRedisClient();
if ("0".equals(pos)) {
client = null;
}
return new ScanIteration<byte[]>(Long.parseUnsignedLong(pos), res.getValues());
}
}.open();
} | @Test
public void testScan() {
Map<byte[], byte[]> map = new HashMap<>();
for (int i = 0; i < 10000; i++) {
map.put(RandomString.make(32).getBytes(), RandomString.make(32).getBytes(StandardCharsets.UTF_8));
}
connection.mSet(map);
Cursor<byte[]> b = connection.scan(ScanOptions.scanOptions().build());
Set<String> sett = new HashSet<>();
int counter = 0;
while (b.hasNext()) {
byte[] tt = b.next();
sett.add(new String(tt));
counter++;
}
assertThat(sett.size()).isEqualTo(map.size());
assertThat(counter).isEqualTo(map.size());
} |
@Override
protected boolean isContextRequired() {
return false;
} | @Test
public void isContextRequiredTest() {
assertFalse(exporter.isContextRequired());
} |
public static UserGroupInformation getUGI(HttpServletRequest request,
Configuration conf) throws IOException {
return getUGI(null, request, conf);
} | @Test
public void testGetUgiDuringStartup() throws Exception {
conf.set(DFSConfigKeys.FS_DEFAULT_NAME_KEY, "hdfs://localhost:4321/");
ServletContext context = mock(ServletContext.class);
String realUser = "TheDoctor";
String user = "TheNurse";
conf.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
UserGroupInformation.setConfiguration(conf);
HttpServletRequest request;
Text ownerText = new Text(user);
DelegationTokenIdentifier dtId = new DelegationTokenIdentifier(
ownerText, ownerText, new Text(realUser));
Token<DelegationTokenIdentifier> token =
new Token<DelegationTokenIdentifier>(dtId,
new DummySecretManager(0, 0, 0, 0));
String tokenString = token.encodeToUrlString();
// token with auth-ed user
request = getMockRequest(realUser, null, null);
when(request.getParameter(JspHelper.DELEGATION_PARAMETER_NAME)).thenReturn(
tokenString);
NameNode mockNN = mock(NameNode.class);
Mockito.doCallRealMethod().when(mockNN)
.verifyToken(Mockito.any(), Mockito.any());
when(context.getAttribute("name.node")).thenReturn(mockNN);
LambdaTestUtils.intercept(RetriableException.class,
"Namenode is in startup mode",
() -> JspHelper.getUGI(context, request, conf));
} |
@GetMapping("/by-release")
public PageDTO<InstanceDTO> getByRelease(@RequestParam("releaseId") long releaseId,
Pageable pageable) {
Release release = releaseService.findOne(releaseId);
if (release == null) {
throw NotFoundException.releaseNotFound(releaseId);
}
Page<InstanceConfig> instanceConfigsPage = instanceService.findActiveInstanceConfigsByReleaseKey
(release.getReleaseKey(), pageable);
List<InstanceDTO> instanceDTOs = Collections.emptyList();
if (instanceConfigsPage.hasContent()) {
Multimap<Long, InstanceConfig> instanceConfigMap = HashMultimap.create();
Set<String> otherReleaseKeys = Sets.newHashSet();
for (InstanceConfig instanceConfig : instanceConfigsPage.getContent()) {
instanceConfigMap.put(instanceConfig.getInstanceId(), instanceConfig);
otherReleaseKeys.add(instanceConfig.getReleaseKey());
}
Set<Long> instanceIds = instanceConfigMap.keySet();
List<Instance> instances = instanceService.findInstancesByIds(instanceIds);
if (!CollectionUtils.isEmpty(instances)) {
instanceDTOs = BeanUtils.batchTransform(InstanceDTO.class, instances);
}
for (InstanceDTO instanceDTO : instanceDTOs) {
Collection<InstanceConfig> configs = instanceConfigMap.get(instanceDTO.getId());
List<InstanceConfigDTO> configDTOs = configs.stream().map(instanceConfig -> {
InstanceConfigDTO instanceConfigDTO = new InstanceConfigDTO();
//to save some space
instanceConfigDTO.setRelease(null);
instanceConfigDTO.setReleaseDeliveryTime(instanceConfig.getReleaseDeliveryTime());
instanceConfigDTO.setDataChangeLastModifiedTime(instanceConfig
.getDataChangeLastModifiedTime());
return instanceConfigDTO;
}).collect(Collectors.toList());
instanceDTO.setConfigs(configDTOs);
}
}
return new PageDTO<>(instanceDTOs, pageable, instanceConfigsPage.getTotalElements());
} | @Test
public void getByRelease() throws Exception {
long someReleaseId = 1;
long someInstanceId = 1;
long anotherInstanceId = 2;
String someReleaseKey = "someKey";
Release someRelease = new Release();
someRelease.setReleaseKey(someReleaseKey);
String someAppId = "someAppId";
String anotherAppId = "anotherAppId";
String someCluster = "someCluster";
String someDataCenter = "someDC";
String someConfigAppId = "someConfigAppId";
String someConfigNamespace = "someNamespace";
String someIp = "someIp";
Date someReleaseDeliveryTime = new Date();
Date anotherReleaseDeliveryTime = new Date();
when(releaseService.findOne(someReleaseId)).thenReturn(someRelease);
InstanceConfig someInstanceConfig = assembleInstanceConfig(someInstanceId, someConfigAppId,
someConfigNamespace, someReleaseKey, someReleaseDeliveryTime);
InstanceConfig anotherInstanceConfig = assembleInstanceConfig(anotherInstanceId,
someConfigAppId, someConfigNamespace, someReleaseKey, anotherReleaseDeliveryTime);
List<InstanceConfig> instanceConfigs = Lists.newArrayList(someInstanceConfig,
anotherInstanceConfig);
Page<InstanceConfig> instanceConfigPage = new PageImpl<>(instanceConfigs, pageable,
instanceConfigs.size());
when(instanceService.findActiveInstanceConfigsByReleaseKey(someReleaseKey, pageable))
.thenReturn(instanceConfigPage);
Instance someInstance = assembleInstance(someInstanceId, someAppId,
someCluster, someDataCenter, someIp);
Instance anotherInstance = assembleInstance(anotherInstanceId, anotherAppId,
someCluster, someDataCenter, someIp);
List<Instance> instances = Lists.newArrayList(someInstance, anotherInstance);
Set<Long> instanceIds = Sets.newHashSet(someInstanceId, anotherInstanceId);
when(instanceService.findInstancesByIds(instanceIds))
.thenReturn(instances);
PageDTO<InstanceDTO> result = instanceConfigController.getByRelease(someReleaseId, pageable);
assertEquals(2, result.getContent().size());
InstanceDTO someInstanceDto = null;
InstanceDTO anotherInstanceDto = null;
for (InstanceDTO instanceDTO : result.getContent()) {
if (instanceDTO.getId() == someInstanceId) {
someInstanceDto = instanceDTO;
} else if (instanceDTO.getId() == anotherInstanceId) {
anotherInstanceDto = instanceDTO;
}
}
verifyInstance(someInstance, someInstanceDto);
verifyInstance(anotherInstance, anotherInstanceDto);
assertEquals(1, someInstanceDto.getConfigs().size());
assertEquals(someReleaseDeliveryTime, someInstanceDto.getConfigs().get(0).getReleaseDeliveryTime());
assertEquals(1, anotherInstanceDto.getConfigs().size());
assertEquals(anotherReleaseDeliveryTime, anotherInstanceDto.getConfigs().get(0).getReleaseDeliveryTime());
} |
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) {
return new CreateStreamCommand(
outputNode.getSinkName().get(),
outputNode.getSchema(),
outputNode.getTimestampColumn(),
outputNode.getKsqlTopic().getKafkaTopicName(),
Formats.from(outputNode.getKsqlTopic()),
outputNode.getKsqlTopic().getKeyFormat().getWindowInfo(),
Optional.of(outputNode.getOrReplace()),
Optional.of(false)
);
} | @Test
public void shouldThrowOnRowTimeKeyColumn() {
// Given:
final CreateStream statement = new CreateStream(
SOME_NAME,
TableElements.of(tableElement(ROWTIME_NAME.text(), new Type(BIGINT), KEY_CONSTRAINT)),
false,
true,
withProperties,
false
);
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> createSourceFactory.createStreamCommand(statement, ksqlConfig)
);
// Then:
assertThat(e.getMessage(), containsString(
"'ROWTIME' is a reserved column name."));
} |
public ReferenceBuilder<T> addMethods(List<MethodConfig> methods) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.addAll(methods);
return getThis();
} | @Test
void addMethods() {
MethodConfig method = new MethodConfig();
ReferenceBuilder builder = new ReferenceBuilder();
builder.addMethods(Collections.singletonList(method));
Assertions.assertTrue(builder.build().getMethods().contains(method));
Assertions.assertEquals(1, builder.build().getMethods().size());
} |
public static boolean isLetter(CharSequence value) {
return StrUtil.isAllCharMatch(value, Character::isLetter);
} | @Test
public void isLetterTest() {
assertTrue(Validator.isLetter("asfdsdsfds"));
assertTrue(Validator.isLetter("asfdsdfdsfVCDFDFGdsfds"));
assertTrue(Validator.isLetter("asfdsdf你好dsfVCDFDFGdsfds"));
} |
public void mergeRuntimeUpdate(
List<TimelineEvent> pendingTimeline, Map<String, Artifact> pendingArtifacts) {
if (timeline.addAll(pendingTimeline)) {
synced = false;
}
if (pendingArtifacts != null && !pendingArtifacts.isEmpty()) {
for (Map.Entry<String, Artifact> entry : pendingArtifacts.entrySet()) {
String key = entry.getKey();
if (!entry.getValue().equals(artifacts.get(key))) {
if (artifacts.containsKey(key)
&& artifacts.get(key).getType() == Artifact.Type.DEFAULT
&& entry.getValue().getType() == Artifact.Type.DEFAULT) {
artifacts.get(key).asDefault().getData().putAll(entry.getValue().asDefault().getData());
} else {
artifacts.put(entry.getKey(), entry.getValue());
}
synced = false;
}
}
}
if (!synced) {
runtimeState.setModifyTime(System.currentTimeMillis());
}
} | @Test
public void testMergeTimeline() throws Exception {
StepRuntimeSummary summary =
loadObject(
"fixtures/execution/sample-step-runtime-summary-1.json", StepRuntimeSummary.class);
assertTrue(summary.isSynced());
TimelineEvent curEvent = summary.getTimeline().getTimelineEvents().get(0);
TimelineEvent newEvent = TimelineLogEvent.builder().message("world").build();
summary.mergeRuntimeUpdate(Collections.singletonList(newEvent), null);
assertFalse(summary.isSynced());
assertEquals(new Timeline(Arrays.asList(curEvent, newEvent)), summary.getTimeline());
} |
public static MulticastMappingInstruction multicastWeight(int weight) {
return new MulticastMappingInstruction.WeightMappingInstruction(
MulticastType.WEIGHT, weight);
} | @Test
public void testMulticastWeightMethod() {
final MappingInstruction instruction = MappingInstructions.multicastWeight(2);
final MulticastMappingInstruction.WeightMappingInstruction weightMappingInstruction =
checkAndConvert(instruction,
MulticastMappingInstruction.Type.MULTICAST,
MulticastMappingInstruction.WeightMappingInstruction.class);
assertThat(weightMappingInstruction.weight(), is(equalTo(2)));
} |
@Override
public short getShortLE(int index) {
checkIndex(index, 2);
return _getShortLE(index);
} | @Test
public void testGetShortLEAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().getShortLE(0);
}
});
} |
public AggregationType computeAggregationType(String name) {
return this.aggregationAssessor.computeAggregationType(name);
} | @Test
public void testCanAggregateComponent() {
assertEquals(AggregationType.AS_COMPLEX_PROPERTY, setter.computeAggregationType("door"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("count"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("Count"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("name"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("Name"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("Duration"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("fs"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("open"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("Open"));
assertEquals(AggregationType.AS_COMPLEX_PROPERTY_COLLECTION, setter.computeAggregationType("Window"));
assertEquals(AggregationType.AS_BASIC_PROPERTY_COLLECTION, setter.computeAggregationType("adjective"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("filterReply"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("houseColor"));
} |
@Nonnull
public static Number shiftLeft(@Nonnull Number value, @Nonnull Number shift) {
// Check for widest types first, go down the type list to narrower types until reaching int.
if (value instanceof Long) {
return value.longValue() << shift.longValue();
} else {
return value.intValue() << shift.intValue();
}
} | @Test
void testShiftLeft() {
assertEquals(2 << 1, NumberUtil.shiftLeft(2, 1));
assertEquals(2L << 1, NumberUtil.shiftLeft(2L, 1));
} |
public static ECKeyPair decrypt(String password, WalletFile walletFile) throws CipherException {
validate(walletFile);
WalletFile.Crypto crypto = walletFile.getCrypto();
byte[] mac = Numeric.hexStringToByteArray(crypto.getMac());
byte[] iv = Numeric.hexStringToByteArray(crypto.getCipherparams().getIv());
byte[] cipherText = Numeric.hexStringToByteArray(crypto.getCiphertext());
byte[] derivedKey;
WalletFile.KdfParams kdfParams = crypto.getKdfparams();
if (kdfParams instanceof WalletFile.ScryptKdfParams) {
WalletFile.ScryptKdfParams scryptKdfParams =
(WalletFile.ScryptKdfParams) crypto.getKdfparams();
int dklen = scryptKdfParams.getDklen();
int n = scryptKdfParams.getN();
int p = scryptKdfParams.getP();
int r = scryptKdfParams.getR();
byte[] salt = Numeric.hexStringToByteArray(scryptKdfParams.getSalt());
derivedKey = generateDerivedScryptKey(password.getBytes(UTF_8), salt, n, r, p, dklen);
} else if (kdfParams instanceof WalletFile.Aes128CtrKdfParams) {
WalletFile.Aes128CtrKdfParams aes128CtrKdfParams =
(WalletFile.Aes128CtrKdfParams) crypto.getKdfparams();
int c = aes128CtrKdfParams.getC();
String prf = aes128CtrKdfParams.getPrf();
byte[] salt = Numeric.hexStringToByteArray(aes128CtrKdfParams.getSalt());
derivedKey = generateAes128CtrDerivedKey(password.getBytes(UTF_8), salt, c, prf);
} else {
throw new CipherException("Unable to deserialize params: " + crypto.getKdf());
}
byte[] derivedMac = generateMac(derivedKey, cipherText);
if (!Arrays.equals(derivedMac, mac)) {
throw new CipherException("Invalid password provided");
}
byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16);
byte[] privateKey = performCipherOperation(Cipher.DECRYPT_MODE, iv, encryptKey, cipherText);
return ECKeyPair.create(privateKey);
} | @Test
public void testDecryptAes128Ctr() throws Exception {
WalletFile walletFile = load(AES_128_CTR);
ECKeyPair ecKeyPair = Wallet.decrypt(PASSWORD, walletFile);
assertEquals(Numeric.toHexStringNoPrefix(ecKeyPair.getPrivateKey()), (SECRET));
} |
public static void unbindGlobalLockFlag() {
Boolean lockFlag = (Boolean) CONTEXT_HOLDER.remove(KEY_GLOBAL_LOCK_FLAG);
if (LOGGER.isDebugEnabled() && lockFlag != null) {
LOGGER.debug("unbind global lock flag");
}
} | @Test
public void testUnBindGlobalLockFlag() {
RootContext.bindGlobalLockFlag();
assertThat(RootContext.requireGlobalLock()).isEqualTo(true);
RootContext.unbindGlobalLockFlag();
assertThat(RootContext.requireGlobalLock()).isEqualTo(false);
} |
public static Map<String, String> computeAliases(PluginScanResult scanResult) {
Map<String, Set<String>> aliasCollisions = new HashMap<>();
scanResult.forEach(pluginDesc -> {
aliasCollisions.computeIfAbsent(simpleName(pluginDesc), ignored -> new HashSet<>()).add(pluginDesc.className());
aliasCollisions.computeIfAbsent(prunedName(pluginDesc), ignored -> new HashSet<>()).add(pluginDesc.className());
});
Map<String, String> aliases = new HashMap<>();
for (Map.Entry<String, Set<String>> entry : aliasCollisions.entrySet()) {
String alias = entry.getKey();
Set<String> classNames = entry.getValue();
if (classNames.size() == 1) {
aliases.put(alias, classNames.stream().findAny().get());
} else {
log.debug("Ignoring ambiguous alias '{}' since it refers to multiple distinct plugins {}", alias, classNames);
}
}
return aliases;
} | @Test
public void testMultiVersionAlias() {
SortedSet<PluginDesc<SinkConnector>> sinkConnectors = new TreeSet<>();
// distinct versions don't cause an alias collision (the class name is the same)
sinkConnectors.add(new PluginDesc<>(MockSinkConnector.class, null, PluginType.SINK, MockSinkConnector.class.getClassLoader()));
sinkConnectors.add(new PluginDesc<>(MockSinkConnector.class, "1.0", PluginType.SINK, MockSinkConnector.class.getClassLoader()));
assertEquals(2, sinkConnectors.size());
PluginScanResult result = new PluginScanResult(
sinkConnectors,
Collections.emptySortedSet(),
Collections.emptySortedSet(),
Collections.emptySortedSet(),
Collections.emptySortedSet(),
Collections.emptySortedSet(),
Collections.emptySortedSet(),
Collections.emptySortedSet(),
Collections.emptySortedSet()
);
Map<String, String> actualAliases = PluginUtils.computeAliases(result);
Map<String, String> expectedAliases = new HashMap<>();
expectedAliases.put("MockSinkConnector", MockSinkConnector.class.getName());
expectedAliases.put("MockSink", MockSinkConnector.class.getName());
assertEquals(expectedAliases, actualAliases);
} |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.SMS_TEMPLATE,
allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理
public void deleteSmsTemplate(Long id) {
// 校验存在
validateSmsTemplateExists(id);
// 更新
smsTemplateMapper.deleteById(id);
} | @Test
public void testDeleteSmsTemplate_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> smsTemplateService.deleteSmsTemplate(id), SMS_TEMPLATE_NOT_EXISTS);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.