helper.rs 12 KB

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