Skip to content

Commit

Permalink
发布1.1版本:
Browse files Browse the repository at this point in the history
1. 完善测试用例
2. 提取微信请求基类,不同类型的请求初始化不同的子类
  • Loading branch information
howwrite authored and 朱森林 committed Mar 7, 2020
1 parent 7318553 commit c1a6567
Show file tree
Hide file tree
Showing 29 changed files with 556 additions and 252 deletions.
13 changes: 9 additions & 4 deletions mars-demo/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<artifactId>mars-project</artifactId>
<groupId>com.github.howwrite</groupId>
<version>1.0.RELEASE</version>
<version>1.1.RELEASE</version>
</parent>
<artifactId>mars-demo</artifactId>
<name>mars-demo</name>
Expand All @@ -19,11 +19,16 @@
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.howwrite</groupId>
<artifactId>mars</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
package com.github.howwrite.mars.marsdemo.controller;

import com.github.howwrite.mars.sdk.request.MarsWxRequest;
import com.github.howwrite.mars.sdk.response.BaseMarsWxResponse;
import com.github.howwrite.mars.sdk.request.BaseMarsRequest;
import com.github.howwrite.mars.sdk.request.MarsTextRequest;
import com.github.howwrite.mars.sdk.response.BaseMarsResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author howwrite
* @Description demo controller
* @create 2019/12/15 15:31
*/
@RestController
@Controller
public class MarsController {

@PostMapping("/mars")
public BaseMarsWxResponse helloMars(MarsWxRequest request) {

return BaseMarsWxResponse.createTextResponse(request, "hello " + request.getContent());
public BaseMarsResponse helloMars(BaseMarsRequest request) {
if (request instanceof MarsTextRequest) {
return BaseMarsResponse.createTextResponse(request, "hello " + ((MarsTextRequest) request).getContent());
}
return BaseMarsResponse.createTextResponse(request, "hello world");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.github.howwrite.mars.test;

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
* @author howwrite
* @date 2020/3/7 上午9:24:23
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MarsTestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public abstract class BaseMarsTest {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.github.howwrite.mars.test;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
* @author howwrite
* @date 2020/3/7 上午9:33:24
*/
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MarsTestConfiguration {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.github.howwrite.mars.test.controller;

import com.github.howwrite.mars.sdk.request.BaseMarsRequest;
import com.github.howwrite.mars.sdk.request.MarsTextRequest;
import com.github.howwrite.mars.sdk.response.BaseMarsResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

/**
* @author howwrite
* @date 2020/3/7 上午9:34:07
*/
@Controller
public class MarsTestController {

@PostMapping("/testMars")
public BaseMarsResponse handlerWxMessage(BaseMarsRequest request) {
if (request instanceof MarsTextRequest) {
return BaseMarsResponse.createTextResponse(request, ((MarsTextRequest) request).getContent() + " too");
}
return null;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package com.github.howwrite.mars.test.test;

import com.github.howwrite.mars.test.BaseMarsTest;
import okhttp3.*;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.LocalServerPort;

/**
* 模拟微信请求测试controller消息加解密
*
* @author howwrite
* @date 2020/3/7 上午9:42:09
*/
public class TestController extends BaseMarsTest {
private static final Logger log = LoggerFactory.getLogger(TestController.class);
private static final String REQUEST_PATH = "/testMars";
private static final MediaType XML_MEDIA_TYPE
= MediaType.get("application/xml; charset=utf-8");
private OkHttpClient client = new OkHttpClient();
@LocalServerPort
private int port;

/**
* 测试get请求验证签名
*/
@Test
public void testCheckSign() throws Exception {
String echostr = "abcdefg";
String parameters = "signature=d9ab76da6454d9a719af76994a2424a1b82162bd&nonce=384783965&timestamp=1583549822&echostr=" + echostr;
Request request = new Request.Builder()
.url(getUrl() + "?" + parameters)
.build();
try (Response response = client.newCall(request).execute()) {
Assert.assertEquals(200, response.code());
String result = response.body().string();
log.debug("request result:[{}]", result);
Assert.assertEquals(echostr, result.trim());
}
}

/**
* 测试文本格式明文消息
*/
@Test
public void testTextLaws() throws Exception {
String body = "<xml><ToUserName><![CDATA[testToUserName]]></ToUserName><FromUserName><![CDATA[testFromUserName]]></FromUserName><CreateTime>123456</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[helloMars]]></Content><MsgId>1</MsgId></xml>";
try (Response response = client.newCall(createTextLawsRequest(body, "")).execute()) {
Assert.assertEquals(200, response.code());
String result = response.body().string();
log.debug("request result:[{}]", result);
Document document = DocumentHelper.parseText(result);
Element rootElement = document.getRootElement();
String content = rootElement.elementText("Content");
String toUserName = rootElement.elementText("ToUserName");
String fromUserName = rootElement.elementText("FromUserName");
String msgType = rootElement.elementText("MsgType");
// 发送内容是helloMars, 断言结果是: 用户发送内容+ too
Assert.assertEquals("helloMars too", content);
Assert.assertEquals("testToUserName", fromUserName);
Assert.assertEquals("testFromUserName", toUserName);
Assert.assertEquals("text", msgType);
}
}

/**
* 测试文本格式兼容消息
*/
@Test
public void testTextCompatible() throws Exception {
String body = "<xml><ToUserName><![CDATA[testToUserName]]></ToUserName> <FromUserName><![CDATA[testFromUserName]]></FromUserName> <CreateTime>123456</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[helloMars]]></Content> <MsgId>1</MsgId> <Encrypt><![CDATA[Lmq5gxVEDHIdoEy3NUH86DVXkk2R0z4vCx9cL190d9Kntww43Bpjr3a4lXakn4G4ERpvAXuYYnulg97I5zuZ2bpeUr6au+znWt6tR5eedHZWnUyWLmZc0XX2Y/sK0uEHUtaFsYC9kwXqF/7HTQ1mJ8nT1OTyVtXCckYqHbL4xS0vvUDUqmEdyQEuhU56hjufqo6gzmKZCvz13BCjVqHFfWNV/2jGEtodwhl4fg6/9wxSjnqZXcUKX200jNioKGP43jTzZff7iZiVMuyaCApp7hA/XWRUBlFsrez2uVgSwQIEwddG2joCKxPEG4UEKKcP/8UJ9d9+rq41FdhMCh7pSa7prN5NkDhzIcsjqFC1Uj7IFi/P6OIUVxG64e7LWgDFf70evMsBtHEy78AZ/NK89zNMNeTXjmtxupM0MnwVUHtjCmnD5CZCkw9HlvqC7qdzGis2nGFgxta7CposUGGqSw==]]></Encrypt></xml>";
String parameters = "signature=f41c13f383640b9cb10c22cf2d0bc43994efd3c8&timestamp=1583549370&nonce=423099419";
try (Response response = client.newCall(createTextLawsRequest(body, parameters)).execute()) {
Assert.assertEquals(200, response.code());
String result = response.body().string();
Assert.assertNotNull(result);
}
}


/**
* 测试文本格式加密消息
*/
@Test
public void testTextEncryption() throws Exception {
String body = "<xml> <ToUserName><![CDATA[testToUserName]]></ToUserName> <Encrypt><![CDATA[XmHu1XUAjxg5xqiwM8tjy2Stmm4q8lG8o44o7+0kjChEDQh98/VGu2z4qYkXICradNRp4bFk8gkaREqN9Tg3bVeRB4ulg5wh/0ywHs3ZoL7JlLYagEHeB/cnJvY/QSuRU2x1Fg4DZlQ8kLUTaR4eV6LHAgvWv2uZa+q8lODkeEx5+oHdt9Br8CziQ99L23vrHr5c8Q4tAWebS6slhh7J/hsFzTLn3RwB0H3v8EXHRm0WyAGlgxCML/D5MdLOydlTIc3TPk1HBG8p0qcxtE501nIzyyB+XPv5mkY4zXjsJ65u7JrSsvEhXprOsYFNluDOOrpO5J2tP/dlf8vCfxXdLJiekl5dqPxF2NFFMX/ORdud6OMXfAsAV9KnNI4R8sbERgC+zEBMx5uw0KcwVvOwBF36/lWn1gWUFbhAmUxH+UYwJPHYigVRiQdOmW+nGGqqfYYAJUPrgyulRqRdgxa7Ug==]]></Encrypt></xml>";
String parameters = "signature=069da1d26873136a1f7cd67e9f5dd3e868f9b67f&timestamp=1583549661&nonce=2072430883";
try (Response response = client.newCall(createTextLawsRequest(body, parameters)).execute()) {
Assert.assertEquals(200, response.code());
String result = response.body().string();
Assert.assertNotNull(result);
}
}

private String getUrl() {
return "http://localhost:" + port + REQUEST_PATH;
}


/**
* 生成请求
*/
public Request createTextLawsRequest(String body, String parameters) {
RequestBody requestBody = RequestBody.create(XML_MEDIA_TYPE, body);
return new Request.Builder()
.url(getUrl() + "?" + parameters)
.post(requestBody)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.github.howwrite.mars.test.test;

import com.github.howwrite.mars.sdk.config.MarsWxProperties;
import com.github.howwrite.mars.sdk.utils.WxUtils;
import com.github.howwrite.mars.sdk.utils.wx.aes.Sha1;
import com.github.howwrite.mars.test.BaseMarsTest;
import org.junit.Assert;
import org.junit.Test;

import javax.annotation.Resource;
import java.util.Map;

/**
* @author howwrite
* @date 2020/3/7 上午10:40:45
*/
public class TestWxUtil extends BaseMarsTest {

@Resource
private WxUtils wxUtils;

@Resource
private MarsWxProperties marsWxProperties;

/**
* 测试解密消息
*/
@Test
public void testDecrypt() {
Map<String, Object> decryptResultMap = wxUtils.parseXml("<xml> <ToUserName><![CDATA[testToUserName]]></ToUserName> <Encrypt><![CDATA[XmHu1XUAjxg5xqiwM8tjy2Stmm4q8lG8o44o7+0kjChEDQh98/VGu2z4qYkXICradNRp4bFk8gkaREqN9Tg3bVeRB4ulg5wh/0ywHs3ZoL7JlLYagEHeB/cnJvY/QSuRU2x1Fg4DZlQ8kLUTaR4eV6LHAgvWv2uZa+q8lODkeEx5+oHdt9Br8CziQ99L23vrHr5c8Q4tAWebS6slhh7J/hsFzTLn3RwB0H3v8EXHRm0WyAGlgxCML/D5MdLOydlTIc3TPk1HBG8p0qcxtE501nIzyyB+XPv5mkY4zXjsJ65u7JrSsvEhXprOsYFNluDOOrpO5J2tP/dlf8vCfxXdLJiekl5dqPxF2NFFMX/ORdud6OMXfAsAV9KnNI4R8sbERgC+zEBMx5uw0KcwVvOwBF36/lWn1gWUFbhAmUxH+UYwJPHYigVRiQdOmW+nGGqqfYYAJUPrgyulRqRdgxa7Ug==]]></Encrypt></xml>"
, "069da1d26873136a1f7cd67e9f5dd3e868f9b67f", "1583549661", "2072430883"
);
Assert.assertEquals("helloMars", decryptResultMap.get("Content"));
Assert.assertEquals("123456", decryptResultMap.get("CreateTime"));
Assert.assertEquals(true, decryptResultMap.get("Encryption"));
Assert.assertEquals("testToUserName", decryptResultMap.get("ToUserName"));
Assert.assertEquals("testFromUserName", decryptResultMap.get("FromUserName"));
Assert.assertEquals("text", decryptResultMap.get("MsgType"));
Assert.assertEquals("1", decryptResultMap.get("MsgId"));
}

/**
* 测试加密消息
*/
@Test
public void testEncryption() throws Exception {
String xmlString = "<xml><name>mars</name><Author>howwrite</Author></xml>";
String timeStamp = "1234567";
String nonce = "nonce";
String encryption = wxUtils.encryptMsg(xmlString, timeStamp, nonce);
String decryptSignature = Sha1.getSha1(marsWxProperties.getToken(), timeStamp, nonce);

// 解密加密的消息
Map<String, Object> decryptResult = wxUtils.parseXml(encryption, decryptSignature, timeStamp, nonce);
Assert.assertEquals("mars", decryptResult.get("name"));
Assert.assertEquals("howwrite", decryptResult.get("Author"));
}
}
6 changes: 6 additions & 0 deletions mars-demo/src/test/resources/application-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
mars:
path: /testMars
weixin:
token: testToken
app-id: testAppId
encoding-aes-key: abcdefghijabcdefghijabcdefghijabcdefghijabc
2 changes: 1 addition & 1 deletion mars/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>com.github.howwrite</groupId>
<artifactId>mars-project</artifactId>
<version>1.0.RELEASE</version>
<version>1.1.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.github.howwrite.mars.sdk.config.MarsProperties;
import com.github.howwrite.mars.sdk.config.MarsWxProperties;
import com.github.howwrite.mars.sdk.filter.MarsFilter;
import com.github.howwrite.mars.sdk.support.MarsResolver;
import com.github.howwrite.mars.sdk.support.MarsReturnValueHandler;
import com.github.howwrite.mars.sdk.utils.WxUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
Expand All @@ -12,8 +14,13 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractResourceBasedMessageSource;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
* @author howwrite
Expand All @@ -23,11 +30,24 @@
@Configuration
@ComponentScan
@EnableConfigurationProperties({MarsProperties.class, MarsWxProperties.class})
public class MarsStarterAutoConfiguration {
public class MarsStarterAutoConfiguration implements WebMvcConfigurer {

@Autowired(required = false)
private AbstractResourceBasedMessageSource abstractResourceBasedMessageSource;

@Resource
private WxUtils wxUtils;

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new MarsResolver(wxUtils));
}

@Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
handlers.add(new MarsReturnValueHandler(wxUtils));
}

@PostConstruct
public void registerMessageSource() {
if (!ObjectUtils.isEmpty(abstractResourceBasedMessageSource)) {
Expand Down

This file was deleted.

Loading

0 comments on commit c1a6567

Please sign in to comment.