Coder Social home page Coder Social logo

wiremock / wiremock Goto Github PK

View Code? Open in Web Editor NEW
6.1K 138.0 1.4K 42.59 MB

A tool for mocking HTTP services

Home Page: https://wiremock.org/

License: Apache License 2.0

Shell 0.03% XSLT 0.42% Java 99.00% HTML 0.33% JavaScript 0.04% Scala 0.19%
wiremock json mocking stubbing java xml rest http apis mock-server

wiremock's Introduction

WireMock - flexible and open source API mocking

WireMock Logo

Build Status Docs a Participate Maven Central

WireMock is a popular open-source tool for API mock testing with over 5 million downloads per month. It can help you to create stable test and development environments, isolate yourself from flakey 3rd parties and simulate APIs that don’t exist yet.

Started in 2011 as a Java library by Tom Akehurst, now WireMock spans across multiple programming languages and technology stacks. It can run as a library or client wrapper in many languages, or as a standalone server. There is a big community behind the project and its ecosystem.

WireMock supports several approaches for creating mock APIs - in code, via its REST API, as JSON files and by recording HTTP traffic proxied to another destination. WireMock has a rich matching system, allowing any part of an incoming request to be matched against complex and precise criteria. Responses of any complexity can be dynamically generated via the Handlebars based templating system. Finally, WireMock is easy to integrate into any workflow due to its numerous extension points and comprehensive APIs.

Key Features

WireMock can run in unit tests, as a standalone process or a container. Key features include:

  • HTTP response stubbing, matchable on URL, header and body content patterns
  • Configuration via a fluent Java API, JSON files and JSON over HTTP
  • Record/playback of stubs
  • Request verification
  • Fault and response delays injection
  • Per-request conditional proxying
  • Browser proxying for request inspection and replacement
  • Stateful behaviour simulation
  • Extensibility

Full documentation can be found at wiremock.org/docs.

Questions and Issues

If you have a question about WireMock, or are experiencing a problem you're not sure is a bug please post a message to the WireMock Community Slack in the #help channel.

On the other hand if you're pretty certain you've found a bug please open an issue.

Log4j Notice

WireMock only uses log4j in its test dependencies. Neither the thin nor standalone JAR depends on or embeds log4j, so you can continue to use WireMock 2.32.0 and above without any risk of exposure to the recently discovered vulnerability.

Contributing

WireMock exists and continues to thrive due to the efforts of contributors. Regardless of your expertise and time you could dedicate, there're opportunities to participate and help the project!

See the Contributing Guide for more information.

wiremock's People

Contributors

andre2i avatar chbatey avatar clboettcher avatar dependabot[bot] avatar dieppa avatar g-basak avatar gsmith85 avatar htmldoug avatar ikalu avatar jamietanna avatar jvergeldedios avatar kyle-winkelman avatar leeturner avatar mahoney avatar masonm avatar neilg avatar oleg-nenashev avatar philippe-granet avatar picimako avatar pks-1981 avatar reta avatar rowanhill avatar simonverhoeven avatar sullis avatar tomakehurst avatar tomasbjerre avatar tootedom avatar wojciechbulaty avatar xalvarez avatar zheng-wang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wiremock's Issues

Ability to specify output directory for recorded mapping/files

This is more of a feature request. But it would be nice to be able to specify sub directories for recorded files both the generated mapping & __files.

Example:

java -jar wiremock.jar --record-mappings --mappings-dir=somedir  --files-dir=somedir

Allows for really easy organization when only trying to record variations of a specific endpoint.

Osgi-Version

Hey there,

i tried to use wiremock in my osgi-runtime wit pax-exam. But i was not able to get it running. At many tries i got this exception:

