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, 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::{
 17    elements::*, executor::Deterministic, AnyElement, Entity, ModelHandle, Task, TestAppContext,
 18    View, ViewContext, ViewHandle, WeakViewHandle,
 19};
 20use language::LanguageRegistry;
 21use parking_lot::Mutex;
 22use project::{Project, WorktreeId};
 23use settings::SettingsStore;
 24use std::{
 25    cell::{Ref, RefCell, RefMut},
 26    env,
 27    ops::{Deref, DerefMut},
 28    path::Path,
 29    sync::{
 30        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
 31        Arc,
 32    },
 33};
 34use util::http::FakeHttpClient;
 35use workspace::Workspace;
 36
 37mod channel_tests;
 38mod integration_tests;
 39mod randomized_integration_tests;
 40
 41struct TestServer {
 42    app_state: Arc<AppState>,
 43    server: Arc<Server>,
 44    connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
 45    forbid_connections: Arc<AtomicBool>,
 46    _test_db: TestDb,
 47    test_live_kit_server: Arc<live_kit_client::TestServer>,
 48}
 49
 50impl TestServer {
 51    async fn start(deterministic: &Arc<Deterministic>) -> Self {
 52        static NEXT_LIVE_KIT_SERVER_ID: AtomicUsize = AtomicUsize::new(0);
 53
 54        let use_postgres = env::var("USE_POSTGRES").ok();
 55        let use_postgres = use_postgres.as_deref();
 56        let test_db = if use_postgres == Some("true") || use_postgres == Some("1") {
 57            TestDb::postgres(deterministic.build_background())
 58        } else {
 59            TestDb::sqlite(deterministic.build_background())
 60        };
 61        let live_kit_server_id = NEXT_LIVE_KIT_SERVER_ID.fetch_add(1, SeqCst);
 62        let live_kit_server = live_kit_client::TestServer::create(
 63            format!("http://livekit.{}.test", live_kit_server_id),
 64            format!("devkey-{}", live_kit_server_id),
 65            format!("secret-{}", live_kit_server_id),
 66            deterministic.build_background(),
 67        )
 68        .unwrap();
 69        let app_state = Self::build_app_state(&test_db, &live_kit_server).await;
 70        let epoch = app_state
 71            .db
 72            .create_server(&app_state.config.zed_environment)
 73            .await
 74            .unwrap();
 75        let server = Server::new(
 76            epoch,
 77            app_state.clone(),
 78            Executor::Deterministic(deterministic.build_background()),
 79        );
 80        server.start().await.unwrap();
 81        // Advance clock to ensure the server's cleanup task is finished.
 82        deterministic.advance_clock(CLEANUP_TIMEOUT);
 83        Self {
 84            app_state,
 85            server,
 86            connection_killers: Default::default(),
 87            forbid_connections: Default::default(),
 88            _test_db: test_db,
 89            test_live_kit_server: live_kit_server,
 90        }
 91    }
 92
 93    async fn reset(&self) {
 94        self.app_state.db.reset();
 95        let epoch = self
 96            .app_state
 97            .db
 98            .create_server(&self.app_state.config.zed_environment)
 99            .await
100            .unwrap();
101        self.server.reset(epoch);
102    }
103
104    async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
105        cx.update(|cx| {
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, _| {
282                channel_store.create_channel(channel, None)
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, _| {
292                    channel_store.invite_member(channel_id, member_client.user_id().unwrap(), false)
293                })
294                .await
295                .unwrap();
296
297            admin_cx.foreground().run_until_parked();
298
299            member_client
300                .app_state
301                .channel_store
302                .update(*member_cx, |channels, _| {
303                    channels.respond_to_channel_invite(channel_id, true)
304                })
305                .await
306                .unwrap();
307        }
308
309        channel_id
310    }
311
312    async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
313        self.make_contacts(clients).await;
314
315        let (left, right) = clients.split_at_mut(1);
316        let (_client_a, cx_a) = &mut left[0];
317        let active_call_a = cx_a.read(ActiveCall::global);
318
319        for (client_b, cx_b) in right {
320            let user_id_b = client_b.current_user_id(*cx_b).to_proto();
321            active_call_a
322                .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
323                .await
324                .unwrap();
325
326            cx_b.foreground().run_until_parked();
327            let active_call_b = cx_b.read(ActiveCall::global);
328            active_call_b
329                .update(*cx_b, |call, cx| call.accept_incoming(cx))
330                .await
331                .unwrap();
332        }
333    }
334
335    async fn build_app_state(
336        test_db: &TestDb,
337        fake_server: &live_kit_client::TestServer,
338    ) -> Arc<AppState> {
339        Arc::new(AppState {
340            db: test_db.db().clone(),
341            live_kit_client: Some(Arc::new(fake_server.create_api_client())),
342            config: Default::default(),
343        })
344    }
345}
346
347impl Deref for TestServer {
348    type Target = Server;
349
350    fn deref(&self) -> &Self::Target {
351        &self.server
352    }
353}
354
355impl Drop for TestServer {
356    fn drop(&mut self) {
357        self.server.teardown();
358        self.test_live_kit_server.teardown().unwrap();
359    }
360}
361
362struct TestClient {
363    username: String,
364    state: RefCell<TestClientState>,
365    app_state: Arc<workspace::AppState>,
366}
367
368#[derive(Default)]
369struct TestClientState {
370    local_projects: Vec<ModelHandle<Project>>,
371    remote_projects: Vec<ModelHandle<Project>>,
372    buffers: HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>,
373}
374
375impl Deref for TestClient {
376    type Target = Arc<Client>;
377
378    fn deref(&self) -> &Self::Target {
379        &self.app_state.client
380    }
381}
382
383struct ContactsSummary {
384    pub current: Vec<String>,
385    pub outgoing_requests: Vec<String>,
386    pub incoming_requests: Vec<String>,
387}
388
389impl TestClient {
390    pub fn fs(&self) -> &FakeFs {
391        self.app_state.fs.as_fake()
392    }
393
394    pub fn channel_store(&self) -> &ModelHandle<ChannelStore> {
395        &self.app_state.channel_store
396    }
397
398    pub fn user_store(&self) -> &ModelHandle<UserStore> {
399        &self.app_state.user_store
400    }
401
402    pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
403        &self.app_state.languages
404    }
405
406    pub fn client(&self) -> &Arc<Client> {
407        &self.app_state.client
408    }
409
410    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
411        UserId::from_proto(
412            self.app_state
413                .user_store
414                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
415        )
416    }
417
418    async fn wait_for_current_user(&self, cx: &TestAppContext) {
419        let mut authed_user = self
420            .app_state
421            .user_store
422            .read_with(cx, |user_store, _| user_store.watch_current_user());
423        while authed_user.next().await.unwrap().is_none() {}
424    }
425
426    async fn clear_contacts(&self, cx: &mut TestAppContext) {
427        self.app_state
428            .user_store
429            .update(cx, |store, _| store.clear_contacts())
430            .await;
431    }
432
433    fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
434        Ref::map(self.state.borrow(), |state| &state.local_projects)
435    }
436
437    fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
438        Ref::map(self.state.borrow(), |state| &state.remote_projects)
439    }
440
441    fn local_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
442        RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
443    }
444
445    fn remote_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
446        RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
447    }
448
449    fn buffers_for_project<'a>(
450        &'a self,
451        project: &ModelHandle<Project>,
452    ) -> impl DerefMut<Target = HashSet<ModelHandle<language::Buffer>>> + 'a {
453        RefMut::map(self.state.borrow_mut(), |state| {
454            state.buffers.entry(project.clone()).or_default()
455        })
456    }
457
458    fn buffers<'a>(
459        &'a self,
460    ) -> impl DerefMut<Target = HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>> + 'a
461    {
462        RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
463    }
464
465    fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
466        self.app_state
467            .user_store
468            .read_with(cx, |store, _| ContactsSummary {
469                current: store
470                    .contacts()
471                    .iter()
472                    .map(|contact| contact.user.github_login.clone())
473                    .collect(),
474                outgoing_requests: store
475                    .outgoing_contact_requests()
476                    .iter()
477                    .map(|user| user.github_login.clone())
478                    .collect(),
479                incoming_requests: store
480                    .incoming_contact_requests()
481                    .iter()
482                    .map(|user| user.github_login.clone())
483                    .collect(),
484            })
485    }
486
487    async fn build_local_project(
488        &self,
489        root_path: impl AsRef<Path>,
490        cx: &mut TestAppContext,
491    ) -> (ModelHandle<Project>, WorktreeId) {
492        let project = cx.update(|cx| {
493            Project::local(
494                self.client().clone(),
495                self.app_state.user_store.clone(),
496                self.app_state.languages.clone(),
497                self.app_state.fs.clone(),
498                cx,
499            )
500        });
501        let (worktree, _) = project
502            .update(cx, |p, cx| {
503                p.find_or_create_local_worktree(root_path, true, cx)
504            })
505            .await
506            .unwrap();
507        worktree
508            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
509            .await;
510        (project, worktree.read_with(cx, |tree, _| tree.id()))
511    }
512
513    async fn build_remote_project(
514        &self,
515        host_project_id: u64,
516        guest_cx: &mut TestAppContext,
517    ) -> ModelHandle<Project> {
518        let active_call = guest_cx.read(ActiveCall::global);
519        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
520        room.update(guest_cx, |room, cx| {
521            room.join_project(
522                host_project_id,
523                self.app_state.languages.clone(),
524                self.app_state.fs.clone(),
525                cx,
526            )
527        })
528        .await
529        .unwrap()
530    }
531
532    fn build_workspace(
533        &self,
534        project: &ModelHandle<Project>,
535        cx: &mut TestAppContext,
536    ) -> ViewHandle<Workspace> {
537        struct WorkspaceContainer {
538            workspace: Option<WeakViewHandle<Workspace>>,
539        }
540
541        impl Entity for WorkspaceContainer {
542            type Event = ();
543        }
544
545        impl View for WorkspaceContainer {
546            fn ui_name() -> &'static str {
547                "WorkspaceContainer"
548            }
549
550            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
551                if let Some(workspace) = self
552                    .workspace
553                    .as_ref()
554                    .and_then(|workspace| workspace.upgrade(cx))
555                {
556                    ChildView::new(&workspace, cx).into_any()
557                } else {
558                    Empty::new().into_any()
559                }
560            }
561        }
562
563        // We use a workspace container so that we don't need to remove the window in order to
564        // drop the workspace and we can use a ViewHandle instead.
565        let (window_id, container) = cx.add_window(|_| WorkspaceContainer { workspace: None });
566        let workspace = cx.add_view(window_id, |cx| {
567            Workspace::new(0, project.clone(), self.app_state.clone(), cx)
568        });
569        container.update(cx, |container, cx| {
570            container.workspace = Some(workspace.downgrade());
571            cx.notify();
572        });
573        workspace
574    }
575}
576
577impl Drop for TestClient {
578    fn drop(&mut self) {
579        self.app_state.client.teardown();
580    }
581}
582
583#[derive(Debug, Eq, PartialEq)]
584struct RoomParticipants {
585    remote: Vec<String>,
586    pending: Vec<String>,
587}
588
589fn room_participants(room: &ModelHandle<Room>, cx: &mut TestAppContext) -> RoomParticipants {
590    room.read_with(cx, |room, _| {
591        let mut remote = room
592            .remote_participants()
593            .iter()
594            .map(|(_, participant)| participant.user.github_login.clone())
595            .collect::<Vec<_>>();
596        let mut pending = room
597            .pending_participants()
598            .iter()
599            .map(|user| user.github_login.clone())
600            .collect::<Vec<_>>();
601        remote.sort();
602        pending.sort();
603        RoomParticipants { remote, pending }
604    })
605}