Giter VIP home page Giter VIP logo

restito's Introduction

Restito - testing framework for REST clients

Build Status Maven Central Known Vulnerabilities

Restito is a tool for validating your code's interactions with REST services. It provides the Middle Way between hammering real HTTP services from your tests (thus making them brittle) and mocking too much and not testing the HTTP communication layer at all.

Inspired by Mockito and Rest Assured, Restito provides a handy DSL for:

  • Mimicking a behaviour of a REST server from your tests;
  • Recording your code's HTTP calls to the server and verifying them;
  • Integration with JUnit;
  • (m)TLS and HTTPS support;
  • Avoiding boilerplate code.

It helps you to test an application which makes calls to some HTTP service. Restito sets up a StubServer instance which responds to your application's Calls based on defined Stubs. A stub makes some Action to response when Condition is respected.

For more motivation, please read the Motivation section of the Developer's guide.

Developer's guide is the best place to start. FOR LOTS OF EXAMPLES CLICK -> HERE <- :-)

For more details you can also check Restito's javadoc.

Quick example:

package com.xebialabs.restito;

...

public class SimpleRequestsTest {

    private StubServer server;

    @Before
    public void start() {
        server = new StubServer().run();
        RestAssured.port = server.getPort();
    }

    @After
    public void stop() {
        server.stop();
    }

    @Test
    public void shouldPassVerification() {
        // Restito
        whenHttp(server).
                match(get("/demo")).
                then(status(HttpStatus.OK_200));

        // Rest-assured
        expect().statusCode(200).when().get("/demo");

        // Restito
        verifyHttp(server).once(
                method(Method.GET),
                uri("/demo")
        );
    }

}

Version compatibility

  • Use 1.x if you run JDK 11+;
  • Use 0.9.x if you run JDK 8+

Maven instructions

<dependency>
    <groupId>com.xebialabs.restito</groupId>
    <artifactId>restito</artifactId>
    <version>1.1.0</version>
</dependency>

Building instructions

$ gradle clean build

restito's People

Contributors

aalbul avatar brendan-hofmann avatar dependabot[bot] avatar hierynomus avatar hightml avatar leblonk avatar michelzanini avatar mkotsur avatar patryk-marcin-zielinski avatar rafan avatar ryeats avatar shamoh avatar snyk-bot avatar theon avatar thomasleveil avatar vanta 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

restito's Issues

Resetting stub server

I was wondering if there is a way to reset the state of a stub server. My use case is when I want to verify that a particular URL is only ever invoked once. My app is making a call to a remote HTTP URL (which I am stubbing out with restito), but it protects against duplicate invocations of the downstream HTTP server. So my test invokes my application twice, but only expects the stub to invoked once. What I think I'm looking for is a call to reset the state of the stub server so that I can then assert 0 invocations, after first having asserted 1 invocation.

Restito packages logback.xml

Restito packages a logback.xml file, which causes warnings when running an application relying on logback as a logging framework.

Following message encountered:

21:25:07,021 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs multiple times on the classpath.
21:25:07,021 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs at [jar:file:/Users/ajvanerp/.gradle/caches/modules-2/files-2.1/com.xebialabs.restito/restito/0.4-beta-1/8f037010fff797809ca0382434b39d8e1fdbf57b/restito-0.4-beta-1.jar!/logback.xml]

proposal: more readable stack trace for big JSON payload with restito integration testing

When I try to find bug in my JSON payload in integration tests using restito it doesn't support me with clear debug process.

