dialtone_test_util 0.1.0

Dialtone Testing Utilities
Documentation
use dialtone_axum::start_server::app_router;
use dialtone_reqwest::{api_v1::users::authenticate::authenticate, site_connection::SiteConnection};
use sqlx::{Pool, Postgres};
use std::net::{SocketAddr, TcpListener};

use crate::test_constants::TEST_HOSTNAME;

#[allow(unused_must_use)]
pub async fn start_test_server(pool: Pool<Postgres>) -> SocketAddr {
    std::env::set_var("RUST_LOG", "debug");
    std::env::set_var("JWT_SECRET", "token_secret");
    tracing_subscriber::fmt::try_init();

    let listener = TcpListener::bind("0.0.0.0:0".parse::<SocketAddr>().unwrap()).unwrap();
    let addr = listener.local_addr().unwrap();

    tokio::spawn(async move {
        axum::Server::from_tcp(listener)
            .unwrap()
            .serve(app_router(pool).into_make_service())
            .await
            .unwrap();
    });

    addr
}

/// This method starts a test server and authenticates with the creds passed in.
/// The host name for the test server, and subsequently the authenticated user,
/// is [TEST_HOSTNAME].
pub async fn start_test_srv_and_auth(
    pool: Pool<Postgres>,
    user_name: &str,
    password: &str,
) -> SiteConnection {
    let addr = start_test_server(pool).await;
    let sc = SiteConnection::new_site(&addr.to_string(), TEST_HOSTNAME);
    println!("sites connection = {:?}", sc);

    let action = authenticate(&sc, user_name, password).await;
    action.unwrap()
}