Hi,
first of all I really appreciate the great work diesel is doing to serve as an ORM in the Rust world. I successfully integrated diesel with r2d2 in actix_web (1.0).
However I now wanted to start to do testing my handlers… The integration looks currently like this.
The r2d2 connection pool is created like this and passed to the handler via .data(pool.clone())
let manager = ConnectionManager::<PgConnection>::new(config.database.url.clone());
let pool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
HttpServer::new(move || {
App::new()
.data(pool.clone())
.wrap(Logger::default())
.wrap(CookieSession::signed(&[0; 32]).name("s10s").secure(false))
.service(
web::resource("/register")
.name("register_user")
.route(web::post().to_async(register_user)),
)
The register_user function looks like this. I use the web::block method from actix_web to run the diesel stuff in a separate thread pool.
pub fn register_user(
(user_data, pool, _session): (
Json<rest_schemas::RegisterUserRequest>,
web::Data<Pool>,
Session,
),
) -> impl Future<Item = Json<rest_schemas::RegisterUserSuccessResponse>, Error = Error> {
web::block(move || S10User::register(pool, &user_data.email, &user_data.password)).then(|res| {
match res {
Ok(user) => Box::new(ok::<_, Error>(Json(
rest_schemas::RegisterUserSuccessResponse { user },
))),
Err(msg) => Box::new(err::<_, Error>(error::ErrorInternalServerError(msg))),
}
})
}
The S10Register::register function looks like this:
pub fn register(
pool: web::Data<Pool>,
email: &S10Email,
password: &S10Password,
) -> Result<S10User, String> {
let u = S10User {
id: Uuid::new_v4(),
email: email.to_string(),
password: password.to_string(),
created_at: Utc::now(),
updated_at: None,
deleted_at: None,
status: S10UserStatus::Active,
};
let db_user = NewUser {
email: u.email.clone(),
password: u.password.clone(),
status: S10UserStatus::Active.to_string(),
};
let conn: &PgConnection = &pool.get().unwrap();
diesel::insert_into(user::table)
.values(&db_user)
.get_result::<User>(conn)
.expect("Error saving new user to DB");
return Ok(u);
}
I know of the begin_test_transaction function which looks like exactly what I need to do, but I do not know how to nicely integrate this.I somehow have to create a new Application with a different connection pool, which uses the test_connection instead of a real one.
Any help would be appreciated.
Thanks,
Tim