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, test::FakeHttpClient, Client, Connection, Credentials,
 11    EstablishConnectionError, UserStore,
 12};
 13use collections::{HashMap, HashSet};
 14use fs::FakeFs;
 15use futures::{channel::oneshot, StreamExt as _};
 16use gpui::{executor::Deterministic, test::EmptyView, ModelHandle, TestAppContext, ViewHandle};
 17use language::LanguageRegistry;
 18use parking_lot::Mutex;
 19use project::{Project, WorktreeId};
 20use settings::Settings;
 21use std::{
 22    env,
 23    ops::Deref,
 24    path::{Path, PathBuf},
 25    sync::{
 26        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
 27        Arc,
 28    },
 29};
 30use theme::ThemeRegistry;
 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(Settings::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            themes: ThemeRegistry::new((), cx.font_cache()),
191            fs: fs.clone(),
192            build_window_options: |_, _, _| Default::default(),
193            initialize_workspace: |_, _, _| unimplemented!(),
194            dock_default_item_factory: |_, _| None,
195            background_actions: || &[],
196        });
197
198        Project::init(&client);
199        cx.update(|cx| {
200            workspace::init(app_state.clone(), cx);
201            call::init(client.clone(), user_store.clone(), cx);
202        });
203
204        client
205            .authenticate_and_connect(false, &cx.to_async())
206            .await
207            .unwrap();
208
209        let client = TestClient {
210            client,
211            username: name.to_string(),
212            local_projects: Default::default(),
213            remote_projects: Default::default(),
214            next_root_dir_id: 0,
215            user_store,
216            fs,
217            language_registry: Arc::new(LanguageRegistry::test()),
218            buffers: Default::default(),
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    local_projects: Vec<ModelHandle<Project>>,
318    remote_projects: Vec<ModelHandle<Project>>,
319    next_root_dir_id: usize,
320    pub user_store: ModelHandle<UserStore>,
321    language_registry: Arc<LanguageRegistry>,
322    fs: Arc<FakeFs>,
323    buffers: HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>,
324}
325
326impl Deref for TestClient {
327    type Target = Arc<Client>;
328
329    fn deref(&self) -> &Self::Target {
330        &self.client
331    }
332}
333
334struct ContactsSummary {
335    pub current: Vec<String>,
336    pub outgoing_requests: Vec<String>,
337    pub incoming_requests: Vec<String>,
338}
339
340impl TestClient {
341    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
342        UserId::from_proto(
343            self.user_store
344                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
345        )
346    }
347
348    async fn wait_for_current_user(&self, cx: &TestAppContext) {
349        let mut authed_user = self
350            .user_store
351            .read_with(cx, |user_store, _| user_store.watch_current_user());
352        while authed_user.next().await.unwrap().is_none() {}
353    }
354
355    async fn clear_contacts(&self, cx: &mut TestAppContext) {
356        self.user_store
357            .update(cx, |store, _| store.clear_contacts())
358            .await;
359    }
360
361    fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
362        self.user_store.read_with(cx, |store, _| ContactsSummary {
363            current: store
364                .contacts()
365                .iter()
366                .map(|contact| contact.user.github_login.clone())
367                .collect(),
368            outgoing_requests: store
369                .outgoing_contact_requests()
370                .iter()
371                .map(|user| user.github_login.clone())
372                .collect(),
373            incoming_requests: store
374                .incoming_contact_requests()
375                .iter()
376                .map(|user| user.github_login.clone())
377                .collect(),
378        })
379    }
380
381    async fn build_local_project(
382        &self,
383        root_path: impl AsRef<Path>,
384        cx: &mut TestAppContext,
385    ) -> (ModelHandle<Project>, WorktreeId) {
386        let project = cx.update(|cx| {
387            Project::local(
388                self.client.clone(),
389                self.user_store.clone(),
390                self.language_registry.clone(),
391                self.fs.clone(),
392                cx,
393            )
394        });
395        let (worktree, _) = project
396            .update(cx, |p, cx| {
397                p.find_or_create_local_worktree(root_path, true, cx)
398            })
399            .await
400            .unwrap();
401        worktree
402            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
403            .await;
404        (project, worktree.read_with(cx, |tree, _| tree.id()))
405    }
406
407    async fn build_remote_project(
408        &self,
409        host_project_id: u64,
410        guest_cx: &mut TestAppContext,
411    ) -> ModelHandle<Project> {
412        let active_call = guest_cx.read(ActiveCall::global);
413        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
414        room.update(guest_cx, |room, cx| {
415            room.join_project(
416                host_project_id,
417                self.language_registry.clone(),
418                self.fs.clone(),
419                cx,
420            )
421        })
422        .await
423        .unwrap()
424    }
425
426    fn build_workspace(
427        &self,
428        project: &ModelHandle<Project>,
429        cx: &mut TestAppContext,
430    ) -> ViewHandle<Workspace> {
431        let (_, root_view) = cx.add_window(|_| EmptyView);
432        cx.add_view(&root_view, |cx| Workspace::test_new(project.clone(), cx))
433    }
434
435    fn create_new_root_dir(&mut self) -> PathBuf {
436        format!(
437            "/{}-root-{}",
438            self.username,
439            util::post_inc(&mut self.next_root_dir_id)
440        )
441        .into()
442    }
443}
444
445impl Drop for TestClient {
446    fn drop(&mut self) {
447        self.client.teardown();
448    }
449}