Add first pass at interop tests

This commit is contained in:
Lucio Franco
2019-08-18 21:04:00 -04:00
parent 4835be515f
commit 8dc1185a36
14 changed files with 575 additions and 2 deletions
+79
View File
@@ -0,0 +1,79 @@
#![feature(async_await)]
use clap::{arg_enum, App, Arg, values_t};
use tonic_interop::client;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches = App::new("My Super Program")
.version("1.0")
.about("Does awesome things")
.arg(
Arg::with_name("test_case")
.long("test_case")
.value_name("TESTCASE")
.help(
"The name of the test case to execute. For example,
\"empty_unary\".",
)
.possible_values(&Testcase::variants())
.default_value("large_unary")
.takes_value(true)
.min_values(1)
.use_delimiter(true),
)
.get_matches();
let test_cases = values_t!(matches, "test_case", Testcase).unwrap_or_else(|e| e.exit());
let addr = "127.0.0.1:10000".parse()?;
let mut client = client::create(addr).await?;
for test_case in test_cases {
println!("{:?}:", test_case);
let mut test_results = Vec::new();
match test_case {
Testcase::empty_unary => client::unary_call(&mut client, &mut test_results).await,
_ => unimplemented!(),
}
for result in test_results {
println!(" {}", result);
}
}
Ok(())
}
arg_enum! {
#[derive(Debug, Copy, Clone)]
#[allow(non_camel_case_types)]
enum Testcase {
empty_unary,
cacheable_unary,
large_unary,
client_compressed_unary,
server_compressed_unary,
client_streaming,
client_compressed_streaming,
server_streaming,
server_compressed_streaming,
ping_pong,
empty_stream,
compute_engine_creds,
jwt_token_creds,
oauth2_auth_token,
per_rpc_creds,
custom_metadata,
status_code_and_message,
special_status_message,
unimplemented_method,
unimplemented_service,
cancel_after_begin,
cancel_after_first_response,
timeout_on_sleeping_server,
concurrent_large_unary
}
}
+49
View File
@@ -0,0 +1,49 @@
#![feature(async_await)]
use std::time::Duration;
use tokio::{net::TcpListener, timer::Delay};
use tonic::{Request, Response, Status};
use tower_h2::Server;
pub mod pb {
#![allow(dead_code)]
#![allow(unused_imports)]
include!(concat!(env!("OUT_DIR"), "/grpc.testing.rs"));
tonic::client!(service = "grpc.testing.TestService", proto = "self");
}
use pb::*;
#[derive(Default, Clone)]
pub struct TestService {
data: String,
}
#[tonic::server(service = "grpc.testing.TestService", proto = "pb")]
impl TestService {
pub async fn empty_call(&self, request: Request<Empty>) -> Result<Response<Empty>, Status> {
println!("REQUEST={:?}", request);
Ok(Response::new(Empty {}))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = "[::1]:10000".parse().unwrap();
let mut bind = TcpListener::bind(&addr)?;
let greeter = TestService::default();
let mut server = Server::new(TestServiceServer::new(greeter), Default::default());
while let Ok((sock, _addr)) = bind.accept().await {
if let Err(e) = sock.set_nodelay(true) {
return Err(e.into());
}
if let Err(e) = server.serve(sock).await {
println!("H2 ERROR: {}", e);
}
}
Ok(())
}
+39
View File
@@ -0,0 +1,39 @@
use crate::{pb::*, test_assert, TestAssertion};
use std::net::SocketAddr;
use tokio::net::TcpStream;
use tonic::Request;
use tower_h2::{add_origin::AddOrigin, Connection};
pub type Client = TestServiceClient<AddOrigin<Connection<tonic::BoxBody>>>;
tonic::client!(service = "grpc.testing.TestService", proto = "crate::pb");
pub async fn create(addr: SocketAddr) -> Result<Client, Box<dyn std::error::Error>> {
let io = TcpStream::connect(&addr).await?;
let origin = http::Uri::from_shared(format!("http://{}", addr).into()).unwrap();
let svc = Connection::handshake(io).await?;
let svc = AddOrigin::new(svc, origin);
Ok(TestServiceClient::new(svc))
}
pub async fn unary_call(client: &mut Client, assertions: &mut Vec<TestAssertion>) {
let result = client.empty_call(Request::new(Empty {})).await;
assertions.push(test_assert!(
"call must be successful",
result.is_ok(),
format!("result={:?}", result)
));
if let Ok(response) = result {
let body = response.into_inner();
assertions.push(test_assert!(
"body must not be null",
body == Empty {},
format!("body={:?}", body)
));
}
}
+90
View File
@@ -0,0 +1,90 @@
#![feature(async_await)]
pub mod client;
pub mod pb {
#![allow(dead_code)]
#![allow(unused_imports)]
include!(concat!(env!("OUT_DIR"), "/grpc.testing.rs"));
}
use std::fmt;
#[derive(Debug)]
pub enum TestAssertion {
Passed {
description: &'static str,
},
Failed {
description: &'static str,
expression: &'static str,
why: Option<String>,
},
}
impl fmt::Display for TestAssertion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use console::{style, Emoji};
match *self {
TestAssertion::Passed { ref description } => write!(
f,
"{check} {desc}",
check = style(Emoji("", "+")).green(),
desc = style(description).green(),
),
TestAssertion::Failed {
ref description,
ref expression,
why: Some(ref why),
} => write!(
f,
"{check} {desc}\n in `{exp}`: {why}",
check = style(Emoji("", "x")).red(),
desc = style(description).red(),
exp = style(expression).red(),
why = style(why).red(),
),
TestAssertion::Failed {
ref description,
ref expression,
why: None,
} => write!(
f,
"{check} {desc}\n in `{exp}`",
check = style(Emoji("", "x")).red(),
desc = style(description).red(),
exp = style(expression).red(),
),
}
}
}
#[macro_export]
macro_rules! test_assert {
($description:expr, $assertion:expr) => {
if $assertion {
crate::TestAssertion::Passed {
description: $description,
}
} else {
TestAssertion::Failed {
description: $description,
expression: stringify!($assertion),
why: None,
}
}
};
($description:expr, $assertion:expr, $why:expr) => {
if $assertion {
crate::TestAssertion::Passed {
description: $description,
}
} else {
crate::TestAssertion::Failed {
description: $description,
expression: stringify!($assertion),
why: Some($why),
}
}
};
}