helper.rs 12 KB

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