org.junit.jupiter.params.provider.ArgumentsSource Java Examples

The following examples show how to use org.junit.jupiter.params.provider.ArgumentsSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testFileSystemGet_modifiedFile(String baseUri) throws Exception {
    final Path barFile = tmpDir.resolve("modifiedFile.html");
    final String expectedContentA = "<html/>";
    final String expectedContentB = "<html><body/></html>";
    writeFile(barFile, expectedContentA);
    final long barFileLastModified = Files.getLastModifiedTime(barFile).toMillis();

    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpUriRequest req = new HttpGet(baseUri + "/fs/modifiedFile.html");
        try (CloseableHttpResponse res = hc.execute(req)) {
            assert200Ok(res, "text/html", expectedContentA);
        }

        // Modify the file cached by the service. Update last modification time explicitly
        // so that it differs from the old value.
        writeFile(barFile, expectedContentB);
        Files.setLastModifiedTime(barFile, FileTime.fromMillis(barFileLastModified + 5000));

        try (CloseableHttpResponse res = hc.execute(req)) {
            assert200Ok(res, "text/html", expectedContentB);
        }
    }
}
 
Example #2
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testIdentity_DevNullService_consume(SerializationFormat defaultSerializationFormat) throws Exception {
    final DevNullService.Client client = new DevNullService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_consume(FOO);
    assertThat(out.length()).isGreaterThan(0);

    final THttpService syncService = THttpService.of((DevNullService.Iface) value -> {
        // NOOP
    }, defaultSerializationFormat);

    final THttpService asyncService = THttpService.of(
            (DevNullService.AsyncIface) (value, resultHandler) ->
                    resultHandler.onComplete(null), defaultSerializationFormat);

    invokeTwice(syncService, asyncService);

    assertThat(promise.get()).isEqualTo(promise2.get());
}
 
Example #3
Source File: DeferredStreamMessageTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(AbortCauseArgumentProvider.class)
void testLateAbortWithSubscriber(@Nullable Throwable cause) {
    final DeferredStreamMessage<Object> m = new DeferredStreamMessage<>();
    final DefaultStreamMessage<Object> d = new DefaultStreamMessage<>();
    @SuppressWarnings("unchecked")
    final Subscriber<Object> subscriber = mock(Subscriber.class);

    m.subscribe(subscriber, ImmediateEventExecutor.INSTANCE);
    m.delegate(d);
    verify(subscriber).onSubscribe(any());

    if (cause == null) {
        m.abort();
    } else {
        m.abort(cause);
    }
    if (cause == null) {
        verify(subscriber, times(1)).onError(isA(AbortedStreamException.class));
    } else {
        verify(subscriber, times(1)).onError(isA(cause.getClass()));
    }

    assertAborted(m, cause);
    assertAborted(d, cause);
}
 
Example #4
Source File: DeferredStreamMessageTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(AbortCauseArgumentProvider.class)
void testEarlyAbortWithSubscriber(@Nullable Throwable cause) {
    final DeferredStreamMessage<Object> m = new DeferredStreamMessage<>();
    @SuppressWarnings("unchecked")
    final Subscriber<Object> subscriber = mock(Subscriber.class);
    m.subscribe(subscriber, ImmediateEventExecutor.INSTANCE);
    if (cause == null) {
        m.abort();
    } else {
        m.abort(cause);
    }
    assertAborted(m, cause);

    final DefaultStreamMessage<Object> d = new DefaultStreamMessage<>();
    m.delegate(d);
    assertAborted(d, cause);
}
 
Example #5
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testAsync_FileService_create_reply(SerializationFormat defaultSerializationFormat) throws Exception {
    final FileService.Client client = new FileService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_create(BAR);
    assertThat(out.length()).isGreaterThan(0);

    final THttpService service = THttpService.of(
            (FileService.AsyncIface) (path, resultHandler) ->
                    resultHandler.onError(newFileServiceException()), defaultSerializationFormat);

    invoke(service);

    try {
        client.recv_create();
        fail(FileServiceException.class.getSimpleName() + " not raised.");
    } catch (FileServiceException ignored) {
        // Expected
    }
}
 
