Code Monkey home page Code Monkey logo

Comments (6)

drejc avatar drejc commented on June 3, 2024

Can you paste a code snippet of you unit test ... hard to tell what is wrong.
You can also take a peek at /RouteExceptionHandlerTest.java where those type of situations are tested.

from rest.vertx.

kruckerr avatar kruckerr commented on June 3, 2024

This is my test class. Just running this tests work fine when I start the server before running all tests. Initially, I startet the server before each test. Then I had the issue. But I have a second test class, that starts the server as well and when I run the tests of both test classes, the tests of the second classes will fail. The problem seem to be the static member "forge" in RestRouter, that returns the the ExceptionHandlerCache. Due to this member is static, it will remember the ExceptionHandlers from before. Or do I have a possibility to clean up this ExceptionHandlerCache after the test?

`@ExtendWith({VertxExtension.class})
class WebServerVerticleTest {

public static final int TEST_SERVER_PORT = 8181;
public static final String TEST_SERVER_HOST = "localhost";

@BeforeAll
static void deployVerticle(Vertx vertx, VertxTestContext testContext) {
    List<IRestController> activeControllers = Arrays.asList(new PrivateHelloRestController());
    SocketHandler socketHandler = new SocketHandler(vertx, null);
    vertx.deployVerticle(new WebServerVerticle(TEST_SERVER_PORT, null, socketHandler).with(activeControllers), testContext.succeeding(id -> testContext.completeNow()));
}

@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 2)
void whenCallHello_thenGetResponse(Vertx vertx, VertxTestContext testContext) {
    WebClient webClient = WebClient.create(vertx);
    webClient.get(TEST_SERVER_PORT, TEST_SERVER_HOST, "/api/hello").send(ar -> {
        if (ar.succeeded()) {
            HttpResponse<Buffer> response = ar.result();
            assertThat(response.statusCode()).isEqualTo(200);
            assertThat(response.bodyAsString()).isEqualTo("Hello from Vert.x");
            testContext.completeNow();
        } else {
            testContext.failNow(ar.cause());
        }
    });
}

@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 2)
void whenRequestIsUsedAndResponseIsModfied(Vertx vertx, VertxTestContext testContext) {
    WebClient webClient = WebClient.create(vertx);
    webClient.get(TEST_SERVER_PORT, TEST_SERVER_HOST, "/api/context").send(ar -> {
        if (ar.succeeded()) {
            HttpResponse<Buffer> response = ar.result();
            assertThat(response.statusCode()).isEqualTo(201);
            assertThat(response.bodyAsString()).isEqualTo("/api/context");
            testContext.completeNow();
        } else {
            testContext.failNow(ar.cause());
        }
    });
}

@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 2)
void whenCallPrivateHello_thenGetResponse(Vertx vertx, VertxTestContext testContext) {
    WebClient webClient = WebClient.create(vertx);
    webClient.get(TEST_SERVER_PORT, TEST_SERVER_HOST, "/private/hello").bearerTokenAuthentication(generateToken()).send(ar -> {
        if (ar.succeeded()) {
            HttpResponse<Buffer> response = ar.result();
            assertThat(response.statusCode()).isEqualTo(200);
            assertThat(response.bodyAsString()).isEqualTo("Private hello from Vert.x");
            testContext.completeNow();
        } else {
            testContext.failNow(ar.cause());
        }
    });
}

@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 2)
void whenCallPrivateHelloWithoutToken_thenGetError(Vertx vertx, VertxTestContext testContext) {
    WebClient webClient = WebClient.create(vertx);
    webClient.get(TEST_SERVER_PORT, TEST_SERVER_HOST, "/private/hello").send(ar -> {
        if (ar.succeeded()) {
            HttpResponse<Buffer> response = ar.result();
            assertThat(response.statusCode()).isEqualTo(401);
            assertThat(response.bodyAsString()).isNullOrEmpty();
            testContext.completeNow();
        } else {
            testContext.failNow(ar.cause());
        }
    });
}

private String generateToken() {
    JsonObject data = new JsonObject();
    data.put("sub", "the.user");
    data.put("id", 2);
    data.put("permissions", Arrays.asList("Admin"));
    JWTOptions options = new JWTOptions();
    options.setExpiresInSeconds(10);
    JWTAuth authProvider = JWTAuth.create(Vertx.vertx(), new JWTAuthOptions()
            .addPubSecKey(new PubSecKeyOptions()
                    .setAlgorithm("HS256")
                    .setPublicKey("93C7Z(I2k§h5\"BR1lHqH3jsZG5H8.D§P[!{c.&u1h!q*Ob3D!u-4bvX0iNL2+iP:7QFJ2L94Nv>*##t9")
                    .setSymmetric(true)
            ));
    return authProvider.generateToken(data, options);
}

}`

from rest.vertx.

drejc avatar drejc commented on June 3, 2024

You are correct handlers, readers, writers ... etc. are all cached once registered. This is a feature of the library.
If you take a look at my base test class: VertxTest

you will see that I have a before() method that cleans all caches.

public static void before() {

        vertx = Vertx.vertx();
        vertxTestContext = new VertxTestContext();

        // clear all registered writers or reader and handlers
        RestRouter.getReaders().clear();
        RestRouter.getWriters().clear();
        RestRouter.getExceptionHandlers().clear();
        RestRouter.getContextProviders().clear();

        // clear
        RestRouter.validateWith((Validator) null);
        RestRouter.injectWith((InjectionProvider) null);

        client = WebClient.create(vertx);
    }

All my tests are extended from this VertxTest class and on @BeforeAll I call the before() method cleaning everything up.
I suggest that you do something similar.

from rest.vertx.

kruckerr avatar kruckerr commented on June 3, 2024

That's fine for me. I will do so as well. Thank you.

from rest.vertx.

kruckerr avatar kruckerr commented on June 3, 2024

The last release is already some time ago and there are many useful commits in the meantime. What are your plans. Are you going to create a release soon? And do you have plans to migrate to Vert.x 4?

from rest.vertx.

drejc avatar drejc commented on June 3, 2024

The next release will be coming soon, I'm currently in the process of migrating to Vert.x 4 as they are some breaking changes. So stay tuned.

from rest.vertx.

Related Issues (20)

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.