Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(transport): add user-agent header to client requests. #457

Merged
merged 6 commits into from
Sep 23, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions tests/integration_tests/tests/user_agent.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use futures_util::FutureExt;
use integration_tests::pb::{test_client, test_server, Input, Output};
use std::time::Duration;
use tokio::sync::oneshot;
use tonic::transport::Endpoint;
use tonic::{transport::Server, Request, Response, Status};
alce marked this conversation as resolved.
Show resolved Hide resolved

#[tokio::test]
async fn writes_user_agent_header() {
struct Svc;

#[tonic::async_trait]
impl test_server::Test for Svc {
async fn unary_call(&self, req: Request<Input>) -> Result<Response<Output>, Status> {
match req.metadata().get("user-agent") {
Some(_) => Ok(Response::new(Output {})),
None => Err(Status::internal("user-agent header is missing")),
}
}
}

let svc = test_server::TestServer::new(Svc);

let (tx, rx) = oneshot::channel::<()>();

let jh = tokio::spawn(async move {
Server::builder()
.add_service(svc)
.serve_with_shutdown("127.0.0.1:1322".parse().unwrap(), rx.map(drop))
.await
.unwrap();
});

tokio::time::delay_for(Duration::from_millis(100)).await;

let channel = Endpoint::from_static("http://127.0.0.1:1322")
.user_agent("my-client")
.expect("valid user agent")
.connect()
.await
.unwrap();

let mut client = test_client::TestClient::new(channel);

match client.unary_call(Input {}).await {
Ok(_) => {}
Err(status) => panic!("{}", status.message()),
}

tx.send(()).unwrap();

jh.await.unwrap();
}
23 changes: 23 additions & 0 deletions tonic/src/transport/service/user_agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,26 @@ where
self.inner.call(req)
}
}

#[cfg(test)]
mod tests {
use super::*;

struct Svc;

#[test]
fn sets_default_if_no_custom_user_agent() {
assert_eq!(
UserAgent::new(Svc, None).user_agent,
HeaderValue::from_static(TONIC_USER_AGENT)
)
}

#[test]
fn prepends_custom_user_agent_to_default() {
assert_eq!(
UserAgent::new(Svc, Some(HeaderValue::from_static("Greeter 1.1"))).user_agent,
HeaderValue::from_str(&format!("Greeter 1.1 {}", TONIC_USER_AGENT)).unwrap()
)
}
}