tests.rs

  1use crate::{
  2    db::{NewUserParams, TestDb, UserId},
  3    executor::Executor,
  4    rpc::{Server, CLEANUP_TIMEOUT},
  5    AppState,
  6};
  7use anyhow::anyhow;
  8use call::ActiveCall;
  9use client::{
 10    self, proto::PeerId, test::FakeHttpClient, Client, Connection, Credentials,
 11    EstablishConnectionError, UserStore,
 12};
 13use collections::{HashMap, HashSet};
 14use fs::FakeFs;
 15use futures::{channel::oneshot, StreamExt as _};
 16use gpui::{
 17    executor::Deterministic, test::EmptyView, ModelHandle, Task, TestAppContext, ViewHandle,
 18};
 19use language::LanguageRegistry;
 20use parking_lot::Mutex;
 21use project::{Project, WorktreeId};
 22use settings::Settings;
 23use std::{
 24    env,
 25    ops::Deref,
 26    path::{Path, PathBuf},
 27    sync::{
 28        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
 29        Arc,
 30    },
 31};
 32use theme::ThemeRegistry;
 33use workspace::Workspace;
 34
 35mod integration_tests;
 36mod randomized_integration_tests;
 37
 38struct TestServer {
 39    app_state: Arc<AppState>,
 40    server: Arc<Server>,
 41    connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
 42    forbid_connections: Arc<AtomicBool>,
 43    _test_db: TestDb,
 44    test_live_kit_server: Arc<live_kit_client::TestServer>,
 45}
 46
 47impl TestServer {
 48    async fn start(deterministic: &Arc<Deterministic>) -> Self {
 49        static NEXT_LIVE_KIT_SERVER_ID: AtomicUsize = AtomicUsize::new(0);
 50
 51        let use_postgres = env::var("USE_POSTGRES").ok();
 52        let use_postgres = use_postgres.as_deref();
 53        let test_db = if use_postgres == Some("true") || use_postgres == Some("1") {
 54            TestDb::postgres(deterministic.build_background())
 55        } else {
 56            TestDb::sqlite(deterministic.build_background())
 57        };
 58        let live_kit_server_id = NEXT_LIVE_KIT_SERVER_ID.fetch_add(1, SeqCst);
 59        let live_kit_server = live_kit_client::TestServer::create(
 60            format!("http://livekit.{}.test", live_kit_server_id),
 61            format!("devkey-{}", live_kit_server_id),
 62            format!("secret-{}", live_kit_server_id),
 63            deterministic.build_background(),
 64        )
 65        .unwrap();
 66        let app_state = Self::build_app_state(&test_db, &live_kit_server).await;
 67        let epoch = app_state
 68            .db
 69            .create_server(&app_state.config.zed_environment)
 70            .await
 71            .unwrap();
 72        let server = Server::new(
 73            epoch,
 74            app_state.clone(),
 75            Executor::Deterministic(deterministic.build_background()),
 76        );
 77        server.start().await.unwrap();
 78        // Advance clock to ensure the server's cleanup task is finished.
 79        deterministic.advance_clock(CLEANUP_TIMEOUT);
 80        Self {
 81            app_state,
 82            server,
 83            connection_killers: Default::default(),
 84            forbid_connections: Default::default(),
 85            _test_db: test_db,
 86            test_live_kit_server: live_kit_server,
 87        }
 88    }
 89
 90    async fn reset(&self) {
 91        self.app_state.db.reset();
 92        let epoch = self
 93            .app_state
 94            .db
 95            .create_server(&self.app_state.config.zed_environment)
 96            .await
 97            .unwrap();
 98        self.server.reset(epoch);
 99    }
100
101    async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
102        cx.update(|cx| {
103            cx.set_global(Settings::test(cx));
104        });
105
106        let http = FakeHttpClient::with_404_response();
107        let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
108        {
109            user.id
110        } else {
111            self.app_state
112                .db
113                .create_user(
114                    &format!("{name}@example.com"),
115                    false,
116                    NewUserParams {
117                        github_login: name.into(),
118                        github_user_id: 0,
119                        invite_count: 0,
120                    },
121                )
122                .await
123                .expect("creating user failed")
124                .user_id
125        };
126        let client_name = name.to_string();
127        let mut client = cx.read(|cx| Client::new(http.clone(), cx));
128        let server = self.server.clone();
129        let db = self.app_state.db.clone();
130        let connection_killers = self.connection_killers.clone();
131        let forbid_connections = self.forbid_connections.clone();
132
133        Arc::get_mut(&mut client)
134            .unwrap()
135            .set_id(user_id.0 as usize)
136            .override_authenticate(move |cx| {
137                cx.spawn(|_| async move {
138                    let access_token = "the-token".to_string();
139                    Ok(Credentials {
140                        user_id: user_id.0 as u64,
141                        access_token,
142                    })
143                })
144            })
145            .override_establish_connection(move |credentials, cx| {
146                assert_eq!(credentials.user_id, user_id.0 as u64);
147                assert_eq!(credentials.access_token, "the-token");
148
149                let server = server.clone();
150                let db = db.clone();
151                let connection_killers = connection_killers.clone();
152                let forbid_connections = forbid_connections.clone();
153                let client_name = client_name.clone();
154                cx.spawn(move |cx| async move {
155                    if forbid_connections.load(SeqCst) {
156                        Err(EstablishConnectionError::other(anyhow!(
157                            "server is forbidding connections"
158                        )))
159                    } else {
160                        let (client_conn, server_conn, killed) =
161                            Connection::in_memory(cx.background());
162                        let (connection_id_tx, connection_id_rx) = oneshot::channel();
163                        let user = db
164                            .get_user_by_id(user_id)
165                            .await
166                            .expect("retrieving user failed")
167                            .unwrap();
168                        cx.background()
169                            .spawn(server.handle_connection(
170                                server_conn,
171                                client_name,
172                                user,
173                                Some(connection_id_tx),
174                                Executor::Deterministic(cx.background()),
175                            ))
176                            .detach();
177                        let connection_id = connection_id_rx.await.unwrap();
178                        connection_killers
179                            .lock()
180                            .insert(connection_id.into(), killed);
181                        Ok(client_conn)
182                    }
183                })
184            });
185
186        let fs = FakeFs::new(cx.background());
187        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
188        let app_state = Arc::new(workspace::AppState {
189            client: client.clone(),
190            user_store: user_store.clone(),
191            languages: Arc::new(LanguageRegistry::new(Task::ready(()))),
192            themes: ThemeRegistry::new((), cx.font_cache()),
193            fs: fs.clone(),
194            build_window_options: |_, _, _| Default::default(),
195            initialize_workspace: |_, _, _| unimplemented!(),
196            dock_default_item_factory: |_, _| None,
197            background_actions: || &[],
198        });
199
200        Project::init(&client);
201        cx.update(|cx| {
202            workspace::init(app_state.clone(), cx);
203            call::init(client.clone(), user_store.clone(), cx);
204        });
205
206        client
207            .authenticate_and_connect(false, &cx.to_async())
208            .await
209            .unwrap();
210
211        let client = TestClient {
212            client,
213            username: name.to_string(),
214            local_projects: Default::default(),
215            remote_projects: Default::default(),
216            next_root_dir_id: 0,
217            user_store,
218            fs,
219            language_registry: Arc::new(LanguageRegistry::test()),
220            buffers: Default::default(),
221        };
222        client.wait_for_current_user(cx).await;
223        client
224    }
225
226    fn disconnect_client(&self, peer_id: PeerId) {
227        self.connection_killers
228            .lock()
229            .remove(&peer_id)
230            .unwrap()
231            .store(true, SeqCst);
232    }
233
234    fn forbid_connections(&self) {
235        self.forbid_connections.store(true, SeqCst);
236    }
237
238    fn allow_connections(&self) {
239        self.forbid_connections.store(false, SeqCst);
240    }
241
242    async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
243        for ix in 1..clients.len() {
244            let (left, right) = clients.split_at_mut(ix);
245            let (client_a, cx_a) = left.last_mut().unwrap();
246            for (client_b, cx_b) in right {
247                client_a
248                    .user_store
249                    .update(*cx_a, |store, cx| {
250                        store.request_contact(client_b.user_id().unwrap(), cx)
251                    })
252                    .await
253                    .unwrap();
254                cx_a.foreground().run_until_parked();
255                client_b
256                    .user_store
257                    .update(*cx_b, |store, cx| {
258                        store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
259                    })
260                    .await
261                    .unwrap();
262            }
263        }
264    }
265
266    async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
267        self.make_contacts(clients).await;
268
269        let (left, right) = clients.split_at_mut(1);
270        let (_client_a, cx_a) = &mut left[0];
271        let active_call_a = cx_a.read(ActiveCall::global);
272
273        for (client_b, cx_b) in right {
274            let user_id_b = client_b.current_user_id(*cx_b).to_proto();
275            active_call_a
276                .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
277                .await
278                .unwrap();
279
280            cx_b.foreground().run_until_parked();
281            let active_call_b = cx_b.read(ActiveCall::global);
282            active_call_b
283                .update(*cx_b, |call, cx| call.accept_incoming(cx))
284                .await
285                .unwrap();
286        }
287    }
288
289    async fn build_app_state(
290        test_db: &TestDb,
291        fake_server: &live_kit_client::TestServer,
292    ) -> Arc<AppState> {
293        Arc::new(AppState {
294            db: test_db.db().clone(),
295            live_kit_client: Some(Arc::new(fake_server.create_api_client())),
296            config: Default::default(),
297        })
298    }
299}
300
301impl Deref for TestServer {
302    type Target = Server;
303
304    fn deref(&self) -> &Self::Target {
305        &self.server
306    }
307}
308
309impl Drop for TestServer {
310    fn drop(&mut self) {
311        self.server.teardown();
312        self.test_live_kit_server.teardown().unwrap();
313    }
314}
315
316struct TestClient {
317    client: Arc<Client>,
318    username: String,
319    local_projects: Vec<ModelHandle<Project>>,
320    remote_projects: Vec<ModelHandle<Project>>,
321    next_root_dir_id: usize,
322    pub user_store: ModelHandle<UserStore>,
323    language_registry: Arc<LanguageRegistry>,
324    fs: Arc<FakeFs>,
325    buffers: HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>,
326}
327
328impl Deref for TestClient {
329    type Target = Arc<Client>;
330
331    fn deref(&self) -> &Self::Target {
332        &self.client
333    }
334}
335
336struct ContactsSummary {
337    pub current: Vec<String>,
338    pub outgoing_requests: Vec<String>,
339    pub incoming_requests: Vec<String>,
340}
341
342impl TestClient {
343    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
344        UserId::from_proto(
345            self.user_store
346                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
347        )
348    }
349
350    async fn wait_for_current_user(&self, cx: &TestAppContext) {
351        let mut authed_user = self
352            .user_store
353            .read_with(cx, |user_store, _| user_store.watch_current_user());
354        while authed_user.next().await.unwrap().is_none() {}
355    }
356
357    async fn clear_contacts(&self, cx: &mut TestAppContext) {
358        self.user_store
359            .update(cx, |store, _| store.clear_contacts())
360            .await;
361    }
362
363    fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
364        self.user_store.read_with(cx, |store, _| ContactsSummary {
365            current: store
366                .contacts()
367                .iter()
368                .map(|contact| contact.user.github_login.clone())
369                .collect(),
370            outgoing_requests: store
371                .outgoing_contact_requests()
372                .iter()
373                .map(|user| user.github_login.clone())
374                .collect(),
375            incoming_requests: store
376                .incoming_contact_requests()
377                .iter()
378                .map(|user| user.github_login.clone())
379                .collect(),
380        })
381    }
382
383    async fn build_local_project(
384        &self,
385        root_path: impl AsRef<Path>,
386        cx: &mut TestAppContext,
387    ) -> (ModelHandle<Project>, WorktreeId) {
388        let project = cx.update(|cx| {
389            Project::local(
390                self.client.clone(),
391                self.user_store.clone(),
392                self.language_registry.clone(),
393                self.fs.clone(),
394                cx,
395            )
396        });
397        let (worktree, _) = project
398            .update(cx, |p, cx| {
399                p.find_or_create_local_worktree(root_path, true, cx)
400            })
401            .await
402            .unwrap();
403        worktree
404            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
405            .await;
406        (project, worktree.read_with(cx, |tree, _| tree.id()))
407    }
408
409    async fn build_remote_project(
410        &self,
411        host_project_id: u64,
412        guest_cx: &mut TestAppContext,
413    ) -> ModelHandle<Project> {
414        let active_call = guest_cx.read(ActiveCall::global);
415        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
416        room.update(guest_cx, |room, cx| {
417            room.join_project(
418                host_project_id,
419                self.language_registry.clone(),
420                self.fs.clone(),
421                cx,
422            )
423        })
424        .await
425        .unwrap()
426    }
427
428    fn build_workspace(
429        &self,
430        project: &ModelHandle<Project>,
431        cx: &mut TestAppContext,
432    ) -> ViewHandle<Workspace> {
433        let (_, root_view) = cx.add_window(|_| EmptyView);
434        cx.add_view(&root_view, |cx| Workspace::test_new(project.clone(), cx))
435    }
436
437    fn create_new_root_dir(&mut self) -> PathBuf {
438        format!(
439            "/{}-root-{}",
440            self.username,
441            util::post_inc(&mut self.next_root_dir_id)
442        )
443        .into()
444    }
445}
446
447impl Drop for TestClient {
448    fn drop(&mut self) {
449        self.client.teardown();
450    }
451}