Skip to content

Commit

Permalink
cdc support springMVC springCloud
Browse files Browse the repository at this point in the history
  • Loading branch information
lmx1989219 committed Dec 24, 2018
1 parent 9221e4d commit 8f9511a
Show file tree
Hide file tree
Showing 11 changed files with 200 additions and 123 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import au.com.dius.pact.model.MockProviderConfig;
import au.com.dius.pact.model.RequestResponsePact;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
Expand All @@ -17,49 +15,67 @@
import static org.junit.Assert.assertEquals;

public abstract class AbstractPactInvoker implements InvocationHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
// private Logger logger = LoggerFactory.getLogger(getClass());

@Override
public Object invoke(Object proxy, Method method, Object[] args) {
PactEntity pactEntity = buildPact(method);
Object reqBody = args[0];
PactDslJsonBody req = new PactDslJsonBody();
PactDslJsonBody req_ = null;
try {
req_ = PactDslJsonBodyUtil.buildReqJson(req, reqBody);
} catch (Exception e) {
logger.error("", e);
}
PactDslJsonBody resp = new PactDslJsonBody();
PactDslJsonBodyUtil.buildRespJson(method.getReturnType(), resp);

RequestResponsePact pact = ConsumerPactBuilder
.consumer(pactEntity.getConsumer())
.hasPactWith(pactEntity.getProvider())
.uponReceiving(pactEntity.getUpon())
.path(pactEntity.getPath())
.method(pactEntity.getMethodDesc())
.body(req_)
.willRespondWith()
.status(200)
.body(resp)
.toPact();
MockProviderConfig config = MockProviderConfig.createDefault();
StringBuilder stringBuilder = new StringBuilder();
PactVerificationResult result = runConsumerTest(pact, config, mockServer -> {
try {
org.json.JSONObject jsonObject = new PactProviderClient(mockServer.getUrl()).pactMock((org.json.JSONObject) req.getBody(), pactEntity.getPath());
assertEquals(jsonObject.toString(), resp.getBody().toString());
if (reqBody instanceof String) {
PactDslJsonBody resp = new PactDslJsonBody();
PactDslJsonBody resp_ = PactUtil.buildJson(resp, pactEntity.getMockResp());
RequestResponsePact pact = ConsumerPactBuilder
.consumer(pactEntity.getConsumer())
.hasPactWith(pactEntity.getProvider())
.uponReceiving(pactEntity.getUpon())
.path(pactEntity.getPath())
.method(pactEntity.getMethodDesc())
.body((String) reqBody)
.willRespondWith()
.status(200)
.body(resp_)
.toPact();
MockProviderConfig config = MockProviderConfig.createDefault();
PactVerificationResult result = runConsumerTest(pact, config, mockServer -> {
org.json.JSONObject jsonObject = new PactProviderClient(mockServer.getUrl()).pactMock(new org.json.JSONObject((String) reqBody), pactEntity.getPath());
stringBuilder.append(jsonObject.toString());
} catch (IOException e) {
throw new RuntimeException(e);
});
if (result instanceof PactVerificationResult.Error) {
throw new RuntimeException(((PactVerificationResult.Error) result).getError());
}
});

if (result instanceof PactVerificationResult.Error) {
throw new RuntimeException(((PactVerificationResult.Error) result).getError());
assertEquals(PactVerificationResult.Ok.INSTANCE, result);
} else {
PactDslJsonBody req = new PactDslJsonBody();
PactDslJsonBody req_ = PactUtil.buildJson(req, reqBody);
PactDslJsonBody resp = new PactDslJsonBody();
PactDslJsonBody resp_ = PactUtil.buildJson(resp, pactEntity.getMockResp());
RequestResponsePact pact = ConsumerPactBuilder
.consumer(pactEntity.getConsumer())
.hasPactWith(pactEntity.getProvider())
.uponReceiving(pactEntity.getUpon())
.path(pactEntity.getPath())
.method(pactEntity.getMethodDesc())
.body(req_)
.willRespondWith()
.status(200)
.body(resp_)
.toPact();
MockProviderConfig config = MockProviderConfig.createDefault();
PactVerificationResult result = runConsumerTest(pact, config, mockServer -> {
try {
org.json.JSONObject jsonObject = new PactProviderClient(mockServer.getUrl()).pactMock((org.json.JSONObject) req.getBody(), pactEntity.getPath());
// assertEquals(jsonObject.toString(), resp);
stringBuilder.append(jsonObject.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
});
if (result instanceof PactVerificationResult.Error) {
throw new RuntimeException(((PactVerificationResult.Error) result).getError());
}
assertEquals(PactVerificationResult.Ok.INSTANCE, result);
}
assertEquals(PactVerificationResult.Ok.INSTANCE, result);
return JSONObject.parseObject(stringBuilder.toString(), method.getReturnType());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@
String reqMethod() default "post";

String reqHead() default "application/json";

String mockResp() default "{\"code\":1,\"message\":\"ok\",\"data\":null}";
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PactEntity {
public class PactEntity<T> {
private String methodDesc;
private String path;
private String upon;
private String provider;
private String consumer;
private T mockResp;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.lmx.pactdemoconsumer;

import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

Expand All @@ -21,12 +22,17 @@ public Object getProxyObj(Class interface_) {
public PactEntity buildPact(Method method) {
FeignClient cdc = method.getDeclaringClass().getDeclaredAnnotation(FeignClient.class);
RequestMapping cdcInfo = method.getDeclaredAnnotation(RequestMapping.class);
return PactEntity.builder()
.consumer(System.getProperty("spring.application.name"))
.provider(cdc.value())
.upon("a api desc")
.methodDesc(cdcInfo.method() == null ? "POST" : cdcInfo.method()[0].toString())
.path(cdcInfo.value()[0])
.build();
try {
return PactEntity.builder()
.consumer(System.getProperty("spring.application.name"))
.provider(cdc.value())
.upon("a api desc")
.methodDesc(cdcInfo.method() == null ? "POST" : cdcInfo.method()[0].toString())
.path(cdcInfo.value()[0])
.mockResp(PactUtil.pactHolder.get())
.build();
} finally {
PactUtil.pactHolder.remove();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.lmx.pactdemoconsumer;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

Expand All @@ -12,7 +13,10 @@
@Cdc(provider = "Some Provider", consumer = "Some Consumer", reqDesc = "hello pact")
public interface PactHttp {
@CdcInfo(reqPath = "/api/pact")
Resp hello(Req body);
Resp<LoginDto> hello(Req body);

@CdcInfo(reqPath = "/api/pact")
String hello(String body);

@Data
@NoArgsConstructor
Expand All @@ -34,8 +38,20 @@ class InnerReq {
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class Resp<T> {
private Integer code;
private String message;
private T data;
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class Resp {
class LoginDto {
private String token;
private String lastLoginIp;
private Date lastLoginTime;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.lmx.pactdemoconsumer;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

Expand All @@ -18,12 +20,17 @@ public Object getProxyObj(Class interface_) {
public PactEntity buildPact(Method method) {
Cdc cdc = method.getDeclaringClass().getDeclaredAnnotation(Cdc.class);
CdcInfo cdcInfo = method.getDeclaredAnnotation(CdcInfo.class);
return PactEntity.builder()
.consumer(cdc.consumer())
.provider(cdc.consumer())
.upon(cdc.reqDesc())
.methodDesc(cdcInfo.reqMethod())
.path(cdcInfo.reqPath())
.build();
try {
return PactEntity.builder()
.consumer(cdc.consumer())
.provider(cdc.provider())
.upon(cdc.reqDesc())
.methodDesc(cdcInfo.reqMethod())
.path(cdcInfo.reqPath())
.mockResp(PactUtil.pactHolder.get())
.build();
} finally {
PactUtil.pactHolder.remove();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ public org.json.JSONObject pactMock(org.json.JSONObject body, String path) throw
.execute().returnContent().asString();
org.json.JSONObject resp = new org.json.JSONObject();
JSONObject json = JSONObject.parseObject(response);
if (json == null)
return resp;
for (Map.Entry e : json.entrySet())
resp.put(e.getKey().toString(), e.getValue());
return resp;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.lmx.pactdemoconsumer;

import au.com.dius.pact.consumer.dsl.PactDslJsonBody;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;

@Slf4j
public class PactUtil {
public static ThreadLocal pactHolder = new ThreadLocal();

/**
* 以对象来构建期望的请求或者响应
* <p>
* 定义格式规范:如日期,
* 正则匹配等
* </p>
*
* @param o
* @param pactDslJsonBody
*/
public static PactDslJsonBody buildJson(PactDslJsonBody pactDslJsonBody, Object o) {
for (Field field : o.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
String name = field.getType().getName();
if (!ifObject(name) && field.getType().isInstance(new String())) {
pactDslJsonBody.stringMatcher(field.getName(), "^[A-Za-z0-9.@\\u4e00-\\u9fa5]+$", (String) field.get(o));
} else if (!ifObject(name) && (field.getType().isInstance(new Integer(1))
|| field.getType().isInstance(new Long(1))
|| field.getType().isInstance(new BigDecimal(1)))) {
pactDslJsonBody.numberType(field.getName(), (Number) field.get(o));
} else if (!ifObject(name) && field.getType().isInstance(new Date()))
pactDslJsonBody.date(field.getName(), "yyyy-MM-dd HH:mm:ss", (Date) field.get(o));
else if (/*ifObject(name) &&*/ field.getType().newInstance() instanceof Object) {
PactDslJsonBody innerBodyObj = pactDslJsonBody.object(field.getName());
Object innerObj = field.get(o);
return buildJson(innerBodyObj, innerObj);
}
} catch (Exception e) {
log.error("", e);
}
}
return pactDslJsonBody;

}

static boolean ifObject(String fieldTypeName) {
return fieldTypeName.equals("java.lang.Object");
}
}
Loading

0 comments on commit 8f9511a

Please sign in to comment.