helper.rs 12 KB

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