java.lang.IllegalAccessError: tried to access method org.apache.commons.logging.LogFactory.<init>()V from class org.apache.commons.logging.impl.SLF4JLogFactory
    at org.apache.commons.logging.impl.SLF4JLogFactory.<init>(SLF4JLogFactory.java:66)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance0(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at wiremock.org.apache.commons.logging.LogFactory.createFactory(LogFactory.java:1160)
    at wiremock.org.apache.commons.logging.LogFactory$2.run(LogFactory.java:1065)
    at java.security.AccessController.doPrivileged(Native Method)
    at wiremock.org.apache.commons.logging.LogFactory.newFactory(LogFactory.java:1062)
    at wiremock.org.apache.commons.logging.LogFactory.getFactory(LogFactory.java:569)
    at wiremock.org.apache.commons.logging.LogFactory.getLog(LogFactory.java:685)
    at wiremock.org.apache.http.impl.conn.PoolingClientConnectionManager.<init>(PoolingClientConnectionManager.java:73)
    at wiremock.org.apache.http.impl.conn.PoolingClientConnectionManager.<init>(PoolingClientConnectionManager.java:99)
    at wiremock.org.apache.http.impl.conn.PoolingClientConnectionManager.<init>(PoolingClientConnectionManager.java:85)
    at com.github.tomakehurst.wiremock.http.HttpClientFactory.createClientConnectionManagerWithSSLSettings(HttpClientFactory.java:85)
    at com.github.tomakehurst.wiremock.http.HttpClientFactory.createClient(HttpClientFactory.java:53)
    at com.github.tomakehurst.wiremock.http.HttpClientFactory.createClient(HttpClientFactory.java:69)
    at com.github.tomakehurst.wiremock.http.ProxyResponseRenderer.<init>(ProxyResponseRenderer.java:50)
    at com.github.tomakehurst.wiremock.WireMockServer.<init>(WireMockServer.java:80)
    at com.github.tomakehurst.wiremock.WireMockServer.<init>(WireMockServer.java:129)
    at com.bosch.sh.devicedriver.itest.WireMockSampleTest.testThis(WireMockSampleTest.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runChild(ContainerTestRunner.java:67)
    at org.ops4j.pax.exam.invoker.junit.internal.ContainerTestRunner.runChild(ContainerTestRunner.java:37)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
    at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.invokeViaJUnit(JUnitProbeInvoker.java:111)
    at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.findAndInvoke(JUnitProbeInvoker.java:84)
    at org.ops4j.pax.exam.invoker.junit.internal.JUnitProbeInvoker.call(JUnitProbeInvoker.java:72)
    at org.ops4j.pax.exam.nat.internal.NativeTestContainer.call(NativeTestContainer.java:106)
    at org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactor.invoke(AllConfinedStagedReactor.java:84)
    at org.ops4j.pax.exam.junit.PaxExam$2.evaluate(PaxExam.java:294)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.ops4j.pax.exam.junit.PaxExam.run(PaxExam.java:111)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

or

javax.servlet.UnavailableException: Servlet class com.github.tomakehurst.wiremock.servlet.HandlerDispatchingServlet is not a javax.servlet.Servlet

Has anyone tried to get WireMock running in an OSGi-Environment?

jsonRepresentation test fails

I tried building the master branch on Ubuntu 13.04 with openjdk-7 and the build reports one test is failing. Before I started digging through the code I thought I'd post here to see if this is something someone has seen before. The Test report follows... FYI I tried the 1.25 release and that built with just warnings...

java.lang.AssertionError:
Expected: eqIgnoringWhiteSpace("{\n "url" : "/my/url",\n "absoluteUrl" : "http://mydomain.com/my/url\",\n "method" : "GET",\n "headers" : {\n "Accept-Language" : "en-us,en;q=0.5"\n },\n "body" : "some text",\n "browserProxyRequest" : true,\n "loggedDate" : 1339083581000,\n "loggedDateString" : "2012-06-07 16:39:41"\n }")
got: "{\n "url" : "/my/url",\n "absoluteUrl" : "http://mydomain.com/my/url\",\n "method" : "GET",\n "headers" : {\n "Accept-Language" : "en-us,en;q=0.5"\n },\n "body" : "some text",\n "browserProxyRequest" : true,\n "loggedDate" : 1339101581000,\n "loggedDateString" : "2012-06-07 16:39:41"\n}"

at org.junit.Assert.assertThat(Assert.java:780)
at org.junit.Assert.assertThat(Assert.java:738)
at com.github.tomakehurst.wiremock.verification.LoggedRequestTest.jsonRepresentation(LoggedRequestTest.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
at org.jmock.integration.junit4.JMock$1.invoke(JMock.java:37)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:105)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMethod(JUnit4ClassRunner.java:98)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:54)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:52)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:80)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:47)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:49)
at sun.reflect.GeneratedMethodAccessor56.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103)
at sun.reflect.GeneratedMethodAccessor55.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:66)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)

urlPattern with question mark

hi, tom

I have used the wiremock, it's a good job.
I hava a problerm to use the urlPattern.

my url is like this: "http://192.168.181.22:8080/NBS?Action=describeVolume&name=abc"

Test 1

so, I define the mapping file like this:
{
"request": {
"method": "GET",
"urlPattern": "/NBS?Action=describeVolume&name=.*"
},
"response": {
"status": 200,
"bodyFileName": "desc.json",
"headers": {
"Content-Type": "application/json",
"Cache-Control": "max-age=86400"
}
}
}

