helper.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. use backend::{
  2. application::{get_connection_pool, init_app_context, Application},
  3. config::{get_configuration, DatabaseSettings},
  4. context::AppContext,
  5. };
  6. use backend_service::{
  7. configuration::{get_client_server_configuration, ClientServerConfiguration},
  8. errors::ServerError,
  9. user_request::*,
  10. workspace_request::*,
  11. };
  12. use flowy_collaboration::entities::doc::{CreateDocParams, DocIdentifier, DocumentInfo};
  13. use flowy_core_data_model::entities::prelude::*;
  14. use flowy_document::services::server::{create_doc_request, read_doc_request};
  15. use flowy_user_data_model::entities::*;
  16. use sqlx::{Connection, Executor, PgConnection, PgPool};
  17. use uuid::Uuid;
  18. pub struct TestUserServer {
  19. pub pg_pool: PgPool,
  20. pub user_token: Option<String>,
  21. pub user_id: Option<String>,
  22. pub client_server_config: ClientServerConfiguration,
  23. }
  24. impl TestUserServer {
  25. pub async fn new() -> Self {
  26. let mut server: TestUserServer = spawn_server().await.into();
  27. let response = server.register_user().await;
  28. server.user_token = Some(response.token);
  29. server.user_id = Some(response.user_id);
  30. server
  31. }
  32. pub async fn sign_in(&self, params: SignInParams) -> Result<SignInResponse, ServerError> {
  33. let url = format!("{}/api/auth", self.http_addr());
  34. let resp = user_sign_in_request(params, &url).await?;
  35. Ok(resp)
  36. }
  37. pub async fn sign_out(&self) {
  38. let url = format!("{}/api/auth", self.http_addr());
  39. let _ = user_sign_out_request(self.user_token(), &url).await.unwrap();
  40. }
  41. pub fn user_token(&self) -> &str { self.user_token.as_ref().expect("must call register_user first ") }
  42. pub fn user_id(&self) -> &str { self.user_id.as_ref().expect("must call register_user first ") }
  43. pub async fn get_user_profile(&self) -> UserProfile {
  44. let url = format!("{}/api/user", self.http_addr());
  45. let user_profile = get_user_profile_request(self.user_token(), &url).await.unwrap();
  46. user_profile
  47. }
  48. pub async fn update_user_profile(&self, params: UpdateUserParams) -> Result<(), ServerError> {
  49. let url = format!("{}/api/user", self.http_addr());
  50. let _ = update_user_profile_request(self.user_token(), params, &url).await?;
  51. Ok(())
  52. }
  53. pub async fn create_workspace(&self, params: CreateWorkspaceParams) -> Workspace {
  54. let url = format!("{}/api/workspace", self.http_addr());
  55. let workspace = create_workspace_request(self.user_token(), params, &url).await.unwrap();
  56. workspace
  57. }
  58. pub async fn read_workspaces(&self, params: WorkspaceIdentifier) -> RepeatedWorkspace {
  59. let url = format!("{}/api/workspace", self.http_addr());
  60. let workspaces = read_workspaces_request(self.user_token(), params, &url).await.unwrap();
  61. workspaces
  62. }
  63. pub async fn update_workspace(&self, params: UpdateWorkspaceParams) {
  64. let url = format!("{}/api/workspace", self.http_addr());
  65. update_workspace_request(self.user_token(), params, &url).await.unwrap();
  66. }
  67. pub async fn delete_workspace(&self, params: WorkspaceIdentifier) {
  68. let url = format!("{}/api/workspace", self.http_addr());
  69. delete_workspace_request(self.user_token(), params, &url).await.unwrap();
  70. }
  71. pub async fn create_app(&self, params: CreateAppParams) -> App {
  72. let url = format!("{}/api/app", self.http_addr());
  73. let app = create_app_request(self.user_token(), params, &url).await.unwrap();
  74. app
  75. }
  76. pub async fn read_app(&self, params: AppIdentifier) -> Option<App> {
  77. let url = format!("{}/api/app", self.http_addr());
  78. let app = read_app_request(self.user_token(), params, &url).await.unwrap();
  79. app
  80. }
  81. pub async fn update_app(&self, params: UpdateAppParams) {
  82. let url = format!("{}/api/app", self.http_addr());
  83. update_app_request(self.user_token(), params, &url).await.unwrap();
  84. }
  85. pub async fn delete_app(&self, params: AppIdentifier) {
  86. let url = format!("{}/api/app", self.http_addr());
  87. delete_app_request(self.user_token(), params, &url).await.unwrap();
  88. }
  89. pub async fn create_view(&self, params: CreateViewParams) -> View {
  90. let url = format!("{}/api/view", self.http_addr());
  91. let view = create_view_request(self.user_token(), params, &url).await.unwrap();
  92. view
  93. }
  94. pub async fn read_view(&self, params: ViewIdentifier) -> Option<View> {
  95. let url = format!("{}/api/view", self.http_addr());
  96. let view = read_view_request(self.user_token(), params, &url).await.unwrap();
  97. view
  98. }
  99. pub async fn update_view(&self, params: UpdateViewParams) {
  100. let url = format!("{}/api/view", self.http_addr());
  101. update_view_request(self.user_token(), params, &url).await.unwrap();
  102. }
  103. pub async fn delete_view(&self, params: ViewIdentifiers) {
  104. let url = format!("{}/api/view", self.http_addr());
  105. delete_view_request(self.user_token(), params, &url).await.unwrap();
  106. }
  107. pub async fn create_view_trash(&self, view_id: &str) {
  108. let identifier = TrashIdentifier {
  109. id: view_id.to_string(),
  110. ty: TrashType::View,
  111. };
  112. let url = format!("{}/api/trash", self.http_addr());
  113. create_trash_request(self.user_token(), vec![identifier].into(), &url)
  114. .await
  115. .unwrap();
  116. }
  117. pub async fn delete_view_trash(&self, trash_identifiers: TrashIdentifiers) {
  118. let url = format!("{}/api/trash", self.http_addr());
  119. delete_trash_request(self.user_token(), trash_identifiers, &url)
  120. .await
  121. .unwrap();
  122. }
  123. pub async fn read_trash(&self) -> RepeatedTrash {
  124. let url = format!("{}/api/trash", self.http_addr());
  125. read_trash_request(self.user_token(), &url).await.unwrap()
  126. }
  127. pub async fn read_doc(&self, params: DocIdentifier) -> Option<DocumentInfo> {
  128. let url = format!("{}/api/doc", self.http_addr());
  129. let doc = read_doc_request(self.user_token(), params, &url).await.unwrap();
  130. doc
  131. }
  132. pub async fn create_doc(&self, params: CreateDocParams) {
  133. let url = format!("{}/api/doc", self.http_addr());
  134. let _ = create_doc_request(self.user_token(), params, &url).await.unwrap();
  135. }
  136. pub async fn register_user(&self) -> SignUpResponse {
  137. let params = SignUpParams {
  138. email: "[email protected]".to_string(),
  139. name: "annie".to_string(),
  140. password: "HelloAppFlowy123!".to_string(),
  141. };
  142. self.register(params).await
  143. }
  144. pub async fn register(&self, params: SignUpParams) -> SignUpResponse {
  145. let url = format!("{}/api/register", self.http_addr());
  146. let response = user_sign_up_request(params, &url).await.unwrap();
  147. response
  148. }
  149. pub fn http_addr(&self) -> String { self.client_server_config.base_url() }
  150. pub fn ws_addr(&self) -> String {
  151. format!(
  152. "{}/{}",
  153. self.client_server_config.ws_addr(),
  154. self.user_token.as_ref().unwrap()
  155. )
  156. }
  157. }
  158. impl std::convert::From<TestServer> for TestUserServer {
  159. fn from(server: TestServer) -> Self {
  160. TestUserServer {
  161. pg_pool: server.pg_pool,
  162. user_token: None,
  163. user_id: None,
  164. client_server_config: server.client_server_config,
  165. }
  166. }
  167. }
  168. pub async fn spawn_user_server() -> TestUserServer {
  169. let server: TestUserServer = spawn_server().await.into();
  170. server
  171. }
  172. pub struct TestServer {
  173. pub pg_pool: PgPool,
  174. pub app_ctx: AppContext,
  175. pub client_server_config: ClientServerConfiguration,
  176. }
  177. pub async fn spawn_server() -> TestServer {
  178. let database_name = Uuid::new_v4().to_string();
  179. let configuration = {
  180. let mut c = get_configuration().expect("Failed to read configuration.");
  181. c.database.database_name = database_name.clone();
  182. // Use a random OS port
  183. c.application.port = 0;
  184. c
  185. };
  186. let _ = configure_database(&configuration.database).await;
  187. let app_ctx = init_app_context(&configuration).await;
  188. let application = Application::build(configuration.clone(), app_ctx.clone())
  189. .await
  190. .expect("Failed to build application.");
  191. let application_port = application.port();
  192. let _ = tokio::spawn(async {
  193. let _ = application.run_until_stopped();
  194. // drop_test_database(database_name).await;
  195. });
  196. let mut client_server_config = get_client_server_configuration().expect("Failed to read configuration.");
  197. client_server_config.reset_host_with_port("localhost", application_port);
  198. TestServer {
  199. pg_pool: get_connection_pool(&configuration.database)
  200. .await
  201. .expect("Failed to connect to the database"),
  202. app_ctx,
  203. client_server_config,
  204. }
  205. }
  206. async fn configure_database(config: &DatabaseSettings) -> PgPool {
  207. // Create database
  208. let mut connection = PgConnection::connect_with(&config.without_db())
  209. .await
  210. .expect("Failed to connect to Postgres");
  211. connection
  212. .execute(&*format!(r#"CREATE DATABASE "{}";"#, config.database_name))
  213. .await
  214. .expect("Failed to create database.");
  215. // Migrate database
  216. let connection_pool = PgPool::connect_with(config.with_db())
  217. .await
  218. .expect("Failed to connect to Postgres.");
  219. sqlx::migrate!("./migrations")
  220. .run(&connection_pool)
  221. .await
  222. .expect("Failed to migrate the database");
  223. connection_pool
  224. }
  225. #[allow(dead_code)]
  226. async fn drop_test_database(database_name: String) {
  227. // https://stackoverflow.com/questions/36502401/postgres-drop-database-error-pq-cannot-drop-the-currently-open-database?rq=1
  228. let configuration = {
  229. let mut c = get_configuration().expect("Failed to read configuration.");
  230. c.database.database_name = "flowy".to_owned();
  231. c.application.port = 0;
  232. c
  233. };
  234. let mut connection = PgConnection::connect_with(&configuration.database.without_db())
  235. .await
  236. .expect("Failed to connect to Postgres");
  237. connection
  238. .execute(&*format!(r#"Drop DATABASE "{}";"#, database_name))
  239. .await
  240. .expect("Failed to drop database.");
  241. }
  242. pub async fn create_test_workspace(server: &TestUserServer) -> Workspace {
  243. let params = CreateWorkspaceParams {
  244. name: "My first workspace".to_string(),
  245. desc: "This is my first workspace".to_string(),
  246. };
  247. let workspace = server.create_workspace(params).await;
  248. workspace
  249. }
  250. pub async fn create_test_app(server: &TestUserServer, workspace_id: &str) -> App {
  251. let params = CreateAppParams {
  252. workspace_id: workspace_id.to_owned(),
  253. name: "My first app".to_string(),
  254. desc: "This is my first app".to_string(),
  255. color_style: ColorStyle::default(),
  256. };
  257. let app = server.create_app(params).await;
  258. app
  259. }
  260. pub async fn create_test_view(application: &TestUserServer, app_id: &str) -> View {
  261. let name = "My first view".to_string();
  262. let desc = "This is my first view".to_string();
  263. let thumbnail = "http://1.png".to_string();
  264. let params = CreateViewParams::new(app_id.to_owned(), name, desc, ViewType::Doc, thumbnail);
  265. let app = application.create_view(params).await;
  266. app
  267. }
  268. pub struct WorkspaceTest {
  269. pub server: TestUserServer,
  270. pub workspace: Workspace,
  271. }
  272. impl WorkspaceTest {
  273. pub async fn new() -> Self {
  274. let server = TestUserServer::new().await;
  275. let workspace = create_test_workspace(&server).await;
  276. Self { server, workspace }
  277. }
  278. pub async fn create_app(&self) -> App { create_test_app(&self.server, &self.workspace.id).await }
  279. }
  280. pub struct AppTest {
  281. pub server: TestUserServer,
  282. pub workspace: Workspace,
  283. pub app: App,
  284. }
  285. impl AppTest {
  286. pub async fn new() -> Self {
  287. let server = TestUserServer::new().await;
  288. let workspace = create_test_workspace(&server).await;
  289. let app = create_test_app(&server, &workspace.id).await;
  290. Self { server, workspace, app }
  291. }
  292. }
  293. pub struct ViewTest {
  294. pub server: TestUserServer,
  295. pub workspace: Workspace,
  296. pub app: App,
  297. pub view: View,
  298. }
  299. impl ViewTest {
  300. pub async fn new() -> Self {
  301. let server = TestUserServer::new().await;
  302. let workspace = create_test_workspace(&server).await;
  303. let app = create_test_app(&server, &workspace.id).await;
  304. let view = create_test_view(&server, &app.id).await;
  305. Self {
  306. server,
  307. workspace,
  308. app,
  309. view,
  310. }
  311. }
  312. }