Example #6
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testAsync_NameService_removeMiddle(SerializationFormat defaultSerializationFormat) throws Exception {
    final NameService.Client client = new NameService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_removeMiddle(new Name(BAZ, BAR, FOO));
    assertThat(out.length()).isGreaterThan(0);

    final THttpService service = THttpService.of(
            (NameService.AsyncIface) (name, resultHandler) ->
                    resultHandler.onComplete(new Name(name.first, null, name.last)),
            defaultSerializationFormat);

    invoke(service);

    assertThat(client.recv_removeMiddle()).isEqualTo(new Name(BAZ, null, FOO));
}
 
Example #7
Source File: HttpClientResponseTimeoutTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(TimeoutDecoratorSource.class)
void setRequestTimeoutAtPendingTimeoutTask(Consumer<? super ClientRequestContext> timeoutCustomizer) {
    final WebClient client = WebClient
            .builder(server.httpUri())
            .option(ClientOption.RESPONSE_TIMEOUT_MILLIS.newValue(30L))
            .decorator((delegate, ctx, req) -> {
                // set timeout before initializing timeout controller
                timeoutCustomizer.accept(ctx);
                return delegate.execute(ctx, req);
            })
            .build();
    await().timeout(Duration.ofSeconds(5)).untilAsserted(() -> {
        assertThatThrownBy(() -> client.get("/no-timeout")
                                       .aggregate().join())
                .isInstanceOf(CompletionException.class)
                .hasCauseInstanceOf(ResponseTimeoutException.class);
    });
}
 
Example #8
Source File: DeferredStreamMessageTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(AbortCauseArgumentProvider.class)
void testLateAbort(@Nullable Throwable cause) {
    final DeferredStreamMessage<Object> m = new DeferredStreamMessage<>();
    final DefaultStreamMessage<Object> d = new DefaultStreamMessage<>();

    m.delegate(d);
    if (cause == null) {
        m.abort();
    } else {
        m.abort(cause);
    }

    assertAborted(m, cause);
    assertAborted(d, cause);
}
 
Example #9
Source File: InvestorTest.java    From robozonky with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SessionType.class)
void irrelevantFail(final SessionInfo sessionType) {
    final boolean isDryRun = sessionType.isDryRun();
    final Tenant t = mockTenant(zonky, isDryRun);
    doThrow(IllegalStateException.class).when(zonky)
        .invest(notNull(), anyInt());
    final Investor i = Investor.build(t);
    final RecommendedLoan r = DESCRIPTOR.recommend(Money.from(200))
        .orElse(null);
    if (isDryRun) { // the endpoint is not actually called, therefore cannot return error
        assertThat(i.invest(r)
            .get()).isEqualTo(Money.from(200));
    } else {
        assertThatThrownBy(() -> i.invest(r)).isInstanceOf(IllegalStateException.class);
    }
}
 
Example #10
Source File: RequestCompressionPluginTest.java    From riptide with MIT License 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(RequestFactorySource.class)
void shouldCompressRequestBody(final ClientHttpRequestFactory factory) {
    driver.addExpectation(onRequestTo("/")
                    .withMethod(POST)
                    .withHeader("X-Content-Encoding", "gzip") // written by Jetty's GzipHandler
                    .withBody(equalTo("{}"), "application/json"),
            giveResponse("", "text/plain"));

    final Http http = buildHttp(factory, new RequestCompressionPlugin());
    http.post("/")
            .contentType(MediaType.APPLICATION_JSON)
            .body(new HashMap<>())
            .call(pass())
            .join();
}
 