When access this url(http://192.168.181.22:8080/NBS?Action=describeVolume&name=abc) in brower, it returns

HTTP ERROR 404Problem accessing /__files/NBS. Reason:
NOT_FOUND

Test 2

I modify urlPattern(add / before ?) to:
"urlPattern": "/NBS/?Action=describeVolume&name=.*"

Then, access this url(http://192.168.181.22:8080/NBS/?Action=describeVolume&name=abc) in brower, it returns

HTTP ERROR 404Problem accessing /__files/NBS. Reason:
NOT_FOUND

And, I modify the url(drop the question mark)
http://192.168.181.22:8080/NBS/Action=describeVolume&name=abc
The browser retuen my expcted result.

So, my question is, how can i modify the urlPattern to get my expect result with the original url.

best regards

kerry jin

Not Recording Post Body

This is a feature request. It would be nice if we could record post body strings. We have the body in the response right before we create the mapping into json. If we send it along then add a little medicine to the json creation we should be good to go.

How to build standalone jar?

I'm interested in running WireMock in Standalone mode. The documentation says to use this command:

$ java -jar wiremock-1.30-standalone.jar

However, I've thus far been unable to build this jar file. I tried running "gradle build", and it got part way through the build process before failing with:

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':signArchives'.

    Cannot perform signing task ':signArchives' because it has no configured signatory

In spite of this failure, it appears that the task did manage to build the following jars:

wiremock-1.31.jar
wiremock-1.31-javadoc.jar
wiremock-1.31-sources.jar

but not

wiremock-1.31-standalone.jar

I'm not seeing any other gradle tasks that look like they're used to build the standalone jar. Am I missing something?

Body JSON matcher thoughts

Hi Tom,
Excellent library - we are finding it very useful when integration testing REST APIs!

Just wondering what your thoughts are regarding the best way to verify JSON body content? I notice you have JSON path matching, but my understanding is that this can only verify the presence of a JSON element rather than the entire document?

Ideally we would abstract away from the String, to match on the JSON AST, so that the formatting (concise or pretty) and spacing of the JSON is not important.

To do this, my approach would be to write a custom ValueMatchingStrategy and ValuePattern, but the JSON transmission between the client and the admin interface then causes significantly more complexity with the deserialisation side given the polymorphic nature of the model.

An alternative would be for me to submit a patch that adds full JSON AST content matching to the existing ValueMatchingStrategy and ValuePattern?

Cheers.

Header matching does not seem to work

Discovered this when attempting to setup stubbing to expect basic auth.

The following setup should never match and therefore fail the JUnit test, since it's expecting a contrived header that my client isn't sending. However, wiremock is matching the requests anyway, returning the response, and my test passes anyway.

stubFor(post(urlEqualTo("/some/url"))
        .withRequestBody(containing(expectedBodyContent))
        .withHeader("NoSuchHeader", equalTo("This better not be here"))
        .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(json)));

SSL errors when proxying with WireMock in Java 7 on Mac

Certain SSL certs will cause errors if you are trying to proxy thru WireMock on Java 7 on a Mac.

I am leaving this as a note to people encountering these exceptions.

The solution is to execute WireMock using Java 6 on your Mac.
Depending on your setup you might find Java 6 here: /System/Library/Frameworks/JavaVM.framework/Home/bin/java

This may be more of a Java 7 issue than a WireMock issue, so you can close this if you like. Maybe you can add it to the documentation site. Also, maybe issue a warning at WireMock startup if it is running in Java 7.

Here are some of the exceptions you might encounter:

java.lang.RuntimeException: javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
    at com.github.tomakehurst.wiremock.http.ProxyResponseRenderer.render(ProxyResponseRenderer.java:75)
    at com.github.tomakehurst.wiremock.http.StubResponseRenderer.render(StubResponseRenderer.java:47)
    at com.github.tomakehurst.wiremock.http.AbstractRequestHandler.handle(AbstractRequestHandler.java:40)
    at com.github.tomakehurst.wiremock.servlet.HandlerDispatchingServlet.service(HandlerDispatchingServlet.java:75)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at wiremock.org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at wiremock.org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:401)
    at wiremock.org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
    at wiremock.org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
    at wiremock.org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at wiremock.org.mortbay.jetty.Server.handle(Server.java:326)
    at wiremock.org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at wiremock.org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
    at wiremock.org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
    at wiremock.org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
    at wiremock.org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at wiremock.org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
    at com.github.tomakehurst.wiremock.jetty.DelayableSocketConnector$1.run(DelayableSocketConnector.java:49)
    at wiremock.org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:541)
    at sun.security.ssl.InputRecord.read(InputRecord.java:374)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
    at wiremock.org.mortbay.jetty.security.SslSocketConnector$SslConnection.run(SslSocketConnector.java:708)
    at com.github.tomakehurst.wiremock.jetty.DelayableSslSocketConnector$1.run(DelayableSslSocketConnector.java:54)
    at wiremock.org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints
    at com.github.tomakehurst.wiremock.http.ProxyResponseRenderer.render(ProxyResponseRenderer.java:75)
    at com.github.tomakehurst.wiremock.http.StubResponseRenderer.render(StubResponseRenderer.java:47)
    at com.github.tomakehurst.wiremock.http.AbstractRequestHandler.handle(AbstractRequestHandler.java:40)
    at com.github.tomakehurst.wiremock.servlet.HandlerDispatchingServlet.service(HandlerDispatchingServlet.java:75)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at wiremock.org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at wiremock.org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:401)
    at wiremock.org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
    at wiremock.org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
    at wiremock.org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at wiremock.org.mortbay.jetty.Server.handle(Server.java:326)
    at wiremock.org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at wiremock.org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
    at wiremock.org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
    at wiremock.org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
    at wiremock.org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at wiremock.org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
    at wiremock.org.mortbay.jetty.security.SslSocketConnector$SslConnection.run(SslSocketConnector.java:713)
    at com.github.tomakehurst.wiremock.jetty.DelayableSslSocketConnector$1.run(DelayableSslSocketConnector.java:54)
    at wiremock.org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

QueryString parameters

Currently, it is supported to add some criteria to the incoming request using MappingBuilder.withHeader and MappingBuilder.withRequestBody. Parameter-criteria can only be added by appending the expected querystring to the URI.

It would be great if something like withParameter() would be added, just like the withHeader(). It would allow more filtering possibilities.

Question: Avoiding the static defaultInstance of WireMock

More of a question than an "issue" (is there a better forum for questions like this?)

If I new up a server

WireMockServer server = new WireMockServer(wireMockConfig().port(port));

the stubFor calls will set the stubbed response on the "defaultInstance" within WireMock. This is a different instance than my server above. The example being

stubFor(get(urlEqualTo("/test")).willReturn(aResponse().withHeader("Content-Type", "text/plain").withBody("Hello world!")));

How do I setup the stub for my private instance and not the default instance? I can do the following before setting the stub but this seems like I must have got something wrong? Does it rely on a static variable for the instance?

configureFor("localhost", port);

release tags

Could you add git tags corresponding to releases? :)

Failed to generate mappings for URL with empty path (e.g. http://www.google.com)

generateNewUniqueFileNameFromRequest fails to generate mapping filename if URI from request contains nothing after "/", e.g http://google.com or http://s3.amazonaws.com:

private String generateNewUniqueFileNameFromRequest(Request request, String prefix, String id) {
    URI uri = URI.create(request.getUrl());
    String[] pathNodes = uri.getPath().split("/");
    StringBuilder sb = new StringBuilder(prefix).append("-");
    if (pathNodes.length > 1) {
        sb.append(pathNodes[pathNodes.length - 2]).append("-");
    }

    sb.append(pathNodes[pathNodes.length - 1])  <-- ArrayIndexOutOfBoundsException
        .append("-")
        .append(id)
        .append(".json");

    return sb.toString();
}

WireMock mocking also the proxy?

Hi,

me again :)
I want to test whether the proxy konfigured in my program is used for each request. So is there any way to mock also the proxy with WireMock. In the end this means, that I have to run two WireMocks inparallel, have I?

Best Regards

Limit in memory journaling

From looking at the code I see that in memory journaling is always enabled when running in standalone mode, and additionally this journaling has no limit set. Are you planning to implement any limits on this journaling (like configuring wiremock to only hold last X requests), or alternative pluggable journaling mechanisms (like file, or db journaling)?

I'm asking this because I plan to use wiremock, among other things, to mock services while I do stress testing over my service that uses other "mocked" services. So if there is no limit on journaling the wiremock memory will increase without limits.

WireMock server failing to stop with Cucumber

I've been using WireMock with Cucumber (Cuke4Duke and CucumberJVM) and have been experiencing problems with the lifecycle of WireMock.

I start the server with the following as I can't use the @rule as it is for JUnit, not cucumber.

wireMockServer = new WireMockServer(wireMockConfig().port(8082));
wireMockServer.start();
WireMock.configureFor("localhost", 8082);
WireMock.reset();

and stopping with

wireMockServer.stop();

When wireMockServer.stop() is called then I get an exception

[INFO] 2013-05-31 15:26:24,748 [main] ERROR wiremock.org.mortbay.log - EXCEPTION 
[INFO] java.lang.NullPointerException
[INFO]        at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:205)
[INFO]        at javax.servlet.GenericServlet.log(GenericServlet.java:300)
[INFO]        at javax.servlet.GenericServlet.destroy(GenericServlet.java:122)
[INFO]        at wiremock.org.mortbay.jetty.servlet.ServletHolder.destroyInstance(ServletHolder.java:318)
[INFO]        at wiremock.org.mortbay.jetty.servlet.ServletHolder.doStop(ServletHolder.java:289)
[INFO]        at wiremock.org.mortbay.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:76)
[INFO]        at wiremock.org.mortbay.jetty.servlet.ServletHandler.doStop(ServletHandler.java:185)
[INFO]        at wiremock.org.mortbay.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:76)
[INFO]        at wiremock.org.mortbay.jetty.handler.HandlerWrapper.doStop(HandlerWrapper.java:142)
[INFO]        at wiremock.org.mortbay.jetty.handler.ContextHandler.doStop(ContextHandler.java:592)
[INFO]        at wiremock.org.mortbay.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:76)
[INFO]        at wiremock.org.mortbay.jetty.handler.HandlerCollection.doStop(HandlerCollection.java:169)
[INFO]        at wiremock.org.mortbay.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:76)
[INFO]        at wiremock.org.mortbay.jetty.handler.HandlerWrapper.doStop(HandlerWrapper.java:142)
[INFO]        at wiremock.org.mortbay.jetty.Server.doStop(Server.java:283)
[INFO]        at wiremock.org.mortbay.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:76)
[INFO]        at com.github.tomakehurst.wiremock.WireMockServer.stop(WireMockServer.java:148)
[INFO]        at com.thehutgroup.acceptancetests.support.MockOrderManager.stop(MockOrderManager.java:39)
[INFO]        at com.thehutgroup.acceptancetests.steps.SetupSteps.tearDown(SetupSteps.java:27)
[INFO]        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[INFO]        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[INFO]        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[INFO]        at java.lang.reflect.Method.invoke(Method.java:597)
[INFO]        at cuke4duke.internal.java.MethodInvoker.invoke(MethodInvoker.java:21)
[INFO]        at cuke4duke.internal.jvmclass.ClassLanguage.invoke(ClassLanguage.java:120)
[INFO]        at cuke4duke.internal.jvmclass.ClassLanguage.invokeHook(ClassLanguage.java:114)
[INFO]        at cuke4duke.internal.java.JavaHook.invoke(JavaHook.java:22)
[INFO]        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[INFO]        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[INFO]        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[INFO]        at java.lang.reflect.Method.invoke(Method.java:597)

Jetty seems not to close and the port (8082) is left occupied, such that should I start to run another test, starting WireMock fails to bind to port 8082.

Negative matching

Hi,

Is it already possible to check the absence of a header? For example, something like

verify(getRequestedFor(urlEqualTo("/test")).withoutHeader("Authorization"));

How to control scenario names?

Hi,

started using wiremock couple of months ago, really speeds up development. Thank you very much for the effort!

Now that I feel more comfortable with it, I have started using it in a bit more complicated cases ... and some of them are just not solvable without the state machine.

http://wiremock.org/stateful-behaviour.html -> this is helpful, but none of the examples states how to modify the scenario you're in ... and I just cannot get this to work.

thanks in advance for any tips!

regards,
Adrian

some state being persisted between tests

I have some tests that give different results when run as a suite and when run individually.

I am using

@Rule
@ClassRule
public static WireMockClassRule wireMockRule = new WireMockClassRule(8888);

each test then has a setup similar to

stubFor(post(urlEqualTo("/test")).willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "text/xml; charset=UTF-8") ....

The problem is that when run as a suite, my first test is not sending the charset=UTF-8, and I get gibberish characters. This same test when run on it's own is fine.

So given the way this is set up is it possible some state is leaking?

HttpHostConnectException on Windows XP using JUnit with multiple test methods

We are seeing an HttpHostConnectException which appears to only occur on Windows XP when using wiremock in a JUnit test case which contains multiple test methods (Note: The same test works fine on Windows 7 and Linux). The first test method which runs does so successfully and you can see in the output there is no exception the first time it starts/stops wiremock, but all test methods after that result in the same exception while attempting to stub files:

<![CDATA[2013-11-14 07:45:42.546:INFO::Logging to STDERR via wiremock.org.mortbay.log.StdErrLog
2013-11-14 07:45:42.625:INFO::jetty-6.1.x
2013-11-14 07:45:42.750:INFO::Started [email protected]:9898
log4j:WARN No appenders could be found for logger (wiremock.org.apache.http.impl.conn.PoolingClientConnectionManager).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
2013-11-14 07:45:43.484:INFO:/__admin:RequestHandlerClass from context returned com.github.tomakehurst.wiremock.http.AdminRequestHandler
2013-11-14 07:45:43.812:INFO:/:RequestHandlerClass from context returned com.github.tomakehurst.wiremock.http.StubRequestHandler
2013-11-14 07:45:44.187:INFO::Stopped [email protected]:9898
2013-11-14 07:45:44.187:INFO::jetty-6.1.x
2013-11-14 07:45:44.187:INFO::Started [email protected]:9898
wiremock.org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:9898 refused
at wiremock.org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:190)
at wiremock.org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)
at wiremock.org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:645)
at wiremock.org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:480)
at wiremock.org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at wiremock.org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at wiremock.org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at com.github.tomakehurst.wiremock.client.HttpAdminClient.postJsonAssertOkAndReturnBody(HttpAdminClient.java:136)
at com.github.tomakehurst.wiremock.client.HttpAdminClient.addStubMapping(HttpAdminClient.java:67)
at com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:109)
at com.github.tomakehurst.wiremock.client.WireMock.givenThat(WireMock.java:60)
at com.github.tomakehurst.wiremock.client.WireMock.stubFor(WireMock.java:64)
at com.dummy.test.common.net.TestDownloadRequest.stubFile(TestDownloadRequest.java:327)
at com.dummy.test.common.net.TestDownloadRequest.stubFile(TestDownloadRequest.java:313)
at com.dummy.test.common.net.TestDownloadRequest.stubFile(TestDownloadRequest.java:308)
at com.dummy.test.common.net.TestDownloadRequest.testBegunTimeout(TestDownloadRequest.java:129)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at com.github.tomakehurst.wiremock.junit.WireMockRule$1.evaluate(WireMockRule.java:73)
at org.junit.rules.RunRules.evaluate(RunRules.java:18)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:518)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1052)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:906)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.TwoStacksPlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at wiremock.org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:127)
at wiremock.org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)
... 40 more
2013-11-14 07:45:45.203:INFO::Stopped [email protected]:9898
2013-11-14 07:45:45.234:INFO::jetty-6.1.x
2013-11-14 07:45:45.234:INFO::Started [email protected]:9898
wiremock.org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:9898 refused

etc...

In the JUnit test we have:
@rule
public WireMockRule _wireMockRule = new WireMockRule(PORT);

Where PORT is currently 8989 and then each test method stubs the files which should be expected for that test.

Remote Stop/Kill Command in standalone mode

Hi,

First of all great little tool, this is realy good stuff!

I was wondering whether it might be possible to request a feature which will allow for a remote stop/kill command (for example via an admin REST call).
This could be very handy for example when using maven and you want to start WireMock up in the pre-integration-phase, and then stop it afterwards in the post-integration-phase, ala jetty/tomcat type style. An actual maven plugin to do this would be most ideal :) but just the basic remote kill functionality would be a great addition IMHO.

Many thanks for all the good work thus far
Nicki

Server running out of memory

I started one standalone server version 1.33 and I created only one mock and then I tried to hit it with our load generation tool, initially I was able to get 6000 requests per second but in 10-15 mins server ran out of memory, I was using -Xms1g and -Xmx2g. Is it a bug or I am using it in wrong way??

NoClassDefFoundError: org/mortbay/component/LifeCycle

When I try to start things up I get the exception.

The Jetty dependency in build.gradle and the pom.xml in central repo doesn't include this class. Bit confused :S

java.lang.NoClassDefFoundError: org/mortbay/component/LifeCycle
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

I start up with the following

private final WireMockServer server = new WireMockServer(new WireMockConfiguration().port(port));

wiremock 1.35 proxy modifies requests before calling the actual web service

I would love to use Wiremock to help unit test some client software I'm writing that calls a third-party REST service. It appears that running the standalone jar with --proxy-all causes the header to be rewritten in a way that is not compatible with the web service I'm calling. I need the request to be passed through to the proxy without the header changes, etc.

I'm writing to see if this is something you'd be interested in supporting, or perhaps someone in the community has a suggestion for how to get Wiremock to behave in a way that will work with this web service. Any thoughts?

Wiremock is started like this:
java -jar wiremock-1.35-standalone.jar --proxy-all="http://10.0.1.65" --record-mappings --verbose

The web service calls arrive at the Wiremock proxy looking like this:

PUT /rest/testdata/22fb095c8fac450296bf889e8192a5b5 HTTP/1.1
Cookie: hcp-ns-auth=cmlhbHRv:89efe08fe280e438f3b3085fa94309b1
User-Agent: Jakarta Commons-HttpClient/3.0.1
Host: rialto.rialto.something-demo.somethingdomain.com
Transfer-Encoding: chunked

3
abc
0

However, the call to the actual web service is rewritten: it has a Content-Length instead of chunked encoding, and some of the headers are removed or changed:

PUT /rest/testdata/299e861855584fbfa8121af313edbff5 HTTP/1.1
Cookie: hcp-ns-auth=cmlhbHRv:89efe08fe280e438f3b3085fa94309b1
User-Agent: Jakarta Commons-HttpClient/3.0.1
Content-Length: 3
Content-Type: text/plain; charset=utf-8
Host: 10.0.1.65
Connection: Keep-Alive

abc

SSL exception when trying to proxy https

Hi,

we're trying to use wiremock as an https proxy between our application and a remote server (we would like to filter a subset of requests). We set the https port in the wiremock configuration. However, we are getting the following error when our application tries to establish an https connection:

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:671) ~[na:1.7.0_45]
at sun.security.ssl.InputRecord.read(InputRecord.java:504) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323) ~[na:1.7.0_45]
at wiremock.org.mortbay.jetty.security.SslSocketConnector$SslConnection.run(SslSocketConnector.java:708) ~[wiremock-1.36-standalone.jar:na]
at com.github.tomakehurst.wiremock.jetty.DelayableSslSocketConnector$1.run(DelayableSslSocketConnector.java:54) [wiremock-1.36-standalone.jar:na]
at wiremock.org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) [wiremock-1.36-standalone.jar:na]

Did we miss anything or is this a known issue? Thanks for your help.

Feature Request: Java coded responses

First, i believe Wiremock is totally great.
The only missing part is the ability to add a custom response to it.

Let say i want to make a POST to /api/rareCalculation with some numbers,
and make the server return some calculated numbers.
I am not talking about complex logic or using complicated classes,
just the basic java applied to a calculation or logic flow.

One solution could take the form of one or several jar files, maybe in a "jars" folder.
Wiremock would load those jars at startup and then use them as described
in classic stub json files.

Under these conditions one could code a handler class, put it in a jar file,
then write the stub file specifying URL mapping and conditions, and use Wiremock as usual.

I offer my help if needed, as long as it does not include figuring out how to do this,
without any help whatsoever, since i don't have that kind of time.
Regards.

Android support

Any plans for Android support? I tried it and it didn't work out of the box.

[Question] Use GET request parameters in response?

Hi,

I want to use WireMock to mock the backend for my app.
Just a simple question: Is it possible to use parameter values of my get request in my response?

Example:
If I send a request like

"/api/events\\?date=*"

I would like to response a JSON like:

{
   "events":{
      "event":{
         "name":"event1",
         "date":"[date]"
      },
      "event":{
         "name":"event2",
         "date":"[date+1]"
      },
      "event":{
         "name":"event3",
         "date":"[date+2]"
      }

[date] should be replaced by the value from the request.
Is this possible using WireMock?

Thanks for the great tool and your answer ;)

Yours sincerely
Illaz

SSL issues on Fedora 18 and Windows

I have been trying to evaluate Wiremock, but I am unable to get an SSL connection to proxy through it.

I am running it with:
java -jar wiremock-1.34-standalone.jar --enable-browser-proxying --port 9090 --https-port 9091 --verbose

and then configured firefox & chrome to use ports 9090 & 9091.

HTTP works fine.

But HTTPS never works.
In every case I receive the following exception, and no data back:

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.net.ssl.internal.ssl.InputRecord.handleUnknownRecord(InputRecord.java:652)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:484)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:863)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1215)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1199)
at wiremock.org.mortbay.jetty.security.SslSocketConnector$SslConnection.run(SslSocketConnector.java:708)
at com.github.tomakehurst.wiremock.jetty.DelayableSslSocketConnector$1.run(DelayableSslSocketConnector.java:54)
at wiremock.org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

Am I missing something in the configuration?
Is this something you know about?

PS: I also tried to run Wiremock on a windows machine, and got the same failure.

Use SLF4J instead of Log4j

Rather than using Log4j directly, it would be better to use the SLF4J API so that users can choose the underlying logger themselves.

Regex matching fails in certain cases

Found some odd behavior

/api/something/somelong-string does not match /api/something/.*

I would expect that to match. There is also a mapping for /api/.* that has a priority of 6 but the other mapping listed above has a priority of 1. So I don't think it is a precedence bug.

Documentation flaw in 'Request body matching'

The documentation mentions the options for withRequestBody(): equalTo, matching, notMatching, containing. The same options for the JSON variant have differing names: equalTo, matches, doesNotMatch, contains. This should be pointed out. Additionally the options matchingJsonPath / matchesJsonPath are not mentioned.

Friendly output of Http messages

It's be great if I could just toString the logged HTTP messages.

So far, I've decorated the classes with something to add a basic string representation but I'd really like to see as close to the actually raw HTTP message as possible.

For example, I'm doing this for now...

public class WiremockLoggedRequest {

    private final List<LoggedRequest> requests;

    public WiremockLoggedRequest(List<LoggedRequest> requests) {
        this.requests = requests;
    }

    public String toString() {
        LoggedRequest request = requests.get(0);
        StringBuilder builder = new StringBuilder()
                .append(request.getMethod())
                .append(" ")
                .append(request.getUrl())
                .append("\n")
                .append(new WiremockHttpHeaders(request.getHeaders()));
        return builder.toString();
    }
}

and

class WiremockHttpHeaders {

    private final HttpHeaders headers;

    public WiremockHttpHeaders(HttpHeaders headers) {
        this.headers = headers;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (String header : headers.keys())
            builder.append(headers.getHeader(header));
        return builder.toString();
    }
}

but these might as well be on the objects themselves.

Also, the docs imply that Wiremock will allow requests without setting up a specific stubFor when using findAll for example. This doesn't seem to be the case (Jersey returns 404 if I try). Have I got the wrong end of the stick?

Server starts on 8080 port only. 1.30 version

This code throws HttpHostConnectException. However it works fine with 8080 port.

        WireMockServer wireMockServer = new WireMockServer(wireMockConfig().port(8888)); // works only with 8080 port
        wireMockServer.start();
        Thread.sleep(2000);
        WireMock.reset();
        wireMockServer.stop();

I just created empty maven module with 1.30-th wiremock dependency. Issue reproduced on several machines.

Full trace:

Exception in thread "main" java.lang.RuntimeException: org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8080 refused
    at com.github.tomakehurst.wiremock.client.HttpAdminClient.postJsonAndReturnStatus(HttpAdminClient.java:135)
    at com.github.tomakehurst.wiremock.client.HttpAdminClient.postEmptyBodyAndReturnStatus(HttpAdminClient.java:162)
    at com.github.tomakehurst.wiremock.client.HttpAdminClient.resetMappings(HttpAdminClient.java:78)
    at com.github.tomakehurst.wiremock.client.WireMock.resetMappings(WireMock.java:78)
    at com.github.tomakehurst.wiremock.client.WireMock.reset(WireMock.java:82)
    at main.main(main.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8080 refused
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:190)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:645)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:480)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
    at com.github.tomakehurst.wiremock.client.HttpAdminClient.postJsonAndReturnStatus(HttpAdminClient.java:127)
    ... 10 more
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:127)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)
    ... 17 more

Gradle Build

Gradle was failing to build the script on line 57 due to being deprecated. It might just be affecting newer versions of Gradle.

Before:

repositories {
        mavenRepo url:['https://oss.sonatype.org']
        mavenCentral()
    }

After:

repositories {
        maven {
            url "https://oss.sonatype.org"
        }
        mavenCentral()
    }

[ - Illegal character in the query

Apache HttpClient + WireMock

Hi,

I have observed strange behavior when accessing a mocked server instance of WireMock with the Apache HttpClient.
When I debug the test, and go to the mocked server address in my browser, I got the expected response. However accessing the same address with the Apache HttpClient leads to a 404 response.

Necessary Information about the Test (not the whole test, only WireMock related configurations):

 @RunWith(SpringJUnit4ClassRunner.class)
 public class Test {

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(9999);

    @Before
    public void reset() {
        WireMock.reset();
    }

    @Test
    public void test() {
        String request = "Any Request";
        stubFor(get(urlEqualTo("/")).willReturn(aResponse().withStatus(200).withBody(response.getBytes())));

        verify(postRequestedFor(urlEqualTo("/"))
            .withHeader("Content-Type", equalTo("text/xml; charset=UTF-8"))
            .withHeader("SOAPAction", equalTo("")).withRequestBody(equalTo(request)));
     }
 }

Nice to know is, that the verification is valid. So the mock is obviously called correctly.

HttpClient-Code calling the mocked server address:

HttpClient client = new DefaultHttpClient();
ByteArrayEntity requestEntity = new ByteArrayEntity(_requestStr_.getBytes());
requestEntity.setContentType("text/xml; charset=UTF-8");
requestEntity.setContentEncoding("UTF-8");

HttpPost httpPost = new HttpPost("http://localhost:9999");
httpPost.addHeader("SOAPAction", "");
httpPost.setEntity(requestEntity);
HttpResponse response = client.execute(httpPost);

HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream in = entity.getContent();
    try {
        System.out.print(new String(IOUtils.toByteArray(in)));
    } finally {
        in.close();
    }
}

Now I got the 404 Error html page from jetty, although the browser shows the right mocked response:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 404 NOT_FOUND</title>
</head>
<body><h2>HTTP ERROR 404</h2>
<p>Problem accessing /. Reason:
<pre>    NOT_FOUND</pre></p><hr /><i><small>Powered by Jetty://</small></i><br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                
<br/>                                                

</body>
</html>

Any suggestions why I got the right answer in my firefox browser and got a 404 via the Apache HttpClient? Perhaps are there any headers which are assumed to be in the request in order to let WireMock match the called URL and provide a declared response?

Reload of mappings

Are there any plans to include, or is there any existing functionality to either periodically and/or through the admin api to reload the mappings?. So whenever I add new mapping, or modify existing ones through the files within mappings folder in standalone, those changes can take place without having to restart the application.

Empty Request Body

A very strange issue that baffles me completely. Using WireMock in a test case with usage similar to

stubFor(get(urlEqualTo("/some/thing"))
        .willReturn(aResponse()
            .withHeader("Content-Type", "application/json")
            .withBody(bigLumpOfJSON)));

then the code under test was convinced that the body was empty. Under real use, the code is cheerfully seeing the expected JSON body, and flipping to use REST-Driver allowed me to successfully stub. The only thing I could think of was that it arises from the way that WireMock is writing to the output stream and Apache HTTP Client is trying to read from the input stream. The code under test uses HttpClient to handle the request, roughly as follows:

try {
    final HttpGet request = new HttpGet(statusUrl.toURI());
    final HttpResponse httpResponse = httpClient.execute(request);
    final int statusCode = getResponseCode(httpResponse);

    if (HttpStatus.SC_OK == statusCode) {
        final HttpEntity entity = httpResponse.getEntity();

        if (entity == null) {
            throw new ServiceUnavailable("No content in the response");
        } else {
            final String body = EntityUtils.toString(entity, "UTF-8");
            final Map<String, Object> statusData = mapper.readValue(body, Map.class);
            return Status.valueOf((String) statusData.get("status"));
        }

    } else {
        throw new ServiceUnavailable("Server Returned " + statusCode);
    }
} catch (URISyntaxException urie) {
    throw new ServiceUnavailable("invalid URL", urie);
} catch (IOException ioe) {
    throw new ServiceUnavailable("IO failure", ioe);
}

Debugging I could see that there was a non-null entity coming out of the response (yay!) but then the EntityUtils.toString() was returning an empty string. Ferreting into that a bit further, I could see that the various levels of HttpResponse contained an InputStream that was very definitely empty.

I'm more than happy to continue trying to get to the bottom of this issue, as the framework looks like a perfect match for our needs. It's just that my forehead is still sore from beating it on the desk last week before switching to REST-Driver.

URL Not Matching

Any ideas why this doesn't work any more? With the urlEqualTo UrlMatchingStrategy, one using .* or the following

    public static UrlMatchingStrategy urlEndingWith(String url) {
        UrlMatchingStrategy urlStrategy = new UrlMatchingStrategy();
        urlStrategy.setUrlPattern(".*" + url);
        return urlStrategy;
    }

but I can't get a match when a call is made to http://localhost:8000/customer/0001. The only strange thing is that the origin of the request is on another server (http://localhost:7000).

I'm verifying with WireMock.verify(getRequestedFor(urlMatchingStrategy)); which was working fine.

Expected at least one request matching: {
  "url" : ".*/customer/0001",
  "method" : "GET"
}
Requests received: [ {
  "url" : "/customer/0001",
  "absoluteUrl" : "http://localhost:8000/customer/0001",
  "method" : "GET",
  "headers" : {
    "Host" : "localhost:8000",
    "User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.28.10 (KHTML, like Gecko) Version/6.0.3 Safari/536.28.10",
    "Accept" : "*/*",
    "Origin" : "http://localhost:7000",
    "Referer" : "http://localhost:7000/index.html",
    "DNT" : "1",
    "Accept-Language" : "en-us",
    "Accept-Encoding" : "gzip, deflate",
    "Connection" : "keep-alive"
  },
  "body" : "",
  "browserProxyRequest" : false,
  "loggedDate" : 1364217267589,
  "loggedDateString" : "2013-03-25 13:14:27"
} ]

persist mappings to file (standalone)

Is it possible for mappings that have been created via POST to be written to file?

i.e

"/__admin/save"

would create the relevent files in "__files" and "mappings" so they are not lost on restart?

Dan

Switch scenarios

Hello,
I was wondering if it possible to switch between scenarios? I have recorded two different scenarios on the same url and I would like to switch between them when needed.

At the moment we have different loops on one scenario, and we have recorded action for each loop switching to it directly[by changing the state to the one of required loop].

However as there are scenario names, I am wondering if maybe there is already a functionality for switching scenarios?
Regards,
ksq

Basic Authentication

It doesn't seem that wiremock supports Basic Authentication. If that is true, is there any plans for support? Should I start mucking around with the code?

Currently I get a 400 from the Wiremock server when I execute:

String encoding = Base64.encodeBase64String((userName + ":" + password).getBytes());
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(protocol + "://" + host + ":" + port + path + merchantId + "/credentials");
httpPost.setHeader("Authorization", "Basic " + encoding);
try {
    HttpResponse response = httpClient.execute(httpPost);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.