Replies: 2 comments 1 reply
-
I’m not sure and I’m currently traveling so don’t have access to a computer where I can try stuff. I’d recommend using a trait object instead for this though. It’s probably gonna be simpler. Try asking in discordDiscord instead. |
Beta Was this translation helpful? Give feedback.
-
The immediate problem, suggested on Discord, was totally unrelated: This will compile: use axum::{
Router,
extract::State,
routing::get
};
trait DB: Clone + Send + Sync {
fn value(&self) -> &'static str;
}
#[derive(Clone)]
struct DBImpl {}
impl DB for DBImpl {
fn value(&self) -> &'static str {
"real"
}
}
async fn projects_get<D: DB + 'static>(State(db): State<D>) -> &'static str {
db.value()
}
fn routes<D: DB + 'static>() -> Router<D>
{
Router::new()
.route(
"/projects",
get(projects_get::<D>)
)
}
#[tokio::main]
async fn main() {
let db = DBImpl {};
let app: Router = routes::<DBImpl>().with_state(db);
}
#[cfg(test)]
mod test {
use super::*;
use axum::{
body::Body,
http::{Method, Request, StatusCode}
};
use tower::ServiceExt; // for oneshot
#[derive(Clone)]
struct FakeDBImpl {}
impl DB for FakeDBImpl {
fn value(&self) -> &'static str {
"test"
}
}
#[tokio::test]
async fn projects_get_ok() {
let db = FakeDBImpl {};
let app: Router = routes::<FakeDBImpl>().with_state(db);
let response = app
.oneshot(
Request::builder()
.method(Method::GET)
.uri(&format!("/projects"))
.body(Body::empty())
.unwrap()
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
assert_eq!(&body[..], b"test");
}
} I can make my test double as I intended. The second problem is that it seems impossible (?) to implement |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm trying to make a generic router using generic state, similar to #2184.
This doesn't compile:
I get the following error:
I can't use
#[axum::debug_handler]
as suggested, because that doesn't work for generic functions. What bound am I not satisfying? The error message seems not to say what it is.Beta Was this translation helpful? Give feedback.
All reactions