For example output for failed test:

    Condition failed with Exception:

    verifyHttp(restitoServer) .once(post("/endpoint"), withPostBodyContainingJson(asString(mySpecialBigPayload)))
    |          |               |    |                     |                          |        |
    |          |               |    |                     |                          |        class path resource [payload_big.json]
    |          |               |    |                     |                          {
    |          |               |    |                     |                            "id": "51abb572-c22b-11e8-b3f9-699386e0b5fe-54091516",
    |          |               |    |                     |                            "prop": "value",
    |          |               |    |                     |                            "id": [
    |          |               |    |                     |                              "54091516"
    |          |               |    |                     |                            ],

... ~500 lines of big JSON

    |          |               |    |                     com.xebialabs.restito.semantics.Condition@6d442a82
    |          |               |    com.xebialabs.restito.semantics.ConditionWithApplicables@70b57756
    |          |               java.lang.AssertionError: Expected to happen 1 time(s), but happened 0 times instead
    |          com.xebialabs.restito.server.StubServer@73101e8b
    com.xebialabs.restito.builder.verify.VerifyHttp@7361820a
        at
 ...
        Caused by:
        java.lang.AssertionError: Expected to happen 1 time(s), but happened 0 times instead
            at com.xebialabs.restito.builder.verify.VerifyHttp.times(VerifyHttp.java:58)
            at com.xebialabs.restito.builder.verify.VerifyHttp.once(VerifyHttp.java:42)

I had wrong values in two JSON properties/fields and I think searching/debugging phase problems too longer than I expected.

Ideal solution it will be suggest what is different or probably wrong.

It will be possible to add more clear output when test failed ?

Stub and method toString()

When calling method gotStubsCommitmentsDone() in EnsureHttp, in case of AssertionError the error message is not comprehensive. This makes testing and debugging hell.

Example:

"Expected stub com.xebialabs.restito.semantics.Stub@6a5f05f5 to be called 1 times, called 0 times instead"

[Important] Critical racing condition on Stub Server while registering the calls

Hi,

I have been using this library for a few years and I really enjoyed it.
However, there has been cases where the tests would randomly fail when doing assertions if a call was made.

I have never had time to properly investigate so today I decided to give some time to investigate deeply.
I was able to find the issue and it's on the StubServer class, where the requests are received on method stubsToHandler.

In that class, there's a part that writes the response of a call to the user if the call is found on a stub with stub.apply(response). And then after that it does:

if (isRegisterCalls()) {
    calls.add(call);
}

The problem here is that the call is added to the list after the response has been applied. In some VERY RARE cases, if the computer has a fast processor and you run thousands of tests, the response is written fast, the test resumes and checks if the call happened, all while the thread that finished stub.apply(response) has not yet reached calls.add(call).

So in a simple test like this one:

whenHttp(server).match(get("/")).then(ok());
expect().statusCode(200).get("/");
assertEquals(1, server.getStubs().size());

It is possible that the assertEquals will happen before the calls.add(call). For that to happen is very rare, specially on a small request like this one, but I was able to reproduce the problem with this test case:

@Test
public void reproduceRacingCondition() {
    whenHttp(server)
        .match(startsWithUri("/test-large"))
        .then(resourceContent("large-content.json"));

    for (int i = 0; i < 20000; i++) {
        expect()
            .header("Content-Type", is("application/json"))
            .header("Content-Length", is(not(nullValue())))
            .when().get("/test-large");

        assertEquals(1, server.getCalls().size());

        server.clearCalls();
    }
}

When you run this 20000 times, at least one time the problem is reproduced. If it does not reproduce, the tests passes in around 2 minutes. More often than not it fails. Almost every time.

To fix this issue the only change is to move the block:

if (isRegisterCalls()) {
    calls.add(call);
}

To happen before processing the stubs.

I have done this on a fork of this repository and the reproducing test always passes now.

I consider this to be a CRITICAL bug, and it has a simple fix which I can PR to your repository.

Here comes one problem, however, the master branch has changed to Java 10, not sure why. I need this on Java 8 as many people would. So I took a branch from the 0.9.3 commit.

What I ask is if you could create a branch 0.9.x from the commit 444896fc08aa2ee11199f50bcd24789fdb42a787 : 0.9.3 release (the same I did). I can create a PR to that branch and you can release 0.9.4 with this fix from there. That's if you do plan to change the Java version on this library, which should then, in the future, at least generate a versions such as 0.10.0 or 1.0.0.

If you intend to continue with Java 8 and the master branch I can try to help fixing the master branch to Java 8 etc...
But would prefer that you do a "hot fix" branch as its easier for me.

This should only take a few minutes of your time.

Create the 0.9.x branch, let me know, I submit the PR, you merge and release 0.9.4. This would help me a lot.

Thanks.

Multiple requests frome the same server instance

Hi, not sure if it's a bug or my misunderstanding:

I am trying to run in the same test 2 separate requests that should return different content:

whenHttp(server)
            .match(get('/something').parameter('par1', '1').parameter('par2', '2').withHeader('SOME-AUTH-TOKEN', AUTH_TOKEN))
            .then(
                contentType('text/csv'),
                stringContent("first content"),
                status(OK_200))

whenHttp(server)
            .match(get('/something').parameter('par1', '1').parameter('par2', '100').withHeader('SOME-AUTH-TOKEN', AUTH_TOKEN))
            .then(
                contentType('text/csv'),
                stringContent("second content"),
                status(OK_200))

When test runs two requests are created correctly (par2 only changes) but the content returned is always from the first successful request.

Am I doing something wrong or is it a bug?

Thanks!

Slow server response

Restito looks great and I was hoping to use it, however I was looking for a way to imitate a slow server response (or fixed delay, like WireMock allows). This would be a very useful feature to add.

New 0.9.0 version does not automatically identity contentType if the XML or JSON file is too big

Hi,

After 0.9.0 version, if you have a big XML file, and do a test like this:

       whenHttp(server).
                match(endsWithUri("/demo")).
                then(resourceContent("big.xml"));

        expect().contentType(ContentType.XML).when().get("/demo");

The content type should be application/xml but it's empty!

On version 0.8.2 this works. Also, if the XML is small, it also works.
I figured if it's bigger then 300 lines or so, the problem start happening.
Not sure why is that.

Attaching an example project with failing tests to help.

This is a major problem for me.
Can you please fix and release a 0.9.1 version?

content-type-issue.zip

connection refused error.

We integrated entire restito as our mock framework and it is working fine. Suddenly we are seeing connection refused . Take as example that we have one mock service up and running /something. and first request send to mock , It is success . When we send second request. It send error saying connection refused. Is this something new issue or something advice how we can handle this kind of error ?

StubServer getters are not thread-safe

In the StubServer class, getStubs() and especially getCalls() are not thread safe, as they return the server's internal instance of those collections. Those methods should probably return copies of the collections instead, and you should use one of the thread-safe collection implementations that Java provides for the internal instances.

Support java 6 in newer versions

Hi, i try to update Restito verion to 0.4 and i got 0.51 java error.
Can you provide a release of newer versions compiled in java 6?
The dependency was downloaded using maven.

Multiply headers in request

Matching multiple headers not working

StubHttp.whenHttp(stubServer)
                .match(
                        Condition.get("/test"),
                        withHeader("Authorization", "Bearer 123233")
                )

when request has 2 same header with "Authorization" key, it won't fail.

Problem is in Call class

        for (String s : request.getHeaderNames()) {
            call.headers.put(s, request.getHeader(s));
        }

request.getHeader will return arbitrary one header so even with Condition.custom we won't be able to hadle the case with multiply same headers

Composite conditions: log failling condition

I think it would be really useful to log which condition is failing the rule as a whole. For example, lets say I have

URI uri = UriBuilder.fromUri("http://localhost:{PORT}/authzforce-ce/domains").port(port).build();
        whenHttp(server)
                .match(
                        get(f.toString()),
                        parameter("externalId", domain))
                .then(ok());

and fails when I do GET http://localhost:8080/authzforce-ce/domains?externalId=1
but if I have

URI uri = UriBuilder.fromUri("http://localhost:{PORT}/authzforce-ce/domains").port(port).build();
        whenHttp(server)
                .match(
    //                    get(f.toString()),
                        parameter("externalId", domain))
                .then(ok());

it succeeds. Then I'd want to know what part is causing it to fail.

NOTE: this is a hypothetical simple case, I only put it as an example (in reality I get 200 😛) but in more complex cases like POST with multiple conditions it would be useful

Some tests fail on my machine: M1 MBP

While CircleCI is happy, some tests keep failing on my laptop.
I tried to run them with JDK 11 and 17 – all the same.

com.xebialabs.restito.semantics.ActionTest > shouldApplyContentWithCustomType FAILED
    java.lang.reflect.InaccessibleObjectException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldApplyHeader FAILED
    org.mockito.exceptions.misusing.UnfinishedStubbingException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldBuildOkStub FAILED
    java.lang.reflect.InaccessibleObjectException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldApplyCharset FAILED
    org.mockito.exceptions.misusing.UnfinishedStubbingException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldBuildSuccessfulStub FAILED
    java.lang.reflect.InaccessibleObjectException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldCreateCompositeActionFromApplicables FAILED
    org.mockito.exceptions.misusing.UnfinishedStubbingException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldCreateCompositeActionFromActions FAILED
    java.lang.reflect.InaccessibleObjectException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldBuildNoContentStub FAILED
    org.mockito.exceptions.misusing.UnfinishedStubbingException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldApplyXmlContent FAILED
    java.lang.reflect.InaccessibleObjectException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldApplyUnicodeJsonContent FAILED
    org.mockito.exceptions.misusing.UnfinishedStubbingException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldApplyJsonContent FAILED
    java.lang.reflect.InaccessibleObjectException at ActionTest.java:34

com.xebialabs.restito.semantics.ActionTest > shouldApplyStringContent FAILED
    org.mockito.exceptions.misusing.UnfinishedStubbingException at ActionTest.java:34

com.xebialabs.restito.server.StubServerTest > reproduceRacingCondition FAILED
    java.net.BindException at StubServerTest.java:150

com.xebialabs.restito.server.StubServerTest > shouldReturn404WhenTheRequestIsNotCoveredByStubs FAILED
    java.net.BindException at StubServerTest.java:137

com.xebialabs.restito.support.junit.StartServerTest > shouldStartAnotherServerForInstanceRule FAILED
    java.net.BindException at StartServerTest.java:43

com.xebialabs.restito.support.junit.StartServerTest > shouldStartServerForInstanceRule FAILED
    java.net.BindException at StartServerTest.java:33

guide.AutodiscoveryOfStubsContentTest > shouldFindXmlResourceFileByUrl FAILED
    java.net.BindException at AutodiscoveryOfStubsContentTest.java:36

guide.AutomaticContentTypeTest > shouldSetContentTypeXmlAccordingToResourceExtension FAILED
    java.net.BindException at AutomaticContentTypeTest.java:46

guide.AutomaticContentTypeTest > shouldSetContentTypeJsonAccordingToResourceExtension FAILED
    java.net.BindException at AutomaticContentTypeTest.java:37

guide.ComplexScenarioTest > shouldWork FAILED
    java.net.BindException at ComplexScenarioTest.java:48

guide.ExpectedStubTest > shouldPassWhenTheSequenceHasBeenCompleted FAILED
    java.net.BindException at ExpectedStubTest.java:133

guide.ExpectedStubTest > shouldFailWithTheErrorMessageThatContainsStubLabel FAILED
    java.lang.AssertionError at MatcherAssert.java:20

155 tests completed, 22 failed

> Task :test FAILED

There seem to be two culprits:

  1. This line in ActionTest
when(response.getWriter()).thenReturn(mock(Writer.class));

triggers

    java.lang.reflect.InaccessibleObjectException: Unable to make protected java.io.Writer(java.lang.Object) accessible: module java.base does not "opens java.io" to unnamed module @2c767a52
        at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
        at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
        at java.base/java.lang.reflect.Constructor.checkCanSetAccessible(Constructor.java:188)
        at java.base/java.lang.reflect.Constructor.setAccessible(Constructor.java:181)
        at org.mockito.internal.creation.cglib.ClassImposterizer.setConstructorsAccessible(ClassImposterizer.java:86)
        at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:56)
        at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
        at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
        at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
        at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
        at org.mockito.Mockito.mock(Mockito.java:1285)
        at org.mockito.Mockito.mock(Mockito.java:1163)
        at com.xebialabs.restito.semantics.ActionTest.init(ActionTest.java:34)
  1. reproduceRacingCondition in StubServerTest throws exceptions java.net.BindException and java.net.NoRouteToHostException after ~ 10000+ iterations.

