helper.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. use backend::{
  2. application::{get_connection_pool, 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::entities::doc::{CreateDocParams, DocIdentifier, DocumentInfo};
  13. use flowy_core_data_model::entities::prelude::*;
  14. use flowy_document::services::server::{create_doc_request, read_doc_request};
  15. use flowy_user_data_model::entities::*;
  16. use sqlx::{Connection, Executor, PgConnection, PgPool};
  17. use uuid::Uuid;
  18. pub struct TestUserServer {
  19. pub inner: TestServer,
  20. pub user_token: Option<String>,
  21. pub user_id: Option<String>,
  22. }
  23. impl TestUserServer {
  24. pub async fn new() -> Self {
  25. let mut server: TestUserServer = spawn_server().await.into();
  26. let response = server.register_user().await;
  27. server.user_token = Some(response.token);
  28. server.user_id = Some(response.user_id);
  29. server
  30. }
  31. pub async fn sign_in(&self, params: SignInParams) -> Result<SignInResponse, ServerError> {
  32. let url = format!("{}/api/auth", self.http_addr());
  33. let resp = user_sign_in_request(params, &url).await?;
  34. Ok(resp)
  35. }
  36. pub async fn sign_out(&self) {
  37. let url = format!("{}/api/auth", self.http_addr());
  38. let _ = user_sign_out_request(self.user_token(), &url).await.unwrap();
  39. }
  40. pub fn user_token(&self) -> &str { self.user_token.as_ref().expect("must call register_user first ") }
  41. pub fn user_id(&self) -> &str { self.user_id.as_ref().expect("must call register_user first ") }
  42. pub async fn get_user_profile(&self) -> UserProfile {
  43. let url = format!("{}/api/user", self.http_addr());
  44. let user_profile = get_user_profile_request(self.user_token(), &url).await.unwrap();
  45. user_profile
  46. }
  47. pub async fn update_user_profile(&self, params: UpdateUserParams) -> Result<(), ServerError> {
  48. let url = format!("{}/api/user", self.http_addr());
  49. let _ = update_user_profile_request(self.user_token(), params, &url).await?;
  50. Ok(())
  51. }
  52. pub async fn create_workspace(&self, params: CreateWorkspaceParams) -> Workspace {
  53. let url = format!("{}/api/workspace", self.http_addr());
  54. let workspace = create_workspace_request(self.user_token(), params, &url).await.unwrap();
  55. workspace
  56. }
  57. pub async fn read_workspaces(&self, params: WorkspaceIdentifier) -> RepeatedWorkspace {
  58. let url = format!("{}/api/workspace", self.http_addr());
  59. let workspaces = read_workspaces_request(self.user_token(), params, &url).await.unwrap();
  60. workspaces
  61. }
  62. pub async fn update_workspace(&self, params: UpdateWorkspaceParams) {
  63. let url = format!("{}/api/workspace", self.http_addr());
  64. update_workspace_request(self.user_token(), params, &url).await.unwrap();
  65. }
  66. pub async fn delete_workspace(&self, params: WorkspaceIdentifier) {
  67. let url = format!("{}/api/workspace", self.http_addr());
  68. delete_workspace_request(self.user_token(), params, &url).await.unwrap();
  69. }
  70. pub async fn create_app(&self, params: CreateAppParams) -> App {
  71. let url = format!("{}/api/app", self.http_addr());
  72. let app = create_app_request(self.user_token(), params, &url).await.unwrap();
  73. app
  74. }
  75. pub async fn read_app(&self, params: AppIdentifier) -> Option<App> {
  76. let url = format!("{}/api/app", self.http_addr());
  77. let app = read_app_request(self.user_token(), params, &url).await.unwrap();
  78. app
  79. }
  80. pub async fn update_app(&self, params: UpdateAppParams) {
  81. let url = format!("{}/api/app", self.http_addr());
  82. update_app_request(self.user_token(), params, &url).await.unwrap();
  83. }
  84. pub async fn delete_app(&self, params: AppIdentifier) {
  85. let url = format!("{}/api/app", self.http_addr());
  86. delete_app_request(self.user_token(), params, &url).await.unwrap();
  87. }
  88. pub async fn create_view(&self, params: CreateViewParams) -> View {
  89. let url = format!("{}/api/view", self.http_addr());
  90. let view = create_view_request(self.user_token(), params, &url).await.unwrap();
  91. view
  92. }
  93. pub async fn read_view(&self, params: ViewIdentifier) -> Option<View> {
  94. let url = format!("{}/api/view", self.http_addr());
  95. let view = read_view_request(self.user_token(), params, &url).await.unwrap();
  96. view
  97. }
  98. pub async fn update_view(&self, params: UpdateViewParams) {
  99. let url = format!("{}/api/view", self.http_addr());
  100. update_view_request(self.user_token(), params, &url).await.unwrap();
  101. }
  102. pub async fn delete_view(&self, params: ViewIdentifiers) {
  103. let url = format!("{}/api/view", self.http_addr());
  104. delete_view_request(self.user_token(), params, &url).await.unwrap();
  105. }
  106. pub async fn create_view_trash(&self, view_id: &str) {
  107. let identifier = TrashIdentifier {
  108. id: view_id.to_string(),
  109. ty: TrashType::View,
  110. };
  111. let url = format!("{}/api/trash", self.http_addr());
  112. create_trash_request(self.user_token(), vec![identifier].into(), &url)
  113. .await
  114. .unwrap();
  115. }
  116. pub async fn delete_view_trash(&self, trash_identifiers: TrashIdentifiers) {
  117. let url = format!("{}/api/trash", self.http_addr());
  118. delete_trash_request(self.user_token(), trash_identifiers, &url)
  119. .await
  120. .unwrap();
  121. }
  122. pub async fn read_trash(&self) -> RepeatedTrash {
  123. let url = format!("{}/api/trash", self.http_addr());
  124. read_trash_request(self.user_token(), &url).await.unwrap()
  125. }
  126. pub async fn read_doc(&self, params: DocIdentifier) -> Option<DocumentInfo> {
  127. let url = format!("{}/api/doc", self.http_addr());
  128. let doc = read_doc_request(self.user_token(), params, &url).await.unwrap();
  129. doc
  130. }
  131. pub async fn create_doc(&self, params: CreateDocParams) {
  132. let url = format!("{}/api/doc", self.http_addr());
  133. let _ = create_doc_request(self.user_token(), params, &url).await.unwrap();
  134. }
  135. pub async fn register_user(&self) -> SignUpResponse {
  136. let params = SignUpParams {
  137. email: "[email protected]".to_string(),
  138. name: "annie".to_string(),
  139. password: "HelloAppFlowy123!".to_string(),
  140. };
  141. self.register(params).await
  142. }
  143. pub async fn register(&self, params: SignUpParams) -> SignUpResponse {
  144. let url = format!("{}/api/register", self.http_addr());
  145. let response = user_sign_up_request(params, &url).await.unwrap();
  146. response
  147. }
  148. pub fn http_addr(&self) -> String { self.inner.client_server_config.base_url() }
  149. pub fn ws_addr(&self) -> String {
  150. format!(
  151. "{}/{}",
  152. self.inner.client_server_config.ws_addr(),
  153. self.user_token.as_ref().unwrap()
  154. )
  155. }
  156. }
  157. impl std::convert::From<TestServer> for TestUserServer {
  158. fn from(server: TestServer) -> Self {
  159. TestUserServer {
  160. inner: server,
  161. user_token: None,
  162. user_id: None,
  163. }
  164. }
  165. }
  166. pub async fn spawn_user_server() -> TestUserServer {
  167. let server: TestUserServer = spawn_server().await.into();
  168. server
  169. }
  170. #[derive(Clone)]
  171. pub struct TestServer {
  172. pub pg_pool: PgPool,
  173. pub app_ctx: AppContext,
  174. pub client_server_config: ClientServerConfiguration,
  175. }
  176. pub async fn spawn_server() -> TestServer {
  177. let database_name = Uuid::new_v4().to_string();
  178. let configuration = {
  179. let mut c = get_configuration().expect("Failed to read configuration.");
  180. c.database.database_name = database_name.clone();
  181. // Use a random OS port
  182. c.application.port = 0;
  183. c
  184. };
  185. let _ = configure_database(&configuration.database).await;
  186. let app_ctx = init_app_context(&configuration).await;
  187. let application = Application::build(configuration.clone(), app_ctx.clone())
  188. .await
  189. .expect("Failed to build application.");
  190. let application_port = application.port();
  191. let _ = tokio::spawn(async {
  192. let _ = application.run_until_stopped();
  193. // drop_test_database(database_name).await;
  194. });
  195. let mut client_server_config = get_client_server_configuration().expect("Failed to read configuration.");
  196. client_server_config.reset_host_with_port("localhost", application_port);
  197. TestServer {
  198. pg_pool: get_connection_pool(&configuration.database)
  199. .await
  200. .expect("Failed to connect to the database"),
  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(app_id.to_owned(), name, desc, ViewType::Doc, thumbnail);
  264. let app = application.create_view(params).await;
  265. app
  266. }
  267. pub struct WorkspaceTest {
  268. pub server: TestUserServer,
  269. pub workspace: Workspace,
  270. }
  271. impl WorkspaceTest {
  272. pub async fn new() -> Self {
  273. let server = TestUserServer::new().await;
  274. let workspace = create_test_workspace(&server).await;
  275. Self { server, workspace }
  276. }
  277. pub async fn create_app(&self) -> App { create_test_app(&self.server, &self.workspace.id).await }
  278. }
  279. pub struct AppTest {
  280. pub server: TestUserServer,
  281. pub workspace: Workspace,
  282. pub app: App,
  283. }
  284. impl AppTest {
  285. pub async fn new() -> Self {
  286. let server = TestUserServer::new().await;
  287. let workspace = create_test_workspace(&server).await;
  288. let app = create_test_app(&server, &workspace.id).await;
  289. Self { server, workspace, app }
  290. }
  291. }
  292. pub struct ViewTest {
  293. pub server: TestUserServer,
  294. pub workspace: Workspace,
  295. pub app: App,
  296. pub view: View,
  297. }
  298. impl ViewTest {
  299. pub async fn new() -> Self {
  300. let server = TestUserServer::new().await;
  301. let workspace = create_test_workspace(&server).await;
  302. let app = create_test_app(&server, &workspace.id).await;
  303. let view = create_test_view(&server, &app.id).await;
  304. Self {
  305. server,
  306. workspace,
  307. app,
  308. view,
  309. }
  310. }
  311. }