helper.rs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. use backend::{
  2. application::{get_connection_pool, Application},
  3. config::{get_configuration, DatabaseSettings},
  4. };
  5. use flowy_net::request::HttpRequestBuilder;
  6. use flowy_user::prelude::*;
  7. use sqlx::{Connection, Executor, PgConnection, PgPool};
  8. use uuid::Uuid;
  9. pub struct TestApp {
  10. pub address: String,
  11. pub port: u16,
  12. pub pg_pool: PgPool,
  13. }
  14. impl TestApp {
  15. pub async fn register_user(&self, params: SignUpParams) -> SignUpResponse {
  16. let url = format!("{}/api/register", self.address);
  17. let resp = user_sign_up(params, &url).await.unwrap();
  18. resp
  19. }
  20. pub async fn sign_in(&self, params: SignInParams) -> SignInResponse {
  21. let url = format!("{}/api/auth", self.address);
  22. let resp = user_sign_in(params, &url).await.unwrap();
  23. resp
  24. }
  25. }
  26. pub async fn spawn_app() -> TestApp {
  27. let configuration = {
  28. let mut c = get_configuration().expect("Failed to read configuration.");
  29. c.database.database_name = Uuid::new_v4().to_string();
  30. // Use a random OS port
  31. c.application.port = 0;
  32. c
  33. };
  34. let _ = configure_database(&configuration.database).await;
  35. let application = Application::build(configuration.clone())
  36. .await
  37. .expect("Failed to build application.");
  38. let application_port = application.port();
  39. let _ = tokio::spawn(application.run_until_stopped());
  40. TestApp {
  41. address: format!("http://localhost:{}", application_port),
  42. port: application_port,
  43. pg_pool: get_connection_pool(&configuration.database)
  44. .await
  45. .expect("Failed to connect to the database"),
  46. }
  47. }
  48. async fn configure_database(config: &DatabaseSettings) -> PgPool {
  49. // Create database
  50. let mut connection = PgConnection::connect_with(&config.without_db())
  51. .await
  52. .expect("Failed to connect to Postgres");
  53. connection
  54. .execute(&*format!(r#"CREATE DATABASE "{}";"#, config.database_name))
  55. .await
  56. .expect("Failed to create database.");
  57. // Migrate database
  58. let connection_pool = PgPool::connect_with(config.with_db())
  59. .await
  60. .expect("Failed to connect to Postgres.");
  61. sqlx::migrate!("./migrations")
  62. .run(&connection_pool)
  63. .await
  64. .expect("Failed to migrate the database");
  65. connection_pool
  66. }