There seem to be issues with the HTTP client not closing connections and exceeding the limit of open sockets.

See https://stackoverflow.com/questions/61667650/apache-defaulthttpclient-java-net-bindexception-address-already-in-use-conne

Severe encoding bug in Action.stringContent(String content).

From looking at the code there appears to be a severe encoding bug in Action.stringContent(String content).

public static Action stringContent(final String content) {
  return bytesContent(content.getBytes());
}

You are simply retrieving the bytes of the string using String.getBytes() without indicating any encoding. String.getBytes() simply uses the system default charset which you almost never want to do. This will make code work differently on different platforms; moreover you won't be able to test what you want to test unless the charset just happens to match the one you expect. Tests shouldn't depend on luck.

There are two complementary ways to fix this:

  • Have Action.stringContent(final String content) check to see if Action.charset(Charset charset) has been called, and if so, use that charset when retrieving the bytes (and if not preferably throw an exception to be very explicit in the documentation the bad things that will happen if you don't specify a charset). Note that it may not be possible to see if a charset has already been indicated, as the actions are independent; in this case, it would be best to remove this method altogether or highly discourage it (in which case people will still unwittingly use it).
  • Add a Action.stringContent(final String content, Charset charset) method that provides a charset to use when retrieving the bytes of the string. This would be a convenience method that would also add an Action.charset(Charset charset), much like resourceContent(URL resourceUrl, Charset charset) and the like already do.

It is absolutely crucial to add the latter method above. Developers should not be using content.getBytes() in 99.9% of cases.

Allow @NeedsServer for types as well

I think it will be helpful to have @NeedsServer to support type annotation as well as if I use restito for a specific test the whole class is an integration test plus it'll allow me to run the server before and after class instead of before and after every test

@Before
    public void setUp() throws Exception {
        if (serverDependency.isServerDependent()) {
            server = new StubServer(9968).run();
        }
    }

0.8 has not been tagged

Hi,
looks like version 0.8 has been released on maven central, but the 0.8 tag has not been creates so it's not on GitHub releases.
Can you please tag it?

improve charset indication of return type

The restito approach for indicating the charset of an HTTP response is convoluted and confusing.

Let's say I have a custom file format call the Foo Format. It is based upon XML, but it has its own MIME type and an extension .foo.

Strangely, here is the only way that I've been able to correctly return a foo file:

...
then(ok(),
    charset(UTF_8.toString()),
    contentType(FOO_MIME_TYPE),
    resourceContent(fooFileURL, UTF_8.toString())

First of all, I don't understand why I need to specify the charset when I call resourceContent(). Even though this file is to be interpreted as UTF-8 when parsed, at the HTTP level it should be sent back as binary. As long as the HTTP response indicates UTF-8, then it is up to the client to recognize the charset and use that to parse the entity. In other words, why is restito parsing my resource? Restito should simply send back the bytes.

Secondly, if restito feels it has to parse my resource, why do I need to specify it again? Didn't I already indicate a charset() of UTF-8? Why do I need to specify it twice?

Another odd thing: if I put the charset() designation at the end, it doesn't work. Why does the order matter?

Note also that charset(String) should accept an actual Charset instance, e.g. charset(java.nio.charset.CharSet). This class has been around since Java 1.4. That way I can use. e.g. java.nio.charset.StandardCharsets.UTF_8, introduced in Java 7.

Similarly it would be nice if contentType(String) would support the JAX-RS javax.ws.rs.core.MediaType class.

Lastly I need a way to associate MIME types and charsets with extensions. If I were to simply associate the FOO_MIME_TYPE with the .foo extension, then I could simply use contentType(FOO_MIME_TYPE) and all the above would be taken care of for me.

Add GET/POST parameter matching #loprio

In some cases it's easier to make stubs based on parameters as well -

blah.match(get("/file/report").withQueryParam("id", "aaa"))
                .then(ok(), resourceContent("..."));
blah.match(get("/file/report").withQueryParam("id", "bbb"))
                .then(notFound());

Of course, it doesn't make much sense to do this before #19 is implemented, as there could be some running time benefit when rule would be started on class level and not for every test in 30-case test suite.

add overloaded URI, UriBuilder, etc. method methods

This is a little thing but it sure would add to the convenience.

If I do a match(get(myURIString)), why can't I use a URI itself, as in match(get(myURI))? In fact, it would be nice to pass parameters. That way I could do this:

URI myURI=URI.create("foo/{bar}");
match(get(myURI, "example")) ...

This implementation of get() would be something like this:

public static ConditionWithApplicables get(final URI uri, Object... values) {
  return get(UriBuilder.fromUri(uri).build(values).toASCIIString());
}

The UriBuilder version might be something like this:

public static ConditionWithApplicables get(final UriBuilder uriBuilder, Object... values) {
  return get(uriBuilder.clone().build(values).toASCIIString());
}

Thanks for considering this.

Restito Certificate has expired for SSL

When setting up a secured server, I get the following Java exception...

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateExpiredException: NotAfter: Thu Jan 24 06:30:07 CST 2013

Clarify methods that accept a "URI".

I see things like Condition.get(String uri) which say that they accept a URI. But the examples show things like get("/demo"), which is not a URI at all --- it's a path. And there's no documentation about encoding at all.

Yes I know that Request.getRequestURI() really returns a path, but that's an old API and it was named badly to begin with. There are so many variations of things that are partial paths, full paths, encoded, raw, etc.; see https://stackoverflow.com/a/21046620/421049 for just a taste.

So it would really help if the API documentation to indicate:

  • Whether the argument should be a URI or a path.
  • If a path, whether it should be an absolute path or relative to some webapp.
  • Whether the path should be URI-encoded or not.

Verify Http with a timeout?

Hi,

Is there any way to verify that a Http call has been made within a certain time just as Mockito's timeout?

Remove requirement to specify path with per-HTTP-method methods.

I see that Condition has convenience methods for specific HTTP methods, such as Condition.get(String uri). That's fine if I want to specify an exact path. But what if I want to use that in conjunction with Condition.matchesUri(Pattern p)? Why isn't there a Condition.get() method I can use like this?

whenHttp(server).matches(get(), matchesUri(Pattern.compile("a?b+c*")))…

Why can't I just use get() by itself, to combine it with any matcher I want?

You might say I could just use Condition.method(Method m), but as explained in #22 that forces me to use the Glassfish API --- and there's no need for that. If there is a Condition.get() method at all, why is it tied to a URI, when I could simply say matches(get(), uri("foo")) to do the same thing as matches(get("foo"))?

Yes, I understand that get(String uri) is a convenience method, but convenience methods should allow the long, more flexible form as well. Put another way, it is more flexible to allow matches(get(), uri("foo")), and provide matches(get("foo")) as an additional convenience. Only providing the latter without the former makes the API less flexible.

Add a way to use anonymous classes for on-demand stubbing

There is only one way to stub on condition and it's through Action:

/**
* Attach actions to the stub
*/
public StubExpected then(Action... actions) {
Stub s = new Stub(condition, Action.composite(actions));
stubServer.addStub(s);
return new StubExpected(s);
}

For more convenience there should be a way to pass in Applicable anonymous class instance to actioned stub. Or should be there applicable stub?

Match uris that contains regex for http methods

So I tried to test with stub that contains regex but it didn't work with different variations

whenHttp(server).
                match(method(Method.PUT),  matchesUri(Pattern.compile(URI_CONTAINS_REGEX)).
                then(ok(), resourceContent("response.json"));
whenHttp(server).
                match(new ConditionWithApplicables(composite(new Condition[]{method(Method.PUT), 
                        matchesUri(Pattern.compile(URI_CONTAINS_REGEX))}),
                        new Applicable[]{Action.noop()})).
                then(ok(), resourceContent("response.json"));

For that specific stub I always get 404 as a response. Request hasn't been covered by any of 3 stubs.

Unable to specify keystore and truststore

Currently their is no way to configure the keystore and truststore that is used when you configured for https it would be nice if you could specify the keystore and truststore that would be used.

Port selection is too random

From what I understand restito tries to start a server using StubServer.DEFAULT_PORT as port, if that port is not available it will try a higher port number. This is pretty clear in SpecificVsRandomPortTest.

I made a small test to reproduce the problem:

    System.out.println("Default port:" + StubServer.DEFAULT_PORT);;
    server = new StubServer().run();
    System.out.println("Port:" + server.getPort());
    server2 = new StubServer().run();
    System.out.println("Port2:" + server2.getPort());

And I get the following output:

Default port:6666
Port:14193
Port2:23342

The problem is that in case of having to open the ports to be able to run the tests, I have no idea which ports to open, I thought that opening 6666-6766 would be enough.
Is the only solution in this case to generate each port manually? 6666 6667 6668...

It would be nice to be able to set the default port and let it generate ports from that on.

Support for file POST / GET / PUT

Does Restito support image upload by POST / PUT and retrieval by GET?
input.postBody is defaulted to String. Not sure whether I can do this

Mocking root "/" with Restito

Hi,

I have an external api that does not have any path, like - http://xyz.com:4080/?query=...
But it looks like Restito does not support mocking the root path. Is there a workaround for this?

Below does not work -
whenHttp(server) .match(get("/").parameter("query", "%28%28%28userid:%xyz%22%29%29%20ANDNOT%20%28%29%29") .then(status(HttpStatus.OK_200) .composite(header("Content-Type", ContentType.JSON.getAcceptHeader())), resourceContent("search-results.xml"));
Thanks

Remove Glassfish dependencies from the API.

This is a very nice start to a framework. But although it is natural that restito would use some server dependency under the covers, the specifics of this server should not be promoted to the API. That is, I should be able to use restito without knowing what server implementation is used.

For instance, restito's Condition.method(Method) method requires a Method parameter, but the org.glassfish.grizzly.http.Method type is part of Glassfish. It would be better to use a string parameter, as in Condition.method(String). This way my code can be completely server agnostic. In addition, I can use more standard method constants, such as javax.ws.rs.Httpmethod.

Upgrade to Gradle 7

Being stuck with Gradle 4 causes a lot of troubles:

  • It doesn't work with Java 11;
  • It doesn't support EdDSA GPG keys for signing archives.
  • It doesn't work with new GPG's pubring.kbx.

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.