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