From 2e8ac69ae741fc61f613a0c58fa1b26327b7bad6 Mon Sep 17 00:00:00 2001 From: kazk Date: Sun, 21 Feb 2021 16:28:35 -0800 Subject: [PATCH] Add mock service example https://github.com/clux/kube-rs/issues/429 --- kube/src/api/typed.rs | 47 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/kube/src/api/typed.rs b/kube/src/api/typed.rs index 89160fb5a..8c6250f6a 100644 --- a/kube/src/api/typed.rs +++ b/kube/src/api/typed.rs @@ -339,3 +339,50 @@ impl From> for Client { api.client } } + +#[cfg(test)] +mod tests { + use futures::pin_mut; + use http::{Request, Response}; + use hyper::Body; + use k8s_openapi::api::core::v1::Pod; + use tower_test::mock; + + use crate::{Api, Client, Service}; + + #[tokio::test] + async fn test_mock() { + let (mock_service, handle) = mock::pair::, Response>(); + let spawned = tokio::spawn(async move { + pin_mut!(handle); + let (request, send) = handle.next_request().await.expect("service not called"); + assert_eq!(request.method(), http::Method::GET); + assert_eq!(request.uri().to_string(), "/api/v1/namespaces/default/pods/test"); + let pod: Pod = serde_json::from_value(serde_json::json!({ + "apiVersion": "v1", + "kind": "Pod", + "metadata": { + "name": "test", + "annotations": { + "kube-rs": "test", + }, + }, + "spec": { + "containers": [{ "name": "test", "image": "test-image" }], + } + })) + .unwrap(); + send.send_response( + Response::builder() + .body(Body::from(serde_json::to_vec(&pod).unwrap())) + .unwrap(), + ); + }); + + let service = Service::new(mock_service); + let pods: Api = Api::namespaced(Client::new(service), "default"); + let pod = pods.get("test").await.unwrap(); + assert_eq!(pod.metadata.annotations.unwrap().get("kube-rs").unwrap(), "test"); + spawned.await.unwrap(); + } +}