Example #11
Source File: RequestCompressionPluginTest.java    From riptide with MIT License 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(RequestFactorySource.class)
void shouldCompressWithGivenAlgorithm(final ClientHttpRequestFactory factory) {
    driver.addExpectation(onRequestTo("/")
                    .withMethod(POST)
                    .withHeader("Content-Encoding", "identity") // not handled by Jetty
                    .withoutHeader("X-Content-Encoding")
                    .withBody(equalTo("{}"), "application/json"),
            giveResponse("", "text/plain"));

    final Http http = buildHttp(factory, new RequestCompressionPlugin(Compression.of("identity", it -> it)));
    http.post("/")
            .contentType(MediaType.APPLICATION_JSON)
            .body(new HashMap<>())
            .call(pass())
            .join();
}
 
Example #12
Source File: CircuitBreakerRuleWithContentBuilderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ArgumentsSource(CircuitBreakerRuleSource.class)
@ParameterizedTest
void shouldReportAsWithContent(String message, CircuitBreakerDecision decision) {
    final CircuitBreakerRuleWithContent<HttpResponse> rule =
            CircuitBreakerRuleWithContent
                    .<HttpResponse>builder()
                    .onResponse((unused, response) -> response.aggregate().thenApply(content -> false))
                    .onResponse((unused, response) -> response.aggregate().thenApply(content -> false))
                    .onResponse((unused, response) -> {
                        return response.aggregate()
                                       .thenApply(content -> content.contentUtf8().contains(message));
                    })
                    .thenSuccess()
                    .orElse(CircuitBreakerRuleWithContent
                                    .<HttpResponse>builder()
                                    .thenFailure());

    ctx1.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.OK));
    assertFuture(rule.shouldReportAsSuccess(ctx1, HttpResponse.of("Hello Armeria!"), null))
            .isSameAs(decision);
}
 
Example #13
Source File: Java9RequestContextAwareFutureTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(Java9CallbackArgumentsProvider.class)
void makeContextAwareCompletableFutureWithDifferentContext(
        BiConsumer<CompletableFuture<?>, AtomicBoolean> callback) {
    final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
    final ServiceRequestContext ctx1 = ServiceRequestContext.builder(req).build();
    final ServiceRequestContext ctx2 = ServiceRequestContext.builder(req).build();
    try (SafeCloseable ignored = ctx1.push()) {
        final CompletableFuture<Object> future = new CompletableFuture<>();
        final CompletableFuture<Object> contextAwareFuture = ctx2.makeContextAware(future);
        final AtomicBoolean callbackCalled = new AtomicBoolean();
        callback.accept(contextAwareFuture, callbackCalled);

        future.complete(null);

        assertThat(callbackCalled.get()).isFalse();
        verify(appender, atLeast(0)).doAppend(eventCaptor.capture());
        assertThat(eventCaptor.getAllValues()).anySatisfy(event -> {
            assertThat(event.getLevel()).isEqualTo(Level.WARN);
            assertThat(event.getMessage()).startsWith("An error occurred while pushing");
        });
    }
}
 
Example #14
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BlockingClientProvider.class)
void error_withMessage(UnitTestServiceBlockingStub blockingClient) throws Exception {
    final StatusRuntimeException t = (StatusRuntimeException) catchThrowable(
            () -> blockingClient.errorWithMessage(REQUEST_MESSAGE));
    assertThat(t.getStatus().getCode()).isEqualTo(Code.ABORTED);
    assertThat(t.getStatus().getDescription()).isEqualTo("aborted call");
    assertThat(t.getTrailers().getAll(STRING_VALUE_KEY))
            .containsExactly(StringValue.newBuilder().setValue("custom metadata").build());
    assertThat(t.getTrailers().getAll(INT_32_VALUE_KEY))
            .containsExactly(Int32Value.newBuilder().setValue(10).build(),
                             Int32Value.newBuilder().setValue(20).build());
    assertThat(t.getTrailers().get(CUSTOM_VALUE_KEY)).isEqualTo("custom value");

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/ErrorWithMessage");
        assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE);
        assertThat(grpcStatus).isNotNull();
        assertThat(grpcStatus.getCode()).isEqualTo(Code.ABORTED);
        assertThat(grpcStatus.getDescription()).isEqualTo("aborted call");
    });
}
 
