tests.rs

  1use crate::{
  2    db::{test_db::TestDb, NewUserParams, UserId},
  3    executor::Executor,
  4    rpc::{Server, CLEANUP_TIMEOUT},
  5    AppState,
  6};
  7use anyhow::anyhow;
  8use call::{ActiveCall, Room};
  9use client::{
 10    self, proto::PeerId, ChannelStore, Client, Connection, Credentials, EstablishConnectionError,
 11    UserStore,
 12};
 13use collections::{HashMap, HashSet};
 14use fs::FakeFs;
 15use futures::{channel::oneshot, StreamExt as _};
 16use gpui::{executor::Deterministic, ModelHandle, Task, TestAppContext, WindowHandle};
 17use language::LanguageRegistry;
 18use parking_lot::Mutex;
 19use project::{Project, WorktreeId};
 20use settings::SettingsStore;
 21use std::{
 22    cell::{Ref, RefCell, RefMut},
 23    env,
 24    ops::{Deref, DerefMut},
 25    path::Path,
 26    sync::{
 27        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
 28        Arc,
 29    },
 30};
 31use util::http::FakeHttpClient;
 32use workspace::Workspace;
 33
 34mod channel_tests;
 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            if cx.has_global::<SettingsStore>() {
104                panic!("Same cx used to create two test clients")
105            }
106            cx.set_global(SettingsStore::test(cx));
107        });
108
109        let http = FakeHttpClient::with_404_response();
110        let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
111        {
112            user.id
113        } else {
114            self.app_state
115                .db
116                .create_user(
117                    &format!("{name}@example.com"),
118                    false,
119                    NewUserParams {
120                        github_login: name.into(),
121                        github_user_id: 0,
122                        invite_count: 0,
123                    },
124                )
125                .await
126                .expect("creating user failed")
127                .user_id
128        };
129        let client_name = name.to_string();
130        let mut client = cx.read(|cx| Client::new(http.clone(), cx));
131        let server = self.server.clone();
132        let db = self.app_state.db.clone();
133        let connection_killers = self.connection_killers.clone();
134        let forbid_connections = self.forbid_connections.clone();
135
136        Arc::get_mut(&mut client)
137            .unwrap()
138            .set_id(user_id.0 as usize)
139            .override_authenticate(move |cx| {
140                cx.spawn(|_| async move {
141                    let access_token = "the-token".to_string();
142                    Ok(Credentials {
143                        user_id: user_id.0 as u64,
144                        access_token,
145                    })
146                })
147            })
148            .override_establish_connection(move |credentials, cx| {
149                assert_eq!(credentials.user_id, user_id.0 as u64);
150                assert_eq!(credentials.access_token, "the-token");
151
152                let server = server.clone();
153                let db = db.clone();
154                let connection_killers = connection_killers.clone();
155                let forbid_connections = forbid_connections.clone();
156                let client_name = client_name.clone();
157                cx.spawn(move |cx| async move {
158                    if forbid_connections.load(SeqCst) {
159                        Err(EstablishConnectionError::other(anyhow!(
160                            "server is forbidding connections"
161                        )))
162                    } else {
163                        let (client_conn, server_conn, killed) =
164                            Connection::in_memory(cx.background());
165                        let (connection_id_tx, connection_id_rx) = oneshot::channel();
166                        let user = db
167                            .get_user_by_id(user_id)
168                            .await
169                            .expect("retrieving user failed")
170                            .unwrap();
171                        cx.background()
172                            .spawn(server.handle_connection(
173                                server_conn,
174                                client_name,
175                                user,
176                                Some(connection_id_tx),
177                                Executor::Deterministic(cx.background()),
178                            ))
179                            .detach();
180                        let connection_id = connection_id_rx.await.unwrap();
181                        connection_killers
182                            .lock()
183                            .insert(connection_id.into(), killed);
184                        Ok(client_conn)
185                    }
186                })
187            });
188
189        let fs = FakeFs::new(cx.background());
190        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
191        let channel_store =
192            cx.add_model(|cx| ChannelStore::new(client.clone(), user_store.clone(), cx));
193        let app_state = Arc::new(workspace::AppState {
194            client: client.clone(),
195            user_store: user_store.clone(),
196            channel_store: channel_store.clone(),
197            languages: Arc::new(LanguageRegistry::test()),
198            fs: fs.clone(),
199            build_window_options: |_, _, _| Default::default(),
200            initialize_workspace: |_, _, _, _| Task::ready(Ok(())),
201            background_actions: || &[],
202        });
203
204        cx.update(|cx| {
205            theme::init((), cx);
206            Project::init(&client, cx);
207            client::init(&client, cx);
208            language::init(cx);
209            editor::init_settings(cx);
210            workspace::init(app_state.clone(), cx);
211            audio::init((), cx);
212            call::init(client.clone(), user_store.clone(), cx);
213        });
214
215        client
216            .authenticate_and_connect(false, &cx.to_async())
217            .await
218            .unwrap();
219
220        let client = TestClient {
221            app_state,
222            username: name.to_string(),
223            state: Default::default(),
224        };
225        client.wait_for_current_user(cx).await;
226        client
227    }
228
229    fn disconnect_client(&self, peer_id: PeerId) {
230        self.connection_killers
231            .lock()
232            .remove(&peer_id)
233            .unwrap()
234            .store(true, SeqCst);
235    }
236
237    fn forbid_connections(&self) {
238        self.forbid_connections.store(true, SeqCst);
239    }
240
241    fn allow_connections(&self) {
242        self.forbid_connections.store(false, SeqCst);
243    }
244
245    async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
246        for ix in 1..clients.len() {
247            let (left, right) = clients.split_at_mut(ix);
248            let (client_a, cx_a) = left.last_mut().unwrap();
249            for (client_b, cx_b) in right {
250                client_a
251                    .app_state
252                    .user_store
253                    .update(*cx_a, |store, cx| {
254                        store.request_contact(client_b.user_id().unwrap(), cx)
255                    })
256                    .await
257                    .unwrap();
258                cx_a.foreground().run_until_parked();
259                client_b
260                    .app_state
261                    .user_store
262                    .update(*cx_b, |store, cx| {
263                        store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
264                    })
265                    .await
266                    .unwrap();
267            }
268        }
269    }
270
271    async fn make_channel(
272        &self,
273        channel: &str,
274        admin: (&TestClient, &mut TestAppContext),
275        members: &mut [(&TestClient, &mut TestAppContext)],
276    ) -> u64 {
277        let (admin_client, admin_cx) = admin;
278        let channel_id = admin_client
279            .app_state
280            .channel_store
281            .update(admin_cx, |channel_store, cx| {
282                channel_store.create_channel(channel, None, cx)
283            })
284            .await
285            .unwrap();
286
287        for (member_client, member_cx) in members {
288            admin_client
289                .app_state
290                .channel_store
291                .update(admin_cx, |channel_store, cx| {
292                    channel_store.invite_member(
293                        channel_id,
294                        member_client.user_id().unwrap(),
295                        false,
296                        cx,
297                    )
298                })
299                .await
300                .unwrap();
301
302            admin_cx.foreground().run_until_parked();
303
304            member_client
305                .app_state
306                .channel_store
307                .update(*member_cx, |channels, _| {
308                    channels.respond_to_channel_invite(channel_id, true)
309                })
310                .await
311                .unwrap();
312        }
313
314        channel_id
315    }
316
317    async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
318        self.make_contacts(clients).await;
319
320        let (left, right) = clients.split_at_mut(1);
321        let (_client_a, cx_a) = &mut left[0];
322        let active_call_a = cx_a.read(ActiveCall::global);
323
324        for (client_b, cx_b) in right {
325            let user_id_b = client_b.current_user_id(*cx_b).to_proto();
326            active_call_a
327                .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
328                .await
329                .unwrap();
330
331            cx_b.foreground().run_until_parked();
332            let active_call_b = cx_b.read(ActiveCall::global);
333            active_call_b
334                .update(*cx_b, |call, cx| call.accept_incoming(cx))
335                .await
336                .unwrap();
337        }
338    }
339
340    async fn build_app_state(
341        test_db: &TestDb,
342        fake_server: &live_kit_client::TestServer,
343    ) -> Arc<AppState> {
344        Arc::new(AppState {
345            db: test_db.db().clone(),
346            live_kit_client: Some(Arc::new(fake_server.create_api_client())),
347            config: Default::default(),
348        })
349    }
350}
351
352impl Deref for TestServer {
353    type Target = Server;
354
355    fn deref(&self) -> &Self::Target {
356        &self.server
357    }
358}
359
360impl Drop for TestServer {
361    fn drop(&mut self) {
362        self.server.teardown();
363        self.test_live_kit_server.teardown().unwrap();
364    }
365}
366
367struct TestClient {
368    username: String,
369    state: RefCell<TestClientState>,
370    app_state: Arc<workspace::AppState>,
371}
372
373#[derive(Default)]
374struct TestClientState {
375    local_projects: Vec<ModelHandle<Project>>,
376    remote_projects: Vec<ModelHandle<Project>>,
377    buffers: HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>,
378}
379
380impl Deref for TestClient {
381    type Target = Arc<Client>;
382
383    fn deref(&self) -> &Self::Target {
384        &self.app_state.client
385    }
386}
387
388struct ContactsSummary {
389    pub current: Vec<String>,
390    pub outgoing_requests: Vec<String>,
391    pub incoming_requests: Vec<String>,
392}
393
394impl TestClient {
395    pub fn fs(&self) -> &FakeFs {
396        self.app_state.fs.as_fake()
397    }
398
399    pub fn channel_store(&self) -> &ModelHandle<ChannelStore> {
400        &self.app_state.channel_store
401    }
402
403    pub fn user_store(&self) -> &ModelHandle<UserStore> {
404        &self.app_state.user_store
405    }
406
407    pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
408        &self.app_state.languages
409    }
410
411    pub fn client(&self) -> &Arc<Client> {
412        &self.app_state.client
413    }
414
415    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
416        UserId::from_proto(
417            self.app_state
418                .user_store
419                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
420        )
421    }
422
423    async fn wait_for_current_user(&self, cx: &TestAppContext) {
424        let mut authed_user = self
425            .app_state
426            .user_store
427            .read_with(cx, |user_store, _| user_store.watch_current_user());
428        while authed_user.next().await.unwrap().is_none() {}
429    }
430
431    async fn clear_contacts(&self, cx: &mut TestAppContext) {
432        self.app_state
433            .user_store
434            .update(cx, |store, _| store.clear_contacts())
435            .await;
436    }
437
438    fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
439        Ref::map(self.state.borrow(), |state| &state.local_projects)
440    }
441
442    fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
443        Ref::map(self.state.borrow(), |state| &state.remote_projects)
444    }
445
446    fn local_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
447        RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
448    }
449
450    fn remote_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
451        RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
452    }
453
454    fn buffers_for_project<'a>(
455        &'a self,
456        project: &ModelHandle<Project>,
457    ) -> impl DerefMut<Target = HashSet<ModelHandle<language::Buffer>>> + 'a {
458        RefMut::map(self.state.borrow_mut(), |state| {
459            state.buffers.entry(project.clone()).or_default()
460        })
461    }
462
463    fn buffers<'a>(
464        &'a self,
465    ) -> impl DerefMut<Target = HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>> + 'a
466    {
467        RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
468    }
469
470    fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
471        self.app_state
472            .user_store
473            .read_with(cx, |store, _| ContactsSummary {
474                current: store
475                    .contacts()
476                    .iter()
477                    .map(|contact| contact.user.github_login.clone())
478                    .collect(),
479                outgoing_requests: store
480                    .outgoing_contact_requests()
481                    .iter()
482                    .map(|user| user.github_login.clone())
483                    .collect(),
484                incoming_requests: store
485                    .incoming_contact_requests()
486                    .iter()
487                    .map(|user| user.github_login.clone())
488                    .collect(),
489            })
490    }
491
492    async fn build_local_project(
493        &self,
494        root_path: impl AsRef<Path>,
495        cx: &mut TestAppContext,
496    ) -> (ModelHandle<Project>, WorktreeId) {
497        let project = cx.update(|cx| {
498            Project::local(
499                self.client().clone(),
500                self.app_state.user_store.clone(),
501                self.app_state.languages.clone(),
502                self.app_state.fs.clone(),
503                cx,
504            )
505        });
506        let (worktree, _) = project
507            .update(cx, |p, cx| {
508                p.find_or_create_local_worktree(root_path, true, cx)
509            })
510            .await
511            .unwrap();
512        worktree
513            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
514            .await;
515        (project, worktree.read_with(cx, |tree, _| tree.id()))
516    }
517
518    async fn build_remote_project(
519        &self,
520        host_project_id: u64,
521        guest_cx: &mut TestAppContext,
522    ) -> ModelHandle<Project> {
523        let active_call = guest_cx.read(ActiveCall::global);
524        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
525        room.update(guest_cx, |room, cx| {
526            room.join_project(
527                host_project_id,
528                self.app_state.languages.clone(),
529                self.app_state.fs.clone(),
530                cx,
531            )
532        })
533        .await
534        .unwrap()
535    }
536
537    fn build_workspace(
538        &self,
539        project: &ModelHandle<Project>,
540        cx: &mut TestAppContext,
541    ) -> WindowHandle<Workspace> {
542        cx.add_window(|cx| Workspace::new(0, project.clone(), self.app_state.clone(), cx))
543    }
544}
545
546impl Drop for TestClient {
547    fn drop(&mut self) {
548        self.app_state.client.teardown();
549    }
550}
551
552#[derive(Debug, Eq, PartialEq)]
553struct RoomParticipants {
554    remote: Vec<String>,
555    pending: Vec<String>,
556}
557
558fn room_participants(room: &ModelHandle<Room>, cx: &mut TestAppContext) -> RoomParticipants {
559    room.read_with(cx, |room, _| {
560        let mut remote = room
561            .remote_participants()
562            .iter()
563            .map(|(_, participant)| participant.user.github_login.clone())
564            .collect::<Vec<_>>();
565        let mut pending = room
566            .pending_participants()
567            .iter()
568            .map(|user| user.github_login.clone())
569            .collect::<Vec<_>>();
570        remote.sort();
571        pending.sort();
572        RoomParticipants { remote, pending }
573    })
574}