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