helper.rs 12 KB

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