#include <thread>
#include <grpcpp/impl/codegen/config.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h>
#include <grpc/support/log.h>
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "test/core/util/port.h"
#include <gtest/gtest.h>
namespace grpc {
namespace {
TEST(ServerRequestCallTest, ShortDeadlineDoesNotCauseOkayFalse) {
std::mutex mu;
bool shutting_down = false;
std::ostringstream s;
int p = grpc_pick_unused_port_or_die();
s << "[::1]:" << p;
const string address = s.str();
testing::EchoTestService::AsyncService service;
ServerBuilder builder;
builder.AddListeningPort(address, InsecureServerCredentials());
auto cq = builder.AddCompletionQueue();
builder.RegisterService(&service);
auto server = builder.BuildAndStart();
std::thread t([address, &service, &cq, &mu, &shutting_down] {
for (int n = 0; true; n++) {
ServerContext ctx;
testing::EchoRequest req;
ServerAsyncResponseWriter<testing::EchoResponse> responder(&ctx);
{
std::lock_guard<std::mutex> lock(mu);
if (!shutting_down) {
service.RequestEcho(&ctx, &req, &responder, cq.get(), cq.get(),
(void*)1);
}
}
bool ok;
void* tag;
if (!cq->Next(&tag, &ok)) {
break;
}
EXPECT_EQ((void*)1, tag);
{
std::lock_guard<std::mutex> lock(mu);
if (!shutting_down && !ok) {
gpr_log(GPR_INFO, "!ok on request %d", n);
abort();
}
if (shutting_down && !ok) {
continue;
}
}
gpr_log(GPR_INFO, "Got request %d", n);
testing::EchoResponse response;
response.set_message("foobar");
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
gpr_time_from_millis(50, GPR_TIMESPAN)));
{
std::lock_guard<std::mutex> lock(mu);
if (shutting_down) {
gpr_log(GPR_INFO,
"shut down while processing call, not calling Finish()");
continue;
}
gpr_log(GPR_INFO, "Finishing request %d", n);
responder.Finish(response, grpc::Status::OK, (void*)2);
if (!cq->Next(&tag, &ok)) {
break;
}
EXPECT_EQ((void*)2, tag);
}
}
});
auto stub = testing::EchoTestService::NewStub(
CreateChannel(address, InsecureChannelCredentials()));
for (int i = 0; i < 100; i++) {
gpr_log(GPR_INFO, "Sending %d.", i);
testing::EchoRequest request;
request.set_message("foobar");
testing::EchoResponse response;
::grpc::ClientContext ctx;
ctx.set_fail_fast(false);
ctx.set_deadline(std::chrono::system_clock::now() +
std::chrono::milliseconds(1));
grpc::Status status = stub->Echo(&ctx, request, &response);
EXPECT_EQ(DEADLINE_EXCEEDED, status.error_code());
gpr_log(GPR_INFO, "Success.");
}
gpr_log(GPR_INFO, "Done sending RPCs.");
gpr_log(GPR_INFO, "Shutting down.");
{
std::lock_guard<std::mutex> lock(mu);
shutting_down = true;
}
server->Shutdown();
cq->Shutdown();
server->Wait();
t.join();
}
} }
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}