Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding test for actix-web #698

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion examples/actix4_example/entity/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ features = [
"debug-print",
"runtime-actix-native-tls",
"sqlx-mysql",
"mock",
# "sqlx-postgres",
# "sqlx-sqlite",
]
default-features = false
default-features = false
10 changes: 7 additions & 3 deletions examples/actix4_example/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
#[path = "main_test.rs"]
#[cfg(test)]
mod main_test;

use actix_files::Files as Fs;
use actix_web::{
error, get, middleware, post, web, App, Error, HttpRequest, HttpResponse, HttpServer, Result,
Expand All @@ -16,11 +20,11 @@ use tera::Tera;

const DEFAULT_POSTS_PER_PAGE: usize = 5;

#[derive(Debug, Clone)]
struct AppState {
templates: tera::Tera,
conn: DatabaseConnection,
}

#[derive(Debug, Deserialize)]
pub struct Params {
page: Option<usize>,
Expand Down Expand Up @@ -174,13 +178,13 @@ async fn main() -> std::io::Result<()> {
let conn = sea_orm::Database::connect(&db_url).await.unwrap();
Migrator::up(&conn, None).await.unwrap();
let templates = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap();
let state = AppState { templates, conn };
let state = web::Data::new(AppState { templates, conn });

let mut listenfd = ListenFd::from_env();
let mut server = HttpServer::new(move || {
App::new()
.service(Fs::new("/static", "./static"))
.data(state.clone())
.app_data(state.clone())
.wrap(middleware::Logger::default()) // enable logger
.configure(init)
});
Expand Down
56 changes: 56 additions & 0 deletions examples/actix4_example/src/main_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use actix_web::{http, test};
use serde::Serialize;
use crate::sea_orm::{MockDatabase, MockExecResult, DatabaseBackend, Transaction};

#[derive(Serialize)]
struct PostForm {
title: String,
text: String,
}

#[cfg(test)]
#[actix_web::test]
async fn test_create() {
use super::*;
let post_db: post::Model = post::Model {
id: 15.to_owned(),
title: "title".to_owned(),
text: "text".to_owned(),
};

let conn = MockDatabase::new(DatabaseBackend::Postgres)
.append_query_results(vec![vec![post_db.clone()]])
.append_exec_results(vec![
MockExecResult {
last_insert_id: 15,
rows_affected: 1,
},
])
.into_connection();
let templates = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap();
let state = web::Data::new(AppState { conn, templates });
let app = test::init_service(App::new().app_data(state.clone()).service(create)).await;

let form = web::Form(PostForm {
title: "title".into(),
text: "text".into(),
});

let req = test::TestRequest::post().set_form(&form).uri("/").to_request();
let resp = test::call_service(&app, req).await;

assert_eq!(resp.status(), http::StatusCode::FOUND);

// the commenting the following will allow the test to pass
// otherwise the borrow checker complains about using the conn variable after it is moved
assert_eq!(
conn.into_transaction_log(),
vec![
Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"INSERT INTO "posts" ("title", "text") VALUES ($1, $2) RETURNING "id", "title", "text""#,
vec![1u64.into()]
),
],
);
}