428 lines
14 KiB
Rust
428 lines
14 KiB
Rust
// use std::io::Write;
|
|
|
|
// use common_multipart_rfc7578::client::multipart::{Body as MultipartBody, Form as MultipartForm};
|
|
// use tower::ServiceExt;
|
|
|
|
use textsender_api::db;
|
|
|
|
mod db_mgr {
|
|
use std::str::FromStr;
|
|
|
|
pub const LIMIT: usize = 6;
|
|
|
|
pub async fn get_pool() -> Result<sqlx::PgPool, sqlx::Error> {
|
|
let tm_db_url = textsender_models::envy::environment::get_db_url()
|
|
.await
|
|
.value;
|
|
let tm_options = sqlx::postgres::PgConnectOptions::from_str(&tm_db_url).unwrap();
|
|
sqlx::PgPool::connect_with(tm_options).await
|
|
}
|
|
|
|
pub async fn generate_db_name() -> String {
|
|
let db_name =
|
|
get_database_name().await.unwrap() + &"_" + &uuid::Uuid::new_v4().to_string()[..LIMIT];
|
|
db_name
|
|
}
|
|
|
|
pub async fn connect_to_db(db_name: &str) -> Result<sqlx::PgPool, sqlx::Error> {
|
|
let db_url = textsender_models::envy::environment::get_db_url()
|
|
.await
|
|
.value;
|
|
let options = sqlx::postgres::PgConnectOptions::from_str(&db_url)?.database(db_name);
|
|
sqlx::PgPool::connect_with(options).await
|
|
}
|
|
|
|
pub async fn create_database(
|
|
template_pool: &sqlx::PgPool,
|
|
db_name: &str,
|
|
) -> Result<(), sqlx::Error> {
|
|
let create_query = format!("CREATE DATABASE {}", db_name);
|
|
match sqlx::query(&create_query).execute(template_pool).await {
|
|
Ok(_) => Ok(()),
|
|
Err(e) => Err(e),
|
|
}
|
|
}
|
|
|
|
// Function to drop a database
|
|
pub async fn drop_database(
|
|
template_pool: &sqlx::PgPool,
|
|
db_name: &str,
|
|
) -> Result<(), sqlx::Error> {
|
|
let drop_query = format!("DROP DATABASE IF EXISTS {} WITH (FORCE)", db_name);
|
|
sqlx::query(&drop_query).execute(template_pool).await?;
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn get_database_name() -> Result<String, Box<dyn std::error::Error>> {
|
|
let database_url = textsender_models::envy::environment::get_db_url()
|
|
.await
|
|
.value;
|
|
let parsed_url = url::Url::parse(&database_url)?;
|
|
|
|
if parsed_url.scheme() == "postgres" || parsed_url.scheme() == "postgresql" {
|
|
match parsed_url
|
|
.path_segments()
|
|
.and_then(|segments| segments.last().map(|s| s.to_string()))
|
|
{
|
|
Some(sss) => Ok(sss),
|
|
None => Err("Error parsing".into()),
|
|
}
|
|
} else {
|
|
// Handle other database types if needed
|
|
Err("Error parsing".into())
|
|
}
|
|
}
|
|
|
|
/*
|
|
pub async fn migrations(pool: &sqlx::PgPool) {
|
|
// Run migrations using the sqlx::migrate! macro
|
|
// Assumes your test migrations are in a ./test_migrations folder relative to Cargo.toml
|
|
sqlx::migrate!("./migrations")
|
|
.run(pool)
|
|
.await
|
|
.expect("Failed to run migrations");
|
|
}
|
|
*/
|
|
}
|
|
|
|
mod init {
|
|
pub async fn app(pool: sqlx::PgPool) -> axum::Router {
|
|
textsender_api::config::init::routes()
|
|
.await
|
|
.layer(axum::Extension(pool))
|
|
.layer(axum::extract::DefaultBodyLimit::max(1024 * 1024 * 1024))
|
|
.layer(tower_http::timeout::TimeoutLayer::with_status_code(
|
|
axum::http::StatusCode::OK,
|
|
std::time::Duration::from_secs(300),
|
|
))
|
|
}
|
|
}
|
|
|
|
mod util {
|
|
pub async fn resp_to_bytes(
|
|
response: axum::response::Response,
|
|
) -> Result<axum::body::Bytes, axum::Error> {
|
|
axum::body::to_bytes(response.into_body(), std::usize::MAX).await
|
|
}
|
|
|
|
pub async fn get_resp_data<Data>(response: axum::response::Response) -> Data
|
|
where
|
|
Data: for<'a> serde::Deserialize<'a>,
|
|
{
|
|
let body = resp_to_bytes(response).await.unwrap();
|
|
serde_json::from_slice(&body).unwrap()
|
|
}
|
|
|
|
/*
|
|
pub async fn format_url_with_value(endpoint: &str, value: &uuid::Uuid) -> String {
|
|
let last = endpoint.len() - 5;
|
|
format!("{}/{value}", &endpoint[0..last])
|
|
}
|
|
*/
|
|
}
|
|
|
|
pub fn token_fields() -> (String, String, String) {
|
|
(
|
|
String::from("What a twist!"),
|
|
String::from("textsender_test"),
|
|
String::from("textsender"),
|
|
)
|
|
}
|
|
|
|
pub const TEST_USER_ID: uuid::Uuid = uuid::uuid!("cc938368-615a-4694-b2ca-6e122fa31c52");
|
|
|
|
pub async fn test_token() -> Result<String, josekit::JoseError> {
|
|
let key: String = textsender_models::envy::environment::get_secret_main_key()
|
|
.await
|
|
.value;
|
|
let (message, issuer, audience) = token_fields();
|
|
|
|
let token_resource = textsender_models::token::TokenResource {
|
|
message: message,
|
|
issuer: issuer,
|
|
audiences: vec![audience],
|
|
user_id: TEST_USER_ID,
|
|
};
|
|
|
|
match textsender_models::token::create_token(&key, &token_resource, time::Duration::hours(1)) {
|
|
Ok((access_token, _some_time)) => Ok(access_token),
|
|
Err(err) => Err(err),
|
|
}
|
|
}
|
|
|
|
pub async fn bearer_auth() -> String {
|
|
let token = match test_token().await {
|
|
Ok(access_token) => access_token,
|
|
Err(err) => {
|
|
assert!(false, "Error: {err:?}");
|
|
String::new()
|
|
}
|
|
};
|
|
|
|
format!("Bearer {token}")
|
|
}
|
|
|
|
mod request {
|
|
// use common_multipart_rfc7578::client::multipart::{
|
|
// Body as MultipartBody, Form as MultipartForm,
|
|
// };
|
|
use tower::ServiceExt;
|
|
|
|
pub async fn create_contact(
|
|
app: &axum::Router,
|
|
) -> Result<axum::response::Response, std::convert::Infallible> {
|
|
let payload = serde_json::json!({
|
|
"phone_number": super::TEST_CONTACT_PHONE_NUMBER,
|
|
"user_id": super::TEST_USER_ID,
|
|
});
|
|
|
|
let req = axum::http::Request::builder()
|
|
.method(axum::http::Method::POST)
|
|
.uri(textsender_api::caller::endpoints::ADD_CONTACT)
|
|
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
|
.header(
|
|
axum::http::header::AUTHORIZATION,
|
|
super::bearer_auth().await,
|
|
)
|
|
.body(axum::body::Body::from(payload.to_string()))
|
|
.unwrap();
|
|
app.clone().oneshot(req).await
|
|
}
|
|
|
|
pub async fn get_contact(
|
|
app: &axum::Router,
|
|
id: &uuid::Uuid,
|
|
) -> Result<axum::response::Response, std::convert::Infallible> {
|
|
let uri = format!(
|
|
"{}?id={}",
|
|
textsender_api::caller::endpoints::GET_CONTACT,
|
|
id
|
|
);
|
|
|
|
let req = axum::http::Request::builder()
|
|
.method(axum::http::Method::GET)
|
|
.uri(uri)
|
|
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
|
.header(
|
|
axum::http::header::AUTHORIZATION,
|
|
super::bearer_auth().await,
|
|
)
|
|
.body(axum::body::Body::empty())
|
|
.unwrap();
|
|
|
|
app.clone().oneshot(req).await
|
|
}
|
|
|
|
pub async fn update_contact_names(
|
|
app: &axum::Router,
|
|
id: &uuid::Uuid,
|
|
firstname: Option<&str>,
|
|
lastname: Option<&str>,
|
|
nickname: Option<&str>
|
|
) -> Result<axum::response::Response, std::convert::Infallible> {
|
|
let payload = serde_json::json!({
|
|
"firstname": firstname,
|
|
"lastname": lastname,
|
|
"nickname": nickname,
|
|
"phone_number": super::TEST_CONTACT_PHONE_NUMBER,
|
|
"id": id
|
|
});
|
|
|
|
let req = axum::http::Request::builder()
|
|
.method(axum::http::Method::PATCH)
|
|
.uri(textsender_api::caller::endpoints::UPDATE_CONTACT_NAME)
|
|
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
|
.header(
|
|
axum::http::header::AUTHORIZATION,
|
|
super::bearer_auth().await,
|
|
)
|
|
.body(axum::body::Body::from(payload.to_string()))
|
|
.unwrap();
|
|
app.clone().oneshot(req).await
|
|
}
|
|
}
|
|
|
|
/// Test contact phone number
|
|
pub const TEST_CONTACT_PHONE_NUMBER: &str = "+10123456789";
|
|
|
|
/// Test contact updated firstname
|
|
pub const TEST_CONTACT_UPDATED_FIRSTNAME: &str = "Johnny";
|
|
/// Test contact updated lastname
|
|
pub const TEST_CONTACT_UPDATED_LASTNAME: &str = "CASH";
|
|
/// Test contact updated nickname
|
|
pub const TEST_CONTACT_UPDATED_NICKNAME: &str = "The Man in Black";
|
|
|
|
#[tokio::test]
|
|
async fn test_create_contact() {
|
|
let tm_pool = db_mgr::get_pool().await.unwrap();
|
|
let db_name = db_mgr::generate_db_name().await;
|
|
|
|
match db_mgr::create_database(&tm_pool, &db_name).await {
|
|
Ok(_) => {
|
|
println!("Success");
|
|
}
|
|
Err(err) => {
|
|
assert!(false, "Error: {:?}", err);
|
|
}
|
|
}
|
|
|
|
let pool = db_mgr::connect_to_db(&db_name).await.unwrap();
|
|
db::migrations(&pool).await;
|
|
|
|
let app = init::app(pool).await;
|
|
|
|
// Send request
|
|
match request::create_contact(&app).await {
|
|
Ok(response) => {
|
|
let resp = util::get_resp_data::<
|
|
textsender_api::caller::contact::response::AddContactResponse,
|
|
>(response)
|
|
.await;
|
|
assert_eq!(false, resp.data.is_empty(), "Should not be empty");
|
|
}
|
|
Err(err) => {
|
|
assert!(false, "Error: {:?}", err);
|
|
}
|
|
};
|
|
|
|
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_get_contact() {
|
|
let tm_pool = db_mgr::get_pool().await.unwrap();
|
|
let db_name = db_mgr::generate_db_name().await;
|
|
|
|
match db_mgr::create_database(&tm_pool, &db_name).await {
|
|
Ok(_) => {
|
|
println!("Success");
|
|
}
|
|
Err(err) => {
|
|
assert!(false, "Error: {:?}", err);
|
|
}
|
|
}
|
|
|
|
let pool = db_mgr::connect_to_db(&db_name).await.unwrap();
|
|
db::migrations(&pool).await;
|
|
|
|
let app = init::app(pool).await;
|
|
|
|
// Send request
|
|
match request::create_contact(&app).await {
|
|
Ok(response) => {
|
|
let resp = util::get_resp_data::<
|
|
textsender_api::caller::contact::response::AddContactResponse,
|
|
>(response)
|
|
.await;
|
|
assert_eq!(false, resp.data.is_empty(), "Should not be empty");
|
|
let contact = &resp.data[0];
|
|
assert_eq!(true, contact.id.is_some(), "Missing Contact Id");
|
|
let id = contact.id.unwrap();
|
|
match request::get_contact(&app, &id).await {
|
|
Ok(response) => {
|
|
let resp = util::get_resp_data::<
|
|
textsender_api::caller::contact::response::GetContactResponse,
|
|
>(response)
|
|
.await;
|
|
assert_eq!(
|
|
false,
|
|
resp.data.is_empty(),
|
|
"At least Contact record should have been returned"
|
|
);
|
|
}
|
|
Err(err) => {
|
|
assert!(false, "Error: {err:?}");
|
|
}
|
|
}
|
|
}
|
|
Err(err) => {
|
|
assert!(false, "Error: {:?}", err);
|
|
}
|
|
};
|
|
|
|
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_update_contact_names() {
|
|
let tm_pool = db_mgr::get_pool().await.unwrap();
|
|
let db_name = db_mgr::generate_db_name().await;
|
|
|
|
match db_mgr::create_database(&tm_pool, &db_name).await {
|
|
Ok(_) => {
|
|
println!("Success");
|
|
}
|
|
Err(err) => {
|
|
assert!(false, "Error: {:?}", err);
|
|
}
|
|
}
|
|
|
|
let pool = db_mgr::connect_to_db(&db_name).await.unwrap();
|
|
db::migrations(&pool).await;
|
|
|
|
let app = init::app(pool).await;
|
|
|
|
let mut opt_contact: Option<textsender_models::contact::Contact> = None;
|
|
|
|
// Send request
|
|
match request::create_contact(&app).await {
|
|
Ok(response) => {
|
|
let resp = util::get_resp_data::<
|
|
textsender_api::caller::contact::response::AddContactResponse,
|
|
>(response)
|
|
.await;
|
|
assert_eq!(false, resp.data.is_empty(), "Should not be empty");
|
|
let contact = &resp.data[0];
|
|
assert_eq!(true, contact.id.is_some(), "Missing Contact Id");
|
|
let id = contact.id.unwrap();
|
|
match request::get_contact(&app, &id).await {
|
|
Ok(response) => {
|
|
let resp = util::get_resp_data::<
|
|
textsender_api::caller::contact::response::GetContactResponse,
|
|
>(response)
|
|
.await;
|
|
assert_eq!(
|
|
false,
|
|
resp.data.is_empty(),
|
|
"At least Contact record should have been returned"
|
|
);
|
|
opt_contact = Some(resp.data[0].clone())
|
|
}
|
|
Err(err) => {
|
|
assert!(false, "Error: {err:?}");
|
|
}
|
|
}
|
|
}
|
|
Err(err) => {
|
|
assert!(false, "Error: {:?}", err);
|
|
}
|
|
};
|
|
|
|
match opt_contact {
|
|
Some(contact) => {
|
|
let new_firstname = Some(TEST_CONTACT_UPDATED_FIRSTNAME);
|
|
let new_lastname = Some(TEST_CONTACT_UPDATED_LASTNAME);
|
|
let new_nickname = Some(TEST_CONTACT_UPDATED_NICKNAME);
|
|
|
|
let contact_id = contact.id.unwrap();
|
|
match request::update_contact_names(&app, &contact_id, new_firstname, new_lastname, new_nickname).await {
|
|
Ok(response) => {
|
|
let resp = util::get_resp_data::<
|
|
textsender_api::caller::contact::response::UpdateContactNamesResponse,
|
|
>(response)
|
|
.await;
|
|
assert_eq!(false, resp.data.is_empty(), "Error updating Contact names");
|
|
}
|
|
Err(err) => {
|
|
assert!(false, "Error: {err:?}");
|
|
}
|
|
}
|
|
}
|
|
None => {
|
|
assert!(false, "Contact not found");
|
|
}
|
|
}
|
|
|
|
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
|
|
}
|