Created
May 17, 2020 21:41
-
-
Save wontheone1/5a80471e5dc1e576f1fc243ddfeb859f to your computer and use it in GitHub Desktop.
Failing actix test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use actix_web::{App, web, get, HttpResponse, HttpServer}; | |
use std::sync::Mutex; | |
struct AppStateWithCounter { | |
counter: Mutex<i32>, // <- Mutex is necessary to mutate safely across threads | |
} | |
#[get("/")] | |
async fn index(data: web::Data<AppStateWithCounter>) -> HttpResponse { | |
let mut counter = data.counter.lock().unwrap(); // <- get counter's MutexGuard | |
*counter += 1; // <- access counter inside MutexGuard | |
HttpResponse::Ok().body(format! ("Request number: {}!", counter)) | |
} | |
#[get("/again")] | |
async fn index2(data: web::Data<AppStateWithCounter>) -> HttpResponse { | |
let mut counter = data.counter.lock().unwrap(); // <- get counter's MutexGuard | |
*counter += 1; // <- access counter inside MutexGuard | |
HttpResponse::Ok().body(format! ("Request number: {}, again!", counter)) | |
} | |
#[actix_rt::main] | |
async fn main() -> std::io::Result<()> { | |
let counter = web::Data::new(AppStateWithCounter { | |
counter: Mutex::new(0), | |
}); | |
HttpServer::new(move || { | |
App::new() | |
.app_data(counter.clone()) | |
.service(index) | |
.service(index2) | |
}) | |
.bind("127.0.0.1:8088")? | |
.run() | |
.await | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
use actix_web::{http}; | |
#[actix_rt::test] | |
async fn test_index_status_code() { | |
let counter = web::Data::new(AppStateWithCounter { | |
counter: Mutex::new(0), | |
}); | |
let resp = index(counter).await; | |
assert_eq!(resp.status(), http::StatusCode::OK); | |
} | |
#[actix_rt::test] | |
async fn test_index_body() { | |
let counter = web::Data::new(AppStateWithCounter { | |
counter: Mutex::new(0), | |
}); | |
let resp = index(counter).await; | |
let (body, mut resp) = resp.take_body().into_future().await; | |
assert_eq!(body, "moi"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Error message from test shows