Skip to content

Commit

Permalink
Add test for the HttpService::list_routes method/cli command
Browse files Browse the repository at this point in the history
  • Loading branch information
spencewenski committed May 12, 2024
1 parent 332dee1 commit 35af026
Showing 1 changed file with 57 additions and 4 deletions.
61 changes: 57 additions & 4 deletions src/service/http/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ impl<A: App> AppService<A> for HttpService {
RoadsterCommand::Roadster(args) => match &args.command {
#[cfg(feature = "open-api")]
RoadsterSubCommand::ListRoutes(_) => {
self.list_routes();
info!("API routes:");
self.list_routes()
.iter()
.for_each(|(path, method)| info!("[{method}]\t{path}"));
return Ok(true);
}
#[cfg(feature = "open-api")]
Expand Down Expand Up @@ -94,13 +97,13 @@ impl HttpService {

/// List the available HTTP API routes.
#[cfg(feature = "open-api")]
pub fn list_routes(&self) {
info!("API routes:");
pub fn list_routes(&self) -> Vec<(&str, &str)> {
self.api
.as_ref()
.operations()
.sorted_by(|(path_a, _, _), (path_b, _, _)| Ord::cmp(&path_a, &path_b))
.for_each(|(path, method, _operation)| info!("[{method}]\t{path}"));
.map(|(path, method, _)| (path, method))
.collect()
}

/// Generate an OpenAPI schema for the HTTP API.
Expand All @@ -125,3 +128,53 @@ impl HttpService {
Ok(())
}
}

#[cfg(test)]
mod tests {
use crate::service::http::service::HttpService;
use aide::axum::routing::{delete_with, get_with, post_with, put_with};
use aide::axum::ApiRouter;
use aide::openapi::OpenApi;
use itertools::Itertools;
use std::collections::BTreeMap;
use std::sync::Arc;

async fn api_method() {}

#[test]
#[cfg(feature = "open-api")]
fn list_routes() {
let mut open_api = OpenApi::default();
let router = ApiRouter::new()
.api_route("/foo", get_with(api_method, |op| op))
.api_route("/bar", post_with(api_method, |op| op))
.api_route("/baz", put_with(api_method, |op| op))
.api_route("/a", delete_with(api_method, |op| op))
.api_route("/c", get_with(api_method, |op| op))
.api_route("/b", get_with(api_method, |op| op))
.finish_api(&mut open_api);

let service = HttpService {
router,
api: Arc::new(open_api),
};

let paths = service
.list_routes()
.iter()
.map(|(path, _)| path.to_string())
.collect_vec();
assert_eq!(
paths,
["/a", "/b", "/bar", "/baz", "/c", "/foo"]
.iter()
.map(|s| s.to_string())
.collect_vec()
);
let paths: BTreeMap<&str, &str> = service.list_routes().into_iter().collect();
assert_eq!(paths.get("/foo").unwrap(), &"get");
assert_eq!(paths.get("/bar").unwrap(), &"post");
assert_eq!(paths.get("/baz").unwrap(), &"put");
assert_eq!(paths.get("/a").unwrap(), &"delete");
}
}

0 comments on commit 35af026

Please sign in to comment.