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