Example #15
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(StreamingClientProvider.class)
void requestContextSet(UnitTestServiceStub streamingClient) throws Exception {
    final StreamRecorder<SimpleResponse> response = StreamRecorder.create();
    final StreamObserver<SimpleRequest> request = streamingClient.checkRequestContext(response);
    request.onNext(REQUEST_MESSAGE);
    request.onNext(REQUEST_MESSAGE);
    request.onNext(REQUEST_MESSAGE);
    request.onCompleted();
    response.awaitCompletion();
    final SimpleResponse expectedResponse =
            SimpleResponse.newBuilder()
                          .setPayload(Payload.newBuilder()
                                             .setBody(ByteString.copyFromUtf8("3")))
                          .build();
    assertThat(response.getValues()).containsExactly(expectedResponse);

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.method()).isEqualTo(
                "armeria.grpc.testing.UnitTestService/CheckRequestContext");
        assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE);
        assertThat(rpcRes.get()).isEqualTo(expectedResponse);
    });
}
 
Example #16
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BlockingClientProvider.class)
void error_noMessage(UnitTestServiceBlockingStub blockingClient) throws Exception {
    final StatusRuntimeException t = (StatusRuntimeException) catchThrowable(
            () -> blockingClient.errorNoMessage(REQUEST_MESSAGE));
    assertThat(t.getStatus().getCode()).isEqualTo(Code.ABORTED);
    assertThat(t.getStatus().getDescription()).isNull();

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/ErrorNoMessage");
        assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE);
        assertThat(grpcStatus).isNotNull();
        assertThat(grpcStatus.getCode()).isEqualTo(Code.ABORTED);
        assertThat(grpcStatus.getDescription()).isNull();
    });
}
 
Example #17
Source File: StreamMessageTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(StreamProvider.class)
void flowControlled_writeThenDemandThenProcess_eventLoop(StreamMessage<Integer> stream,
                                                         List<Integer> values) {
    writeTenIntegers(stream);
    eventLoop.get().submit(
            () ->
                    stream.subscribe(new ResultCollectingSubscriber() {
                        private Subscription subscription;

                        @Override
                        public void onSubscribe(Subscription s) {
                            subscription = s;
                            subscription.request(1);
                        }

                        @Override
                        public void onNext(Integer value) {
                            subscription.request(1);
                            super.onNext(value);
                        }
                    }, eventLoop.get())).syncUninterruptibly();
    assertSuccess(values);
}
 
Example #18
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testIdentity_FileService_create_exception(SerializationFormat defaultSerializationFormat)
        throws Exception {
    final FileService.Client client = new FileService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_create(BAZ);
    assertThat(out.length()).isGreaterThan(0);

    final RuntimeException exception = Exceptions.clearTrace(new RuntimeException());
    final THttpService syncService = THttpService.of((FileService.Iface) path -> {
        throw exception;
    }, defaultSerializationFormat);

    final THttpService asyncService = THttpService.of(
            (FileService.AsyncIface) (path, resultHandler) ->
                    resultHandler.onError(exception), defaultSerializationFormat);

    invokeTwice(syncService, asyncService);

    assertThat(promise.get()).isEqualTo(promise2.get());
}
 
Example #19
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void contextCaptorSync(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final HelloService.Iface client = Clients.builder(uri(Handlers.HELLO, format, protocol))
                                             .options(clientOptions)
                                             .build(Handlers.HELLO.iface());
    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        client.hello("kukuman");
        final ClientRequestContext ctx = ctxCaptor.get();
        final RpcRequest rpcReq = ctx.rpcRequest();
        assertThat(rpcReq).isNotNull();
        assertThat(rpcReq.method()).isEqualTo("hello");
        assertThat(rpcReq.params()).containsExactly("kukuman");
    }
}
 
