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

Merge branch 'master' into feature/20180108

# Conflicts:
#	src/main/java/cn/quantgroup/xyqb/controller/external/user/InnerController.java
parents 2a077f4f 55158c49
......@@ -22,9 +22,10 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<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>
<org.springframework.security.version>3.2.7.RELEASE</org.springframework.security.version>
</properties>
<dependencies>
......@@ -56,7 +57,6 @@
<artifactId>log4j-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
......@@ -93,6 +93,26 @@
<scope>test</scope>
</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 -->
<dependency>
<groupId>org.hibernate</groupId>
......@@ -128,7 +148,7 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.3</version>
<version>4.4</version>
</dependency>
<dependency>
......@@ -139,7 +159,7 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
<version>4.4.1</version>
</dependency>
<!-- hibernate end -->
......@@ -230,12 +250,6 @@
<artifactId>apollo-client</artifactId>
<version>0.10.1</version>
</dependency>
<!--<dependency>-->
<!--<groupId>cn.quantgroup</groupId>-->
<!--<artifactId>quantgroup-config-sdk</artifactId>-->
<!--<version>1.0.3-SNAPSHOT</version>-->
<!--</dependency>-->
<!-- motan -->
<dependency>
<groupId>com.weibo</groupId>
......
......@@ -19,11 +19,9 @@ import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.EnableAsync;
@ComponentScan(basePackages = {"cn.quantgroup.sms", "cn.quantgroup.xyqb"})
@EnableAutoConfiguration
@SpringBootApplication
@EnableCaching
//@EnableApolloConfig({"application", "tech.msg.sdk", "cash.common"})
@EnableApolloConfig
@PropertySource(value = {"classpath:application.properties", "classpath:xyqb.properties"}, ignoreResourceNotFound = true)
@Configuration
......@@ -35,7 +33,6 @@ public class Bootstrap {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Bootstrap.class);
springApplication.addInitializers(new ApolloPropertySourceInitializer("application", "tech.msg.sdk", "cash.common","tech.service.urls"));
springApplication.addListeners(new ApplicationListener<ContextRefreshedEvent>() {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
......@@ -46,7 +43,6 @@ public class Bootstrap {
springApplication.setRegisterShutdownHook(true);
springApplication.run(args);
log.info("server start...");
Sentry.init("http://13ef5642903a414c910f8d0e0a2c56ee:8b351ad1abf44de3b4c25f39105fb927@172.16.4.89:9000/6");
}
}
......@@ -182,7 +182,8 @@ public class UserDetailServiceImpl implements IUserDetailService {
return userDetailRepository.findAll(spec, pageRequest);
}
@Override public void fixedIdNoAndGender() {
@Override
public void fixedIdNoAndGender() {
List<UserDetail> details=userDetailRepository.selectUserDetailsBy();
if(!CollectionUtils.isEmpty(details)){
for (UserDetail detail:details){
......
app.id=xyqb-user2
namespace=application, tech.msg.sdk, cash.common,tech.service.urls
\ No newline at end of file
namespace=application,tech.msg.sdk,cash.common,tech.service.urls
\ No newline at end of file
//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.Constants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
......@@ -12,7 +12,8 @@ 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.ContextConfiguration;
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;
......@@ -20,19 +21,13 @@ 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 static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Bootstrap.class)
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
@WebAppConfiguration
public class OneTimeTokenTests {
final String userName = "root";
final String password = "!QAZ2wsx";
final String phoneNo = "13461067662";
public class MvcTests {
private MockMvc mvc;
@Autowired
WebApplicationContext webApplicationConnect;
......@@ -40,7 +35,6 @@ public class OneTimeTokenTests {
@Before
public void setUp() throws JsonProcessingException {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();
}
/**
......@@ -51,87 +45,22 @@ public class OneTimeTokenTests {
public void testServer() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/token/oneTime").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
/**
* 测试OneTime-Token发放服务
* @throws Exception
*/
@Test
public void testOneTimeToken() throws Exception{
String tokenOnceUri = "/token/oneTime";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(tokenOnceUri).accept(MediaType.APPLICATION_JSON))
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 = JSON.parseObject(new String(content));
JSONObject jsonResult = new JSONObject(content);
Object code = jsonResult.get("code");
Assert.assertEquals("0000", code);
Object data = jsonResult.getString("data");
Object data = jsonResult.get("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.Constants;
......@@ -6,14 +6,10 @@ import cn.quantgroup.xyqb.controller.external.user.InnerController;
import cn.quantgroup.xyqb.controller.internal.user.UserController;
import cn.quantgroup.xyqb.model.AuthBean;
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 org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
......@@ -24,14 +20,9 @@ import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
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.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
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
namespace=application
\ No newline at end of file
namespace=application,tech.msg.sdk,cash.common,tech.service.urls
\ 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