我们试图提供以下特征的合同:
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method(GET())
url("/v2/entity")
headers {
accept(applicationJson())
}
}
response {
status 200
body( """
{
"saveLink": "http://<requestedHost>:<requestedPort>/v2/entity/save"
}
)
}
}
如果我们的客户使用Stubrunner并选择了另一个端口,则E.Q。9876," savelink"应在响应URL中反映出此端口。我们无法找到一种简单的API来获取主机和端口信息。FromRequest()或URL()仅返回请求URL的相对部分。是否有API方法或该要求的简单解决方案?还有其他建议吗?
首先,我认为您正在误解合同测试的概念。我想知道为什么在那里拥有那些具体的值对您来说至关重要?在合同测试中,您只对链接包含URL和端口的某些值感兴趣。您甚至都不会打电话给该网址。因此,很可能您应该在进行进一步之前改变方法。
但是,如果您决定这是唯一的方法,我就对您如何解决这个问题提出了我的看法(尽管我尚未测试它,但看起来它应该起作用;))。
)。当前使所有工作都不容易。此https://github.com/spring-cloud/spring-cloud-contract/pull/429合并后,在即将发布的EDGware版本中会更容易。
不过,我会尝试考虑解决方法。我们要做的是添加一种转换机制,该机制将在从WireMock发送回响应有效载荷之前修改响应有效载荷。我们将需要转换类,我们也需要扩展现有的存根机制。
首先,让我们创建一个自定义的WireMock扩展程序,该扩展名将分析WireMock消耗的每个映射。我们将只需要修改其中包含saveLink
的一个。
class CustomExtension extends ResponseTransformer {
@Override
String getName() {
return "url-transformer";
}
/**
* Transformer that converts the save the way we want it to look like
*/
@Override
Response transform(Request request, Response response, FileSource files, Parameters parameters) {
if (requestRelatedToMyParticularCase(response)) {
String body = ""{"saveLink" : "http://"+ url.host + ":" + url.port + "/v2/entity/save"}"";
return new Response(response.getStatus(), response.getStatusMessage(),
body, response.getHeaders(), response.wasConfigured(), response.getFault(), response.isFromProxy());
}
// if it's not related continue as usual
return response;
}
private boolean requestRelatedToMyParticularCase(Response response) {
// is it related to your particular scenario ?
return response.bodyAsString.contains("saveLink");
}
/**
* We want to apply this transformation for all mappings
*/
@Override
boolean applyGlobally() {
return true
}
}
现在,您可以创建一个实现HttpServerStub
的类,并按照此处介绍的方式注册-http://cloud.spring.io/spring-cloud-cloud-static/dalston.sr3/#_custom_stub_runner。它基本上是WireMockHttpServerStub
的副本,并具有更改,我们可以手动添加变压器
public class MyCustomWireMockHttpServerStub implements HttpServerStub {
private static final Logger log = LoggerFactory.getLogger(MyCustomWireMockHttpServerStub.class);
private static final int INVALID_PORT = -1;
private WireMockServer wireMockServer;
@Override
public HttpServerStub start(int port) {
this.wireMockServer = new WireMockServer(myConfig().port(port)
.notifier(new Slf4jNotifier(true)));
this.wireMockServer.start();
return this;
}
private WireMockConfiguration myConfig() {
if (ClassUtils.isPresent("org.springframework.cloud.contract.wiremock.WireMockSpring", null)) {
return WireMockSpring.options()
.extensions(responseTransformers());
}
return new WireMockConfiguration().extensions(responseTransformers());
}
private Extension[] responseTransformers() {
List<Extension> extensions = new ArrayList<>();
extensions.add(defaultResponseTemplateTransformer());
extensions.add(new CustomExtension());
return extensions.toArray(new Extension[extensions.size()]);
}
private ResponseTemplateTransformer defaultResponseTemplateTransformer() {
return new ResponseTemplateTransformer(false, helpers());
}
@Override
public int port() {
return isRunning() ? this.wireMockServer.port() : INVALID_PORT;
}
@Override
public boolean isRunning() {
return this.wireMockServer != null && this.wireMockServer.isRunning();
}
@Override
public HttpServerStub start() {
if (isRunning()) {
if (log.isDebugEnabled()) {
log.debug("The server is already running at port [" + port() + "]");
}
return this;
}
return start(SocketUtils.findAvailableTcpPort());
}
@Override
public HttpServerStub stop() {
if (!isRunning()) {
if (log.isDebugEnabled()) {
log.debug("Trying to stop a non started server!");
}
return this;
}
this.wireMockServer.stop();
return this;
}
@Override
public HttpServerStub registerMappings(Collection<File> stubFiles) {
if (!isRunning()) {
throw new IllegalStateException("Server not started!");
}
registerStubMappings(stubFiles);
return this;
}
@Override public String registeredMappings() {
Collection<String> mappings = new ArrayList<>();
for (StubMapping stubMapping : this.wireMockServer.getStubMappings()) {
mappings.add(stubMapping.toString());
}
return jsonArrayOfMappings(mappings);
}
private String jsonArrayOfMappings(Collection<String> mappings) {
return "[" + StringUtils.collectionToDelimitedString(mappings, ",n") + "]";
}
@Override
public boolean isAccepted(File file) {
return file.getName().endsWith(".json");
}
StubMapping getMapping(File file) {
try (InputStream stream = Files.newInputStream(file.toPath())) {
return StubMapping.buildFrom(
StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
}
catch (IOException e) {
throw new IllegalStateException("Cannot read file", e);
}
}
private void registerStubMappings(Collection<File> stubFiles) {
WireMock wireMock = new WireMock("localhost", port(), "");
registerDefaultHealthChecks(wireMock);
registerStubs(stubFiles, wireMock);
}
private void registerDefaultHealthChecks(WireMock wireMock) {
registerHealthCheck(wireMock, "/ping");
registerHealthCheck(wireMock, "/health");
}
private void registerStubs(Collection<File> sortedMappings, WireMock wireMock) {
for (File mappingDescriptor : sortedMappings) {
try {
wireMock.register(getMapping(mappingDescriptor));
if (log.isDebugEnabled()) {
log.debug("Registered stub mappings from [" + mappingDescriptor + "]");
}
}
catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Failed to register the stub mapping [" + mappingDescriptor + "]", e);
}
}
}
}
private void registerHealthCheck(WireMock wireMock, String url) {
registerHealthCheck(wireMock, url, "OK");
}
private void registerHealthCheck(WireMock wireMock, String url, String body) {
wireMock.register(
WireMock.get(WireMock.urlEqualTo(url)).willReturn(WireMock.aResponse().withBody(body).withStatus(200)));
}
}