Example #20
Source File: FileServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testGetWithoutPreCompression(String baseUri) throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpGet request = new HttpGet(baseUri + "/compressed/foo_alone.txt");
        request.setHeader("Accept-Encoding", "gzip");
        try (CloseableHttpResponse res = hc.execute(request)) {
            assertThat(res.getFirstHeader("Content-Encoding")).isNull();
            assertThat(headerOrNull(res, "Content-Type")).isEqualTo(
                    "text/plain; charset=utf-8");
            final byte[] content = content(res);
            assertThat(new String(content, StandardCharsets.UTF_8)).isEqualTo("foo_alone");

            // Confirm path not cached when cache disabled.
            assertThat(PathAndQuery.cachedPaths())
                    .doesNotContain("/compressed/foo_alone.txt");
        }
    }
}
 
Example #21
Source File: FileServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testClassPathGetFromJar(String baseUri) throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        // Read a class from a third-party library JAR.
        try (CloseableHttpResponse res =
                     hc.execute(new HttpGet(baseUri + "/classes/io/netty/util/NetUtil.class"))) {
            assert200Ok(res, null, content -> assertThat(content).isNotEmpty());
        }
        // Read a class from a third-party library JAR.
        try (CloseableHttpResponse res =
                     hc.execute(new HttpGet(baseUri + "/by-entry/classes/io/netty/util/NetUtil.class"))) {
            assert200Ok(res, null, content -> assertThat(content).isNotEmpty());
        }
    }
}
 
Example #22
Source File: FileServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testFileSystemGet_newFile(String baseUri) throws Exception {
    final String barFileName = baseUri.substring(baseUri.lastIndexOf('/') + 1) + "_newFile.html";
    assertThat(barFileName).isIn("cached_newFile.html", "uncached_newFile.html");

    final Path barFile = tmpDir.resolve(barFileName);
    final String expectedContentA = "<html/>";

    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpUriRequest req = new HttpGet(baseUri + "/fs/" + barFileName);
        try (CloseableHttpResponse res = hc.execute(req)) {
            assert404NotFound(res);
        }
        writeFile(barFile, expectedContentA);
        try (CloseableHttpResponse res = hc.execute(req)) {
            assert200Ok(res, "text/html", expectedContentA);
        }
    }
}
 
Example #23
Source File: FileServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(BaseUriProvider.class)
void testClassPathGetFromModule(String baseUri) throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        // Read a class from a JDK module (java.base).
        try (CloseableHttpResponse res =
                     hc.execute(new HttpGet(baseUri + "/classes/java/lang/Object.class"))) {
            assert200Ok(res, null, content -> assertThat(content).isNotEmpty());
        }
        // Read a class from a JDK module (java.base).
        try (CloseableHttpResponse res =
                     hc.execute(new HttpGet(baseUri + "/by-entry/classes/java/lang/Object.class"))) {
            assert200Ok(res, null, content -> assertThat(content).isNotEmpty());
        }
    }
}
 
Example #24
Source File: StreamMessageTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(StreamProvider.class)
void flowControlled_writeThenProcessThenDemand(StreamMessage<Integer> stream, List<Integer> values) {
    writeTenIntegers(stream);
    stream.subscribe(new ResultCollectingSubscriber() {
        private Subscription subscription;

        @Override
        public void onSubscribe(Subscription s) {
            subscription = s;
            subscription.request(1);
        }

        @Override
        public void onNext(Integer value) {
            super.onNext(value);
            subscription.request(1);
        }
    });
    assertSuccess(values);
}
 
