helper.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. use backend::{
  2. application::{get_connection_pool, Application},
  3. config::{get_configuration, DatabaseSettings},
  4. context::AppContext,
  5. };
  6. use backend::application::init_app_context;
  7. use flowy_document::{
  8. entities::doc::{Doc, DocIdentifier},
  9. prelude::*,
  10. };
  11. use flowy_user::{errors::UserError, prelude::*};
  12. use flowy_workspace::prelude::{server::*, *};
  13. use sqlx::{Connection, Executor, PgConnection, PgPool};
  14. use uuid::Uuid;
  15. pub struct TestUserServer {
  16. pub host: String,
  17. pub port: u16,
  18. pub pg_pool: PgPool,
  19. pub user_token: Option<String>,
  20. pub user_id: Option<String>,
  21. }
  22. impl TestUserServer {
  23. pub async fn new() -> Self {
  24. let mut server: TestUserServer = spawn_server().await.into();
  25. let response = server.register_user().await;
  26. server.user_token = Some(response.token);
  27. server.user_id = Some(response.user_id);
  28. server
  29. }
  30. pub async fn sign_in(&self, params: SignInParams) -> Result<SignInResponse, UserError> {
  31. let url = format!("{}/api/auth", self.http_addr());
  32. user_sign_in_request(params, &url).await
  33. }
  34. pub async fn sign_out(&self) {
  35. let url = format!("{}/api/auth", self.http_addr());
  36. let _ = user_sign_out_request(self.user_token(), &url).await.unwrap();
  37. }
  38. pub fn user_token(&self) -> &str { self.user_token.as_ref().expect("must call register_user first ") }
  39. pub fn user_id(&self) -> &str { self.user_id.as_ref().expect("must call register_user first ") }
  40. pub async fn get_user_profile(&self) -> UserProfile {
  41. let url = format!("{}/api/user", self.http_addr());
  42. let user_profile = get_user_profile_request(self.user_token(), &url).await.unwrap();
  43. user_profile
  44. }
  45. pub async fn update_user_profile(&self, params: UpdateUserParams) -> Result<(), UserError> {
  46. let url = format!("{}/api/user", self.http_addr());
  47. update_user_profile_request(self.user_token(), params, &url).await
  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: QueryWorkspaceParams) -> 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: DeleteWorkspaceParams) {
  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: DeleteAppParams) {
  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: DeleteViewParams) {
  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_id: &str) {
  114. let url = format!("{}/api/trash", self.http_addr());
  115. let identifier = TrashIdentifier {
  116. id: trash_id.to_string(),
  117. ty: TrashType::View,
  118. };
  119. delete_trash_request(self.user_token(), vec![identifier].into(), &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/doc", 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 { format!("http://{}", self.host) }
  146. pub fn ws_addr(&self) -> String { format!("ws://{}/ws/{}", self.host, self.user_token.as_ref().unwrap()) }
  147. }
  148. impl std::convert::From<TestServer> for TestUserServer {
  149. fn from(server: TestServer) -> Self {
  150. TestUserServer {
  151. host: server.host,
  152. port: server.port,
  153. pg_pool: server.pg_pool,
  154. user_token: None,
  155. user_id: None,
  156. }
  157. }
  158. }
  159. pub async fn spawn_user_server() -> TestUserServer {
  160. let server: TestUserServer = spawn_server().await.into();
  161. server
  162. }
  163. pub struct TestServer {
  164. pub host: String,
  165. pub port: u16,
  166. pub pg_pool: PgPool,
  167. pub app_ctx: AppContext,
  168. }
  169. pub async fn spawn_server() -> TestServer {
  170. let database_name = format!("{}", Uuid::new_v4().to_string());
  171. let configuration = {
  172. let mut c = get_configuration().expect("Failed to read configuration.");
  173. c.database.database_name = database_name.clone();
  174. // Use a random OS port
  175. c.application.port = 0;
  176. c
  177. };
  178. let _ = configure_database(&configuration.database).await;
  179. let app_ctx = init_app_context(&configuration).await;
  180. let application = Application::build(configuration.clone(), app_ctx.clone())
  181. .await
  182. .expect("Failed to build application.");
  183. let application_port = application.port();
  184. let _ = tokio::spawn(async {
  185. let _ = application.run_until_stopped();
  186. // drop_test_database(database_name).await;
  187. });
  188. TestServer {
  189. host: format!("localhost:{}", application_port),
  190. port: application_port,
  191. pg_pool: get_connection_pool(&configuration.database)
  192. .await
  193. .expect("Failed to connect to the database"),
  194. app_ctx,
  195. }
  196. }
  197. async fn configure_database(config: &DatabaseSettings) -> PgPool {
  198. // Create database
  199. let mut connection = PgConnection::connect_with(&config.without_db())
  200. .await
  201. .expect("Failed to connect to Postgres");
  202. connection
  203. .execute(&*format!(r#"CREATE DATABASE "{}";"#, config.database_name))
  204. .await
  205. .expect("Failed to create database.");
  206. // Migrate database
  207. let connection_pool = PgPool::connect_with(config.with_db())
  208. .await
  209. .expect("Failed to connect to Postgres.");
  210. sqlx::migrate!("./migrations")
  211. .run(&connection_pool)
  212. .await
  213. .expect("Failed to migrate the database");
  214. connection_pool
  215. }
  216. #[allow(dead_code)]
  217. async fn drop_test_database(database_name: String) {
  218. // https://stackoverflow.com/questions/36502401/postgres-drop-database-error-pq-cannot-drop-the-currently-open-database?rq=1
  219. let configuration = {
  220. let mut c = get_configuration().expect("Failed to read configuration.");
  221. c.database.database_name = "flowy".to_owned();
  222. c.application.port = 0;
  223. c
  224. };
  225. let mut connection = PgConnection::connect_with(&configuration.database.without_db())
  226. .await
  227. .expect("Failed to connect to Postgres");
  228. connection
  229. .execute(&*format!(r#"Drop DATABASE "{}";"#, database_name))
  230. .await
  231. .expect("Failed to drop database.");
  232. }
  233. pub async fn create_test_workspace(server: &TestUserServer) -> Workspace {
  234. let params = CreateWorkspaceParams {
  235. name: "My first workspace".to_string(),
  236. desc: "This is my first workspace".to_string(),
  237. };
  238. let workspace = server.create_workspace(params).await;
  239. workspace
  240. }
  241. pub async fn create_test_app(server: &TestUserServer, workspace_id: &str) -> App {
  242. let params = CreateAppParams {
  243. workspace_id: workspace_id.to_owned(),
  244. name: "My first app".to_string(),
  245. desc: "This is my first app".to_string(),
  246. color_style: ColorStyle::default(),
  247. };
  248. let app = server.create_app(params).await;
  249. app
  250. }
  251. pub async fn create_test_view(application: &TestUserServer, app_id: &str) -> View {
  252. let name = "My first view".to_string();
  253. let desc = "This is my first view".to_string();
  254. let thumbnail = "http://1.png".to_string();
  255. let params = CreateViewParams::new(app_id.to_owned(), name, desc, ViewType::Doc, thumbnail);
  256. let app = application.create_view(params).await;
  257. app
  258. }
  259. pub struct WorkspaceTest {
  260. pub server: TestUserServer,
  261. pub workspace: Workspace,
  262. }
  263. impl WorkspaceTest {
  264. pub async fn new() -> Self {
  265. let server = TestUserServer::new().await;
  266. let workspace = create_test_workspace(&server).await;
  267. Self { server, workspace }
  268. }
  269. pub async fn create_app(&self) -> App { create_test_app(&self.server, &self.workspace.id).await }
  270. }
  271. pub struct AppTest {
  272. pub server: TestUserServer,
  273. pub workspace: Workspace,
  274. pub app: App,
  275. }
  276. impl AppTest {
  277. pub async fn new() -> Self {
  278. let server = TestUserServer::new().await;
  279. let workspace = create_test_workspace(&server).await;
  280. let app = create_test_app(&server, &workspace.id).await;
  281. Self { server, workspace, app }
  282. }
  283. }
  284. pub struct ViewTest {
  285. pub server: TestUserServer,
  286. pub workspace: Workspace,
  287. pub app: App,
  288. pub view: View,
  289. }
  290. impl ViewTest {
  291. pub async fn new() -> Self {
  292. let server = TestUserServer::new().await;
  293. let workspace = create_test_workspace(&server).await;
  294. let app = create_test_app(&server, &workspace.id).await;
  295. let view = create_test_view(&server, &app.id).await;
  296. Self {
  297. server,
  298. workspace,
  299. app,
  300. view,
  301. }
  302. }
  303. }