helper.rs 12 KB

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