helper.rs 11 KB

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