Commit f410f1c5 authored by 技术部-任文超's avatar 技术部-任文超

Merge branch 'master' into 20180105-user-auth

# Conflicts:
#	src/main/java/cn/quantgroup/xyqb/Bootstrap.java

升级了Apollo相关代码,和jUnit各层测试用例Demo
parents 84d4af3e 53da9383
...@@ -22,9 +22,10 @@ ...@@ -22,9 +22,10 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<junit.version>4.12</junit.version>
<junit.jupiter.version>5.0.2</junit.jupiter.version>
<maven.test.skip>true</maven.test.skip> <maven.test.skip>true</maven.test.skip>
<org.springframework.security.version>3.2.7.RELEASE</org.springframework.security.version> <org.springframework.security.version>3.2.7.RELEASE</org.springframework.security.version>
</properties> </properties>
<dependencies> <dependencies>
...@@ -56,7 +57,6 @@ ...@@ -56,7 +57,6 @@
<artifactId>log4j-over-slf4j</artifactId> <artifactId>log4j-over-slf4j</artifactId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
...@@ -92,6 +92,25 @@ ...@@ -92,6 +92,25 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- jUnit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- hibernate --> <!-- hibernate -->
<dependency> <dependency>
...@@ -128,7 +147,7 @@ ...@@ -128,7 +147,7 @@
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId> <artifactId>httpcore</artifactId>
<version>4.3.3</version> <version>4.4</version>
</dependency> </dependency>
<dependency> <dependency>
...@@ -139,7 +158,7 @@ ...@@ -139,7 +158,7 @@
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>4.3.6</version> <version>4.4.1</version>
</dependency> </dependency>
<!-- hibernate end --> <!-- hibernate end -->
...@@ -229,12 +248,14 @@ ...@@ -229,12 +248,14 @@
<groupId>com.ctrip.framework.apollo</groupId> <groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId> <artifactId>apollo-client</artifactId>
<version>0.10.1</version> <version>0.10.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>cn.quantgroup</groupId>
<artifactId>commons</artifactId>
<version>0.0.5</version>
<scope>compile</scope>
</dependency> </dependency>
<!--<dependency>-->
<!--<groupId>cn.quantgroup</groupId>-->
<!--<artifactId>quantgroup-config-sdk</artifactId>-->
<!--<version>1.0.3-SNAPSHOT</version>-->
<!--</dependency>-->
<!-- motan --> <!-- motan -->
<dependency> <dependency>
...@@ -371,7 +392,6 @@ ...@@ -371,7 +392,6 @@
<id>test</id> <id>test</id>
<properties> <properties>
<profiles.activation>test</profiles.activation> <profiles.activation>test</profiles.activation>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
......
package cn.quantgroup.xyqb; package cn.quantgroup.xyqb;
import cn.quantgroup.tech.shutdown.DefaultSignalHandler;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer; import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import com.weibo.api.motan.common.MotanConstants; import com.weibo.api.motan.common.MotanConstants;
...@@ -11,21 +12,20 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; ...@@ -11,21 +12,20 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
import sun.misc.Signal;
@ComponentScan(basePackages = {"cn.quantgroup.sms", "cn.quantgroup.xyqb"}) @ComponentScan(basePackages = {"cn.quantgroup.sms", "cn.quantgroup.xyqb"})
@EnableAutoConfiguration @EnableAutoConfiguration
@SpringBootApplication @SpringBootApplication
@EnableCaching @EnableCaching
//@EnableApolloConfig({"application", "tech.msg.sdk", "cash.common"}) @EnableApolloConfig(value ={"application", "tech.msg.sdk", "tech.sleuth", "tech.common", "tech.service.urls", "cash.common"})
@EnableApolloConfig
@PropertySource(value = {"classpath:application.properties", "classpath:xyqb.properties"}, ignoreResourceNotFound = true)
@Configuration @Configuration
@EnableAspectJAutoProxy @EnableAspectJAutoProxy
@EnableAsync @EnableAsync
...@@ -34,8 +34,6 @@ public class Bootstrap { ...@@ -34,8 +34,6 @@ public class Bootstrap {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Bootstrap.class); SpringApplication springApplication = new SpringApplication(Bootstrap.class);
springApplication.addInitializers(new ApolloPropertySourceInitializer("application", "tech.msg.sdk", "cash.common","tech.service.urls"));
springApplication.addListeners(new ApplicationListener<ContextRefreshedEvent>() { springApplication.addListeners(new ApplicationListener<ContextRefreshedEvent>() {
@Override @Override
public void onApplicationEvent(ContextRefreshedEvent event) { public void onApplicationEvent(ContextRefreshedEvent event) {
...@@ -44,9 +42,11 @@ public class Bootstrap { ...@@ -44,9 +42,11 @@ public class Bootstrap {
} }
}); });
springApplication.setRegisterShutdownHook(true); springApplication.setRegisterShutdownHook(true);
ConfigurableApplicationContext run = springApplication.run(args);
springApplication.run(args); springApplication.run(args);
log.info("server start..."); log.info("server start...");
// 启用平滑退出功能
Signal.handle(new Signal("INT"), new DefaultSignalHandler(run));
//Sentry.init("http://13ef5642903a414c910f8d0e0a2c56ee:8b351ad1abf44de3b4c25f39105fb927@172.16.4.89:9000/6"); //Sentry.init("http://13ef5642903a414c910f8d0e0a2c56ee:8b351ad1abf44de3b4c25f39105fb927@172.16.4.89:9000/6");
} }
} }
...@@ -53,6 +53,8 @@ public class InnerController implements IBaseController { ...@@ -53,6 +53,8 @@ public class InnerController implements IBaseController {
@Autowired @Autowired
private IUserDetailService userDetailService; private IUserDetailService userDetailService;
@Autowired @Autowired
private IUserBtRegisterService userBtRegisterService;
@Autowired
private IIdCardService idCardService; private IIdCardService idCardService;
@Autowired @Autowired
private IUserExtInfoService userExtInfoService; private IUserExtInfoService userExtInfoService;
...@@ -577,54 +579,78 @@ public class InnerController implements IBaseController { ...@@ -577,54 +579,78 @@ public class InnerController implements IBaseController {
return JsonResult.buildSuccessResult("success", wechatUserInfo.getOpenId()); return JsonResult.buildSuccessResult("success", wechatUserInfo.getOpenId());
} }
/**
* 按照用户主键查询用户综合信息模型
* 综合信息模型包含:
* {
* 账号信息
* 个人信息
* 扩展信息
* 地址信息
* 联系人信息
* }
* @param userId - 用户表主键
* @return
*/
@RequestMapping("/user-association/search/userId")
@LogHttpCaller @LogHttpCaller
@RequestMapping("/user-association/search/phone") public JsonResult findUserAssociationModelByUserId(Long userId) {
public JsonResult findUserAssociationByPhone(String phoneNo) { if(Objects.isNull(userId) || userId < 0){
UserDetail userDetail = userDetailService.findByPhoneNo(phoneNo); return JsonResult.buildErrorStateResult("", "");
UserAssociation bean = new UserAssociation(); }
UserAssociationModel bean = new UserAssociationModel();
if (null != userDetail) { UserDetail userDetail = userDetailService.findByUserId(userId);
Address address = addressService.findByUserId(userDetail.getUserId()); if (!Objects.isNull(userDetail)) {
List<Contact> contacts = contactService.findByUserId(userDetail.getUserId(), true); bean.setId(userDetail.getUserId());
UserExtInfo extInfo = userExtInfoService.findByUserId(userDetail.getUserId());
bean.setUserId(userDetail.getUserId());
bean.setPhoneNo(userDetail.getPhoneNo()); bean.setPhoneNo(userDetail.getPhoneNo());
bean.setName(userDetail.getName()); bean.setName(userDetail.getName());
bean.setIdNo(userDetail.getIdNo()); bean.setIdNo(userDetail.getIdNo());
bean.setQq(userDetail.getQq()); bean.setQq(userDetail.getQq());
bean.setGender(Optional.ofNullable(userDetail.getGender()).orElse(cn.quantgroup.xyqb.model.Gender.UNKNOWN).getName()); bean.setGender(Optional.ofNullable(userDetail.getGender()).orElse(cn.quantgroup.xyqb.model.Gender.UNKNOWN).getName());
}
if (null != address) { User user = userService.findById(userId);
bean.setCity(address.getCity()); if (!Objects.isNull(user)) {
bean.setDistrict(address.getDistrict()); bean.setUuid(user.getUuid());
bean.setAddress(address.getAddress()); bean.setRegisterFrom(user.getRegisteredFrom());
bean.setProvince(address.getProvince()); }
UserBtRegister userBtRegister = userBtRegisterService.findByUserId(userId);
if (!Objects.isNull(userBtRegister)) {
bean.setMerchantId(userBtRegister.getRegisterBtMerchantId());
}
UserExtInfo extInfo = userExtInfoService.findByUserId(userDetail.getUserId());
if (!Objects.isNull(extInfo)) {
if(null==extInfo.getEducationEnum()){
bean.setEducationEnum(cn.quantgroup.user.enums.EducationEnum.UNKNOWN.getName());
}else{
bean.setEducationEnum(extInfo.getEducationEnum().getName());
} }
if (null != extInfo) { if(null==extInfo.getOccupationEnum()){
if(null==extInfo.getEducationEnum()){ bean.setOccupationEnum(cn.quantgroup.user.enums.OccupationEnum.UNKNOWN.getName());
bean.setEducationEnum(cn.quantgroup.user.enums.EducationEnum.UNKNOWN.getName()); }else{
}else{ bean.setOccupationEnum(extInfo.getOccupationEnum().getName());
bean.setEducationEnum(extInfo.getEducationEnum().getName());
}
if(null==extInfo.getOccupationEnum()){
bean.setOccupationEnum(cn.quantgroup.user.enums.OccupationEnum.UNKNOWN.getName());
}else{
bean.setOccupationEnum(extInfo.getOccupationEnum().getName());
}
if(null==extInfo.getMarryStatus()){
bean.setMarryStatus(cn.quantgroup.user.enums.MaritalStatus.UNKNOWN.getDescription());
}else{
bean.setMarryStatus(extInfo.getMarryStatus().getDescription());
}
} }
if (org.apache.commons.collections.CollectionUtils.isNotEmpty(contacts)) { if(null==extInfo.getMarryStatus()){
List<XContactInfo> userContacts = contacts2ContactRets(contacts); bean.setMarryStatus(cn.quantgroup.user.enums.MaritalStatus.UNKNOWN.getDescription());
bean.setContractResults(userContacts); }else{
bean.setMarryStatus(extInfo.getMarryStatus().getDescription());
} }
} }
Address address = addressService.findByUserId(userDetail.getUserId());
if (!Objects.isNull(address)) {
bean.putAddressList(Arrays.asList(address));
}
List<Contact> contacts = contactService.findByUserId(userDetail.getUserId(), true);
if (!Objects.isNull(address)) {
bean.putContactList(contacts);
}
return JsonResult.buildSuccessResult("", bean);
}
@LogHttpCaller
@RequestMapping("/user-association/search/phone")
public JsonResult findUserAssociationByPhone(String phoneNo) {
UserDetail userDetail = userDetailService.findByPhoneNo(phoneNo);
UserAssociation bean = getUserAssociation(userDetail);
return JsonResult.buildSuccessResult("", bean); return JsonResult.buildSuccessResult("", bean);
} }
...@@ -632,8 +658,17 @@ public class InnerController implements IBaseController { ...@@ -632,8 +658,17 @@ public class InnerController implements IBaseController {
@LogHttpCaller @LogHttpCaller
public JsonResult findUserAssociationByUid(Long uid) { public JsonResult findUserAssociationByUid(Long uid) {
UserDetail userDetail = userDetailService.findByUserId(uid); UserDetail userDetail = userDetailService.findByUserId(uid);
UserAssociation bean = new UserAssociation(); UserAssociation bean = getUserAssociation(userDetail);
return JsonResult.buildSuccessResult("", bean);
}
/**
* 获取用户综合信息
* @param userDetail
* @return
*/
private UserAssociation getUserAssociation(UserDetail userDetail){
UserAssociation bean = new UserAssociation();
if (null != userDetail) { if (null != userDetail) {
Address address = addressService.findByUserId(userDetail.getUserId()); Address address = addressService.findByUserId(userDetail.getUserId());
List<Contact> contacts = contactService.findByUserId(userDetail.getUserId(), true); List<Contact> contacts = contactService.findByUserId(userDetail.getUserId(), true);
...@@ -644,12 +679,11 @@ public class InnerController implements IBaseController { ...@@ -644,12 +679,11 @@ public class InnerController implements IBaseController {
bean.setIdNo(userDetail.getIdNo()); bean.setIdNo(userDetail.getIdNo());
bean.setQq(userDetail.getQq()); bean.setQq(userDetail.getQq());
bean.setGender(Optional.ofNullable(userDetail.getGender()).orElse(cn.quantgroup.xyqb.model.Gender.UNKNOWN).getName()); bean.setGender(Optional.ofNullable(userDetail.getGender()).orElse(cn.quantgroup.xyqb.model.Gender.UNKNOWN).getName());
if (null != address) { if (null != address) {
bean.setProvince(address.getProvince());
bean.setCity(address.getCity()); bean.setCity(address.getCity());
bean.setDistrict(address.getDistrict()); bean.setDistrict(address.getDistrict());
bean.setAddress(address.getAddress()); bean.setAddress(address.getAddress());
bean.setProvince(address.getProvince());
} }
if (null != extInfo) { if (null != extInfo) {
if(null==extInfo.getEducationEnum()){ if(null==extInfo.getEducationEnum()){
...@@ -662,7 +696,6 @@ public class InnerController implements IBaseController { ...@@ -662,7 +696,6 @@ public class InnerController implements IBaseController {
}else{ }else{
bean.setOccupationEnum(extInfo.getOccupationEnum().getName()); bean.setOccupationEnum(extInfo.getOccupationEnum().getName());
} }
if(null==extInfo.getMarryStatus()){ if(null==extInfo.getMarryStatus()){
bean.setMarryStatus(cn.quantgroup.user.enums.MaritalStatus.UNKNOWN.getDescription()); bean.setMarryStatus(cn.quantgroup.user.enums.MaritalStatus.UNKNOWN.getDescription());
}else{ }else{
...@@ -674,8 +707,7 @@ public class InnerController implements IBaseController { ...@@ -674,8 +707,7 @@ public class InnerController implements IBaseController {
bean.setContractResults(userContacts); bean.setContractResults(userContacts);
} }
} }
return bean;
return JsonResult.buildSuccessResult("", bean);
} }
public static XContactInfo contact2ContactRet(Contact c) { public static XContactInfo contact2ContactRet(Contact c) {
...@@ -865,7 +897,7 @@ public class InnerController implements IBaseController { ...@@ -865,7 +897,7 @@ public class InnerController implements IBaseController {
String districtCode, String districtCode,
String district, String district,
String address, String address,
String contacts) { String contacts,@RequestParam(defaultValue = "0",required =false ) Long btRegisterChannelId) {
LOGGER.info("[/innerapi/user/save_multi]保存用户、联系人、地址信息:registeredFrom:[{}], phoneNo[{}],name[{}],idNo[{}],provinceCode[{}],cityCode[{}],districtCode[{}]," + LOGGER.info("[/innerapi/user/save_multi]保存用户、联系人、地址信息:registeredFrom:[{}], phoneNo[{}],name[{}],idNo[{}],provinceCode[{}],cityCode[{}],districtCode[{}]," +
"address[{}],contacts[{}]", registeredFrom, phoneNo, name, idNo, provinceCode, cityCode, districtCode, address, contacts); "address[{}],contacts[{}]", registeredFrom, phoneNo, name, idNo, provinceCode, cityCode, districtCode, address, contacts);
...@@ -917,7 +949,7 @@ public class InnerController implements IBaseController { ...@@ -917,7 +949,7 @@ public class InnerController implements IBaseController {
return JsonResult.buildErrorStateResult("用户已存在,手机号被占用", null); return JsonResult.buildErrorStateResult("用户已存在,手机号被占用", null);
} }
user = userRegisterService.register(Long.valueOf(registeredFrom), Long.valueOf(channelId), phoneNo, name, idNo, provinceCode, province, cityCode, city, districtCode, district, address, contacts); user = userRegisterService.register(Long.valueOf(registeredFrom), Long.valueOf(channelId), phoneNo, name, idNo, provinceCode, province, cityCode, city, districtCode, district, address, contacts,btRegisterChannelId);
UserRet userRet = new UserRet(user); UserRet userRet = new UserRet(user);
return JsonResult.buildSuccessResult(null, userRet); return JsonResult.buildSuccessResult(null, userRet);
......
package cn.quantgroup.xyqb.model;
import cn.quantgroup.xyqb.entity.Address;
import lombok.Data;
import java.io.Serializable;
/**
* 地址信息数据模型
* @author renwc
* @date 2018-01-04
*/
@Data
public class AddressModel implements Serializable {
private static final long serialVersionUID = -1L;
private Long provinceCode;
private String province;
private Long cityCode;
private String city;
private Long districtCode;
private String district;
private String address;
private AddressModel(){}
public static AddressModel entity2Model(Address entity) {
if (entity == null) {
return null;
}
AddressModel model = new AddressModel();
model.setProvinceCode(entity.getProvinceCode());
model.setCityCode(entity.getCityCode());
model.setDistrictCode(entity.getDistrictCode());
model.setDistrict(entity.getDistrict());
model.setProvince(entity.getProvince());
model.setCity(entity.getCity());
model.setAddress(entity.getAddress());
return model;
}
}
package cn.quantgroup.xyqb.model;
import cn.quantgroup.user.enums.Relation;
import cn.quantgroup.xyqb.entity.Contact;
import lombok.Data;
import java.io.Serializable;
import java.util.Optional;
/**
* 联系人数据模型
* @author renwc
* @date 2018-01-04
*/
@Data
public class ContactModel implements Serializable {
private static final long serialVersionUID = -1L;
private String name;
private String phoneNo;
private String relationName;
private String relation;
private ContactModel(){}
public static ContactModel entity2Model(Contact entity) {
if (entity == null) {
return null;
}
ContactModel model = new ContactModel();
model.setName(entity.getName());
model.setPhoneNo(entity.getPhoneNo());
model.setRelationName(Optional.ofNullable(entity.getRelation()).orElse(Relation.OTHER).getDescription());
model.setRelation(entity.getRelation().name());
return model;
}
}
package cn.quantgroup.xyqb.model;
import cn.quantgroup.xyqb.entity.Address;
import cn.quantgroup.xyqb.entity.Contact;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 用户综合信息数据模型
* @author renwc
* @date 2018-01-04
*/
@Data
public class UserAssociationModel implements Serializable {
private static final long serialVersionUID = -1L;
private Long id;
private String uuid;
private String phoneNo;
private String idNo;
private String name;
private String gender;
private String marryStatus;
private String educationEnum;
private String occupationEnum;
private String qq;
private Long registerFrom;
private Long merchantId;
private List<AddressModel> addressList;
private List<ContactModel> contactList;
/**
* 填充地址模型列表
* @param entitylist
*/
public void putAddressList(List<Address> entitylist){
if(Objects.isNull(entitylist)){
return;
}
if(Objects.isNull(this.addressList)){
this.addressList = new ArrayList<AddressModel>(entitylist.size());
}
for (Address entity : entitylist) {
this.addressList.add(AddressModel.entity2Model(entity));
}
}
/**
* 填充联系人模型列表
* @param entitylist
*/
public void putContactList(List<Contact> entitylist){
if(Objects.isNull(entitylist)){
return;
}
if(Objects.isNull(this.contactList)){
this.contactList = new ArrayList<ContactModel>(entitylist.size());
}
for (Contact entity : entitylist) {
this.contactList.add(ContactModel.entity2Model(entity));
}
}
}
package cn.quantgroup.xyqb.model;
import lombok.Data;
/**
* Created by xuran on 2017/8/1.
*/
@Data
public class XContactIn {
private static final long serialVersionUID = -1L;
private Long id;
private Long userId;
private String name;
private String phoneNo;
private String relation;
}
...@@ -92,7 +92,7 @@ public interface IUserRegisterService { ...@@ -92,7 +92,7 @@ public interface IUserRegisterService {
* @param contacts * @param contacts
* @return * @return
*/ */
User register(Long registeredFrom, Long channelId, String phoneNo, String name, String idNo, String provinceCode, String province, String cityCode, String city, String districtCode, String district, String address, String contacts); User register(Long registeredFrom, Long channelId, String phoneNo, String name, String idNo, String provinceCode, String province, String cityCode, String city, String districtCode, String district, String address, String contacts,Long btRegisterChannelId);
/** /**
* 替换MotanUserServiceImpl.appLoginAndFetchLoginInfo和MotanUserServiceImpl.appLogin里的register * 替换MotanUserServiceImpl.appLoginAndFetchLoginInfo和MotanUserServiceImpl.appLogin里的register
......
...@@ -79,7 +79,7 @@ public class UserRegisterServiceImpl extends AbstractUserRegisterService { ...@@ -79,7 +79,7 @@ public class UserRegisterServiceImpl extends AbstractUserRegisterService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@Override @Override
public User register(Long registeredFrom, Long channelId, String phoneNo, String name, String idNo, String provinceCode, String province, String cityCode, String city, String districtCode, String district, String address, String contacts) { public User register(Long registeredFrom, Long channelId, String phoneNo, String name, String idNo, String provinceCode, String province, String cityCode, String city, String districtCode, String district, String address, String contacts,Long btRegisterChannelId) {
Address addressObj = new Address(); Address addressObj = new Address();
addressObj.setProvinceCode(Long.valueOf(provinceCode)); addressObj.setProvinceCode(Long.valueOf(provinceCode));
addressObj.setProvince(province); addressObj.setProvince(province);
...@@ -91,6 +91,7 @@ public class UserRegisterServiceImpl extends AbstractUserRegisterService { ...@@ -91,6 +91,7 @@ public class UserRegisterServiceImpl extends AbstractUserRegisterService {
UserRegisterParam userRegisterParam = UserRegisterParam.builder() UserRegisterParam userRegisterParam = UserRegisterParam.builder()
.registerFrom(registeredFrom).phoneNo(phoneNo).idNo(idNo).name(name) .registerFrom(registeredFrom).phoneNo(phoneNo).idNo(idNo).name(name)
.channelId(channelId) .channelId(channelId)
.btRegisterChannelId(btRegisterChannelId)
.address(addressObj).contacts(contacts) .address(addressObj).contacts(contacts)
.generateRandomPwd(true).sendSuccessSms(true).sendAppSms(true) .generateRandomPwd(true).sendSuccessSms(true).sendAppSms(true)
.sendSuccessMq(true) .sendSuccessMq(true)
......
...@@ -12,6 +12,7 @@ import org.springframework.web.context.request.RequestContextHolder; ...@@ -12,6 +12,7 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/** /**
* Created by Miraculous on 2016/12/29. * Created by Miraculous on 2016/12/29.
...@@ -23,63 +24,24 @@ public class XyqbSessionContextHolder { ...@@ -23,63 +24,24 @@ public class XyqbSessionContextHolder {
public static RedisTemplate<String, String> redisTemplate = null; public static RedisTemplate<String, String> redisTemplate = null;
public static SessionStruct getXSession() { public static SessionStruct getXSession() {
SessionStruct sessionStruct;
if (threadSession.get() != null) { if (threadSession.get() != null) {
return threadSession.get(); sessionStruct = threadSession.get();
} }else {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); sessionStruct = getXSessionFromRedis();
String token = request.getHeader(Constants.X_AUTH_TOKEN);
if (token == null || token.length() != 36) {
return null;
}
String result = redisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + token);
if (StringUtils.isEmpty(result)) {
return null;
}
try {
SessionValue values = JSON.parseObject(result, SessionValue.class);
if (values == null) {
return null;
}
SessionStruct sessionStruct = new SessionStruct();
sessionStruct.setSid(token);
sessionStruct.setValues(values);
threadSession.set(sessionStruct); threadSession.set(sessionStruct);
return sessionStruct;
} catch (Exception ex) {
LOGGER.error("序列化session出错", ex);
return null;
} }
return sessionStruct;
} }
public static SessionStruct getXSessionFromRedis(){ public static SessionStruct getXSessionFromRedis(){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader(Constants.X_AUTH_TOKEN); String token = request.getHeader(Constants.X_AUTH_TOKEN);
if (token == null || token.length() != 36) { return getXSessionFromRedis(token);
return null;
}
String result = redisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + token);
if (StringUtils.isEmpty(result)) {
return null;
}
try {
SessionValue values = JSON.parseObject(result, SessionValue.class);
if (values == null) {
return null;
}
SessionStruct sessionStruct = new SessionStruct();
sessionStruct.setSid(token);
sessionStruct.setValues(values);
return sessionStruct;
}catch (Exception ex){
LOGGER.error("序列化session出错", ex);
return null;
}
} }
public static SessionStruct getXSessionFromRedis(String token){ public static SessionStruct getXSessionFromRedis(String token){
if (token == null || token.length() != 36) { if (Objects.isNull(token) || token.length() != 36 || Objects.isNull(redisTemplate)) {
return null; return null;
} }
String result = redisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + token); String result = redisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + token);
......
app.id=xyqb-user2 app.id=xyqb-user2
namespace=application, tech.msg.sdk, cash.common,tech.service.urls namespace=application,tech.msg.sdk,tech.sleuth,tech.common,tech.service.urls,cash.common
\ No newline at end of file \ No newline at end of file
security.sessions=if_required
spring.aop.proxy-target-class=true
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{ISO8601} [%thread] [%-5level] %logger - %msg%n</pattern>
</layout>
</appender>
<logger name="com.atomikos" level="warn"/>
<logger name="org.springframework" level="warn"/>
<logger name="org.hibernate" level="warn"/>
<logger name="org.apache" level="warn"/>
<logger name="ch.qos.logback" level="warn"/>
<logger name="feign" level="debug"/>
<root level="info">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
\ No newline at end of file
security.sessions=if_required
spring.aop.proxy-target-class=true
security.sessions=if_required
spring.aop.proxy-target-class=true
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{ISO8601} [%thread] [%-5level] %logger - %msg%n</pattern>
</layout>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/home/quant_group/logs/xyqb_user.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>/home/quant_group/logs/xyqb_user.log.%d{yyyy-MM-dd}</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{ISO8601} [%thread] [%-5level] %logger - %msg%n</pattern>
</layout>
</appender>
<logger name="com.atomikos" level="warn"/>
<logger name="org.springframework" level="warn"/>
<logger name="org.hibernate" level="warn"/>
<logger name="org.apache" level="warn"/>
<logger name="ch.qos.logback" level="warn"/>
<root level="info">
<appender-ref ref="FILE"/>
<!-- <appender-ref ref="STDOUT"/>-->
</root>
</configuration>
\ No newline at end of file
configserver.disable=1
configserver.system=xyqb-user
xyqb.data.mysql.jdbc-url=jdbc:mysql://192.168.4.104:3306/xyqb_user?useUnicode=true&characterEncoding=UTF8
xyqb.data.mysql.password=qatest
xyqb.data.mysql.user=qa
xyqb.data.mysql.max-pool-size=20
# CORS
xyqb.filter.allowedOrigin=*
xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,Authorization
xyqb.data.redis.defaultExpiration=3600
# redis
xyqb.redis.master.host=192.168.4.103
xyqb.redis.master.port=6379
xyqb.redis.master.name=
xyqb.redis.sentinel1.host=
xyqb.redis.sentinel1.port=0
xyqb.redis.sentinel2.host=
xyqb.redis.sentinel2.port=0
xyqb.redis.sentinel3.host=
xyqb.redis.sentinel3.port=0
# 短信平台配置
sms.is.debug=1
# LKB client
lkb.client.url=http://192.168.192.251:8082/LKBClient/openapi
lkb.client.user.register.app=/new/register/registerApp.json
lkb.client.user.update=/new/register/updateUser.json
lkb.client.user.push=/user/push.json
# LKB import
lkb.import.url=http://spider.quantgroup.cn
# LKB
lkb.url=http://192.168.192.251:8081/LKB
# xyqb
xyqb.url=http://192.168.192.206:8999
xyqb.api.url=http://192.168.192.206:9004
# 图形验证码
# 是否启用超级验证码 "__SUPERQG__", 用于测试环境自动化测试, 线上环境可忽略此参数
xyqb.auth.captcha.super.enable=1
#首参数校验
xyqb.fplock.limit.byhour=3
xyqb.fplock.limit.byday=5
#sdk
model.quantgroup.url=http://model.quantgroup.cn
xyqb.auth.url=http://192.168.192.206:9001
usersys.url=http://localhost:9001
xyqb-user.ui=http://192.168.12.40:8080
wechat.appid=wxcdf6077af8127559
wechat.secret=16eaec16084d0d9c52d4114f359cc72c
#xyqb-user-域名
xyqb.user.domain=passport.xyqb.com
xyqb.user.query.url=http://userqry.xyqb.com
xyqb.domain = http://192.168.4.153:7003
#马甲包
loanvest.rabbitmq.connection.virtual-host=/loan_order
#loanvest.rabbitmq.stateMsgQueue=loan_vest_msg_queue
loanvest.rabbitmq.queue=loan_user_queue
loanvest.rabbitmq.exchange=loan_vest_exchange
loanvest.rabbitmq.connection.host=192.168.4.46
loanvest.rabbitmq.connection.port=5672
loanvest.rabbitmq.connection.user=qa
loanvest.rabbitmq.connection.password=qatest
#用户注册广播
register.rabbitmq.connection.virtual-host=/user_register
register.rabbitmq.queue=user_register_queue
register.rabbitmq.exchange=user_register_exchange
register.rabbitmq.connection.host=192.168.4.24
register.rabbitmq.connection.port=5672
register.rabbitmq.connection.user=qa
register.rabbitmq.connection.password=qatest
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<springProperty name="spring.application.name" source="spring.application.name"/>
<property name="LOG_LEVEL_PATTERN" value="%clr(%5p) %clr([${spring.application.name:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}]){yellow}"/>
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%10.10t]){faint} [%40.40file:%4.4line] %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!-- 这里面定义了 CONSOLE_LOG_PATTERN, FILE_LOG_PATTERN 等日志格式, 还定义了一些日志级别 -->
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<logger name="cn.quantgroup" level="DEBUG" />
<logger name="org.springframework" level="INFO" />
<!--<logger name="java.sql.Connection" level="DEBUG"/>-->
<!--<logger name="java.sql.Statement" level="DEBUG"/>-->
<!--<logger name="java.sql.PreparedStatement" level="DEBUG"/>-->
<logger name="org.hibernate" level="warn"/>
<logger name="org.apache" level="warn"/>
<logger name="ch.qos.logback" level="warn"/>
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="UTF-8" ?>
<configuration> <configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <springProperty name="spring.application.name" source="spring.application.name"/>
<layout class="ch.qos.logback.classic.PatternLayout"> <property name="LOG_LEVEL_PATTERN" value="%5p [${spring.application.name:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}]"/>
<pattern>%d{ISO8601} [%thread] [%-5level] %logger - %msg%n</pattern> <property name="FILE_LOG_PATTERN" value="${FILE_LOG_PATTERN:-%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} --- [%thread] [%file:%line] %logger - %msg%n}"/>
</layout>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/home/quant_group/logs/xyqb_user.log</file> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/home/quant_group/logs/${spring.application.name:-application}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>/home/quant_group/logs/xyqb_user.log.%d{yyyy-MM-dd}</fileNamePattern> <fileNamePattern>/home/quant_group/logs/${spring.application.name:-application}.log.%d{yyyy-MM-dd}</fileNamePattern>
<maxHistory>30</maxHistory> <maxHistory>30</maxHistory>
</rollingPolicy> </rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout"> <encoder>
<pattern>%d{ISO8601} [%thread] [%-5level] %logger - %msg%n</pattern> <pattern>${FILE_LOG_PATTERN}</pattern>
</layout> </encoder>
</appender> </appender>
<logger name="com.atomikos" level="warn"/>
<logger name="org.springframework" level="warn"/> <logger name="org.springframework" level="warn"/>
<logger name="org.hibernate" level="warn"/> <logger name="org.hibernate" level="warn"/>
<logger name="org.apache" level="warn"/> <logger name="org.apache" level="warn"/>
......
//package demo;
//
//import cn.quantgroup.xyqb.Bootstrap;
//import cn.quantgroup.xyqb.controller.internal.sms.SmsController;
//import cn.quantgroup.xyqb.controller.internal.user.UserController;
//import cn.quantgroup.xyqb.model.JsonResult;
//import org.junit.Assert;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//import org.springframework.test.context.web.WebAppConfiguration;
//
//@RunWith(SpringJUnit4ClassRunner.class)
//@SpringBootTest(classes = Bootstrap.class)
//@WebAppConfiguration
//public class DemoApplicationTests {
//
// @Autowired
// private UserController userController;
//
// @Autowired
// private SmsController smsController;
//
// private String smsRegCode = "";
//
// @Test
// public void sendRegCode() {
// JsonResult jsonResult = smsController.sendRegistCode("18611428880", null);
// System.out.print(jsonResult.getMsg());
// Assert.assertEquals(jsonResult.getCode(), "0000");
// Assert.assertEquals(jsonResult.getBusinessCode(), "0000");
//
// }
//
// @Test
// public void registerFast() {
//// JsonResult jsonResult = userController.registerFast("18611428880", "000000", null, null, "");
//// Assert.assertEquals(jsonResult.getCode(), "0000");
// }
//
// @Test
// public void sendLoginCode() {
// JsonResult jsonResult = smsController.sendLoginCode("18611428880", null);
// Assert.assertEquals(jsonResult.getCode(), "0000");
// }
//
// @Test
// public void loginFast() {
//
// }
//
//
//}
package demo;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.function.ThrowingConsumer;
import java.util.*;
import java.util.function.Function;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.DynamicContainer.dynamicContainer;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
/**
* 动态批量测试
* @author renwc
* @date 2018-01-05
*/
@Tag("Test Factory")
public class DynamicTests {
// This will result in a JUnitException!
@Disabled
@TestFactory
List<String> dynamicTestsWithInvalidReturnType() {
return Arrays.asList("Hello");
}
@TestFactory
Collection<DynamicTest> dynamicTestsFromCollection() {
return Arrays.asList(
dynamicTest("1st dynamic test", () -> assertTrue(true)),
dynamicTest("2nd dynamic test", () -> assertEquals(4, 2 * 2))
);
}
@TestFactory
Iterable<DynamicTest> dynamicTestsFromIterable() {
return Arrays.asList(
dynamicTest("3rd dynamic test", () -> assertTrue(true)),
dynamicTest("4th dynamic test", () -> assertEquals(4, 2 * 2))
);
}
@TestFactory
Iterator<DynamicTest> dynamicTestsFromIterator() {
return Arrays.asList(
dynamicTest("5th dynamic test", () -> assertTrue(true)),
dynamicTest("6th dynamic test", () -> assertEquals(4, 2 * 2))
).iterator();
}
@TestFactory
Stream<DynamicTest> dynamicTestsFromStream() {
return Stream.of("A", "B", "C")
.map(str -> dynamicTest("test" + str, () -> { /* ... */ }));
}
@TestFactory
Stream<DynamicTest> dynamicTestsFromIntStream() {
// Generates tests for the first 10 even integers.
return IntStream.iterate(0, n -> n + 2).limit(10)
.mapToObj(n -> dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
}
@TestFactory
Stream<DynamicTest> generateRandomNumberOfTests() {
// Generates random positive integers between 0 and 100 until
// a number evenly divisible by 7 is encountered.
Iterator<Integer> inputGenerator = new Iterator<Integer>() {
Random random = new Random();
int current;
@Override
public boolean hasNext() {
current = random.nextInt(100);
return current % 7 != 0;
}
@Override
public Integer next() {
return current;
}
};
// Generates display names like: input:5, input:37, input:85, etc.
Function<Integer, String> displayNameGenerator = (input) -> "input:" + input;
// Executes tests based on the current input value.
ThrowingConsumer<Integer> testExecutor = (input) -> assertTrue(input % 7 != 0);
// Returns a stream of dynamic tests.
return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor);
}
@TestFactory
Stream<DynamicNode> dynamicTestsWithContainers() {
return Stream.of("A", "B", "C")
.map(input -> dynamicContainer("Container " + input, Stream.of(
dynamicTest("not null", () -> assertNotNull(input)),
dynamicContainer("properties", Stream.of(
dynamicTest("length > 0", () -> assertTrue(input.length() > 0)),
dynamicTest("not empty", () -> assertFalse(input.isEmpty()))
))
)));
}
}
\ No newline at end of file
package demo;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.config.data.JpaConfig;
import cn.quantgroup.xyqb.config.data.RedisConfig;
import cn.quantgroup.xyqb.controller.internal.user.UserController;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.service.user.IUserService;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import jdk.nashorn.internal.runtime.regexp.joni.Config;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest({UserController.class})
@ContextConfiguration(classes = {JpaConfig.class, RedisConfig.class}, initializers = ApolloPropertySourceInitializer.class)
public class MockMvcTests {
@Autowired
private MockMvc mvc;
@MockBean
private IUserService userService;
/**
* 测试Server是否可达
* @throws Exception
*/
@Test
public void testServer() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
@Test
public void mvcTest() throws Exception {
String uri = "/lock/key";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)
.header("lock_ipv4", Constants.CLEAR_LOCK_FOR_IPV4)
.param("act", Boolean.TRUE.toString()))
.andExpect(status().isOk())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
JSONObject jsonResult = new JSONObject(content);
Object code = jsonResult.get("code");
Assert.assertEquals("0000", code);
Object data = jsonResult.get("data");
Assert.assertNotNull(data);
}
@Test
public void testExample() throws Exception {
String phone = "13461067662";
User user = new User();
user.setPhoneNo(phone);
given(userService.findByPhoneInDb(phone)).willReturn(user);
mvc.perform(get("/log/list").accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk()).andExpect(content().string("Honda Civic"));
}
}
package token; package demo;
import cn.quantgroup.xyqb.Bootstrap; import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.Constants; import cn.quantgroup.xyqb.Constants;
import com.alibaba.fastjson.JSON; import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONObject;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
...@@ -12,7 +12,8 @@ import org.junit.runner.RunWith; ...@@ -12,7 +12,8 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.MvcResult;
...@@ -20,19 +21,13 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; ...@@ -20,19 +21,13 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import java.nio.charset.Charset;
import java.util.Base64;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = Bootstrap.class) @SpringBootTest(classes = Bootstrap.class)
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
@WebAppConfiguration @WebAppConfiguration
public class OneTimeTokenTests { public class MvcTests {
final String userName = "root";
final String password = "!QAZ2wsx";
final String phoneNo = "13461067662";
private MockMvc mvc; private MockMvc mvc;
@Autowired @Autowired
WebApplicationContext webApplicationConnect; WebApplicationContext webApplicationConnect;
...@@ -40,7 +35,6 @@ public class OneTimeTokenTests { ...@@ -40,7 +35,6 @@ public class OneTimeTokenTests {
@Before @Before
public void setUp() throws JsonProcessingException { public void setUp() throws JsonProcessingException {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build(); mvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();
} }
/** /**
...@@ -51,87 +45,22 @@ public class OneTimeTokenTests { ...@@ -51,87 +45,22 @@ public class OneTimeTokenTests {
public void testServer() throws Exception { public void testServer() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()); .andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/token/oneTime").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
} }
/**
* 测试OneTime-Token发放服务
* @throws Exception
*/
@Test @Test
public void testOneTimeToken() throws Exception{ public void mvcTest() throws Exception {
String tokenOnceUri = "/token/oneTime"; String uri = "/lock/key";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(tokenOnceUri).accept(MediaType.APPLICATION_JSON)) MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)
.header("lock_ipv4", Constants.CLEAR_LOCK_FOR_IPV4)
.param("act", Boolean.TRUE.toString()))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andReturn(); .andReturn();
String content = mvcResult.getResponse().getContentAsString(); String content = mvcResult.getResponse().getContentAsString();
JSONObject jsonResult = JSON.parseObject(new String(content)); JSONObject jsonResult = new JSONObject(content);
Object code = jsonResult.get("code"); Object code = jsonResult.get("code");
Assert.assertEquals("0000", code); Assert.assertEquals("0000", code);
Object data = jsonResult.getString("data"); Object data = jsonResult.get("data");
Assert.assertNotNull(data); Assert.assertNotNull(data);
String oneTimeToken = String.valueOf(data);
Assert.assertNotEquals("", oneTimeToken);
}
/**
* 测试OneTime-Token切面
* @throws Exception
*/
// TODO 用户注册先不加OneTime-Token校验,进一步确认后再添加或删除本用例
//@Test
public void testAspect() throws Exception{
// 获取OneTime-Token
String oneTimeTokenUri = "/token/oneTime";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(oneTimeTokenUri).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
JSONObject jsonResult = JSON.parseObject(new String(content));
Object code = jsonResult.get("code");
Assert.assertEquals("0000", code);
Object data = jsonResult.getString("data");
Assert.assertNotNull(data);
String oneTimeToken = String.valueOf(data);
Assert.assertNotEquals("", oneTimeToken);
// 第一次使用OneTime-Token
String aspectUri = "/user/loginForH5";
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON)
.param("phoneNo", userName)
.param("password", password))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Object businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0000", code);
Assert.assertNotEquals("0002", businessCode);
// 使用过期的TokenOnce
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON)
.param("phoneNo", userName)
.param("password", password))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Assert.assertEquals("0000", code);
businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0002", businessCode);
// 不使用TokenOnce
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON)
.param("phoneNo", userName)
.param("password", password))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Assert.assertEquals("0000", code);
businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0002", businessCode);
} }
} }
package demo;
import org.junit.Test;
import org.junit.jupiter.api.Tag;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
/**
* jUnit4风格参数化批量测试(用例)
* @author renwc
* @date 2018-01-05
*/
@Tag("Parameters")
@RunWith(value = Parameterized.class)
public class ParametersJunit4Tests {
private String key;
private int value;
public ParametersJunit4Tests(String key, int value) {
this.key = key;
this.value = value;
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] {{"1", 1}, {"2", 2}, {"3", 3}, {"4", 4}};
return Arrays.asList(data);
}
@Test
public void pushTest() {
System.out.println("Parameterized is : key="+ key+", value="+value);
}
}
\ No newline at end of file
package demo;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* jUnit5风格参数化批量测试(用例)
* @author renwc
* @date 2018-01-05
*/
@Tag("Parameters")
public class ParametersJunit5Tests {
@ParameterizedTest
@ValueSource(strings = { "racecar", "radar", "able was I ere I saw elba" })
void palindromes(String candidate) {
Assert.assertNotNull(candidate);
}
@Ignore("Not Ready to Run")
@Test
public void loginFast() {
System.out.println("Not Ready to Run");
}
@Ignore("Not Ready to Run")
@DisplayName("My 1st JUnit 5 test! 😎")
@org.junit.jupiter.api.Test
public void myFirstTest(TestInfo testInfo) {
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
assertEquals("My 1st JUnit 5 test! 😎", testInfo.getDisplayName(), () -> "TestInfo is injected correctly");
}
}
\ No newline at end of file
package demo;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.config.data.JpaConfig;
import cn.quantgroup.xyqb.config.data.RedisConfig;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.repository.IUserRepository;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.PersistenceException;
import java.sql.Timestamp;
import java.time.Instant;
/**
* 持久层测试用例
* @author renwc
* @date 2018-01-05
*/
@Rollback
@Transactional
@RunWith(SpringRunner.class)
@DataJpaTest
@ContextConfiguration(classes = {JpaConfig.class, RedisConfig.class}, initializers = ApolloPropertySourceInitializer.class)
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
public class RepsitoryJpaTests {
@Autowired
private TestEntityManager entityManager;
@Autowired
private IUserRepository userRepository;
@Test(expected = PersistenceException.class)
public void testSaveExample() throws Exception {
String phone = "13461067662";
User user = new User();
user = userRepository.save(user);
User userRep = userRepository.findByPhoneNo(phone);
Assert.assertEquals(user, userRep);
}
@Test
public void testExample() throws Exception {
String phone = "13461067662";
String password = "318e235d3e52648b236faa3f748000d5";//123456
User user = new User();
user.setPhoneNo(phone);
user.setPassword(password);
user.setCreatedAt(Timestamp.from(Instant.now()));
user.setUpdatedAt(user.getCreatedAt());
user = userRepository.save(user);
User userRep = userRepository.findByPhoneNo(phone);
Assert.assertEquals(user, userRep);
}
}
package demo;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.repository.IUserRepository;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.PersistenceException;
import java.sql.Timestamp;
import java.time.Instant;
/**
* 持久层测试用例
* @author renwc
* @date 2018-01-05
*/
@Rollback
@Transactional
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Bootstrap.class)
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
public class RepsitoryTests {
@Autowired
private IUserRepository userRepository;
@Test
public void testSaveExample() throws Exception {
String phone = "13461067662";
User user = new User();
user = userRepository.save(user);
User userRep = userRepository.findByPhoneNo(phone);
Assert.assertEquals(user, userRep);
}
@Test
public void testInsertExample() throws Exception {
String phone = "13461067662";
String password = "318e235d3e52648b236faa3f748000d5";//123456
User user = new User();
user.setPhoneNo(phone);
user.setPassword(password);
user.setCreatedAt(Timestamp.from(Instant.now()));
user.setUpdatedAt(user.getCreatedAt());
user = userRepository.save(user);
User userRep = userRepository.findByPhoneNo(phone);
Assert.assertEquals(user, userRep);
}
}
package demo;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.service.user.IUserService;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.PersistenceException;
import java.sql.Timestamp;
import java.time.Instant;
/**
* 业务层测试用例
* @author renwc
* @date 2018-01-05
*/
@Rollback
@Transactional
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Bootstrap.class)
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
public class ServiceTests {
@Autowired
private IUserService userService;
@Test
public void testSaveExample() throws Exception {
String phone = "13461067662";
User user = new User();
user = userService.saveUser(user);
User userRep = userService.findByPhoneInDb(phone);
Assert.assertEquals(user, userRep);
}
@Test
public void testInsertExample() throws Exception {
String phone = "13461067662";
String password = "318e235d3e52648b236faa3f748000d5";//123456
User user = new User();
user.setPhoneNo(phone);
user.setPassword(password);
user.setCreatedAt(Timestamp.from(Instant.now()));
user.setUpdatedAt(user.getCreatedAt());
user = userService.saveUser(user);
User userRep = userService.findByPhoneInDb(phone);
Assert.assertEquals(user, userRep);
}
}
package demo;
import cn.quantgroup.xyqb.Bootstrap;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 控制层测试用例
* @author renwc
* @date 2018-01-05
*/
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Bootstrap.class, webEnvironment= WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
public class WebTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {
Assert.assertTrue(true);
}
@Test
public void test() {
ResponseEntity<String> phil = restTemplate.getForEntity("/{model}/list", String.class, "log");
Assert.assertEquals(phil.getStatusCode(), HttpStatus.OK);
}
}
package login;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.Constants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.octo.captcha.service.CaptchaServiceException;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.Optional;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Bootstrap.class)
@WebAppConfiguration
public class LoginForH5Tests {
final String phoneNo = "13461067662";
final String userName = "root";
final String password = "!QAZ2wsx";
private MockMvc mvc;
@Autowired
WebApplicationContext webApplicationConnect;
@Before
public void setUp() throws JsonProcessingException {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();
}
/**
* 测试Server是否可达
* @throws Exception
*/
@Test
public void testServer() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/user/loginForH5").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/user/login/fastForH5").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/api/captcha").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/api/sms/send_login_code").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
/**
* 测试图形验证码账密登录
* @throws Exception
*/
@Test
public void testLoginFoH5() throws Exception{
Assert.assertTrue(false);
}
/**
* 测试TokenOnce切面
* @throws Exception
*/
@Test
public void testLoginFastFoH5() throws Exception{
// 获取TokenOnce
String oneTimeTokenUri = "/token/oneTime";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(oneTimeTokenUri).accept(MediaType.APPLICATION_JSON)
.param("phoneNo", phoneNo))
.andExpect(status().isOk())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
JSONObject jsonResult = JSON.parseObject(new String(content));
Object code = jsonResult.get("code");
Assert.assertEquals("0000", code);
Object data = jsonResult.get("data");
Assert.assertNotNull(data);
String oneTimeToken = String.valueOf(data);
Assert.assertNotEquals("", oneTimeToken);
String smsUri = "/api/sms/send_login_code";
mvcResult = mvc.perform(MockMvcRequestBuilders.get(oneTimeTokenUri).accept(MediaType.APPLICATION_JSON)
.param("phoneNo", phoneNo))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Assert.assertEquals("0000", code);
data = jsonResult.get("data");
Assert.assertNotNull(data);
String verificationCode = "1234";
StringBuilder verificationBuilder = new StringBuilder();
String authorization = "Verification " + new String(Base64.getEncoder().encodeToString(verificationBuilder.append(phoneNo).append(":").append(verificationCode).toString().getBytes(Charset.forName("UTF-8"))));
// 第一次使用TokenOnce
String aspectUri = "/user/login/fastForH5";
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON)
.header("authorization", authorization))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Object businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0000", code);
Assert.assertNotEquals("0002", businessCode);
// 使用过期的TokenOnce与verificationCode
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON)
.header("authorization", authorization))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Assert.assertEquals("0000", code);
businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0002", businessCode);
// 不使用TokenOnce和verificationCode
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Assert.assertEquals("0000", code);
businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0002", businessCode);
}
}
package user; package login;
import cn.quantgroup.xyqb.Bootstrap; import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.Constants; import cn.quantgroup.xyqb.Constants;
...@@ -6,14 +6,10 @@ import cn.quantgroup.xyqb.controller.external.user.InnerController; ...@@ -6,14 +6,10 @@ import cn.quantgroup.xyqb.controller.external.user.InnerController;
import cn.quantgroup.xyqb.controller.internal.user.UserController; import cn.quantgroup.xyqb.controller.internal.user.UserController;
import cn.quantgroup.xyqb.model.AuthBean; import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.JsonResult; import cn.quantgroup.xyqb.model.JsonResult;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.weibo.api.motan.common.MotanConstants;
import com.weibo.api.motan.util.MotanSwitcherUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
...@@ -24,14 +20,9 @@ import org.apache.http.util.EntityUtils; ...@@ -24,14 +20,9 @@ import org.apache.http.util.EntityUtils;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.io.IOException; import java.io.IOException;
......
package service;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.entity.Address;
import cn.quantgroup.xyqb.service.user.IAddressService;
import cn.quantgroup.xyqb.service.user.IContactService;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Created by xuran on 2017/12/26.
*/
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
@SpringBootTest(classes = Bootstrap.class )
@Slf4j
@Rollback
@Transactional
@RunWith(Parameterized.class)
public class TestUserService {
private TestContextManager testContextManager;
@Autowired
private IAddressService addressService;
@Autowired
private IContactService contactService;
private Address addressObj;
public TestUserService(Address addressObj) {
super();
this.addressObj = addressObj;
}
@Before
public void setUpContext() throws Exception {
//this is where the magic happens, we actually do "by hand" what the spring runner would do for us,
// read the JavaDoc for the class bellow to know exactly what it does, the method names are quite accurate though
this.testContextManager = new TestContextManager(getClass());
this.testContextManager.prepareTestInstance(this);
}
@Parameterized.Parameters
public static Collection data() {
Address addressObj =new Address();
addressObj.setUserId(123456L);
addressObj.setCity("悉尼");
addressObj.setCityCode(1L);
addressObj.setDistrict("悉尼");
addressObj.setDistrictCode(1L);
addressObj.setProvince("悉尼");
addressObj.setProvinceCode(1L);
addressObj.setAddress("嘻哈");
Timestamp timestamp=Timestamp.valueOf( LocalDateTime.now());
addressObj.setCreatedAt(timestamp);
addressObj.setUpdateAt(timestamp);
return Arrays.asList(new Object[][]{{addressObj}});
}
@Test
public void testAddress() {
addressService.save(addressObj);
addressObj=addressService.findByUserId(addressObj.getUserId());
System.out.println("测试地址"+addressObj);
List<Long> userIds= Lists.newArrayList();
userIds.add(123456L);
List<Address> addresses= addressService.findByUserIds(userIds);
System.out.println("测试地址集合"+addresses.get(0));
}
}
app.id=xyqb-user2 app.id=xyqb-user2
namespace=application namespace=application,tech.msg.sdk,tech.sleuth,tech.common,tech.service.urls,cash.common
\ No newline at end of file \ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment