dreamhead / moco Goto Github PK
View Code? Open in Web Editor NEWEasy Setup Stub Server
License: MIT License
Easy Setup Stub Server
License: MIT License
with moco-runner-0.9.1-standalone.jar, so many methods disappear, such as server.post, server.get, when server is an instance of HttpServer.
more detail, just like the code below.
server.post(by(uri(uri))).response(file(f.getAbsolutePath()));
I checked the moco source and found them, I think the proguard feature may break it.
I think it would be useful for Moco to allow multiple config files to be loaded into a single instance, each with a different namespace.
This would avoid needing to spin up multiple instances of Moco when you want to run a few different stubs at the same time (for example during a build pipeline).
Here's a rough example of how this could work:
Runner runner = new NamespacedRunner(8080);
runner.addConfig("myApp1", "/path/to/myConfig1.json");
runner.addConfig("myApp2", "/path/to/myConfig2.json");
runner.run()
After doing this, the matchers in myConfig1.json
will all be implicitly prepended with the path myApp1
.
E.g if myConfig1.json
defines a matcher to catch all GET requests, it will catch requests to localhost:8080/myApp1**
, but not localhost:8080/somethingElse
.
Do you agree that this would be a useful feature? I would be happy to help in implementation.
Thanks,
Garrett
Fixed by this:
assertThat(globalSettings.get(0).getInclude().replaceAll("\","/"), is("src/test/resources/multiple/fileroot.json"));
java.lang.AssertionError:
Expected: is "src/test/resources/multiple/fileroot.json"
but: was "src\test\resources\multiple\fileroot.json"
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.junit.Assert.assertThat(Assert.java:865)
at org.junit.Assert.assertThat(Assert.java:832)
at com.github.dreamhead.moco.parser.GlobalSettingParserTest.should_parse_setting_file_with_file_root(GlobalSettingParserTest.java:51)
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 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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
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.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)
Dear Dada, could you please make the config.json file reloaded automatically when we edited it?
I wonder that you forgot to commit the "httpserver" class. and the name with bad smell....
I wanted to combine a request monitor and a log monitor for my unit test like this:
HttpServer server = httpserver(8080, Moco.log(), MocoRequestHit.requestHit());
The current API only allows one monitor at the time.
After set up the environment with the steps - "Global Settings" https://github.com/dreamhead/moco/blob/master/moco-doc/global-settings.md
It throws an error:
$ java -jar moco-runner-0.8-standalone.jar start -p 12306 -c settings.json
23 7▒▒ 2013 11:03:30 [main] INFO Unrecognized field: Unrecognized field "include" (class com.github.dreamhead.moco.parser.model.SessionSetting), not marked as ignorable (4 known properties: , "response", "mount", "request", "redirectTo"])
at [Source: java.io.FileInputStream@4ac74ac7; line: 3, column: 22](through reference chain: com.github.dreamhead.moco.parser.model.SessionSetting["include"])
23 7▒▒ 2013 11:03:30 [main] ERROR Unrecognized field [ include ], please check!
如果配了surefire的并发,则会提示端口占用,不知如何写一个支持并发的测试
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<parallel>methods</parallel>
<useUnlimitedThreads>true</useUnlimitedThreads>
<argLine>-Xms512m -Xmx1024m</argLine>
<forkMode>once</forkMode>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
@Before
public void setup(){
server = httpserver(12306);
String respQueryWltCredit="xx1";
server.request(by(uri("/xx1"))).response(respQueryWltCredit);
String respAdd="xx2";
server.request(by(uri("/xx2"))).response(respAdd);
}
running(server, new Runnable() {
@Override
public void run() throws IOException {
some http get request as following format:
http://localhost:8080/getorder?{"id" : 123456}
Does moco support such format
{
{
"request" : {
"uri" : "/getorder",
"method" : "get"
"querystring" : "{"id" : 123456}"
},
"response" : {
"text" : "balabala"
}
}
}
Global setting document https://github.com/dreamhead/moco/blob/master/moco-doc/global-settings.md
Environment configure
[
{
"env" : "remote",
"include": "foo.json",
},
{
"env" : "local",
"include": "bar.json",
}
]
Which have "," and cause error while run MOCO
java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException: Unrecognized character escape 'U' (code 85)
at [Source: java.io.FileInputStream@2598c6f3; line: 1, column: 20](through reference chain: com.github.dreamhead.moco.parser.model.GlobalSetting["include"])
at com.github.dreamhead.moco.parser.GlobalSettingParser.parse(GlobalSettingParser.java:31)
at com.github.dreamhead.moco.runner.SettingRunner.(SettingRunner.java:31)
at com.github.dreamhead.moco.runner.FileRunner$2.createRunner(FileRunner.java:59)
at com.github.dreamhead.moco.runner.FileRunner.(FileRunner.java:23)
at com.github.dreamhead.moco.runner.FileRunner$2.(FileRunner.java:56)
at com.github.dreamhead.moco.runner.FileRunner.createSettingFileRunner(FileRunner.java:56)
at com.github.dreamhead.moco.runner.RunnerFactory.createDynamicSettingRunner(RunnerFactory.java:40)
at com.github.dreamhead.moco.runner.RunnerFactory.createDynamicRunner(RunnerFactory.java:35)
at com.github.dreamhead.moco.runner.RunnerFactory.createRunner(RunnerFactory.java:22)
at com.github.dreamhead.moco.runner.DynamicSettingRunnerTest.should_reload_configuration(DynamicSettingRunnerTest.java:33)
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 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.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
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.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)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Unrecognized character escape 'U' (code 85)
at [Source: java.io.FileInputStream@2598c6f3; line: 1, column: 20](through reference chain: com.github.dreamhead.moco.parser.model.GlobalSetting["include"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.wrapAndThrow(BeanDeserializerBase.java:1311)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:297)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:230)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:207)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:23)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2094)
at com.github.dreamhead.moco.parser.GlobalSettingParser.parse(GlobalSettingParser.java:25)
... 35 more
Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized character escape 'U' (code 85)
at [Source: java.io.FileInputStream@2598c6f3; line: 1, column: 20]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1369)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:532)
at com.fasterxml.jackson.core.base.ParserMinimalBase._handleUnrecognizedCharacterEscape(ParserMinimalBase.java:507)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._decodeEscaped(UTF8StreamJsonParser.java:2728)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._finishString2(UTF8StreamJsonParser.java:2132)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._finishString(UTF8StreamJsonParser.java:2088)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.getValueAsString(UTF8StreamJsonParser.java:286)
at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:29)
at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:464)
at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:107)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:295)
... 42 more
if using log, it is impossible to set hit
Hi there
I'm using moco for testing, and want to konw whether moco can help me in this case or not:
{
"request": {
"uri": {
"match": "/prefix/.*"
}
},
"response": {
"proxy": "http://192.168.1.100:8000/prefix/"
}
}
for example:
I want request sent to
http://localhost:12306/resources/1
be send to
http://192.168.1.100:8000/resources/1
and
http://localhost:12306/resources/2
be send to
http://192.168.1.100:8000/resources/2
can I use matcher or something? I mean automatically, like $1
, $2
in regular expression.
is that possible? if it is, can you provide me an example?
I have a request like: http://localhost/foos/1
And the response json file foos.json has two foos.
[{
"id": "1",
"name": "foo1",
},
{
"id": "2",
"name": "foo2",
}]
Can i use the moco to get the foo1 as the response content?
We used moco in our functional test, and it really works well there, and further more, we want to used it in our performance test, as a simulator, what it is used is to mock a webservice, by receiving the specific request matching via xpath, and return a sample xml response.
Here is the code snippet:
server.post(eq(xpath("//*[local-name()='userId']/text()"), "user-id")).response(with(pathResource("data/sampler_response.xml")), header("Content-Type", "text/xml"));
And if this is possible for performance test, the next step we wanted is to use the latency feature in the mock server, to simulate the behavior that mock server can return the response with some latency delay, is this also possible to be used in performance test?
Currently, the Content-Type
header is always added to responses as "text/html" even if one has been manually added. This is problematic when you want to stub a response of a different content type.
The logic here should be changed to only default the header if one does not already exist.
See com.github.dreamhead.moco.handler.AbstractContentResponseHandler
for where this occurs.
When writing tests using the Java API, it would be nice to let Moco choose a port that is free on the OS and then provide a mechanism for querying that port. This would make tests written using Moco more robust when run on different environments.
This logback.xml file is confusing logback. It finds both moco-core's logback.xml and my application's logback.xml. When logback finds two, it seems to use neither.
I believe logback.xml has been distributed with moco-core by mistake. Can you please remove it from the distribution. Thanks.
Was looking to hack on this a bit and cannot get the tests to run successfully due to OutOfMemoryException's being thrown during the test phase. As I understand, the problem is that the tests are run in a different JVM and the GRADLE_OPTS don't apply to these. I have tried adding the 'java' plugin and configuring the maxHeap on the test task without luck as well.
Is there something else I could be overlooking - or another configuration option that could be done?
Building per spec with: ./gradlew build
I am using moco to simulate a webservice, and it return 400 Bad Request, but if the request is not matched, should it not return the response instead of returning 400?
The moco version I used is 0.8.1
I've noticed that you are working on "HttRequest to Request". Is there any plan to support other protocol, e.g. Redis?
Dear all,
I'm a newer with Moco. I want to mock a remote url like "http://192.168.34.4:8080".
But when I use Moco as follow code, it throw a connect timeout exception.
How could I make it work? Thank you.
test case:
@Test
public void should_response_as_expected() throws Exception {
HttpServer server = httpserver(8080);
server.request(by(uri("http://192.168.34.4:8080"))).response(with("file not found"), status(200));
running(server, new Runnable() {
@Override
public void run() throws Exception {
assertThat(Request.Get("http://192.168.34.4:8080").execute().returnResponse().getStatusLine().getStatusCode(), is(200));
assertThat(Request.Get("http://192.168.34.4:8080").execute().returnContent().asString(), is("file not found"));
}
});
}
result:
org.apache.http.conn.HttpHostConnectException: Connect to 192.168.34.4:8080 [/192.168.34.4] failed: Connection timed out: connect
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:138)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:314)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
...
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
...
At the first,there are some typo.
And when I fixed them, I got some compile error instead.
Is this code sample out of date?
@Test
public void should_response_as_expected() {
HttpServer server = httpserver(12306);
server.reponse("foo");
running(server, new Runnable() {
@Override
public void run() throws IOException {
Content content = Request.Get("http://localhost:12306").execute().returnContent();
assertThat(content.asString(), is("foo"));
}
}
}
Hi,
I would like to call MockHttpServer.start()/stop() in the case, instead of the running(server, new Runnable() {}); but the package name of MocoHttpServer is "internal", should i invoke it directly?
Best wishes
江南白衣
I love the feature about jsonpath
, it's very powerful.
I've got a question about it, I know it's very convenience to people whom want to deteming an existing json formular like:
$..services[0].name == "killHttpd"
you can do it by:
"json_paths":
{
"$..services[0].name": "killHttpd"
}
but sometimes, I just want to know whether a path is existing or not:
$.services
or
$.services.parameter[0]
So, is that possible to walk around this in moco
? What did I miss?
My config is:
[
{
"request" : {
"uri" : "/rest/model/atg/commerce/pricing/PricingActor/skuPrices?skuId=prod10007"
},
"response" : {
"file": "skuPrices.response"
}
}
]
and i got
GET /rest/model/atg/commerce/pricing/PricingActor/skuPrices?skuId=prod10007 HTTP/1.1
Host: localhost:12306
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: __pr.br1=9qvsqknax0; __atuvc=0%7C38%2C0%7C39%2C0%7C40%2C0%7C41%2C1%7C42; l10n-locale=en_GB; fw_cookienames_cookie=
Content-Length: 0
18 Dec 2013 15:31:43 [nioEventLoopGroup-7-1] INFO Response return:
HTTP/1.1 400 Bad Request
and i drop out "?skuId=prod10007", then it works.
Fisrt , I'm a newer for moco , but i love it very much。
My question is:
when i have a url like "https://xxx.abc.com" , moco doesn't work。
Hi I am using Moco to test some REST service. The project is great and fixes some problems that other solutions have. But I have found a problem with performance. Let me show:
Executing this piece of code:
HttpServer server = httpserver(12306);
server.request(by(uri("...."))).response("...");
runner = runner(server);
runner.start();
takes 688 ms to start up.
and the code:
runner.stop();
takes 1129 ms
I think it takes too much time on destroying the instance, which makes our tests run so slowly. Maybe the problem is with Netty and not this framework but I think it should be something to take in considerations.
Thank you so much for this amazing work.
Hi,
I try to use the hit to check how many times client invoke moco during testing.
But when I set the matcher for moco,
the method matcher doesn't work.
Any idea on it? Or you need to add some support for it?
<plugin>
<groupId>com.garrettheel</groupId>
<artifactId>moco-maven-plugin</artifactId>
<version>1.0-SNAPSHOT</version>
<configuration>
<port>8081</port>
<configFile>config.json</configFile>
</configuration>
</plugin>
I run the following command with the above configuration and get plugin parameter error. I don't know what's wrong. Could you please help me on that? I've tried run config.json from both root directory and classpath.
mvn com.garrettheel:moco-maven-plugin:run
A very strange behavior, when i setting one url response latency to 30 seconds, another url is normal, run below test case:
for(i=0; i<5;i++){
testNormalUrl();
}
testLatencyUrl();
for(i=0;i<10;i++){
testNormalUrl();
}
When we start the moco by JSONServer in java code, netty start new thread for each request, but the total number is 8, the 9th request will reuse thread-1. When we run part-2 0-10 testNormalUrl, the netty will reuse the thread-6 which is serving the latencyUrl !!!!!, so timeout happen.
But when we start moco with command line, netty will always resue thread-1 for normal url, and thread-2 for latency url.
Do you have any idea about it?
23 五月 2014 10:42:30 [main] INFO Unrecognized field: Unrecognized field "js
(class com.github.dreamhead.moco.parser.model.ResponseSetting), not marked a
gnorable (9 known properties: "headers", "path_resource", "text", "proxy", "c
ies", "status", "version", "file", "latency"])
at [Source: java.io.FileInputStream@1b48197; line: 7, column: 18](through r
rence chain: com.github.dreamhead.moco.parser.model.SessionSetting["response"
com.github.dreamhead.moco.parser.model.ResponseSetting["json"])
23 五月 2014 10:42:30 [main] ERROR Unrecognized field [ json ], please check!
First, i use it as virtual server and start it with json configuration file.
Second, i use ajax mode access it, and response json data, but i can not receive it.
Your's API don't provided response json data example. Can you provided some example about ajax access and response json data.
very interesting issue, I use moco to simulate a webservice server, and found that moco will close the connection after soap response returned back to the client although there was the "Connection: keep-alive" header in the request.
final HttpsCertificate certificate = certificate(pathResource("cert.jks"), "mocohttps", "mocohttps");
这个HttpsCertificate 、certificate 、 pathResource在哪的?
It seems moco encodes the resposne text by default charset. How can I force it to use utf8?
HI all,
I have multiply likeness urls. How can I put this urls to one request?
Thank you.
server.request(and(by(method(PUT_METHOD)), by(uri("/test/photos/" + PUT_FILE_NAME))
)).response(with("OK"), status(200));
server.request(and(by(method(PUT_METHOD)), by(uri("/test/photos/" + PUT_FILE_NAME + ".0.pacspart"))
)).response(with("OK"), status(200));
server.request(and(by(method(PUT_METHOD)), by(uri("/test/photos/" + PUT_FILE_NAME + ".1.pacspart"))
)).response(with("OK"), status(200));
server.request(and(by(method(PUT_METHOD)), by(uri("/test/photos/" + PUT_FILE_NAME + ".2.pacspart"))
)).response(with("OK"), status(200));
What steps will reproduce the problem?
@Test
public void should_return_expected_response_from_a_large_file_and_run_a_new_server_without_exceptions() throws Exception {
server.response(file("src/test/resources/large.response"));
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(root()), Matchers.notNullValue());
}
});
server = httpserver(port());
running(server, new Runnable() {
@Override
public void run() throws IOException {
assertThat(helper.get(root()), Matchers.notNullValue());
}
});
}
What is the expected output? What do you see instead?
Moco will fail to start on the second attempt
What version of the product are you using? On what operating system?
Moco 0.9, Windows
Workaround:
We used Awaitility and wrote such piece of code that seems to wait until a port is free and we call after each running method:
await().until(mocoShutsDownCompletelyAtPort(PORT));
private Callable<Boolean> mocoShutsDownCompletelyAtPort(final int port) {
return new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
System.out.println("Waiting until port is available");
String url = "http://localhost:"+ port;
try {
final URLConnection connection = new URL(url).openConnection();
connection.connect();
return true;
} catch (final MalformedURLException e) {
throw new IllegalStateException("Bad URL: " + url, e);
} catch (final IOException e) {
e.printStackTrace();
return false;
}
}
};
}
Please provide any additional information below.
We have this issue when starting moco server when junit executes a test method in which we start a new Moco server. The problem is such that when we want to start a new server some big portion of data "blocks" still blocks closing of the previous server. We are working also with CXF and we are sending a lot of data so sometimes we see that the connection to Moco has been suddenly shutdown and we have errors like "Unexpected end of file" or sth like "error writting request body".
We can only put the json string in a seperate file in both Java API and Json file settings, otherwise we need to write many "" in the text response to escape it.
The json response is some common, is there any optimized way to set it just in Java API or Json file without escape char? e.g intruoduce a new type like json beside the text and file.
most time we need to set both header/status and content, i spend much time to findout how to set a json response with content-type header -- use the "with()", please document it out.
server.request(by("foo")).response(header("content-type", "application/json"));
the real sample should has the json content here.
PS. now we has the json shortcut. But i still need to set bot status code(500) and error reason text.
the simple implement like this
{
"request" : {},
"response" : {},
"callback" :
{
"wait" : 1000,
"request" : { like normal request}
}
}
Currently, when using a file as the source of a request or response, the files are obtained via the java.io.File constructor.
It would be useful if files could be loaded from the classpath to simplify the paths that go into configs. This could be implemented as a new static method on Moco
which attempts to load a file using the ClassLoader.
Does Moco support andriod?
When I copy moco package under my testing project, the eclipse throws out
'Unable to execute dex: Multiple dex files define'.
Hello I am developing the arquillian-extension-moco so we can run moco server internally from container automatically while running Arquillian tests instead of having to do manually.
It works great but there is one error when shutting down the Moco server. Let me show you the important code:
This method is called before executing any test and reads a passed json request/response Moco file and starts the runner
public void executeBeforeClass() {
//....
jsonRunner = JsonRunner.newJsonRunnerWithStreams(
streams, of(12306));
jsonRunner.run();
}
and then to stop it:
if(jsonRunner != null) {
jsonRunner.stop();
}
the problem is that when you run it inside a container and without debugging then an exception that a thread group could not be stopped in an amount of time is thrown. But the funny thing is that if I try to debug then all works as expected.
So the first question is, Am I doing something wrong in the way I start and stop Moco server?
Test case
request
<request>
<parameters>
<id>2</id>
<id>1</id>
</parameters>
</request>
// in xapth, /request/parameters/id/ will got all id element ,but in this case , the second node will miss.
server.request(eq(xpath("/request/parameters/id/text()"), "1")).response("foo");
//not enough
return xPathExpression.evaluate(helper.extractAsInputSource(request, extractor))
My question is can I use Moco in Java integration test, just like httpunit for servlet.
I want to use template feature in my test framework. just like "response" : { "file": { "template": "foo_${req.queries['foo']}.json" } }, that means the moco will return a file named foo_1.json. but it does not work.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.