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            dock_default_item_factory: |_, _| None,
199            background_actions: || &[],
200        });
201
202        Project::init(&client);
203        cx.update(|cx| {
204            workspace::init(app_state.clone(), cx);
205            call::init(client.clone(), user_store.clone(), cx);
206        });
207
208        client
209            .authenticate_and_connect(false, &cx.to_async())
210            .await
211            .unwrap();
212
213        let client = TestClient {
214            client,
215            username: name.to_string(),
216            state: Default::default(),
217            user_store,
218            fs,
219            language_registry: Arc::new(LanguageRegistry::test()),
220        };
221        client.wait_for_current_user(cx).await;
222        client
223    }
224
225    fn disconnect_client(&self, peer_id: PeerId) {
226        self.connection_killers
227            .lock()
228            .remove(&peer_id)
229            .unwrap()
230            .store(true, SeqCst);
231    }
232
233    fn forbid_connections(&self) {
234        self.forbid_connections.store(true, SeqCst);
235    }
236
237    fn allow_connections(&self) {
238        self.forbid_connections.store(false, SeqCst);
239    }
240
241    async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
242        for ix in 1..clients.len() {
243            let (left, right) = clients.split_at_mut(ix);
244            let (client_a, cx_a) = left.last_mut().unwrap();
245            for (client_b, cx_b) in right {
246                client_a
247                    .user_store
248                    .update(*cx_a, |store, cx| {
249                        store.request_contact(client_b.user_id().unwrap(), cx)
250                    })
251                    .await
252                    .unwrap();
253                cx_a.foreground().run_until_parked();
254                client_b
255                    .user_store
256                    .update(*cx_b, |store, cx| {
257                        store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
258                    })
259                    .await
260                    .unwrap();
261            }
262        }
263    }
264
265    async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
266        self.make_contacts(clients).await;
267
268        let (left, right) = clients.split_at_mut(1);
269        let (_client_a, cx_a) = &mut left[0];
270        let active_call_a = cx_a.read(ActiveCall::global);
271
272        for (client_b, cx_b) in right {
273            let user_id_b = client_b.current_user_id(*cx_b).to_proto();
274            active_call_a
275                .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
276                .await
277                .unwrap();
278
279            cx_b.foreground().run_until_parked();
280            let active_call_b = cx_b.read(ActiveCall::global);
281            active_call_b
282                .update(*cx_b, |call, cx| call.accept_incoming(cx))
283                .await
284                .unwrap();
285        }
286    }
287
288    async fn build_app_state(
289        test_db: &TestDb,
290        fake_server: &live_kit_client::TestServer,
291    ) -> Arc<AppState> {
292        Arc::new(AppState {
293            db: test_db.db().clone(),
294            live_kit_client: Some(Arc::new(fake_server.create_api_client())),
295            config: Default::default(),
296        })
297    }
298}
299
300impl Deref for TestServer {
301    type Target = Server;
302
303    fn deref(&self) -> &Self::Target {
304        &self.server
305    }
306}
307
308impl Drop for TestServer {
309    fn drop(&mut self) {
310        self.server.teardown();
311        self.test_live_kit_server.teardown().unwrap();
312    }
313}
314
315struct TestClient {
316    client: Arc<Client>,
317    username: String,
318    state: RefCell<TestClientState>,
319    pub user_store: ModelHandle<UserStore>,
320    language_registry: Arc<LanguageRegistry>,
321    fs: Arc<FakeFs>,
322}
323
324#[derive(Default)]
325struct TestClientState {
326    local_projects: Vec<ModelHandle<Project>>,
327    remote_projects: Vec<ModelHandle<Project>>,
328    buffers: HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>,
329}
330
331impl Deref for TestClient {
332    type Target = Arc<Client>;
333
334    fn deref(&self) -> &Self::Target {
335        &self.client
336    }
337}
338
339struct ContactsSummary {
340    pub current: Vec<String>,
341    pub outgoing_requests: Vec<String>,
342    pub incoming_requests: Vec<String>,
343}
344
345impl TestClient {
346    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
347        UserId::from_proto(
348            self.user_store
349                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
350        )
351    }
352
353    async fn wait_for_current_user(&self, cx: &TestAppContext) {
354        let mut authed_user = self
355            .user_store
356            .read_with(cx, |user_store, _| user_store.watch_current_user());
357        while authed_user.next().await.unwrap().is_none() {}
358    }
359
360    async fn clear_contacts(&self, cx: &mut TestAppContext) {
361        self.user_store
362            .update(cx, |store, _| store.clear_contacts())
363            .await;
364    }
365
366    fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
367        Ref::map(self.state.borrow(), |state| &state.local_projects)
368    }
369
370    fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
371        Ref::map(self.state.borrow(), |state| &state.remote_projects)
372    }
373
374    fn local_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
375        RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
376    }
377
378    fn remote_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
379        RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
380    }
381
382    fn buffers_for_project<'a>(
383        &'a self,
384        project: &ModelHandle<Project>,
385    ) -> impl DerefMut<Target = HashSet<ModelHandle<language::Buffer>>> + 'a {
386        RefMut::map(self.state.borrow_mut(), |state| {
387            state.buffers.entry(project.clone()).or_default()
388        })
389    }
390
391    fn buffers<'a>(
392        &'a self,
393    ) -> impl DerefMut<Target = HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>> + 'a
394    {
395        RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
396    }
397
398    fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
399        self.user_store.read_with(cx, |store, _| ContactsSummary {
400            current: store
401                .contacts()
402                .iter()
403                .map(|contact| contact.user.github_login.clone())
404                .collect(),
405            outgoing_requests: store
406                .outgoing_contact_requests()
407                .iter()
408                .map(|user| user.github_login.clone())
409                .collect(),
410            incoming_requests: store
411                .incoming_contact_requests()
412                .iter()
413                .map(|user| user.github_login.clone())
414                .collect(),
415        })
416    }
417
418    async fn build_local_project(
419        &self,
420        root_path: impl AsRef<Path>,
421        cx: &mut TestAppContext,
422    ) -> (ModelHandle<Project>, WorktreeId) {
423        let project = cx.update(|cx| {
424            Project::local(
425                self.client.clone(),
426                self.user_store.clone(),
427                self.language_registry.clone(),
428                self.fs.clone(),
429                cx,
430            )
431        });
432        let (worktree, _) = project
433            .update(cx, |p, cx| {
434                p.find_or_create_local_worktree(root_path, true, cx)
435            })
436            .await
437            .unwrap();
438        worktree
439            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
440            .await;
441        (project, worktree.read_with(cx, |tree, _| tree.id()))
442    }
443
444    async fn build_remote_project(
445        &self,
446        host_project_id: u64,
447        guest_cx: &mut TestAppContext,
448    ) -> ModelHandle<Project> {
449        let active_call = guest_cx.read(ActiveCall::global);
450        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
451        room.update(guest_cx, |room, cx| {
452            room.join_project(
453                host_project_id,
454                self.language_registry.clone(),
455                self.fs.clone(),
456                cx,
457            )
458        })
459        .await
460        .unwrap()
461    }
462
463    fn build_workspace(
464        &self,
465        project: &ModelHandle<Project>,
466        cx: &mut TestAppContext,
467    ) -> ViewHandle<Workspace> {
468        struct WorkspaceContainer {
469            workspace: Option<WeakViewHandle<Workspace>>,
470        }
471
472        impl Entity for WorkspaceContainer {
473            type Event = ();
474        }
475
476        impl View for WorkspaceContainer {
477            fn ui_name() -> &'static str {
478                "WorkspaceContainer"
479            }
480
481            fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
482                if let Some(workspace) = self
483                    .workspace
484                    .as_ref()
485                    .and_then(|workspace| workspace.upgrade(cx))
486                {
487                    ChildView::new(&workspace, cx).into_any()
488                } else {
489                    Empty::new().into_any()
490                }
491            }
492        }
493
494        // We use a workspace container so that we don't need to remove the window in order to
495        // drop the workspace and we can use a ViewHandle instead.
496        let (window_id, container) = cx.add_window(|_| WorkspaceContainer { workspace: None });
497        let workspace = cx.add_view(window_id, |cx| Workspace::test_new(project.clone(), cx));
498        container.update(cx, |container, cx| {
499            container.workspace = Some(workspace.downgrade());
500            cx.notify();
501        });
502        workspace
503    }
504}
505
506impl Drop for TestClient {
507    fn drop(&mut self) {
508        self.client.teardown();
509    }
510}