Merge branch 'dev' into feature-trans2jackson
This commit is contained in:
@@ -26,7 +26,7 @@ public class CorsConfig {
|
||||
config.addAllowedOrigin("https://celess.cn");
|
||||
config.addAllowedOrigin("https://www.celess.cn");
|
||||
// 本地调试时的跨域
|
||||
if ("dev".equals(activeModel)) {
|
||||
if (!"prod".equals(activeModel)) {
|
||||
config.addAllowedOrigin("http://localhost:4200");
|
||||
config.addAllowedOrigin("http://127.0.0.1:4200");
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ public class DruidConfig {
|
||||
@Bean
|
||||
public DruidDataSource druidDataSource() {
|
||||
DruidDataSource dataSource = new DruidDataSource();
|
||||
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
|
||||
dataSource.setDriverClassName(driverClassName);
|
||||
// 数据库基本信息
|
||||
dataSource.setUrl(dbUrl);
|
||||
dataSource.setUsername(username);
|
||||
|
||||
@@ -26,7 +26,7 @@ public class SwaggerConfig {
|
||||
@Bean
|
||||
public Docket createRestApi() {
|
||||
return new Docket(DocumentationType.SWAGGER_2)
|
||||
.enable("dev".equals(environment))
|
||||
.enable(!"prod".equals(environment))
|
||||
.apiInfo(apiInfo())
|
||||
.select()
|
||||
.apis(RequestHandlerSelectors.basePackage("cn.celess.blog"))
|
||||
|
||||
@@ -56,10 +56,13 @@ public class AuthenticationFilter implements HandlerInterceptor {
|
||||
return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request);
|
||||
}
|
||||
String email = jwtUtil.getUsernameFromToken(jwtStr);
|
||||
if (!redisUtil.hasKey(email + "-login") || jwtUtil.isTokenExpired(jwtStr)) {
|
||||
if (jwtUtil.isTokenExpired(jwtStr)) {
|
||||
// 登陆过期
|
||||
return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request);
|
||||
}
|
||||
if (!redisUtil.hasKey(email + "-login")) {
|
||||
return writeResponse(ResponseEnum.LOGOUT, response, request);
|
||||
}
|
||||
String role = userService.getUserRoleByEmail(email);
|
||||
if (role.equals(ROLE_USER) || role.equals(ROLE_ADMIN)) {
|
||||
// 更新token
|
||||
|
||||
@@ -135,8 +135,6 @@ public class CommonController {
|
||||
* FUCK !!!
|
||||
*
|
||||
* @param file 文件
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
@PostMapping("/imgUpload")
|
||||
public void upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("editormd-image-file") MultipartFile file) throws IOException {
|
||||
@@ -159,6 +157,7 @@ public class CommonController {
|
||||
return;
|
||||
}
|
||||
String fileName = file.getOriginalFilename();
|
||||
assert fileName != null;
|
||||
String mime = fileName.substring(fileName.lastIndexOf("."));
|
||||
if (".png".equals(mime.toLowerCase()) || ".jpg".equals(mime.toLowerCase()) ||
|
||||
".jpeg".equals(mime.toLowerCase()) || ".bmp".equals(mime.toLowerCase())) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package cn.celess.blog.controller;
|
||||
import cn.celess.blog.enmu.ResponseEnum;
|
||||
import cn.celess.blog.entity.PartnerSite;
|
||||
import cn.celess.blog.entity.Response;
|
||||
import cn.celess.blog.entity.request.LinkApplyReq;
|
||||
import cn.celess.blog.entity.request.LinkReq;
|
||||
import cn.celess.blog.exception.MyException;
|
||||
import cn.celess.blog.service.MailService;
|
||||
@@ -69,29 +70,12 @@ public class LinksController {
|
||||
}
|
||||
|
||||
@PostMapping("/apply")
|
||||
public Response apply(@RequestParam("name") String name,
|
||||
@RequestParam("url") String url) {
|
||||
// TODO :: 弃用发送邮件的方式。
|
||||
if (name == null || name.replaceAll(" ", "").isEmpty()) {
|
||||
return Response.response(ResponseEnum.PARAMETERS_ERROR, null);
|
||||
}
|
||||
if (!RegexUtil.urlMatch(url)) {
|
||||
return Response.response(ResponseEnum.PARAMETERS_URL_ERROR, null);
|
||||
}
|
||||
String applyTimeStr = redisUtil.get(request.getRemoteAddr() + "-Apply");
|
||||
int applyTime = 0;
|
||||
if (applyTimeStr != null) {
|
||||
applyTime = Integer.parseInt(applyTimeStr);
|
||||
}
|
||||
if (applyTime == 10) {
|
||||
throw new MyException(ResponseEnum.FAILURE.getCode(), "申请次数已达10次,请2小时后重试");
|
||||
}
|
||||
SimpleMailMessage message = new SimpleMailMessage();
|
||||
message.setSubject("友链申请:" + name);
|
||||
message.setTo("a@celess.cn");
|
||||
message.setText("name:" + name + "\nurl:" + url + "\n" + DateFormatUtil.getNow());
|
||||
Boolean send = mailService.send(message);
|
||||
redisUtil.setEx(request.getRemoteAddr() + "-Apply", applyTime + 1 + "", 2, TimeUnit.HOURS);
|
||||
return send ? Response.success("") : Response.failure("");
|
||||
public Response apply(@RequestBody() LinkApplyReq linkApplyReq) {
|
||||
return Response.success(partnerSiteService.apply(linkApplyReq));
|
||||
}
|
||||
|
||||
@PostMapping("/reapply")
|
||||
public Response reapply(@RequestParam("key") String key) {
|
||||
return Response.success(partnerSiteService.reapply(key));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ public enum ResponseEnum {
|
||||
PWD_SAME(3601, "新密码与原密码相同"),
|
||||
PWD_NOT_SAME(3602, "新密码与原密码不相同"),
|
||||
LOGIN_EXPIRED(3700, "登陆过期"),
|
||||
LOGOUT(3710, "账户已注销"),
|
||||
PWD_WRONG(3800, "密码不正确"),
|
||||
|
||||
JWT_EXPIRED(3810, "Token过期"),
|
||||
@@ -57,6 +58,9 @@ public enum ResponseEnum {
|
||||
DATA_HAS_EXIST(7020, "数据已存在"),
|
||||
|
||||
//其他
|
||||
APPLY_LINK_NO_ADD_THIS_SITE(7200, "暂未在您的网站中抓取到本站链接"),
|
||||
DATA_EXPIRED(7300, "数据过期"),
|
||||
CANNOT_GET_DATA(7400, "暂无法获取到数据"),
|
||||
|
||||
//提交更新之前,没有获取数据/,
|
||||
DID_NOT_GET_THE_DATA(8020, "非法访问"),
|
||||
|
||||
@@ -25,6 +25,10 @@ public class PartnerSite {
|
||||
|
||||
private Boolean delete = false;
|
||||
|
||||
private String email;
|
||||
|
||||
private Boolean notification = true;
|
||||
|
||||
public PartnerSite() {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package cn.celess.blog.entity.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author : xiaohai
|
||||
* @date : 2020/07/31 20:50
|
||||
*/
|
||||
@Data
|
||||
public class LinkApplyReq {
|
||||
private String name;
|
||||
private String email;
|
||||
private String url;
|
||||
private String linkUrl;
|
||||
private String desc;
|
||||
private String iconPath;
|
||||
}
|
||||
@@ -39,8 +39,9 @@ public class ExceptionHandle {
|
||||
public Response handle(Exception e) {
|
||||
//自定义错误
|
||||
if (e instanceof MyException) {
|
||||
logger.debug("返回了自定义的exception,[code={},msg={}]", ((MyException) e).getCode(), e.getMessage());
|
||||
return new Response(((MyException) e).getCode(), e.getMessage(), null);
|
||||
MyException exception = (MyException) e;
|
||||
logger.debug("返回了自定义的exception,[code={},msg={},result={}]", exception.getCode(), e.getMessage(), exception.getResult());
|
||||
return new Response(exception.getCode(), e.getMessage(), exception.getResult());
|
||||
}
|
||||
//请求路径不支持该方法
|
||||
if (e instanceof HttpRequestMethodNotSupportedException) {
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package cn.celess.blog.exception;
|
||||
|
||||
import cn.celess.blog.enmu.ResponseEnum;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author : xiaohai
|
||||
* @date : 2019/03/28 16:56
|
||||
*/
|
||||
@Data
|
||||
public class MyException extends RuntimeException {
|
||||
private int code;
|
||||
private Object result;
|
||||
|
||||
public MyException(int code, String msg) {
|
||||
super(msg);
|
||||
@@ -24,11 +27,9 @@ public class MyException extends RuntimeException {
|
||||
this.code = e.getCode();
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
public MyException(ResponseEnum e, String msg, Object result) {
|
||||
super(e.getMsg());
|
||||
this.code = e.getCode();
|
||||
this.result = result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package cn.celess.blog.service;
|
||||
|
||||
import cn.celess.blog.entity.PartnerSite;
|
||||
import cn.celess.blog.entity.model.PageData;
|
||||
import cn.celess.blog.entity.request.LinkApplyReq;
|
||||
import cn.celess.blog.entity.request.LinkReq;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -53,4 +54,19 @@ public interface PartnerSiteService {
|
||||
*/
|
||||
List<PartnerSite> findAll();
|
||||
|
||||
/**
|
||||
* 申请友链
|
||||
*
|
||||
* @param linkApplyReq linkApplyReq
|
||||
* @return linkApplyReq
|
||||
*/
|
||||
PartnerSite apply(LinkApplyReq linkApplyReq);
|
||||
|
||||
/**
|
||||
* 重写申请友链
|
||||
*
|
||||
* @param key key
|
||||
* @return msg
|
||||
*/
|
||||
String reapply(String key);
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ public class CommentServiceImpl implements CommentService {
|
||||
Comment comment = new Comment();
|
||||
comment.setFromUser(user);
|
||||
User userTo = new User();
|
||||
userTo.setId(-1L);
|
||||
userTo.setId(null);
|
||||
if (reqBody.getToUserId() != -1) {
|
||||
userTo = userMapper.findById(reqBody.getToUserId());
|
||||
comment.setToUser(userTo);
|
||||
|
||||
@@ -3,18 +3,30 @@ package cn.celess.blog.service.serviceimpl;
|
||||
import cn.celess.blog.enmu.ResponseEnum;
|
||||
import cn.celess.blog.entity.PartnerSite;
|
||||
import cn.celess.blog.entity.model.PageData;
|
||||
import cn.celess.blog.entity.request.LinkApplyReq;
|
||||
import cn.celess.blog.entity.request.LinkReq;
|
||||
import cn.celess.blog.exception.MyException;
|
||||
import cn.celess.blog.mapper.PartnerMapper;
|
||||
import cn.celess.blog.service.MailService;
|
||||
import cn.celess.blog.service.PartnerSiteService;
|
||||
import cn.celess.blog.util.HttpUtil;
|
||||
import cn.celess.blog.util.JwtUtil;
|
||||
import cn.celess.blog.util.RedisUtil;
|
||||
import cn.celess.blog.util.RegexUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import lombok.SneakyThrows;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author : xiaohai
|
||||
@@ -24,6 +36,13 @@ import java.util.List;
|
||||
public class PartnerSiteServiceImpl implements PartnerSiteService {
|
||||
@Autowired
|
||||
PartnerMapper partnerMapper;
|
||||
@Autowired
|
||||
MailService mailService;
|
||||
@Autowired
|
||||
RedisUtil redisUtil;
|
||||
private static final String SITE_NAME = "小海博客";
|
||||
private static final String SITE_URL = "celess.cn";
|
||||
private static final String SITE_EMAIL = "a@celess.cn";
|
||||
|
||||
@Override
|
||||
public PartnerSite create(LinkReq reqBody) {
|
||||
@@ -86,10 +105,21 @@ public class PartnerSiteServiceImpl implements PartnerSiteService {
|
||||
if (!reqBody.getUrl().contains("http://") && !reqBody.getUrl().contains("https://")) {
|
||||
reqBody.setUrl("http://" + reqBody.getUrl());
|
||||
}
|
||||
if (reqBody.isOpen() != partnerSite.getOpen() && !partnerSite.getNotification() && !StringUtils.isEmpty(partnerSite.getEmail())) {
|
||||
SimpleMailMessage smm = new SimpleMailMessage();
|
||||
smm.setTo(partnerSite.getEmail());
|
||||
smm.setText("您的友链申请,已通过");
|
||||
smm.setSubject("友链申请通过");
|
||||
smm.setSentDate(new Date());
|
||||
mailService.send(smm);
|
||||
partnerSite.setNotification(true);
|
||||
}
|
||||
BeanUtils.copyProperties(reqBody, partnerSite);
|
||||
partnerMapper.update(partnerSite);
|
||||
partnerSite.setName(reqBody.getName());
|
||||
partnerSite.setUrl(reqBody.getUrl());
|
||||
partnerSite.setOpen(reqBody.isOpen());
|
||||
partnerMapper.update(partnerSite);
|
||||
|
||||
return partnerSite;
|
||||
}
|
||||
|
||||
@@ -108,5 +138,92 @@ public class PartnerSiteServiceImpl implements PartnerSiteService {
|
||||
return all;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
@Override
|
||||
public PartnerSite apply(LinkApplyReq linkApplyReq) {
|
||||
// 空值字段
|
||||
if (StringUtils.isEmpty(linkApplyReq.getName())
|
||||
|| StringUtils.isEmpty(linkApplyReq.getUrl())
|
||||
|| StringUtils.isEmpty(linkApplyReq.getEmail())
|
||||
|| StringUtils.isEmpty(linkApplyReq.getLinkUrl())) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
// 链接不合法
|
||||
if (!RegexUtil.emailMatch(linkApplyReq.getEmail())) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR);
|
||||
}
|
||||
if (!RegexUtil.urlMatch(linkApplyReq.getLinkUrl()) || !RegexUtil.urlMatch(linkApplyReq.getUrl())) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR);
|
||||
}
|
||||
if (!StringUtils.isEmpty(linkApplyReq.getIconPath()) && !RegexUtil.urlMatch(linkApplyReq.getIconPath())) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR);
|
||||
}
|
||||
// 非强制字段 设置空
|
||||
if (StringUtils.isEmpty(linkApplyReq.getIconPath())) {
|
||||
linkApplyReq.setIconPath("");
|
||||
}
|
||||
// 抓取页面
|
||||
String resp = HttpUtil.getAfterRendering(linkApplyReq.getLinkUrl());
|
||||
if (resp == null) {
|
||||
throw new MyException(ResponseEnum.CANNOT_GET_DATA);
|
||||
}
|
||||
PartnerSite ps = new PartnerSite();
|
||||
if (resp.contains(SITE_URL)) {
|
||||
//包含站点
|
||||
BeanUtils.copyProperties(linkApplyReq, ps);
|
||||
ps.setNotification(false);
|
||||
ps.setOpen(false);
|
||||
boolean exists = partnerMapper.existsByUrl(linkApplyReq.getUrl());
|
||||
if (!exists) {
|
||||
partnerMapper.insert(ps);
|
||||
} else {
|
||||
ps.setId(partnerMapper.findByUrl(linkApplyReq.getUrl()).getId());
|
||||
}
|
||||
SimpleMailMessage smm = new SimpleMailMessage();
|
||||
smm.setSubject("友链申请");
|
||||
smm.setText("有一条友链申请" + (exists ? ",已存在的友链链接" : "") + ",[\n" + linkApplyReq.toString() + "\n]");
|
||||
smm.setTo(SITE_EMAIL);
|
||||
smm.setSentDate(new Date());
|
||||
mailService.send(smm);
|
||||
} else {
|
||||
// 不包含站点
|
||||
String uuid;
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
if (redisUtil.hasKey(linkApplyReq.getUrl())) {
|
||||
uuid = redisUtil.get(linkApplyReq.getUrl());
|
||||
if (!redisUtil.hasKey(uuid)) {
|
||||
redisUtil.setEx(uuid, mapper.writeValueAsString(linkApplyReq), 10, TimeUnit.MINUTES);
|
||||
}
|
||||
} else {
|
||||
uuid = UUID.randomUUID().toString().replaceAll("-", "");
|
||||
redisUtil.setEx(uuid, mapper.writeValueAsString(linkApplyReq), 10, TimeUnit.MINUTES);
|
||||
redisUtil.setEx(linkApplyReq.getUrl(), uuid, 10, TimeUnit.MINUTES);
|
||||
}
|
||||
throw new MyException(ResponseEnum.APPLY_LINK_NO_ADD_THIS_SITE, null, uuid);
|
||||
}
|
||||
return ps;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
@Override
|
||||
public String reapply(String key) {
|
||||
if (!redisUtil.hasKey(key)) {
|
||||
throw new MyException(ResponseEnum.DATA_EXPIRED);
|
||||
}
|
||||
String s = redisUtil.get(key);
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
LinkApplyReq linkApplyReq = mapper.readValue(s, LinkApplyReq.class);
|
||||
if (linkApplyReq == null) {
|
||||
throw new MyException(ResponseEnum.DATA_NOT_EXIST);
|
||||
}
|
||||
SimpleMailMessage smm = new SimpleMailMessage();
|
||||
smm.setSubject("友链申请");
|
||||
smm.setText("有一条未抓取到信息的友链申请,[\n" + linkApplyReq.toString() + "\n]");
|
||||
smm.setTo(SITE_EMAIL);
|
||||
smm.setSentDate(new Date());
|
||||
mailService.send(smm);
|
||||
redisUtil.delete(key);
|
||||
redisUtil.delete(linkApplyReq.getUrl());
|
||||
return "success";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,110 +1,111 @@
|
||||
package cn.celess.blog.service.serviceimpl;
|
||||
|
||||
import cn.celess.blog.enmu.ResponseEnum;
|
||||
import cn.celess.blog.entity.WebUpdate;
|
||||
import cn.celess.blog.entity.model.PageData;
|
||||
import cn.celess.blog.entity.model.WebUpdateModel;
|
||||
import cn.celess.blog.exception.MyException;
|
||||
import cn.celess.blog.mapper.WebUpdateInfoMapper;
|
||||
import cn.celess.blog.service.WebUpdateInfoService;
|
||||
import cn.celess.blog.util.DateFormatUtil;
|
||||
import cn.celess.blog.util.HttpUtil;
|
||||
import cn.celess.blog.util.ModalTrans;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @author : xiaohai
|
||||
* @date : 2019/05/12 11:43
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
|
||||
@Autowired
|
||||
WebUpdateInfoMapper webUpdateInfoMapper;
|
||||
|
||||
|
||||
@Override
|
||||
public WebUpdateModel create(String info) {
|
||||
if (info == null || info.replaceAll(" ", "").isEmpty()) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
WebUpdate webUpdate = new WebUpdate(info);
|
||||
if (webUpdateInfoMapper.insert(webUpdate) == 0) {
|
||||
throw new MyException(ResponseEnum.FAILURE);
|
||||
}
|
||||
return ModalTrans.webUpdate(webUpdateInfoMapper.findById(webUpdate.getId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean del(long id) {
|
||||
if (!webUpdateInfoMapper.existsById(id)) {
|
||||
throw new MyException(ResponseEnum.DATA_NOT_EXIST);
|
||||
}
|
||||
return webUpdateInfoMapper.delete(id) == 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebUpdateModel update(long id, String info) {
|
||||
WebUpdate webUpdate = webUpdateInfoMapper.findById(id);
|
||||
if (webUpdate == null) {
|
||||
throw new MyException(ResponseEnum.DATA_NOT_EXIST);
|
||||
}
|
||||
if (info == null || info.replaceAll(" ", "").isEmpty()) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
webUpdate.setUpdateInfo(info);
|
||||
webUpdateInfoMapper.update(id, info);
|
||||
return ModalTrans.webUpdate(webUpdate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageData<WebUpdateModel> pages(int count, int page) {
|
||||
PageHelper.startPage(page, count);
|
||||
List<WebUpdate> updateList = webUpdateInfoMapper.findAll();
|
||||
return new PageData<WebUpdateModel>(new PageInfo<WebUpdate>(updateList), list2List(updateList));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<WebUpdateModel> findAll() {
|
||||
List<WebUpdate> all = webUpdateInfoMapper.findAll();
|
||||
return list2List(all);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getLastestUpdateTime() {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("lastUpdateTime", DateFormatUtil.get(webUpdateInfoMapper.getLastestOne().getUpdateTime()));
|
||||
map.put("lastUpdateInfo", webUpdateInfoMapper.getLastestOne().getUpdateInfo());
|
||||
try {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode root = mapper.readTree(HttpUtil.get("https://api.github.com/repos/xiaohai2271/blog-frontEnd/commits?page=1&per_page=1"));
|
||||
Iterator<JsonNode> elements = root.elements();
|
||||
JsonNode next = elements.next();
|
||||
JsonNode commit = next.get("commit");
|
||||
map.put("lastCommit", commit.get("message"));
|
||||
map.put("committerAuthor", commit.get("committer").get("name"));
|
||||
Instant parse = Instant.parse(commit.get("committer").get("date").asText());
|
||||
map.put("committerDate", DateFormatUtil.get(Date.from(parse)));
|
||||
map.put("commitUrl", "https://github.com/xiaohai2271/blog-frontEnd/tree/" + next.get("sha").asText());
|
||||
} catch (IOException e) {
|
||||
log.info("网络请求失败{}", e.getMessage());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private List<WebUpdateModel> list2List(List<WebUpdate> webUpdates) {
|
||||
List<WebUpdateModel> webUpdateModels = new ArrayList<>();
|
||||
webUpdates.forEach(update -> webUpdateModels.add(ModalTrans.webUpdate(update)));
|
||||
return webUpdateModels;
|
||||
}
|
||||
}
|
||||
package cn.celess.blog.service.serviceimpl;
|
||||
|
||||
import cn.celess.blog.enmu.ResponseEnum;
|
||||
import cn.celess.blog.entity.WebUpdate;
|
||||
import cn.celess.blog.entity.model.PageData;
|
||||
import cn.celess.blog.entity.model.WebUpdateModel;
|
||||
import cn.celess.blog.exception.MyException;
|
||||
import cn.celess.blog.mapper.WebUpdateInfoMapper;
|
||||
import cn.celess.blog.service.WebUpdateInfoService;
|
||||
import cn.celess.blog.util.DateFormatUtil;
|
||||
import cn.celess.blog.util.HttpUtil;
|
||||
import cn.celess.blog.util.ModalTrans;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @author : xiaohai
|
||||
* @date : 2019/05/12 11:43
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
|
||||
@Autowired
|
||||
WebUpdateInfoMapper webUpdateInfoMapper;
|
||||
|
||||
|
||||
@Override
|
||||
public WebUpdateModel create(String info) {
|
||||
if (info == null || info.replaceAll(" ", "").isEmpty()) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
WebUpdate webUpdate = new WebUpdate(info);
|
||||
if (webUpdateInfoMapper.insert(webUpdate) == 0) {
|
||||
throw new MyException(ResponseEnum.FAILURE);
|
||||
}
|
||||
return ModalTrans.webUpdate(webUpdateInfoMapper.findById(webUpdate.getId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean del(long id) {
|
||||
if (!webUpdateInfoMapper.existsById(id)) {
|
||||
throw new MyException(ResponseEnum.DATA_NOT_EXIST);
|
||||
}
|
||||
return webUpdateInfoMapper.delete(id) == 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebUpdateModel update(long id, String info) {
|
||||
WebUpdate webUpdate = webUpdateInfoMapper.findById(id);
|
||||
if (webUpdate == null) {
|
||||
throw new MyException(ResponseEnum.DATA_NOT_EXIST);
|
||||
}
|
||||
if (info == null || info.replaceAll(" ", "").isEmpty()) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
webUpdate.setUpdateInfo(info);
|
||||
webUpdateInfoMapper.update(id, info);
|
||||
return ModalTrans.webUpdate(webUpdate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageData<WebUpdateModel> pages(int count, int page) {
|
||||
PageHelper.startPage(page, count);
|
||||
List<WebUpdate> updateList = webUpdateInfoMapper.findAll();
|
||||
return new PageData<WebUpdateModel>(new PageInfo<WebUpdate>(updateList), list2List(updateList));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<WebUpdateModel> findAll() {
|
||||
List<WebUpdate> all = webUpdateInfoMapper.findAll();
|
||||
return list2List(all);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
public Map<String, Object> getLastestUpdateTime() {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("lastUpdateTime", DateFormatUtil.get(webUpdateInfoMapper.getLastestOne().getUpdateTime()));
|
||||
map.put("lastUpdateInfo", webUpdateInfoMapper.getLastestOne().getUpdateInfo());
|
||||
try {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode root = mapper.readTree(HttpUtil.get("https://api.github.com/repos/xiaohai2271/blog-frontEnd/commits?page=1&per_page=1"));
|
||||
Iterator<JsonNode> elements = root.elements();
|
||||
JsonNode next = elements.next();
|
||||
JsonNode commit = next.get("commit");
|
||||
map.put("lastCommit", commit.get("message"));
|
||||
map.put("committerAuthor", commit.get("committer").get("name"));
|
||||
Instant parse = Instant.parse(commit.get("committer").get("date").asText());
|
||||
map.put("committerDate", DateFormatUtil.get(Date.from(parse)));
|
||||
map.put("commitUrl", "https://github.com/xiaohai2271/blog-frontEnd/tree/" + next.get("sha").asText());
|
||||
} catch (IOException e) {
|
||||
log.info("网络请求失败{}", e.getMessage());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private List<WebUpdateModel> list2List(List<WebUpdate> webUpdates) {
|
||||
List<WebUpdateModel> webUpdateModels = new ArrayList<>();
|
||||
webUpdates.forEach(update -> webUpdateModels.add(ModalTrans.webUpdate(update)));
|
||||
return webUpdateModels;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package cn.celess.blog.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import com.gargoylesoftware.htmlunit.BrowserVersion;
|
||||
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
|
||||
import com.gargoylesoftware.htmlunit.WebClient;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @Author: 小海
|
||||
@@ -14,38 +17,34 @@ import java.nio.charset.StandardCharsets;
|
||||
* @Desc:
|
||||
*/
|
||||
public class HttpUtil {
|
||||
private static final OkHttpClient CLIENT = new OkHttpClient();
|
||||
|
||||
public static String get(String urlStr) throws IOException {
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
HttpURLConnection urlConnection = null;
|
||||
try {
|
||||
URL url = new URL(urlStr);
|
||||
|
||||
//打开http
|
||||
urlConnection = (HttpURLConnection) url.openConnection();
|
||||
urlConnection.setDoInput(true);
|
||||
urlConnection.setRequestMethod("GET");
|
||||
urlConnection.connect();
|
||||
|
||||
try (
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
|
||||
) {
|
||||
//将bufferReader的值给放到buffer里
|
||||
String str = null;
|
||||
while ((str = bufferedReader.readLine()) != null) {
|
||||
sb.append(str);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
//断开连接
|
||||
if (urlConnection != null) {
|
||||
urlConnection.disconnect();
|
||||
}
|
||||
public static String get(String urlStr) {
|
||||
Request request = new Request.Builder()
|
||||
.url(urlStr)
|
||||
.get()
|
||||
.build();
|
||||
try (Response response = CLIENT.newCall(request).execute()) {
|
||||
return Objects.requireNonNull(response.body()).string();
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static String getAfterRendering(String url) {
|
||||
try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
|
||||
webClient.getOptions().setCssEnabled(false);
|
||||
webClient.getOptions().setJavaScriptEnabled(true);
|
||||
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
|
||||
webClient.getOptions().setThrowExceptionOnScriptError(false);
|
||||
webClient.getOptions().setDownloadImages(false);
|
||||
webClient.getOptions().setActiveXNative(false);
|
||||
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
|
||||
final HtmlPage page = webClient.getPage(url);
|
||||
return page.asXml();
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,12 @@ spring.datasource.url=
|
||||
spring.datasource.username=
|
||||
spring.datasource.password=
|
||||
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
|
||||
spring.datasource.platform=mysql
|
||||
# never / always / embedded
|
||||
spring.datasource.initialization-mode=never
|
||||
spring.datasource.sql-script-encoding=utf-8
|
||||
spring.datasource.schema=classpath:sql/schema.sql
|
||||
spring.datasource.data=classpath:sql/data.sql
|
||||
|
||||
|
||||
################## mybatis ##################
|
||||
|
||||
96
src/main/resources/application-test.properties
Normal file
96
src/main/resources/application-test.properties
Normal file
@@ -0,0 +1,96 @@
|
||||
server.port=8081
|
||||
|
||||
# 七牛的密钥配置
|
||||
qiniu.accessKey=
|
||||
qiniu.secretKey=
|
||||
qiniu.bucket=
|
||||
# sitemap 存放地址
|
||||
sitemap.path=
|
||||
# 生成JWT时候的密钥
|
||||
jwt.secret=sdaniod213k123123ipoeqowekqwe
|
||||
|
||||
##spring.jpa.show-sql=false
|
||||
##spring.jpa.hibernate.ddl-auto=update
|
||||
|
||||
mybatis.type-handlers-package=cn.celess.blog.mapper.typehandler
|
||||
logging.level.cn.celess.blog.mapper=debug
|
||||
# 上传单个文件的大小
|
||||
spring.servlet.multipart.max-file-size=10MB
|
||||
# 上传文件的总大小
|
||||
spring.servlet.multipart.max-request-size=10MB
|
||||
|
||||
spring.jackson.default-property-inclusion=non_null
|
||||
|
||||
|
||||
################# 数据库 ##################
|
||||
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
|
||||
|
||||
#h2
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.datasource.url=jdbc:h2:mem:testdb;mode=mysql;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
|
||||
|
||||
spring.datasource.platform=h2
|
||||
spring.datasource.sql-script-encoding=utf-8
|
||||
spring.datasource.initialization-mode=ALWAYS
|
||||
spring.datasource.schema=classpath:sql/schema_h2.sql
|
||||
spring.datasource.data=classpath:sql/data.sql
|
||||
|
||||
|
||||
################## mybatis ##################
|
||||
mybatis.mapper-locations=classpath:mapper/*.xml
|
||||
mybatis.type-aliases-package=cn.celess.blog.entity
|
||||
|
||||
|
||||
pagehelper.helper-dialect=mysql
|
||||
pagehelper.reasonable=true
|
||||
pagehelper.support-methods-arguments=true
|
||||
pagehelper.params=count=countSql
|
||||
|
||||
|
||||
|
||||
#### 用于nginx的代理 获取真实ip
|
||||
server.use-forward-headers = true
|
||||
server.tomcat.remote-ip-header = X-Real-IP
|
||||
server.tomcat.protocol-header = X-Forwarded-Proto
|
||||
|
||||
|
||||
############### email ##############
|
||||
spring.mail.host=smtp.163.com
|
||||
spring.mail.username=
|
||||
spring.mail.password=
|
||||
spring.mail.properties.mail.smtp.auth=true
|
||||
spring.mail.properties.mail.smtp.starttls.enable=true
|
||||
spring.mail.properties.mail.smtp.starttls.required=true
|
||||
spring.mail.default-encoding=UTF-8
|
||||
spring.mail.port=465
|
||||
spring.mail.properties.mail.smtp.socketFactory.port=465
|
||||
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
|
||||
spring.mail.properties.mail.smtp.socketFactory.fallback=false
|
||||
|
||||
|
||||
|
||||
############### redis ##############
|
||||
|
||||
# REDIS (RedisProperties)
|
||||
# Redis数据库索引(默认为0)
|
||||
spring.redis.database=1
|
||||
# Redis服务器地址
|
||||
spring.redis.host=127.0.0.1
|
||||
# Redis服务器连接端口 解决端口冲突 防止使用本地的redis
|
||||
spring.redis.port=6380
|
||||
# Redis服务器连接密码(默认为空)
|
||||
spring.redis.password=
|
||||
# 连接池最大连接数(使用负值表示没有限制)
|
||||
spring.redis.jedis.pool.max-active=-1
|
||||
# 连接池最大阻塞等待时间(使用负值表示没有限制)
|
||||
spring.redis.jedis.pool.max-wait=-1
|
||||
# 连接池中的最大空闲连接
|
||||
spring.redis.jedis.pool.max-idle=8
|
||||
# 连接池中的最小空闲连接
|
||||
spring.redis.jedis.pool.min-idle=0
|
||||
# 连接超时时间(毫秒)
|
||||
spring.redis.timeout=5000
|
||||
|
||||
@@ -9,20 +9,26 @@
|
||||
<result column="l_icon_path" property="iconPath"/>
|
||||
<result column="l_desc" property="desc"/>
|
||||
<result column="is_delete" property="delete"/>
|
||||
<result column="l_email" property="email"/>
|
||||
<result column="l_notification" property="notification"/>
|
||||
</resultMap>
|
||||
|
||||
<insert id="insert" parameterType="cn.celess.blog.entity.PartnerSite" useGeneratedKeys="true" keyProperty="id">
|
||||
insert into links (l_name, l_is_open, l_url, l_icon_path, l_desc, is_delete)
|
||||
values (#{name}, #{open}, #{url}, #{iconPath}, #{desc}, false)
|
||||
insert into links (l_name, l_is_open, l_url, l_icon_path, l_desc, l_email, l_notification, is_delete)
|
||||
values (#{name}, #{open}, #{url}, #{iconPath}, #{desc}, #{email}, #{notification}, false)
|
||||
</insert>
|
||||
|
||||
<update id="update" parameterType="cn.celess.blog.entity.PartnerSite">
|
||||
update links set
|
||||
<if test="open!=null">l_is_open=#{open},</if>
|
||||
<if test="iconPath!=null">l_icon_path=#{iconPath},</if>
|
||||
<if test="desc!=null">l_desc=#{desc},</if>
|
||||
<if test="url!=null">l_url=#{url},</if>
|
||||
<if test="name!=null">l_name=#{name}</if>
|
||||
update links
|
||||
<trim prefix="set" suffixOverrides=",">
|
||||
<if test="open!=null">l_is_open=#{open},</if>
|
||||
<if test="iconPath!=null">l_icon_path=#{iconPath},</if>
|
||||
<if test="desc!=null">l_desc=#{desc},</if>
|
||||
<if test="url!=null">l_url=#{url},</if>
|
||||
<if test="name!=null">l_name=#{name},</if>
|
||||
<if test="notification!=null">l_notification=#{notification},</if>
|
||||
<if test="email!=null">l_email=#{email}</if>
|
||||
</trim>
|
||||
where l_id=#{id}
|
||||
</update>
|
||||
|
||||
|
||||
204
src/main/resources/sql/data.sql
Normal file
204
src/main/resources/sql/data.sql
Normal file
File diff suppressed because one or more lines are too long
188
src/main/resources/sql/schema.sql
Normal file
188
src/main/resources/sql/schema.sql
Normal file
@@ -0,0 +1,188 @@
|
||||
drop view if exists articleView;
|
||||
drop view if exists commentView;
|
||||
drop table if exists article_tag;
|
||||
drop table if exists comment;
|
||||
drop table if exists article;
|
||||
drop table if exists user;
|
||||
drop table if exists tag_category;
|
||||
drop table if exists links;
|
||||
drop table if exists visitor;
|
||||
drop table if exists web_update;
|
||||
|
||||
|
||||
CREATE TABLE `user`
|
||||
(
|
||||
`u_id` int not null primary key auto_increment,
|
||||
`u_email` varchar(50) not null,
|
||||
`u_pwd` varchar(40) not null comment '密码',
|
||||
`u_email_status` boolean default false comment '邮箱验证状态',
|
||||
`u_avatar` varchar(255) default null comment '用户头像',
|
||||
`u_desc` tinytext COLLATE utf8mb4_unicode_ci default null comment '用户的描述',
|
||||
`u_recently_landed_time` datetime default null comment '最近的登录时间',
|
||||
`u_display_name` varchar(30) COLLATE utf8mb4_unicode_ci default null comment '展示的昵称',
|
||||
`u_role` varchar(40) not null default 'user' comment '权限组',
|
||||
`status` tinyint(1) not null default 0 comment '账户状态',
|
||||
unique key `uni_user_id` (`u_id`),
|
||||
unique key `uni_user_email` (`u_email`)
|
||||
) comment '用户表';
|
||||
|
||||
CREATE TABLE `tag_category`
|
||||
(
|
||||
`t_id` bigint(20) primary key auto_increment,
|
||||
`t_name` varchar(255) not null,
|
||||
`is_category` boolean not null default true,
|
||||
`is_delete` boolean not null default false comment '该数据是否被删除'
|
||||
) comment '标签和分类表';
|
||||
|
||||
CREATE TABLE `article`
|
||||
(
|
||||
`a_id` bigint(20) primary key auto_increment,
|
||||
`a_title` varchar(255) COLLATE utf8mb4_unicode_ci not null unique comment '文章标题',
|
||||
`a_summary` varchar(255) COLLATE utf8mb4_unicode_ci not null comment '文章摘要',
|
||||
`a_md_content` longtext COLLATE utf8mb4_unicode_ci not null comment '文章Markdown内容',
|
||||
`a_url` tinytext default null comment '转载文章的原文链接',
|
||||
`a_author_id` int not null comment '作者id',
|
||||
`a_is_original` boolean default true comment '文章是否原创',
|
||||
`a_reading_number` int default 0 comment '文章阅读数',
|
||||
`a_like` int default 0 comment '文章点赞数',
|
||||
`a_dislike` int default 0 comment '文章不喜欢数',
|
||||
`a_category_id` bigint not null comment '文章分类id',
|
||||
`a_publish_date` datetime default CURRENT_TIMESTAMP comment '文章发布时间',
|
||||
`a_update_date` datetime default null comment '文章的更新时间',
|
||||
`a_is_open` boolean default true comment '文章是否可见',
|
||||
`is_delete` boolean not null default false comment '该数据是否被删除',
|
||||
foreign key (a_category_id) references tag_category (t_id),
|
||||
foreign key (a_author_id) references user (u_id)
|
||||
) DEFAULT CHARSET = utf8mb4
|
||||
COLLATE utf8mb4_general_ci,comment '文章表';
|
||||
|
||||
CREATE TABLE `article_tag`
|
||||
(
|
||||
`at_id` bigint(20) primary key auto_increment,
|
||||
`a_id` bigint(20) not null comment '文章id',
|
||||
`t_id` bigint not null comment 'tag/category 的id',
|
||||
foreign key (a_id) references article (a_id),
|
||||
foreign key (t_id) references tag_category (t_id)
|
||||
) comment '文章标签表';
|
||||
|
||||
CREATE TABLE `comment`
|
||||
(
|
||||
`co_id` bigint(20) primary key auto_increment,
|
||||
`co_page_path` varchar(255) not null comment '评论/留言的页面',
|
||||
`co_content` text COLLATE utf8mb4_unicode_ci not null comment '评论/留言内容',
|
||||
`co_date` datetime not null comment '评论/留言的日期',
|
||||
`co_status` tinyint not null default 0 comment '评论的状态',
|
||||
`co_pid` bigint not null default -1 comment '评论/留言的父id',
|
||||
`co_from_author_id` int not null comment '留言者id',
|
||||
`co_to_author_id` int default null comment '父评论的作者id',
|
||||
foreign key (co_from_author_id) references user (u_id),
|
||||
foreign key (co_to_author_id) references user (u_id)
|
||||
) DEFAULT CHARSET = utf8mb4
|
||||
COLLATE utf8mb4_general_ci,comment '评论/留言表';
|
||||
|
||||
CREATE TABLE `links`
|
||||
(
|
||||
`l_id` bigint(20) primary key auto_increment,
|
||||
`l_name` varchar(255) COLLATE utf8mb4_unicode_ci not null comment '友站名称',
|
||||
`l_is_open` boolean default true comment '是否公开',
|
||||
`l_url` varchar(255) unique not null comment '首页地址',
|
||||
`l_icon_path` varchar(255) not null comment '友链的icon地址',
|
||||
`l_desc` varchar(255) COLLATE utf8mb4_unicode_ci not null comment '友链的说明描述',
|
||||
`is_delete` boolean not null default false comment '该数据是否被删除',
|
||||
`l_email` varchar(255) comment '网站管理员的邮箱',
|
||||
`l_notification` boolean default false comment '是否通知了'
|
||||
) comment '友站表';
|
||||
|
||||
CREATE TABLE `visitor`
|
||||
(
|
||||
`v_id` bigint(20) primary key auto_increment,
|
||||
`v_date` datetime not null comment '访问时间',
|
||||
`v_ip` varchar(255) not null comment '访客ip',
|
||||
`v_user_agent` text comment '访客ua',
|
||||
`is_delete` boolean not null default false comment '该数据是否被删除'
|
||||
) comment '访客表';
|
||||
|
||||
CREATE TABLE `web_update`
|
||||
(
|
||||
`wu_id` int primary key auto_increment,
|
||||
`wu_info` varchar(255) COLLATE utf8mb4_unicode_ci not null comment '更新内容',
|
||||
`wu_time` datetime not null comment '更新时间',
|
||||
`is_delete` boolean not null default false comment '该数据是否被删除'
|
||||
) comment '更新内容表';
|
||||
|
||||
CREATE VIEW articleView
|
||||
(articleId, title, summary, mdContent, url, isOriginal, readingCount, likeCount, dislikeCount,
|
||||
publishDate, updateDate, isOpen,
|
||||
categoryId, categoryName, tagId, tagName,
|
||||
authorId, userEmail, userAvatar, userDisplayName, isDelete)
|
||||
as
|
||||
select article.a_id as articleId,
|
||||
article.a_title as title,
|
||||
article.a_summary as summary,
|
||||
article.a_md_content as mdContent,
|
||||
article.a_url as url,
|
||||
article.a_is_original as isOriginal,
|
||||
article.a_reading_number as readingCount,
|
||||
article.a_like as likeCount,
|
||||
article.a_dislike as dislikeCount,
|
||||
article.a_publish_date as publishDate,
|
||||
article.a_update_date as updateDate,
|
||||
article.a_is_open as isOpen,
|
||||
category.t_id as categoryId,
|
||||
category.t_name as categoryName,
|
||||
tag.t_id as tagId,
|
||||
tag.t_name as tagName,
|
||||
user.u_id as authorId,
|
||||
user.u_email as userEmail,
|
||||
user.u_avatar as userAvatar,
|
||||
user.u_display_name as userDisplayName,
|
||||
article.is_delete as isDelete
|
||||
from article,
|
||||
tag_category as tag,
|
||||
tag_category as category,
|
||||
article_tag,
|
||||
user
|
||||
where article.a_id = article_tag.a_id
|
||||
and article_tag.t_id = tag.t_id
|
||||
and tag.is_category = false
|
||||
and article.a_category_id = category.t_id
|
||||
and category.is_category = true
|
||||
and article.a_author_id = user.u_id;
|
||||
|
||||
|
||||
CREATE VIEW commentView
|
||||
(commentId, pagePath, content, date, status, pid, toAuthorId, toAuthorEmail, toAuthorDisplayName,
|
||||
toAuthorAvatar, fromAuthorId, fromAuthorEmail, fromAuthorDisplayName,
|
||||
fromAuthorAvatar)
|
||||
as
|
||||
select cuT.co_id as commentId,
|
||||
cuT.co_page_path as pagePath,
|
||||
cuT.co_content as content,
|
||||
cuT.co_date as date,
|
||||
cuT.co_status as status,
|
||||
cuT.co_pid as pid,
|
||||
cuT.co_to_author_id as toAuthorId,
|
||||
cuT.toEmail as toAuthorEmail,
|
||||
cuT.toDisplayName as toAuthorDisplayName,
|
||||
cuT.toAvatar as toAuthorAvatar,
|
||||
userFrom.u_id as fromAuthorId,
|
||||
userFrom.u_email as fromAuthorEmail,
|
||||
userFrom.u_display_name as fromAuthorDisplayName,
|
||||
userFrom.u_avatar as fromAuthorAvatar
|
||||
from (select comment.co_id,
|
||||
comment.co_page_path,
|
||||
comment.co_content,
|
||||
comment.co_date,
|
||||
comment.co_status,
|
||||
comment.co_pid,
|
||||
comment.co_from_author_id,
|
||||
comment.co_to_author_id,
|
||||
userTo.u_email as toEmail,
|
||||
userTo.u_display_name as toDisplayName,
|
||||
userTo.u_avatar as toAvatar
|
||||
from comment
|
||||
left join user userTo on (comment.co_to_author_id = userTo.u_id)
|
||||
) as cuT,
|
||||
user as userFrom
|
||||
where cuT.co_from_author_id = userFrom.u_id;
|
||||
|
||||
193
src/main/resources/sql/schema_h2.sql
Normal file
193
src/main/resources/sql/schema_h2.sql
Normal file
@@ -0,0 +1,193 @@
|
||||
drop view if exists articleView;
|
||||
drop view if exists commentView;
|
||||
drop table if exists article_tag;
|
||||
drop table if exists comment;
|
||||
drop table if exists article;
|
||||
drop table if exists user;
|
||||
drop table if exists tag_category;
|
||||
drop table if exists links;
|
||||
drop table if exists visitor;
|
||||
drop table if exists web_update;
|
||||
|
||||
-- 用户表
|
||||
CREATE TABLE `user`
|
||||
(
|
||||
`u_id` int not null primary key auto_increment,
|
||||
`u_email` varchar(50) not null,
|
||||
`u_pwd` varchar(40) not null comment '密码',
|
||||
`u_email_status` boolean default false comment '邮箱验证状态',
|
||||
`u_avatar` varchar(255) default null comment '用户头像',
|
||||
`u_desc` tinytext default null comment '用户的描述',
|
||||
`u_recently_landed_time` datetime default null comment '最近的登录时间',
|
||||
`u_display_name` varchar(30) default null comment '展示的昵称',
|
||||
`u_role` varchar(40) not null default 'user' comment '权限组',
|
||||
`status` tinyint(1) not null default 0 comment '账户状态',
|
||||
unique key `uni_user_id` (`u_id`),
|
||||
unique key `uni_user_email` (`u_email`)
|
||||
);
|
||||
|
||||
-- 标签和分类表
|
||||
CREATE TABLE `tag_category`
|
||||
(
|
||||
`t_id` bigint(20) primary key auto_increment,
|
||||
`t_name` varchar(255) not null,
|
||||
`is_category` boolean not null default true,
|
||||
`is_delete` boolean not null default false comment '该数据是否被删除'
|
||||
);
|
||||
|
||||
-- 文章表
|
||||
CREATE TABLE `article`
|
||||
(
|
||||
`a_id` bigint(20) primary key auto_increment,
|
||||
`a_title` varchar(255) not null unique comment '文章标题',
|
||||
`a_summary` varchar(255) not null comment '文章摘要',
|
||||
`a_md_content` longtext not null comment '文章Markdown内容',
|
||||
`a_url` tinytext default null comment '转载文章的原文链接',
|
||||
`a_author_id` int not null comment '作者id',
|
||||
`a_is_original` boolean default true comment '文章是否原创',
|
||||
`a_reading_number` int default 0 comment '文章阅读数',
|
||||
`a_like` int default 0 comment '文章点赞数',
|
||||
`a_dislike` int default 0 comment '文章不喜欢数',
|
||||
`a_category_id` bigint not null comment '文章分类id',
|
||||
`a_publish_date` datetime default CURRENT_TIMESTAMP comment '文章发布时间',
|
||||
`a_update_date` datetime default null comment '文章的更新时间',
|
||||
`a_is_open` boolean default true comment '文章是否可见',
|
||||
`is_delete` boolean not null default false comment '该数据是否被删除',
|
||||
foreign key (a_category_id) references tag_category (t_id),
|
||||
foreign key (a_author_id) references user (u_id)
|
||||
);
|
||||
|
||||
-- 文章标签表
|
||||
CREATE TABLE `article_tag`
|
||||
(
|
||||
`at_id` bigint(20) primary key auto_increment,
|
||||
`a_id` bigint(20) not null comment '文章id',
|
||||
`t_id` bigint not null comment 'tag/category 的id',
|
||||
foreign key (a_id) references article (a_id),
|
||||
foreign key (t_id) references tag_category (t_id)
|
||||
);
|
||||
|
||||
-- 评论/留言表
|
||||
CREATE TABLE `comment`
|
||||
(
|
||||
`co_id` bigint(20) primary key auto_increment,
|
||||
`co_page_path` varchar(255) not null comment '评论/留言的页面',
|
||||
`co_content` text not null comment '评论/留言内容',
|
||||
`co_date` datetime not null comment '评论/留言的日期',
|
||||
`co_status` tinyint not null default 0 comment '评论的状态',
|
||||
`co_pid` bigint not null default -1 comment '评论/留言的父id',
|
||||
`co_from_author_id` int not null comment '留言者id',
|
||||
`co_to_author_id` int default null comment '父评论的作者id',
|
||||
foreign key (co_from_author_id) references user (u_id),
|
||||
foreign key (co_to_author_id) references user (u_id)
|
||||
);
|
||||
|
||||
-- 友站表
|
||||
CREATE TABLE `links`
|
||||
(
|
||||
`l_id` bigint(20) primary key auto_increment,
|
||||
`l_name` varchar(255) not null comment '友站名称',
|
||||
`l_is_open` boolean default true comment '是否公开',
|
||||
`l_url` varchar(255) unique not null comment '首页地址',
|
||||
`l_icon_path` varchar(255) not null comment '友链的icon地址',
|
||||
`l_desc` varchar(255) not null comment '友链的说明描述',
|
||||
`is_delete` boolean not null default false comment '该数据是否被删除',
|
||||
`l_email` varchar(255) comment '网站管理员的邮箱',
|
||||
`l_notification` boolean default false comment '是否通知了'
|
||||
);
|
||||
|
||||
-- 访客表
|
||||
CREATE TABLE `visitor`
|
||||
(
|
||||
`v_id` bigint(20) primary key auto_increment,
|
||||
`v_date` datetime not null comment '访问时间',
|
||||
`v_ip` varchar(255) not null comment '访客ip',
|
||||
`v_user_agent` text comment '访客ua',
|
||||
`is_delete` boolean not null default false comment '该数据是否被删除'
|
||||
);
|
||||
|
||||
-- 更新内容表
|
||||
CREATE TABLE `web_update`
|
||||
(
|
||||
`wu_id` int primary key auto_increment,
|
||||
`wu_info` varchar(255) not null comment '更新内容',
|
||||
`wu_time` datetime not null comment '更新时间',
|
||||
`is_delete` boolean not null default false comment '该数据是否被删除'
|
||||
);
|
||||
|
||||
CREATE VIEW articleView
|
||||
(articleId, title, summary, mdContent, url, isOriginal, readingCount, likeCount, dislikeCount,
|
||||
publishDate, updateDate, isOpen,
|
||||
categoryId, categoryName, tagId, tagName,
|
||||
authorId, userEmail, userAvatar, userDisplayName, isDelete)
|
||||
as
|
||||
select article.a_id as articleId,
|
||||
article.a_title as title,
|
||||
article.a_summary as summary,
|
||||
article.a_md_content as mdContent,
|
||||
article.a_url as url,
|
||||
article.a_is_original as isOriginal,
|
||||
article.a_reading_number as readingCount,
|
||||
article.a_like as likeCount,
|
||||
article.a_dislike as dislikeCount,
|
||||
article.a_publish_date as publishDate,
|
||||
article.a_update_date as updateDate,
|
||||
article.a_is_open as isOpen,
|
||||
category.t_id as categoryId,
|
||||
category.t_name as categoryName,
|
||||
tag.t_id as tagId,
|
||||
tag.t_name as tagName,
|
||||
user.u_id as authorId,
|
||||
user.u_email as userEmail,
|
||||
user.u_avatar as userAvatar,
|
||||
user.u_display_name as userDisplayName,
|
||||
article.is_delete as isDelete
|
||||
from article,
|
||||
tag_category as tag,
|
||||
tag_category as category,
|
||||
article_tag,
|
||||
user
|
||||
where article.a_id = article_tag.a_id
|
||||
and article_tag.t_id = tag.t_id
|
||||
and tag.is_category = false
|
||||
and article.a_category_id = category.t_id
|
||||
and category.is_category = true
|
||||
and article.a_author_id = user.u_id;
|
||||
|
||||
|
||||
CREATE VIEW commentView
|
||||
(commentId, pagePath, content, date, status, pid, toAuthorId, toAuthorEmail, toAuthorDisplayName,
|
||||
toAuthorAvatar, fromAuthorId, fromAuthorEmail, fromAuthorDisplayName,
|
||||
fromAuthorAvatar)
|
||||
as
|
||||
select cuT.co_id as commentId,
|
||||
cuT.co_page_path as pagePath,
|
||||
cuT.co_content as content,
|
||||
cuT.co_date as date,
|
||||
cuT.co_status as status,
|
||||
cuT.co_pid as pid,
|
||||
cuT.co_to_author_id as toAuthorId,
|
||||
cuT.toEmail as toAuthorEmail,
|
||||
cuT.toDisplayName as toAuthorDisplayName,
|
||||
cuT.toAvatar as toAuthorAvatar,
|
||||
userFrom.u_id as fromAuthorId,
|
||||
userFrom.u_email as fromAuthorEmail,
|
||||
userFrom.u_display_name as fromAuthorDisplayName,
|
||||
userFrom.u_avatar as fromAuthorAvatar
|
||||
from (select comment.co_id,
|
||||
comment.co_page_path,
|
||||
comment.co_content,
|
||||
comment.co_date,
|
||||
comment.co_status,
|
||||
comment.co_pid,
|
||||
comment.co_from_author_id,
|
||||
comment.co_to_author_id,
|
||||
userTo.u_email as toEmail,
|
||||
userTo.u_display_name as toDisplayName,
|
||||
userTo.u_avatar as toAvatar
|
||||
from comment
|
||||
left join user userTo on (comment.co_to_author_id = userTo.u_id)
|
||||
) as cuT,
|
||||
user as userFrom
|
||||
where cuT.co_from_author_id = userFrom.u_id;
|
||||
|
||||
@@ -1,263 +1,345 @@
|
||||
package cn.celess.blog;
|
||||
|
||||
|
||||
import cn.celess.blog.entity.Response;
|
||||
import cn.celess.blog.entity.model.UserModel;
|
||||
import cn.celess.blog.entity.request.LoginReq;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockHttpSession;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.UUID;
|
||||
|
||||
import static cn.celess.blog.enmu.ResponseEnum.SUCCESS;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* @Author: 小海
|
||||
* @Date: 2019/08/22 12:46
|
||||
* @Description: 测试基类
|
||||
*/
|
||||
@SpringBootTest
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ActiveProfiles("test")
|
||||
public class BaseTest {
|
||||
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
protected MockMvc mockMvc;
|
||||
protected final static String Code = "code";
|
||||
protected final static String Result = "result";
|
||||
protected final static String USERE_MAIL = "zh56462271@qq.com";
|
||||
protected final static String ADMIN_EMAIL = "a@celess.cn";
|
||||
/**
|
||||
* jackson 序列化/反序列化Json
|
||||
*/
|
||||
protected final ObjectMapper mapper = new ObjectMapper();
|
||||
protected static final TypeReference<?> BOOLEAN_TYPE = new TypeReference<Response<Boolean>>() {
|
||||
};
|
||||
protected static final TypeReference<?> STRING_TYPE = new TypeReference<Response<String>>() {
|
||||
};
|
||||
protected static final TypeReference<?> OBJECT_TYPE = new TypeReference<Response<Object>>() {
|
||||
};
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
protected MockHttpSession session;
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||
session = new MockHttpSession();
|
||||
System.out.println("==========> 开始测试 <=========");
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() {
|
||||
System.out.println("==========> 测试结束 <=========");
|
||||
}
|
||||
|
||||
/**
|
||||
* admin 权限用户登录
|
||||
*
|
||||
* @return token
|
||||
*/
|
||||
protected String adminLogin() {
|
||||
LoginReq req = new LoginReq();
|
||||
req.setEmail(ADMIN_EMAIL);
|
||||
req.setPassword("123456789");
|
||||
req.setIsRememberMe(true);
|
||||
String token = login(req);
|
||||
assertNotNull(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* user 权限用户登录
|
||||
*
|
||||
* @return token
|
||||
*/
|
||||
protected String userLogin() {
|
||||
LoginReq req = new LoginReq();
|
||||
req.setEmail(USERE_MAIL);
|
||||
req.setPassword("123456789");
|
||||
req.setIsRememberMe(true);
|
||||
String token = login(req);
|
||||
assertNotNull(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录逻辑
|
||||
*
|
||||
* @param req 用户信息
|
||||
* @return token | null
|
||||
*/
|
||||
protected String login(LoginReq req) {
|
||||
String str = null;
|
||||
try {
|
||||
str = getMockData(post("/login"), null, req)
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
Response<UserModel> response = mapper.readValue(str, new TypeReference<Response<UserModel>>() {
|
||||
});
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
String token = response.getResult().getToken();
|
||||
assertNotNull(token);
|
||||
return token;
|
||||
} catch (Exception e) {
|
||||
logger.error("测试登录错误");
|
||||
e.printStackTrace();
|
||||
}
|
||||
assertNotNull(str);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
// 测试登录
|
||||
assertNotNull(userLogin());
|
||||
assertNotNull(adminLogin());
|
||||
assertNotEquals(userLogin(), adminLogin());
|
||||
try {
|
||||
// 测试getMockData方法
|
||||
assertNotNull(getMockData(get("/headerInfo")));
|
||||
getMockData((get("/headerInfo"))).andDo(result -> assertNotNull(getResponse(result, OBJECT_TYPE)));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 产生指定长度的随机字符
|
||||
*
|
||||
* @param len len
|
||||
* @return str
|
||||
*/
|
||||
protected String randomStr(int len) {
|
||||
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
|
||||
}
|
||||
|
||||
/**
|
||||
* 产生指定长度的随机字符
|
||||
*
|
||||
* @return str
|
||||
*/
|
||||
protected String randomStr() {
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 抽离的mock请求方法
|
||||
*
|
||||
* @param builder MockHttpServletRequestBuilder :get(...) post(...) ....
|
||||
* @return 返回 ResultActions
|
||||
* @throws Exception exc
|
||||
*/
|
||||
protected ResultActions getMockData(MockHttpServletRequestBuilder builder) throws Exception {
|
||||
return getMockData(builder, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 抽离的mock请求方法 重载
|
||||
*
|
||||
* @param builder ..
|
||||
* @param token 用户登录的token
|
||||
* @return ..
|
||||
* @throws Exception ..
|
||||
*/
|
||||
protected ResultActions getMockData(MockHttpServletRequestBuilder builder, String token) throws Exception {
|
||||
return getMockData(builder, token, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 抽离的mock请求方法 重载
|
||||
*
|
||||
* @param builder ..
|
||||
* @param token ..
|
||||
* @param content http中发送的APPLICATION_JSON的json数据
|
||||
* @return ..
|
||||
* @throws Exception ..
|
||||
*/
|
||||
protected ResultActions getMockData(MockHttpServletRequestBuilder builder, String token, Object content) throws Exception {
|
||||
// MockHttpServletRequestBuilder mockHttpServletRequestBuilder = get(url);
|
||||
if (token != null) {
|
||||
builder.header("Authorization", token);
|
||||
}
|
||||
if (content != null) {
|
||||
builder.content(mapper.writeValueAsString(content)).contentType(MediaType.APPLICATION_JSON);
|
||||
logger.debug("param::json->{}", mapper.writeValueAsString(content));
|
||||
}
|
||||
return mockMvc.perform(builder).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
|
||||
protected <T> Response<T> getResponse(String json) {
|
||||
return getResponse(json, OBJECT_TYPE);
|
||||
}
|
||||
|
||||
protected <T> Response<T> getResponse(MvcResult result) {
|
||||
return getResponse(result, OBJECT_TYPE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据json 信息反序列化成Response对象
|
||||
*
|
||||
* @param json json
|
||||
* @param <T> 泛型
|
||||
* @return Response对象
|
||||
*/
|
||||
protected <T> Response<T> getResponse(String json, TypeReference<?> responseType) {
|
||||
Response<T> response = null;
|
||||
try {
|
||||
response = mapper.readValue(json, responseType);
|
||||
} catch (IOException e) {
|
||||
logger.error("解析json Response对象错误,json:[{}]", json);
|
||||
e.printStackTrace();
|
||||
}
|
||||
assertNotNull(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据json 信息反序列化成Response对象
|
||||
*
|
||||
* @param result MvcResult
|
||||
* @param <T> 泛型
|
||||
* @return Response对象
|
||||
*/
|
||||
protected <T> Response<T> getResponse(MvcResult result, TypeReference<?> responseType) {
|
||||
try {
|
||||
return getResponse(result.getResponse().getContentAsString(), responseType);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
logger.error("解析json Response对象错误,result:[{}]", result);
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
package cn.celess.blog;
|
||||
|
||||
|
||||
import cn.celess.blog.entity.Response;
|
||||
import cn.celess.blog.entity.model.QiniuResponse;
|
||||
import cn.celess.blog.entity.model.UserModel;
|
||||
import cn.celess.blog.entity.request.LoginReq;
|
||||
import cn.celess.blog.service.MailService;
|
||||
import cn.celess.blog.service.QiniuService;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.qiniu.storage.model.FileInfo;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mock.web.MockHttpSession;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static cn.celess.blog.enmu.ResponseEnum.SUCCESS;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* @Author: 小海
|
||||
* @Date: 2019/08/22 12:46
|
||||
* @Description: 测试基类
|
||||
*/
|
||||
@SpringBootTest
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ActiveProfiles("test")
|
||||
public class BaseTest {
|
||||
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
protected MockMvc mockMvc;
|
||||
protected final static String Code = "code";
|
||||
protected final static String Result = "result";
|
||||
|
||||
/**
|
||||
* jackson 序列化/反序列化Json
|
||||
*/
|
||||
protected final ObjectMapper mapper = new ObjectMapper();
|
||||
protected static final TypeReference<?> BOOLEAN_TYPE = new TypeReference<Response<Boolean>>() {
|
||||
};
|
||||
protected static final TypeReference<?> STRING_TYPE = new TypeReference<Response<String>>() {
|
||||
};
|
||||
protected static final TypeReference<?> OBJECT_TYPE = new TypeReference<Response<Object>>() {
|
||||
};
|
||||
protected static final TypeReference<?> MAP_OBJECT_TYPE = new TypeReference<Response<Map<String, Object>>>() {
|
||||
};
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
protected MockHttpSession session;
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||
session = new MockHttpSession();
|
||||
System.out.println("==========> 开始测试 <=========");
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() {
|
||||
System.out.println("==========> 测试结束 <=========");
|
||||
}
|
||||
|
||||
/**
|
||||
* admin 权限用户登录
|
||||
*
|
||||
* @return token
|
||||
*/
|
||||
protected String adminLogin() {
|
||||
LoginReq req = new LoginReq();
|
||||
req.setEmail(ADMIN_EMAIL);
|
||||
req.setPassword("123456789");
|
||||
req.setIsRememberMe(true);
|
||||
String token = login(req);
|
||||
assertNotNull(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* user 权限用户登录
|
||||
*
|
||||
* @return token
|
||||
*/
|
||||
protected String userLogin() {
|
||||
LoginReq req = new LoginReq();
|
||||
req.setEmail(USERE_MAIL);
|
||||
req.setPassword("123456789");
|
||||
req.setIsRememberMe(true);
|
||||
String token = login(req);
|
||||
assertNotNull(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录逻辑
|
||||
*
|
||||
* @param req 用户信息
|
||||
* @return token | null
|
||||
*/
|
||||
protected String login(LoginReq req) {
|
||||
String str = null;
|
||||
try {
|
||||
str = getMockData(post("/login"), null, req)
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
Response<UserModel> response = mapper.readValue(str, new TypeReference<Response<UserModel>>() {
|
||||
});
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
String token = response.getResult().getToken();
|
||||
assertNotNull(token);
|
||||
return token;
|
||||
} catch (Exception e) {
|
||||
logger.error("测试登录错误");
|
||||
e.printStackTrace();
|
||||
}
|
||||
assertNotNull(str);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
// 测试登录
|
||||
assertNotNull(userLogin());
|
||||
assertNotNull(adminLogin());
|
||||
assertNotEquals(userLogin(), adminLogin());
|
||||
try {
|
||||
// 测试getMockData方法
|
||||
assertNotNull(getMockData(get("/headerInfo")));
|
||||
getMockData((get("/headerInfo"))).andDo(result -> assertNotNull(getResponse(result, OBJECT_TYPE)));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 产生指定长度的随机字符
|
||||
*
|
||||
* @param len len
|
||||
* @return str
|
||||
*/
|
||||
protected String randomStr(int len) {
|
||||
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
|
||||
}
|
||||
|
||||
/**
|
||||
* 产生指定长度的随机字符
|
||||
*
|
||||
* @return str
|
||||
*/
|
||||
protected String randomStr() {
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 抽离的mock请求方法
|
||||
*
|
||||
* @param builder MockHttpServletRequestBuilder :get(...) post(...) ....
|
||||
* @return 返回 ResultActions
|
||||
* @throws Exception exc
|
||||
*/
|
||||
protected ResultActions getMockData(MockHttpServletRequestBuilder builder) throws Exception {
|
||||
return getMockData(builder, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 抽离的mock请求方法 重载
|
||||
*
|
||||
* @param builder ..
|
||||
* @param token 用户登录的token
|
||||
* @return ..
|
||||
* @throws Exception ..
|
||||
*/
|
||||
protected ResultActions getMockData(MockHttpServletRequestBuilder builder, String token) throws Exception {
|
||||
return getMockData(builder, token, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 抽离的mock请求方法 重载
|
||||
*
|
||||
* @param builder ..
|
||||
* @param token ..
|
||||
* @param content http中发送的APPLICATION_JSON的json数据
|
||||
* @return ..
|
||||
* @throws Exception ..
|
||||
*/
|
||||
protected ResultActions getMockData(MockHttpServletRequestBuilder builder, String token, Object content) throws Exception {
|
||||
// MockHttpServletRequestBuilder mockHttpServletRequestBuilder = get(url);
|
||||
if (token != null) {
|
||||
builder.header("Authorization", token);
|
||||
}
|
||||
if (content != null) {
|
||||
builder.content(mapper.writeValueAsString(content)).contentType(MediaType.APPLICATION_JSON);
|
||||
logger.debug("param::json->{}", mapper.writeValueAsString(content));
|
||||
}
|
||||
return mockMvc.perform(builder).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
|
||||
protected <T> Response<T> getResponse(String json) {
|
||||
return getResponse(json, OBJECT_TYPE);
|
||||
}
|
||||
|
||||
protected <T> Response<T> getResponse(MvcResult result) {
|
||||
return getResponse(result, OBJECT_TYPE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据json 信息反序列化成Response对象
|
||||
*
|
||||
* @param json json
|
||||
* @param <T> 泛型
|
||||
* @return Response对象
|
||||
*/
|
||||
protected <T> Response<T> getResponse(String json, TypeReference<?> responseType) {
|
||||
Response<T> response = null;
|
||||
try {
|
||||
response = mapper.readValue(json, responseType);
|
||||
} catch (IOException e) {
|
||||
logger.error("解析json Response对象错误,json:[{}]", json);
|
||||
e.printStackTrace();
|
||||
}
|
||||
assertNotNull(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据json 信息反序列化成Response对象
|
||||
*
|
||||
* @param result MvcResult
|
||||
* @param <T> 泛型
|
||||
* @return Response对象
|
||||
*/
|
||||
protected <T> Response<T> getResponse(MvcResult result, TypeReference<?> responseType) {
|
||||
try {
|
||||
return getResponse(result.getResponse().getContentAsString(), responseType);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
logger.error("解析json Response对象错误,result:[{}]", result);
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 修改 mailService 的实现类
|
||||
*
|
||||
* @param service service 类
|
||||
* @param mailFiledName service 中自动注入的mailService字段名
|
||||
*/
|
||||
protected void mockInjectInstance(Object service, String mailFiledName, Object impl) {
|
||||
Field field;
|
||||
try {
|
||||
field = service.getClass().getDeclaredField(mailFiledName);
|
||||
field.setAccessible(true);
|
||||
field.set(service, impl);
|
||||
} catch (NoSuchFieldException | IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Slf4j
|
||||
public static class TestMailServiceImpl implements MailService {
|
||||
|
||||
@Override
|
||||
public Boolean AsyncSend(SimpleMailMessage message) {
|
||||
log.debug("异步邮件请求,SimpleMailMessage:[{}]", getJson(message));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean send(SimpleMailMessage message) {
|
||||
log.debug("邮件请求,SimpleMailMessage:[{}]", getJson(message));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转json
|
||||
*
|
||||
* @param o
|
||||
* @return
|
||||
*/
|
||||
private String getJson(Object o) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
try {
|
||||
return mapper.writeValueAsString(o);
|
||||
} catch (JsonProcessingException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Slf4j
|
||||
public static class TestQiNiuServiceImpl implements QiniuService {
|
||||
@Override
|
||||
public QiniuResponse uploadFile(InputStream is, String fileName) {
|
||||
QiniuResponse response = new QiniuResponse();
|
||||
log.debug("上传文件请求,[fileName:{}]", fileName);
|
||||
|
||||
response.key = "key";
|
||||
response.bucket = "bucket";
|
||||
response.hash = "hash";
|
||||
response.fsize = 1;
|
||||
return response;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileInfo[] getFileList() {
|
||||
log.debug("获取文件列表请求");
|
||||
return new FileInfo[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
37
src/test/java/cn/celess/blog/RedisServerMock.java
Normal file
37
src/test/java/cn/celess/blog/RedisServerMock.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package cn.celess.blog;
|
||||
|
||||
import redis.embedded.RedisServer;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author : xiaohai
|
||||
* @date : 2020/08/14 16:20
|
||||
*/
|
||||
@Component
|
||||
public class RedisServerMock {
|
||||
|
||||
private RedisServer redisServer;
|
||||
|
||||
/**
|
||||
* 构造方法之后执行.
|
||||
*
|
||||
* @throws IOException e
|
||||
*/
|
||||
@PostConstruct
|
||||
public void startRedis() throws IOException {
|
||||
redisServer = new RedisServer(6380);
|
||||
redisServer.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* 析构方法之后执行.
|
||||
*/
|
||||
@PreDestroy
|
||||
public void stopRedis() {
|
||||
redisServer.stop();
|
||||
}
|
||||
}
|
||||
@@ -1,162 +1,249 @@
|
||||
package cn.celess.blog.controller;
|
||||
|
||||
import cn.celess.blog.BaseTest;
|
||||
import cn.celess.blog.entity.PartnerSite;
|
||||
import cn.celess.blog.entity.Response;
|
||||
import cn.celess.blog.entity.model.PageData;
|
||||
import cn.celess.blog.entity.request.LinkReq;
|
||||
import cn.celess.blog.mapper.PartnerMapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static cn.celess.blog.enmu.ResponseEnum.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
|
||||
public class LinksControllerTest extends BaseTest {
|
||||
|
||||
@Autowired
|
||||
PartnerMapper mapper;
|
||||
private static final TypeReference<?> LINK_MODEL_TYPE = new TypeReference<Response<PartnerSite>>() {
|
||||
};
|
||||
private static final TypeReference<?> LINK_MODEL_LIST_TYPE = new TypeReference<Response<List<PartnerSite>>>() {
|
||||
};
|
||||
private static final TypeReference<?> LINK_MODEL_PAGE_TYPE = new TypeReference<Response<PageData<PartnerSite>>>() {
|
||||
};
|
||||
|
||||
@Test
|
||||
public void create() throws Exception {
|
||||
LinkReq linkReq = new LinkReq();
|
||||
linkReq.setName(randomStr(4));
|
||||
linkReq.setOpen(false);
|
||||
linkReq.setUrl("https://" + randomStr(4) + "example.com");
|
||||
getMockData(post("/admin/links/create"), adminLogin(), linkReq).andDo(result -> {
|
||||
Response<PartnerSite> response = getResponse(result, LINK_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
PartnerSite site = response.getResult();
|
||||
assertNotNull(site.getId());
|
||||
assertEquals(linkReq.getName(), site.getName());
|
||||
assertEquals(linkReq.getUrl(), site.getUrl());
|
||||
assertEquals(linkReq.isOpen(), site.getOpen());
|
||||
});
|
||||
|
||||
// https/http
|
||||
linkReq.setName(randomStr(4));
|
||||
linkReq.setOpen(false);
|
||||
linkReq.setUrl(randomStr(4) + ".example.com");
|
||||
getMockData(post("/admin/links/create"), adminLogin(), linkReq).andDo(result -> {
|
||||
Response<PartnerSite> response = getResponse(result, LINK_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
PartnerSite site = response.getResult();
|
||||
assertEquals("http://" + linkReq.getUrl(), site.getUrl());
|
||||
});
|
||||
|
||||
// 测试已存在的数据
|
||||
getMockData(post("/admin/links/create"), adminLogin(), linkReq).andDo(result ->
|
||||
assertEquals(DATA_HAS_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void del() throws Exception {
|
||||
PartnerSite partnerSite = new PartnerSite();
|
||||
partnerSite.setName(randomStr(4));
|
||||
partnerSite.setOpen(true);
|
||||
partnerSite.setDesc("");
|
||||
partnerSite.setIconPath("");
|
||||
partnerSite.setUrl("https://" + randomStr(4) + ".celess.cn");
|
||||
mapper.insert(partnerSite);
|
||||
PartnerSite latest = mapper.getLastest();
|
||||
assertNotNull(latest.getId());
|
||||
getMockData(delete("/admin/links/del/" + latest.getId()), adminLogin()).andDo(result -> {
|
||||
Response<Boolean> response = getResponse(result, BOOLEAN_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
assertTrue(response.getResult());
|
||||
});
|
||||
long id = latest.getId();
|
||||
do {
|
||||
id += 1;
|
||||
} while (mapper.existsById(id));
|
||||
System.out.println("删除ID=" + id + "的数据");
|
||||
getMockData(delete("/admin/links/del/" + id), adminLogin()).andDo(result ->
|
||||
assertEquals(DATA_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void update() throws Exception {
|
||||
// 增数据
|
||||
PartnerSite partnerSite = new PartnerSite();
|
||||
partnerSite.setName(randomStr(4));
|
||||
partnerSite.setOpen(true);
|
||||
partnerSite.setDesc("");
|
||||
partnerSite.setIconPath("");
|
||||
partnerSite.setDelete(false);
|
||||
partnerSite.setUrl("https://" + randomStr(5) + ".celess.cn");
|
||||
mapper.insert(partnerSite);
|
||||
// 查数据
|
||||
PartnerSite latest = mapper.getLastest();
|
||||
assertNotNull(latest.getId());
|
||||
// 构建请求
|
||||
LinkReq linkReq = new LinkReq();
|
||||
linkReq.setUrl(latest.getUrl());
|
||||
linkReq.setOpen(!latest.getOpen());
|
||||
linkReq.setName(randomStr(4));
|
||||
linkReq.setId(latest.getId());
|
||||
|
||||
getMockData(put("/admin/links/update"), adminLogin(), linkReq).andDo(result -> {
|
||||
Response<PartnerSite> response = getResponse(result, LINK_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
PartnerSite site = response.getResult();
|
||||
assertNotNull(site.getId());
|
||||
assertEquals(linkReq.getId(), site.getId().longValue());
|
||||
assertEquals(linkReq.getUrl(), site.getUrl());
|
||||
assertEquals(linkReq.getName(), site.getName());
|
||||
assertEquals(linkReq.isOpen(), site.getOpen());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allForOpen() throws Exception {
|
||||
getMockData(get("/links")).andDo(result -> {
|
||||
Response<List<PartnerSite>> response = getResponse(result, LINK_MODEL_LIST_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
response.getResult().forEach(site -> {
|
||||
assertNotNull(site.getUrl());
|
||||
assertNull(site.getOpen());
|
||||
assertNotNull(site.getName());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void all() throws Exception {
|
||||
getMockData(get("/admin/links?page=1&count=10"), adminLogin()).andDo(result -> {
|
||||
Response<PageData<PartnerSite>> response = getResponse(result, LINK_MODEL_PAGE_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
PageData<PartnerSite> pageData = response.getResult();
|
||||
assertEquals(1, pageData.getPageNum());
|
||||
assertEquals(10, pageData.getPageSize());
|
||||
for (PartnerSite site : pageData.getList()) {
|
||||
assertNotNull(site.getUrl());
|
||||
assertNotNull(site.getName());
|
||||
assertNotNull(site.getOpen());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 手动测试
|
||||
// @Test
|
||||
public void apply() throws Exception {
|
||||
long l = System.currentTimeMillis();
|
||||
String url = "https://www.example.com";
|
||||
getMockData(post("/apply?name=小海博客Api测试,请忽略&url=" + url)).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result, OBJECT_TYPE).getCode()));
|
||||
System.out.println("耗时:" + (System.currentTimeMillis() - l) / 1000 + "s");
|
||||
url = "xxx";
|
||||
getMockData(post("/apply?name=小海博客Api测试,请忽略&url=" + url)).andDo(result -> assertEquals(PARAMETERS_URL_ERROR.getCode(), getResponse(result, OBJECT_TYPE).getCode()));
|
||||
|
||||
}
|
||||
package cn.celess.blog.controller;
|
||||
|
||||
import cn.celess.blog.BaseTest;
|
||||
import cn.celess.blog.entity.PartnerSite;
|
||||
import cn.celess.blog.entity.Response;
|
||||
import cn.celess.blog.entity.model.PageData;
|
||||
import cn.celess.blog.entity.request.LinkApplyReq;
|
||||
import cn.celess.blog.entity.request.LinkReq;
|
||||
import cn.celess.blog.exception.MyException;
|
||||
import cn.celess.blog.mapper.PartnerMapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import java.util.List;
|
||||
import cn.celess.blog.service.MailService;
|
||||
import cn.celess.blog.service.PartnerSiteService;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.sf.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.UUID;
|
||||
|
||||
import static cn.celess.blog.enmu.ResponseEnum.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
|
||||
@Slf4j
|
||||
public class LinksControllerTest extends BaseTest {
|
||||
|
||||
@Autowired
|
||||
PartnerMapper mapper;
|
||||
private static final TypeReference<?> LINK_MODEL_TYPE = new TypeReference<Response<PartnerSite>>() {
|
||||
};
|
||||
private static final TypeReference<?> LINK_MODEL_LIST_TYPE = new TypeReference<Response<List<PartnerSite>>>() {
|
||||
};
|
||||
private static final TypeReference<?> LINK_MODEL_PAGE_TYPE = new TypeReference<Response<PageData<PartnerSite>>>() {
|
||||
};
|
||||
@Autowired
|
||||
PartnerSiteService partnerSiteService;
|
||||
|
||||
|
||||
@Test
|
||||
public void create() throws Exception {
|
||||
LinkReq linkReq = new LinkReq();
|
||||
linkReq.setName(randomStr(4));
|
||||
linkReq.setOpen(false);
|
||||
linkReq.setUrl("https://" + randomStr(4) + "example.com");
|
||||
getMockData(post("/admin/links/create"), adminLogin(), linkReq).andDo(result -> {
|
||||
Response<PartnerSite> response = getResponse(result, LINK_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
PartnerSite site = response.getResult();
|
||||
assertNotNull(site.getId());
|
||||
assertEquals(linkReq.getName(), site.getName());
|
||||
assertEquals(linkReq.getUrl(), site.getUrl());
|
||||
assertEquals(linkReq.isOpen(), site.getOpen());
|
||||
});
|
||||
|
||||
// https/http
|
||||
linkReq.setName(randomStr(4));
|
||||
linkReq.setOpen(false);
|
||||
linkReq.setUrl(randomStr(4) + ".example.com");
|
||||
getMockData(post("/admin/links/create"), adminLogin(), linkReq).andDo(result -> {
|
||||
Response<PartnerSite> response = getResponse(result, LINK_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
PartnerSite site = response.getResult();
|
||||
assertEquals("http://" + linkReq.getUrl(), site.getUrl());
|
||||
});
|
||||
|
||||
// 测试已存在的数据
|
||||
getMockData(post("/admin/links/create"), adminLogin(), linkReq).andDo(result ->
|
||||
assertEquals(DATA_HAS_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void del() throws Exception {
|
||||
PartnerSite partnerSite = new PartnerSite();
|
||||
partnerSite.setName(randomStr(4));
|
||||
partnerSite.setOpen(true);
|
||||
partnerSite.setDesc("");
|
||||
partnerSite.setIconPath("");
|
||||
partnerSite.setUrl("https://" + randomStr(4) + ".celess.cn");
|
||||
mapper.insert(partnerSite);
|
||||
PartnerSite latest = mapper.getLastest();
|
||||
assertNotNull(latest.getId());
|
||||
getMockData(delete("/admin/links/del/" + latest.getId()), adminLogin()).andDo(result -> {
|
||||
Response<Boolean> response = getResponse(result, BOOLEAN_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
assertTrue(response.getResult());
|
||||
});
|
||||
long id = latest.getId();
|
||||
do {
|
||||
id += 1;
|
||||
} while (mapper.existsById(id));
|
||||
System.out.println("删除ID=" + id + "的数据");
|
||||
getMockData(delete("/admin/links/del/" + id), adminLogin()).andDo(result ->
|
||||
assertEquals(DATA_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void update() throws Exception {
|
||||
// 增数据
|
||||
PartnerSite partnerSite = new PartnerSite();
|
||||
partnerSite.setName(randomStr(4));
|
||||
partnerSite.setOpen(true);
|
||||
partnerSite.setDesc("");
|
||||
partnerSite.setIconPath("");
|
||||
partnerSite.setDelete(false);
|
||||
partnerSite.setUrl("https://" + randomStr(5) + ".celess.cn");
|
||||
mapper.insert(partnerSite);
|
||||
// 查数据
|
||||
PartnerSite latest = mapper.getLastest();
|
||||
assertNotNull(latest.getId());
|
||||
// 构建请求
|
||||
LinkReq linkReq = new LinkReq();
|
||||
linkReq.setUrl(latest.getUrl());
|
||||
linkReq.setOpen(!latest.getOpen());
|
||||
linkReq.setName(randomStr(4));
|
||||
linkReq.setId(latest.getId());
|
||||
|
||||
getMockData(put("/admin/links/update"), adminLogin(), linkReq).andDo(result -> {
|
||||
Response<PartnerSite> response = getResponse(result, LINK_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
PartnerSite site = response.getResult();
|
||||
assertNotNull(site.getId());
|
||||
assertEquals(linkReq.getId(), site.getId().longValue());
|
||||
assertEquals(linkReq.getUrl(), site.getUrl());
|
||||
assertEquals(linkReq.getName(), site.getName());
|
||||
assertEquals(linkReq.isOpen(), site.getOpen());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allForOpen() throws Exception {
|
||||
getMockData(get("/links")).andDo(result -> {
|
||||
Response<List<PartnerSite>> response = getResponse(result, LINK_MODEL_LIST_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
response.getResult().forEach(site -> {
|
||||
assertNotNull(site.getUrl());
|
||||
assertNull(site.getOpen());
|
||||
assertNotNull(site.getName());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void all() throws Exception {
|
||||
getMockData(get("/admin/links?page=1&count=10"), adminLogin()).andDo(result -> {
|
||||
Response<PageData<PartnerSite>> response = getResponse(result, LINK_MODEL_PAGE_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
PageData<PartnerSite> pageData = response.getResult();
|
||||
assertEquals(1, pageData.getPageNum());
|
||||
assertEquals(10, pageData.getPageSize());
|
||||
for (PartnerSite site : pageData.getList()) {
|
||||
assertNotNull(site.getUrl());
|
||||
assertNotNull(site.getName());
|
||||
assertNotNull(site.getOpen());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apply() {
|
||||
// 做service 层的测试
|
||||
// mockEmailServiceInstance(partnerSiteService, "mailService");
|
||||
mockInjectInstance(partnerSiteService, "mailService", new TestMailServiceImpl());
|
||||
LinkApplyReq req = new LinkApplyReq();
|
||||
req.setName(randomStr(4));
|
||||
req.setUrl("https://" + randomStr(4) + ".celess.cn");
|
||||
req.setIconPath("https://www.celess.cn/example.png");
|
||||
req.setDesc("desc :" + randomStr());
|
||||
req.setEmail(randomStr(4) + "@celess.cn");
|
||||
req.setLinkUrl(req.getUrl() + "/links");
|
||||
try {
|
||||
// 抓取不到数据的链接
|
||||
partnerSiteService.apply(req);
|
||||
} catch (MyException e) {
|
||||
log.debug("测试抓取不到数据");
|
||||
assertEquals(CANNOT_GET_DATA.getCode(), e.getCode());
|
||||
}
|
||||
|
||||
req.setLinkUrl("https://bing.com");
|
||||
req.setUrl(req.getLinkUrl());
|
||||
try {
|
||||
partnerSiteService.apply(req);
|
||||
} catch (MyException e) {
|
||||
log.debug("测试未添加本站链接的友链申请");
|
||||
assertEquals(APPLY_LINK_NO_ADD_THIS_SITE.getCode(), e.getCode());
|
||||
assertNotNull(e.getResult());
|
||||
try {
|
||||
// 测试uuid一致性
|
||||
log.debug("测试uuid一致性");
|
||||
partnerSiteService.apply(req);
|
||||
} catch (MyException e2) {
|
||||
assertEquals(e.getResult(), e2.getResult());
|
||||
}
|
||||
}
|
||||
log.debug("测试正常申请");
|
||||
req.setLinkUrl("https://www.celess.cn");
|
||||
req.setUrl(req.getLinkUrl());
|
||||
PartnerSite apply = partnerSiteService.apply(req);
|
||||
assertNotNull(apply);
|
||||
assertNotNull(apply.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void reapply() {
|
||||
//mockEmailServiceInstance(partnerSiteService, "mailService");
|
||||
try {
|
||||
partnerSiteService.reapply(randomStr());
|
||||
throw new AssertionError();
|
||||
} catch (MyException e) {
|
||||
assertEquals(DATA_EXPIRED.getCode(), e.getCode());
|
||||
}
|
||||
|
||||
LinkApplyReq req = new LinkApplyReq();
|
||||
req.setName(randomStr(4));
|
||||
req.setIconPath("https://www.celess.cn/example.png");
|
||||
req.setDesc("desc :" + randomStr());
|
||||
req.setEmail(randomStr(4) + "@celess.cn");
|
||||
req.setLinkUrl("https://bing.com");
|
||||
req.setUrl(req.getLinkUrl());
|
||||
String uuid = null;
|
||||
try {
|
||||
partnerSiteService.apply(req);
|
||||
// err here
|
||||
throw new AssertionError();
|
||||
} catch (MyException e) {
|
||||
uuid = (String) e.getResult();
|
||||
String reapply = partnerSiteService.reapply(uuid);
|
||||
assertEquals(reapply, "success");
|
||||
}
|
||||
|
||||
try {
|
||||
partnerSiteService.reapply(uuid);
|
||||
throw new AssertionError();
|
||||
} catch (MyException e) {
|
||||
assertEquals(DATA_EXPIRED.getCode(), e.getCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,264 +1,274 @@
|
||||
package cn.celess.blog.controller;
|
||||
|
||||
import cn.celess.blog.BaseTest;
|
||||
import cn.celess.blog.entity.Response;
|
||||
import cn.celess.blog.entity.User;
|
||||
import cn.celess.blog.entity.model.PageData;
|
||||
import cn.celess.blog.entity.model.UserModel;
|
||||
import cn.celess.blog.entity.request.LoginReq;
|
||||
import cn.celess.blog.entity.request.UserReq;
|
||||
import cn.celess.blog.mapper.UserMapper;
|
||||
import cn.celess.blog.util.MD5Util;
|
||||
import cn.celess.blog.util.RedisUtil;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static cn.celess.blog.enmu.ResponseEnum.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
|
||||
public class UserControllerTest extends BaseTest {
|
||||
|
||||
@Autowired
|
||||
UserMapper userMapper;
|
||||
@Autowired
|
||||
RedisUtil redisUtil;
|
||||
private static final TypeReference<?> USER_MODEL_TYPE = new TypeReference<Response<UserModel>>() {
|
||||
};
|
||||
private static final TypeReference<?> USER_MODEL_PAGE_TYPE = new TypeReference<Response<PageData<UserModel>>>() {
|
||||
};
|
||||
private static final TypeReference<?> USER_MODEL_LIST_TYPE = new TypeReference<Response<List<Map<String, Object>>>>() {
|
||||
};
|
||||
|
||||
@Test
|
||||
public void login() throws Exception {
|
||||
assertNotNull(userLogin());
|
||||
assertNotNull(adminLogin());
|
||||
// 用户不存在
|
||||
LoginReq req = new LoginReq();
|
||||
req.setEmail("zh@celess.cn");
|
||||
req.setPassword("123456789");
|
||||
req.setIsRememberMe(false);
|
||||
getMockData(post("/login"), null, req).andDo(result -> assertEquals(USER_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registration() {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logout() throws Exception {
|
||||
getMockData(get("/logout")).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result, STRING_TYPE).getCode()));
|
||||
getMockData(get("/logout"), adminLogin()).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result).getCode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateInfo() throws Exception {
|
||||
String desc = randomStr(4);
|
||||
String disPlayName = randomStr(4);
|
||||
getMockData(put("/user/userInfo/update?desc=" + desc + "&displayName=" + disPlayName), userLogin()).andDo(result -> {
|
||||
Response<UserModel> response = getResponse(result, USER_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
UserModel u = response.getResult();
|
||||
assertEquals(desc, u.getDesc());
|
||||
assertEquals(disPlayName, u.getDisplayName());
|
||||
assertNotNull(u.getId());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getUserInfo() throws Exception {
|
||||
getMockData(get("/user/userInfo"), userLogin()).andDo(result -> {
|
||||
Response<UserModel> response = getResponse(result, USER_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
UserModel u = response.getResult();
|
||||
assertNotNull(u.getId());
|
||||
assertNotNull(u.getEmail());
|
||||
assertNotNull(u.getDisplayName());
|
||||
assertNotNull(u.getEmailStatus());
|
||||
assertNotNull(u.getAvatarImgUrl());
|
||||
assertNotNull(u.getDesc());
|
||||
assertNotNull(u.getRecentlyLandedDate());
|
||||
assertNotNull(u.getRole());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upload() throws Exception {
|
||||
URL url = new URL("https://56462271.oss-cn-beijing.aliyuncs.com/web/logo.png");
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
InputStream inputStream = connection.getInputStream();
|
||||
assertNotNull(inputStream);
|
||||
MockMultipartFile file = new MockMultipartFile("file", "logo.png", MediaType.IMAGE_PNG_VALUE, inputStream);
|
||||
getMockData(multipart("/user/imgUpload").file(file), userLogin()).andDo(result -> {
|
||||
Response<Object> response = getResponse(result, OBJECT_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
assertNotNull(response.getResult());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendResetPwdEmail() {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendVerifyEmail() {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@Test
|
||||
public void emailVerify() throws Exception {
|
||||
String email = randomStr(4) + "@celess.cn";
|
||||
String pwd = MD5Util.getMD5("123456789");
|
||||
userMapper.addUser(new User(email, pwd));
|
||||
String verifyId = randomStr();
|
||||
LoginReq req = new LoginReq(email, "123456789", true);
|
||||
redisUtil.setEx(email + "-verify", verifyId, 2, TimeUnit.DAYS);
|
||||
getMockData(post("/emailVerify").param("verifyId", verifyId).param("email", email), login(req)).andDo(result ->
|
||||
assertEquals(SUCCESS.getCode(), getResponse(result, OBJECT_TYPE).getCode())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resetPwd() throws Exception {
|
||||
String email = randomStr(4) + "@celess.cn";
|
||||
String pwd = MD5Util.getMD5("1234567890");
|
||||
userMapper.addUser(new User(email, pwd));
|
||||
LoginReq req = new LoginReq(email, "1234567890", true);
|
||||
String verifyId = randomStr();
|
||||
// 设置验证id
|
||||
redisUtil.setEx(email + "-resetPwd", verifyId, 2, TimeUnit.DAYS);
|
||||
MockHttpServletRequestBuilder resetPwd = post("/resetPwd").param("verifyId", verifyId).param("email", email).param("pwd", "123456789");
|
||||
// 未验证
|
||||
getMockData(resetPwd, login(req)).andDo(result -> assertEquals(USEREMAIL_NOT_VERIFY.getCode(), getResponse(result, OBJECT_TYPE).getCode()));
|
||||
// 设置未验证
|
||||
userMapper.updateEmailStatus(email, true);
|
||||
// 正常
|
||||
getMockData(resetPwd, login(req)).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result, OBJECT_TYPE).getCode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void multipleDelete() throws Exception {
|
||||
List<User> userList = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
String s = randomStr();
|
||||
String email = s.substring(s.length() - 4) + "@celess.cn";
|
||||
String pwd = MD5Util.getMD5("123456789");
|
||||
User user = new User(email, pwd);
|
||||
int i1 = userMapper.addUser(user);
|
||||
if (i1 == 0) {
|
||||
continue;
|
||||
}
|
||||
userList.add(userMapper.findByEmail(email));
|
||||
if (i == 9) {
|
||||
//设置一个管理员
|
||||
userMapper.setUserRole(userMapper.findByEmail(email).getId(), "admin");
|
||||
}
|
||||
}
|
||||
List<Integer> idList = userList.stream().map(user -> user.getId().intValue()).collect(Collectors.toList());
|
||||
getMockData(delete("/admin/user/delete"), adminLogin(), idList).andDo(result -> {
|
||||
Response<List<Map<String, Object>>> response = getResponse(result, USER_MODEL_LIST_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
response.getResult().forEach(o -> {
|
||||
// 判断响应数据中是否包含输入的id
|
||||
assertTrue(idList.contains((int) o.get("id")));
|
||||
// 判断处理状态
|
||||
boolean status = (boolean) o.get("status");
|
||||
if (o.containsKey("msg"))
|
||||
assertFalse(status);
|
||||
else
|
||||
assertTrue(status);
|
||||
});
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateInfoByAdmin() throws Exception {
|
||||
UserReq userReq = new UserReq();
|
||||
String email = randomStr(4) + "@celess.cn";
|
||||
User user = new User(email, MD5Util.getMD5("123456789"));
|
||||
userMapper.addUser(user);
|
||||
User userByDb = userMapper.findByEmail(email);
|
||||
userReq.setId(userByDb.getId());
|
||||
userReq.setPwd(randomStr().substring(0, 10));
|
||||
userReq.setDesc(randomStr());
|
||||
userReq.setEmailStatus(new Random().nextBoolean());
|
||||
userReq.setRole("admin");
|
||||
userReq.setDisplayName(randomStr(4));
|
||||
userReq.setEmail(randomStr(5) + "@celess.cn");
|
||||
getMockData(put("/admin/user"), adminLogin(), userReq).andDo(result -> {
|
||||
Response<UserModel> response = getResponse(result, USER_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
UserModel userModel = response.getResult();
|
||||
assertEquals(userReq.getId(), userModel.getId());
|
||||
assertEquals(userReq.getRole(), userModel.getRole());
|
||||
assertEquals(userReq.getEmail(), userModel.getEmail());
|
||||
assertEquals(userReq.getDesc(), userModel.getDesc());
|
||||
assertEquals(userReq.getDisplayName(), userModel.getDisplayName());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAllUser() throws Exception {
|
||||
getMockData(get("/admin/users?page=1&count=10"), adminLogin()).andDo(result -> {
|
||||
Response<PageData<UserModel>> response = getResponse(result, USER_MODEL_PAGE_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
// 结果集非空
|
||||
assertNotNull(response.getResult());
|
||||
// 判断pageInfo是否包装完全
|
||||
PageData<UserModel> pageData = response.getResult();
|
||||
assertNotEquals(0, pageData.getTotal());
|
||||
assertEquals(1, pageData.getPageNum());
|
||||
assertEquals(10, pageData.getPageSize());
|
||||
// 内容完整
|
||||
for (UserModel u : pageData.getList()) {
|
||||
assertNotNull(u.getId());
|
||||
assertNotNull(u.getEmail());
|
||||
assertNotNull(u.getRole());
|
||||
assertNotNull(u.getEmailStatus());
|
||||
assertNotNull(u.getDisplayName());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getEmailStatus() throws Exception {
|
||||
String email = randomStr(4) + "@celess.cn";
|
||||
getMockData(get("/emailStatus/" + email)).andDo(result -> assertFalse((Boolean) getResponse(result, BOOLEAN_TYPE).getResult()));
|
||||
getMockData(get("/emailStatus/" + ADMIN_EMAIL)).andDo(result -> assertTrue((Boolean) getResponse(result, BOOLEAN_TYPE).getResult()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setPwd() throws Exception {
|
||||
String email = randomStr(4) + "@celess.cn";
|
||||
assertEquals(1, userMapper.addUser(new User(email, MD5Util.getMD5("1234567890"))));
|
||||
LoginReq req = new LoginReq(email, "1234567890", false);
|
||||
String token = login(req);
|
||||
assertNotNull(token);
|
||||
MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
|
||||
param.add("pwd", "1234567890");
|
||||
param.add("newPwd", "aaabbbccc");
|
||||
param.add("confirmPwd", "aaabbbccc");
|
||||
getMockData(post("/user/setPwd").params(param), token).andDo(result -> {
|
||||
assertEquals(SUCCESS.getCode(), getResponse(result).getCode());
|
||||
assertEquals(MD5Util.getMD5("aaabbbccc"), userMapper.getPwd(email));
|
||||
});
|
||||
}
|
||||
package cn.celess.blog.controller;
|
||||
|
||||
import cn.celess.blog.BaseTest;
|
||||
import cn.celess.blog.entity.Response;
|
||||
import cn.celess.blog.entity.User;
|
||||
import cn.celess.blog.entity.model.PageData;
|
||||
import cn.celess.blog.entity.model.UserModel;
|
||||
import cn.celess.blog.entity.request.LoginReq;
|
||||
import cn.celess.blog.entity.request.UserReq;
|
||||
import cn.celess.blog.mapper.UserMapper;
|
||||
import cn.celess.blog.service.UserService;
|
||||
import cn.celess.blog.util.MD5Util;
|
||||
import cn.celess.blog.util.RedisUtil;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static cn.celess.blog.enmu.ResponseEnum.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static cn.celess.blog.enmu.ResponseEnum.*;
|
||||
|
||||
|
||||
public class UserControllerTest extends BaseTest {
|
||||
|
||||
@Autowired
|
||||
UserMapper userMapper;
|
||||
@Autowired
|
||||
|
||||
RedisUtil redisUtil;
|
||||
private static final TypeReference<?> USER_MODEL_TYPE = new TypeReference<Response<UserModel>>() {
|
||||
};
|
||||
private static final TypeReference<?> USER_MODEL_PAGE_TYPE = new TypeReference<Response<PageData<UserModel>>>() {
|
||||
};
|
||||
private static final TypeReference<?> USER_MODEL_LIST_TYPE = new TypeReference<Response<List<Map<String, Object>>>>() {
|
||||
};
|
||||
UserService userService;
|
||||
|
||||
|
||||
@Test
|
||||
public void login() throws Exception {
|
||||
assertNotNull(userLogin());
|
||||
assertNotNull(adminLogin());
|
||||
// 用户不存在
|
||||
LoginReq req = new LoginReq();
|
||||
req.setEmail("zh@celess.cn");
|
||||
req.setPassword("123456789");
|
||||
req.setIsRememberMe(false);
|
||||
getMockData(post("/login"), null, req).andDo(result -> assertEquals(USER_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registration() {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logout() throws Exception {
|
||||
getMockData(get("/logout")).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result, STRING_TYPE).getCode()));
|
||||
getMockData(get("/logout"), adminLogin()).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result).getCode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateInfo() throws Exception {
|
||||
String desc = randomStr(4);
|
||||
String disPlayName = randomStr(4);
|
||||
getMockData(put("/user/userInfo/update?desc=" + desc + "&displayName=" + disPlayName), userLogin()).andDo(result -> {
|
||||
Response<UserModel> response = getResponse(result, USER_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
UserModel u = response.getResult();
|
||||
assertEquals(desc, u.getDesc());
|
||||
assertEquals(disPlayName, u.getDisplayName());
|
||||
assertNotNull(u.getId());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getUserInfo() throws Exception {
|
||||
getMockData(get("/user/userInfo"), userLogin()).andDo(result -> {
|
||||
Response<UserModel> response = getResponse(result, USER_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
UserModel u = response.getResult();
|
||||
assertNotNull(u.getId());
|
||||
assertNotNull(u.getEmail());
|
||||
assertNotNull(u.getDisplayName());
|
||||
assertNotNull(u.getEmailStatus());
|
||||
assertNotNull(u.getAvatarImgUrl());
|
||||
assertNotNull(u.getDesc());
|
||||
assertNotNull(u.getRecentlyLandedDate());
|
||||
assertNotNull(u.getRole());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upload() throws Exception {
|
||||
URL url = new URL("https://56462271.oss-cn-beijing.aliyuncs.com/web/logo.png");
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
InputStream inputStream = connection.getInputStream();
|
||||
assertNotNull(inputStream);
|
||||
|
||||
// mock 实现类
|
||||
mockInjectInstance(userService, "qiniuService", new TestQiNiuServiceImpl());
|
||||
|
||||
MockMultipartFile file = new MockMultipartFile("file", "logo.png", MediaType.IMAGE_PNG_VALUE, inputStream);
|
||||
getMockData(multipart("/user/imgUpload").file(file), userLogin()).andDo(result -> {
|
||||
Response<Object> response = getResponse(result, OBJECT_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
assertNotNull(response.getResult());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendResetPwdEmail() {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendVerifyEmail() {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@Test
|
||||
public void emailVerify() throws Exception {
|
||||
String email = randomStr(4) + "@celess.cn";
|
||||
String pwd = MD5Util.getMD5("123456789");
|
||||
userMapper.addUser(new User(email, pwd));
|
||||
String verifyId = randomStr();
|
||||
LoginReq req = new LoginReq(email, "123456789", true);
|
||||
redisUtil.setEx(email + "-verify", verifyId, 2, TimeUnit.DAYS);
|
||||
getMockData(post("/emailVerify").param("verifyId", verifyId).param("email", email), login(req)).andDo(result ->
|
||||
assertEquals(SUCCESS.getCode(), getResponse(result, OBJECT_TYPE).getCode())
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resetPwd() throws Exception {
|
||||
String email = randomStr(4) + "@celess.cn";
|
||||
String pwd = MD5Util.getMD5("1234567890");
|
||||
userMapper.addUser(new User(email, pwd));
|
||||
LoginReq req = new LoginReq(email, "1234567890", true);
|
||||
String verifyId = randomStr();
|
||||
// 设置验证id
|
||||
redisUtil.setEx(email + "-resetPwd", verifyId, 2, TimeUnit.DAYS);
|
||||
MockHttpServletRequestBuilder resetPwd = post("/resetPwd").param("verifyId", verifyId).param("email", email).param("pwd", "123456789");
|
||||
// 未验证
|
||||
getMockData(resetPwd, login(req)).andDo(result -> assertEquals(USEREMAIL_NOT_VERIFY.getCode(), getResponse(result, OBJECT_TYPE).getCode()));
|
||||
// 设置未验证
|
||||
userMapper.updateEmailStatus(email, true);
|
||||
// 正常
|
||||
getMockData(resetPwd, login(req)).andDo(result -> assertEquals(SUCCESS.getCode(), getResponse(result, OBJECT_TYPE).getCode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void multipleDelete() throws Exception {
|
||||
List<User> userList = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
String s = randomStr();
|
||||
String email = s.substring(s.length() - 4) + "@celess.cn";
|
||||
String pwd = MD5Util.getMD5("123456789");
|
||||
User user = new User(email, pwd);
|
||||
int i1 = userMapper.addUser(user);
|
||||
if (i1 == 0) {
|
||||
continue;
|
||||
}
|
||||
userList.add(userMapper.findByEmail(email));
|
||||
if (i == 9) {
|
||||
//设置一个管理员
|
||||
userMapper.setUserRole(userMapper.findByEmail(email).getId(), "admin");
|
||||
}
|
||||
}
|
||||
List<Integer> idList = userList.stream().map(user -> user.getId().intValue()).collect(Collectors.toList());
|
||||
getMockData(delete("/admin/user/delete"), adminLogin(), idList).andDo(result -> {
|
||||
Response<List<Map<String, Object>>> response = getResponse(result, USER_MODEL_LIST_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
response.getResult().forEach(o -> {
|
||||
// 判断响应数据中是否包含输入的id
|
||||
assertTrue(idList.contains((int) o.get("id")));
|
||||
// 判断处理状态
|
||||
boolean status = (boolean) o.get("status");
|
||||
if (o.containsKey("msg"))
|
||||
assertFalse(status);
|
||||
else
|
||||
assertTrue(status);
|
||||
});
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateInfoByAdmin() throws Exception {
|
||||
UserReq userReq = new UserReq();
|
||||
String email = randomStr(4) + "@celess.cn";
|
||||
User user = new User(email, MD5Util.getMD5("123456789"));
|
||||
userMapper.addUser(user);
|
||||
User userByDb = userMapper.findByEmail(email);
|
||||
userReq.setId(userByDb.getId());
|
||||
userReq.setPwd(randomStr().substring(0, 10));
|
||||
userReq.setDesc(randomStr());
|
||||
userReq.setEmailStatus(new Random().nextBoolean());
|
||||
userReq.setRole("admin");
|
||||
userReq.setDisplayName(randomStr(4));
|
||||
userReq.setEmail(randomStr(5) + "@celess.cn");
|
||||
getMockData(put("/admin/user"), adminLogin(), userReq).andDo(result -> {
|
||||
Response<UserModel> response = getResponse(result, USER_MODEL_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
UserModel userModel = response.getResult();
|
||||
assertEquals(userReq.getId(), userModel.getId());
|
||||
assertEquals(userReq.getRole(), userModel.getRole());
|
||||
assertEquals(userReq.getEmail(), userModel.getEmail());
|
||||
assertEquals(userReq.getDesc(), userModel.getDesc());
|
||||
assertEquals(userReq.getDisplayName(), userModel.getDisplayName());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAllUser() throws Exception {
|
||||
getMockData(get("/admin/users?page=1&count=10"), adminLogin()).andDo(result -> {
|
||||
Response<PageData<UserModel>> response = getResponse(result, USER_MODEL_PAGE_TYPE);
|
||||
assertEquals(SUCCESS.getCode(), response.getCode());
|
||||
// 结果集非空
|
||||
assertNotNull(response.getResult());
|
||||
// 判断pageInfo是否包装完全
|
||||
PageData<UserModel> pageData = response.getResult();
|
||||
assertNotEquals(0, pageData.getTotal());
|
||||
assertEquals(1, pageData.getPageNum());
|
||||
assertEquals(10, pageData.getPageSize());
|
||||
// 内容完整
|
||||
for (UserModel u : pageData.getList()) {
|
||||
assertNotNull(u.getId());
|
||||
assertNotNull(u.getEmail());
|
||||
assertNotNull(u.getRole());
|
||||
assertNotNull(u.getEmailStatus());
|
||||
assertNotNull(u.getDisplayName());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getEmailStatus() throws Exception {
|
||||
String email = randomStr(4) + "@celess.cn";
|
||||
getMockData(get("/emailStatus/" + email)).andDo(result -> assertFalse((Boolean) getResponse(result, BOOLEAN_TYPE).getResult()));
|
||||
getMockData(get("/emailStatus/" + ADMIN_EMAIL)).andDo(result -> assertTrue((Boolean) getResponse(result, BOOLEAN_TYPE).getResult()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setPwd() throws Exception {
|
||||
String email = randomStr(4) + "@celess.cn";
|
||||
assertEquals(1, userMapper.addUser(new User(email, MD5Util.getMD5("1234567890"))));
|
||||
LoginReq req = new LoginReq(email, "1234567890", false);
|
||||
String token = login(req);
|
||||
assertNotNull(token);
|
||||
MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
|
||||
param.add("pwd", "1234567890");
|
||||
param.add("newPwd", "aaabbbccc");
|
||||
param.add("confirmPwd", "aaabbbccc");
|
||||
getMockData(post("/user/setPwd").params(param), token).andDo(result -> {
|
||||
assertEquals(SUCCESS.getCode(), getResponse(result).getCode());
|
||||
assertEquals(MD5Util.getMD5("aaabbbccc"), userMapper.getPwd(email));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ public class PartnerMapperTest extends BaseTest {
|
||||
partnerSite.setIconPath(randomStr(5));
|
||||
partnerSite.setDesc(randomStr(5));
|
||||
partnerSite.setOpen(false);
|
||||
partnerSite.setUrl("www.celess.cn?random=" + randomStr(4));
|
||||
partnerSite.setUrl("www.celess.cn/?random=" + randomStr(4));
|
||||
assertEquals(1, partnerMapper.update(partnerSite));
|
||||
}
|
||||
|
||||
|
||||
22
src/test/java/cn/celess/blog/util/HttpUtilTest.java
Normal file
22
src/test/java/cn/celess/blog/util/HttpUtilTest.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package cn.celess.blog.util;
|
||||
|
||||
import cn.celess.blog.BaseTest;
|
||||
import cn.celess.blog.enmu.ResponseEnum;
|
||||
import cn.celess.blog.entity.Response;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class HttpUtilTest extends BaseTest {
|
||||
|
||||
@Test
|
||||
public void get() {
|
||||
String s = HttpUtil.get("https://api.celess.cn/headerInfo");
|
||||
assertNotNull(s);
|
||||
// Response<Map<String, Object>> response = getResponse(s, MAP_OBJECT_TYPE);
|
||||
// assertEquals(ResponseEnum.SUCCESS.getCode(), response.getCode());
|
||||
// assertNotEquals(0, response.getResult().size());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user