tests.rs

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