Skip to content

Commit

Permalink
try real axum tests
Browse files Browse the repository at this point in the history
  • Loading branch information
syphar committed Sep 29, 2024
1 parent 41d5e31 commit e5482e6
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 15 deletions.
15 changes: 12 additions & 3 deletions src/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::storage::{AsyncStorage, Storage, StorageKind};
use crate::web::{build_axum_app, cache, page::TemplateData};
use crate::{BuildQueue, Config, Context, Index, InstanceMetrics, RegistryApi, ServiceMetrics};
use anyhow::Context as _;
use axum::async_trait;
use axum::{async_trait, Router};
use fn_error_context::context;
use futures_util::{stream::TryStreamExt, FutureExt};
use once_cell::sync::OnceCell;
Expand Down Expand Up @@ -520,6 +520,13 @@ impl TestEnvironment {
self.runtime().block_on(self.async_fake_release())
}

pub(crate) async fn web_app(&self) -> Router {
let template_data = Arc::new(TemplateData::new(1).unwrap());
build_axum_app(self, template_data)
.await
.expect("could not build axum app")
}

pub(crate) async fn async_fake_release(&self) -> fakes::FakeRelease {
fakes::FakeRelease::new(
self.async_db().await,
Expand Down Expand Up @@ -716,10 +723,12 @@ impl TestFrontend {
let (tx, rx) = tokio::sync::oneshot::channel::<()>();

debug!("building axum app");
let axum_app = build_axum_app(context, template_data).expect("could not build axum app");
let runtime = context.runtime().unwrap();
let axum_app = runtime
.block_on(build_axum_app(context, template_data))
.expect("could not build axum app");

let handle = thread::spawn({
let runtime = context.runtime().unwrap();
move || {
runtime.block_on(async {
axum::serve(axum_listener, axum_app.into_make_service())
Expand Down
20 changes: 13 additions & 7 deletions src/web/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,17 +393,19 @@ async fn set_sentry_transaction_name_from_axum_route(
next.run(request).await
}

fn apply_middleware(
async fn apply_middleware(
router: AxumRouter,
context: &dyn Context,
template_data: Option<Arc<TemplateData>>,
) -> Result<AxumRouter> {
let config = context.config()?;
let has_templates = template_data.is_some();

let runtime = context.runtime()?;
let async_storage = runtime.block_on(context.async_storage())?;
let build_queue = context.build_queue()?;

let async_storage = context.runtime()?.block_on(context.async_storage())?;
Ok(router.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
Expand Down Expand Up @@ -435,15 +437,15 @@ fn apply_middleware(
))
}

pub(crate) fn build_axum_app(
pub(crate) async fn build_axum_app(
context: &dyn Context,
template_data: Arc<TemplateData>,
) -> Result<AxumRouter, Error> {
apply_middleware(routes::build_axum_routes(), context, Some(template_data))
apply_middleware(routes::build_axum_routes(), context, Some(template_data)).await
}

pub(crate) fn build_metrics_axum_app(context: &dyn Context) -> Result<AxumRouter, Error> {
apply_middleware(routes::build_metric_routes(), context, None)
pub(crate) async fn build_metrics_axum_app(context: &dyn Context) -> Result<AxumRouter, Error> {
apply_middleware(routes::build_metric_routes(), context, None).await
}

pub fn start_background_metrics_webserver(
Expand All @@ -458,8 +460,10 @@ pub fn start_background_metrics_webserver(
axum_addr.port()
);

let metrics_axum_app = build_metrics_axum_app(context)?.into_make_service();
let runtime = context.runtime()?;
let metrics_axum_app = runtime
.block_on(build_metrics_axum_app(context))?
.into_make_service();

runtime.spawn(async move {
match tokio::net::TcpListener::bind(axum_addr)
Expand Down Expand Up @@ -501,8 +505,10 @@ pub fn start_web_server(addr: Option<SocketAddr>, context: &dyn Context) -> Resu
context.storage()?;
context.repository_stats_updater()?;

let app = build_axum_app(context, template_data)?.into_make_service();
context.runtime()?.block_on(async {
let app = build_axum_app(context, template_data)
.await?
.into_make_service();
let listener = tokio::net::TcpListener::bind(axum_addr)
.await
.context("error binding socket for metrics web server")?;
Expand Down
37 changes: 32 additions & 5 deletions src/web/sitemap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,14 +203,41 @@ pub(crate) async fn about_handler(subpage: Option<Path<String>>) -> AxumResult<i

#[cfg(test)]
mod tests {
use crate::test::{assert_success, wrapper};
use reqwest::StatusCode;
use crate::{
test::{assert_success, async_wrapper, wrapper},
web::build_axum_app,
};
use axum::{
body::Body,
extract::connect_info::MockConnectInfo,
http::{self, Request, StatusCode},
};
// use http_body_util::BodyExt; // for `collect`
// use reqwest::StatusCode;
use serde_json::{json, Value};
use tokio::net::TcpListener;
use tower::{Service, ServiceExt}; // for `call`, `oneshot`, and `ready`

#[test]
fn sitemap_index() {
wrapper(|env| {
let web = env.frontend();
assert_success("/sitemap.xml", web)
async_wrapper(|env| async move {
// let web = env.frontend();
// assert_success("/sitemap.xml", web)

let app = env.web_app().await;

// let response = app
// .oneshot(
// Request::builder()
// .uri("/sitemap.xml")
// .body(Body::empty())
// .unwrap(),
// )
// .await
// .unwrap();

// assert_eq!(response.status(), StatusCode::OK);
Ok(())
})
}

Expand Down

0 comments on commit e5482e6

Please sign in to comment.