Example #25
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testAsync_HelloService_hello(SerializationFormat defaultSerializationFormat) throws Exception {
    final HelloService.Client client = new HelloService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_hello(FOO);
    assertThat(out.length()).isGreaterThan(0);

    final THttpService service = THttpService.of(
            (HelloService.AsyncIface) (name, resultHandler) ->
                    resultHandler.onComplete("Hello, " + name + '!'), defaultSerializationFormat);

    invoke(service);

    assertThat(client.recv_hello()).isEqualTo("Hello, foo!");
}
 
Example #26
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testSync_FileService_create_exception(SerializationFormat defaultSerializationFormat)
        throws Exception {
    final FileService.Client client = new FileService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_create(BAZ);
    assertThat(out.length()).isGreaterThan(0);

    final RuntimeException exception = Exceptions.clearTrace(new RuntimeException());
    final THttpService service = THttpService.of((FileService.Iface) path -> {
        throw exception;
    }, defaultSerializationFormat);

    invoke(service);

    try {
        client.recv_create();
        fail(TApplicationException.class.getSimpleName() + " not raised.");
    } catch (TApplicationException e) {
        assertThat(e.getType()).isEqualTo(TApplicationException.INTERNAL_ERROR);
        assertThat(e.getMessage()).contains(exception.toString());
    }
}
 
Example #27
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testAsync_HelloService_hello_with_null(SerializationFormat defaultSerializationFormat)
        throws Exception {
    final HelloService.Client client = new HelloService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_hello(null);
    assertThat(out.length()).isGreaterThan(0);

    final THttpService service = THttpService.of(
            (HelloService.AsyncIface) (name, resultHandler) ->
                    resultHandler.onComplete(String.valueOf(name != null)), defaultSerializationFormat);

    invoke(service);

    assertThat(client.recv_hello()).isEqualTo("false");
}
 
Example #28
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testIdentity_HelloService_hello(SerializationFormat defaultSerializationFormat) throws Exception {
    final HelloService.Client client = new HelloService.Client.Factory().getClient(
            inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_hello(FOO);
    assertThat(out.length()).isGreaterThan(0);

    final THttpService syncService = THttpService.of(
            (HelloService.Iface) name -> "Hello, " + name + '!', defaultSerializationFormat);

    final THttpService asyncService = THttpService.of(
            (HelloService.AsyncIface) (name, resultHandler) ->
                    resultHandler.onComplete("Hello, " + name + '!'), defaultSerializationFormat);

    invokeTwice(syncService, asyncService);

    assertThat(promise.get()).isEqualTo(promise2.get());
}
 
Example #29
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testSync_OnewayHelloService_hello(SerializationFormat defaultSerializationFormat) throws Exception {
    final AtomicReference<String> actualName = new AtomicReference<>();

    final OnewayHelloService.Client client =
            new OnewayHelloService.Client.Factory().getClient(
                    inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_hello(FOO);
    assertThat(out.length()).isGreaterThan(0);

    final THttpService service = THttpService.of(
            (OnewayHelloService.Iface) actualName::set, defaultSerializationFormat);

    invoke(service);

    assertThat(promise.get().isEmpty()).isTrue();
    assertThat(actualName.get()).isEqualTo(FOO);
}
 
Example #30
Source File: ThriftServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(SerializationFormatProvider.class)
void testAsync_OnewayHelloService_hello(SerializationFormat defaultSerializationFormat) throws Exception {
    final AtomicReference<String> actualName = new AtomicReference<>();

    final OnewayHelloService.Client client =
            new OnewayHelloService.Client.Factory().getClient(
                    inProto(defaultSerializationFormat), outProto(defaultSerializationFormat));
    client.send_hello(FOO);
    assertThat(out.length()).isGreaterThan(0);

    final THttpService service = THttpService.of((OnewayHelloService.AsyncIface) (name, resultHandler) -> {
        actualName.set(name);
        resultHandler.onComplete(null);
    }, defaultSerializationFormat);

    invoke(service);

    assertThat(promise.get().isEmpty()).isTrue();
    assertThat(actualName.get()).isEqualTo(FOO);
}