helper.rs 12 KB

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