helper.rs 12 KB

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