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::{executor::Deterministic, ModelHandle, TestAppContext, WindowHandle};
 16use language::LanguageRegistry;
 17use parking_lot::Mutex;
 18use project::{Project, WorktreeId};
 19use settings::SettingsStore;
 20use std::{
 21    cell::{Ref, RefCell, RefMut},
 22    env,
 23    ops::{Deref, DerefMut},
 24    path::Path,
 25    sync::{
 26        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
 27        Arc,
 28    },
 29};
 30use util::http::FakeHttpClient;
 31use workspace::Workspace;
 32
 33mod integration_tests;
 34mod randomized_integration_tests;
 35
 36struct TestServer {
 37    app_state: Arc<AppState>,
 38    server: Arc<Server>,
 39    connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
 40    forbid_connections: Arc<AtomicBool>,
 41    _test_db: TestDb,
 42    test_live_kit_server: Arc<live_kit_client::TestServer>,
 43}
 44
 45impl TestServer {
 46    async fn start(deterministic: &Arc<Deterministic>) -> Self {
 47        static NEXT_LIVE_KIT_SERVER_ID: AtomicUsize = AtomicUsize::new(0);
 48
 49        let use_postgres = env::var("USE_POSTGRES").ok();
 50        let use_postgres = use_postgres.as_deref();
 51        let test_db = if use_postgres == Some("true") || use_postgres == Some("1") {
 52            TestDb::postgres(deterministic.build_background())
 53        } else {
 54            TestDb::sqlite(deterministic.build_background())
 55        };
 56        let live_kit_server_id = NEXT_LIVE_KIT_SERVER_ID.fetch_add(1, SeqCst);
 57        let live_kit_server = live_kit_client::TestServer::create(
 58            format!("http://livekit.{}.test", live_kit_server_id),
 59            format!("devkey-{}", live_kit_server_id),
 60            format!("secret-{}", live_kit_server_id),
 61            deterministic.build_background(),
 62        )
 63        .unwrap();
 64        let app_state = Self::build_app_state(&test_db, &live_kit_server).await;
 65        let epoch = app_state
 66            .db
 67            .create_server(&app_state.config.zed_environment)
 68            .await
 69            .unwrap();
 70        let server = Server::new(
 71            epoch,
 72            app_state.clone(),
 73            Executor::Deterministic(deterministic.build_background()),
 74        );
 75        server.start().await.unwrap();
 76        // Advance clock to ensure the server's cleanup task is finished.
 77        deterministic.advance_clock(CLEANUP_TIMEOUT);
 78        Self {
 79            app_state,
 80            server,
 81            connection_killers: Default::default(),
 82            forbid_connections: Default::default(),
 83            _test_db: test_db,
 84            test_live_kit_server: live_kit_server,
 85        }
 86    }
 87
 88    async fn reset(&self) {
 89        self.app_state.db.reset();
 90        let epoch = self
 91            .app_state
 92            .db
 93            .create_server(&self.app_state.config.zed_environment)
 94            .await
 95            .unwrap();
 96        self.server.reset(epoch);
 97    }
 98
 99    async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
100        cx.update(|cx| {
101            cx.set_global(SettingsStore::test(cx));
102        });
103
104        let http = FakeHttpClient::with_404_response();
105        let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
106        {
107            user.id
108        } else {
109            self.app_state
110                .db
111                .create_user(
112                    &format!("{name}@example.com"),
113                    false,
114                    NewUserParams {
115                        github_login: name.into(),
116                        github_user_id: 0,
117                        invite_count: 0,
118                    },
119                )
120                .await
121                .expect("creating user failed")
122                .user_id
123        };
124        let client_name = name.to_string();
125        let mut client = cx.read(|cx| Client::new(http.clone(), cx));
126        let server = self.server.clone();
127        let db = self.app_state.db.clone();
128        let connection_killers = self.connection_killers.clone();
129        let forbid_connections = self.forbid_connections.clone();
130
131        Arc::get_mut(&mut client)
132            .unwrap()
133            .set_id(user_id.0 as usize)
134            .override_authenticate(move |cx| {
135                cx.spawn(|_| async move {
136                    let access_token = "the-token".to_string();
137                    Ok(Credentials {
138                        user_id: user_id.0 as u64,
139                        access_token,
140                    })
141                })
142            })
143            .override_establish_connection(move |credentials, cx| {
144                assert_eq!(credentials.user_id, user_id.0 as u64);
145                assert_eq!(credentials.access_token, "the-token");
146
147                let server = server.clone();
148                let db = db.clone();
149                let connection_killers = connection_killers.clone();
150                let forbid_connections = forbid_connections.clone();
151                let client_name = client_name.clone();
152                cx.spawn(move |cx| async move {
153                    if forbid_connections.load(SeqCst) {
154                        Err(EstablishConnectionError::other(anyhow!(
155                            "server is forbidding connections"
156                        )))
157                    } else {
158                        let (client_conn, server_conn, killed) =
159                            Connection::in_memory(cx.background());
160                        let (connection_id_tx, connection_id_rx) = oneshot::channel();
161                        let user = db
162                            .get_user_by_id(user_id)
163                            .await
164                            .expect("retrieving user failed")
165                            .unwrap();
166                        cx.background()
167                            .spawn(server.handle_connection(
168                                server_conn,
169                                client_name,
170                                user,
171                                Some(connection_id_tx),
172                                Executor::Deterministic(cx.background()),
173                            ))
174                            .detach();
175                        let connection_id = connection_id_rx.await.unwrap();
176                        connection_killers
177                            .lock()
178                            .insert(connection_id.into(), killed);
179                        Ok(client_conn)
180                    }
181                })
182            });
183
184        let fs = FakeFs::new(cx.background());
185        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
186        let app_state = Arc::new(workspace::AppState {
187            client: client.clone(),
188            user_store: user_store.clone(),
189            languages: Arc::new(LanguageRegistry::test()),
190            fs: fs.clone(),
191            build_window_options: |_, _, _| Default::default(),
192            initialize_workspace: |_, _, _, _| unimplemented!(),
193            background_actions: || &[],
194        });
195
196        cx.update(|cx| {
197            theme::init((), cx);
198            Project::init(&client, cx);
199            client::init(&client, cx);
200            language::init(cx);
201            editor::init_settings(cx);
202            workspace::init(app_state.clone(), cx);
203            audio::init((), 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    ) -> WindowHandle<Workspace> {
467        cx.add_window(|cx| Workspace::test_new(project.clone(), cx))
468    }
469}
470
471impl Drop for TestClient {
472    fn drop(&mut self) {
473        self.client.teardown();
474    }
475}