1use crate::{
2 db::{tests::TestDb, NewUserParams, UserId},
3 executor::Executor,
4 rpc::{Server, CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
5 AppState, Config,
6};
7use anyhow::anyhow;
8use call::ActiveCall;
9use channel::{ChannelBuffer, ChannelStore};
10use client::{
11 self, proto::PeerId, Client, Connection, Credentials, EstablishConnectionError, UserStore,
12};
13use collections::{HashMap, HashSet};
14use fs::FakeFs;
15use futures::{channel::oneshot, StreamExt as _};
16use gpui::{BackgroundExecutor, Context, Model, TestAppContext, View, VisualTestContext};
17use language::LanguageRegistry;
18use node_runtime::FakeNodeRuntime;
19
20use notifications::NotificationStore;
21use parking_lot::Mutex;
22use project::{Project, WorktreeId};
23use rpc::{
24 proto::{self, ChannelRole},
25 RECEIVE_TIMEOUT,
26};
27use serde_json::json;
28use settings::SettingsStore;
29use std::{
30 cell::{Ref, RefCell, RefMut},
31 env,
32 ops::{Deref, DerefMut},
33 path::Path,
34 sync::{
35 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
36 Arc,
37 },
38};
39use util::http::FakeHttpClient;
40use workspace::{Workspace, WorkspaceStore};
41
42pub struct TestServer {
43 pub app_state: Arc<AppState>,
44 pub test_live_kit_server: Arc<live_kit_client::TestServer>,
45 server: Arc<Server>,
46 next_github_user_id: i32,
47 connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
48 forbid_connections: Arc<AtomicBool>,
49 _test_db: TestDb,
50}
51
52pub struct TestClient {
53 pub username: String,
54 pub app_state: Arc<workspace::AppState>,
55 channel_store: Model<ChannelStore>,
56 notification_store: Model<NotificationStore>,
57 state: RefCell<TestClientState>,
58}
59
60#[derive(Default)]
61struct TestClientState {
62 local_projects: Vec<Model<Project>>,
63 remote_projects: Vec<Model<Project>>,
64 buffers: HashMap<Model<Project>, HashSet<Model<language::Buffer>>>,
65 channel_buffers: HashSet<Model<ChannelBuffer>>,
66}
67
68pub struct ContactsSummary {
69 pub current: Vec<String>,
70 pub outgoing_requests: Vec<String>,
71 pub incoming_requests: Vec<String>,
72}
73
74impl TestServer {
75 pub async fn start(deterministic: BackgroundExecutor) -> Self {
76 static NEXT_LIVE_KIT_SERVER_ID: AtomicUsize = AtomicUsize::new(0);
77
78 let use_postgres = env::var("USE_POSTGRES").ok();
79 let use_postgres = use_postgres.as_deref();
80 let test_db = if use_postgres == Some("true") || use_postgres == Some("1") {
81 TestDb::postgres(deterministic.clone())
82 } else {
83 TestDb::sqlite(deterministic.clone())
84 };
85 let live_kit_server_id = NEXT_LIVE_KIT_SERVER_ID.fetch_add(1, SeqCst);
86 let live_kit_server = live_kit_client::TestServer::create(
87 format!("http://livekit.{}.test", live_kit_server_id),
88 format!("devkey-{}", live_kit_server_id),
89 format!("secret-{}", live_kit_server_id),
90 deterministic.clone(),
91 )
92 .unwrap();
93 let app_state = Self::build_app_state(&test_db, &live_kit_server).await;
94 let epoch = app_state
95 .db
96 .create_server(&app_state.config.zed_environment)
97 .await
98 .unwrap();
99 let server = Server::new(
100 epoch,
101 app_state.clone(),
102 Executor::Deterministic(deterministic.clone()),
103 );
104 server.start().await.unwrap();
105 // Advance clock to ensure the server's cleanup task is finished.
106 deterministic.advance_clock(CLEANUP_TIMEOUT);
107 Self {
108 app_state,
109 server,
110 connection_killers: Default::default(),
111 forbid_connections: Default::default(),
112 next_github_user_id: 0,
113 _test_db: test_db,
114 test_live_kit_server: live_kit_server,
115 }
116 }
117
118 pub async fn start2(
119 cx_a: &mut TestAppContext,
120 cx_b: &mut TestAppContext,
121 ) -> (TestClient, TestClient, u64) {
122 let mut server = Self::start(cx_a.executor()).await;
123 let client_a = server.create_client(cx_a, "user_a").await;
124 let client_b = server.create_client(cx_b, "user_b").await;
125 let channel_id = server
126 .make_channel("a", None, (&client_a, cx_a), &mut [(&client_b, cx_b)])
127 .await;
128
129 (client_a, client_b, channel_id)
130 }
131
132 pub async fn start1<'a>(cx: &'a mut TestAppContext) -> TestClient {
133 let mut server = Self::start(cx.executor().clone()).await;
134 server.create_client(cx, "user_a").await
135 }
136
137 pub async fn reset(&self) {
138 self.app_state.db.reset();
139 let epoch = self
140 .app_state
141 .db
142 .create_server(&self.app_state.config.zed_environment)
143 .await
144 .unwrap();
145 self.server.reset(epoch);
146 }
147
148 pub async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
149 cx.update(|cx| {
150 if cx.has_global::<SettingsStore>() {
151 panic!("Same cx used to create two test clients")
152 }
153 let settings = SettingsStore::test(cx);
154 cx.set_global(settings);
155 });
156
157 let http = FakeHttpClient::with_404_response();
158 let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
159 {
160 user.id
161 } else {
162 let github_user_id = self.next_github_user_id;
163 self.next_github_user_id += 1;
164 self.app_state
165 .db
166 .create_user(
167 &format!("{name}@example.com"),
168 false,
169 NewUserParams {
170 github_login: name.into(),
171 github_user_id,
172 },
173 )
174 .await
175 .expect("creating user failed")
176 .user_id
177 };
178 let client_name = name.to_string();
179 let mut client = cx.update(|cx| Client::new(http.clone(), cx));
180 let server = self.server.clone();
181 let db = self.app_state.db.clone();
182 let connection_killers = self.connection_killers.clone();
183 let forbid_connections = self.forbid_connections.clone();
184
185 Arc::get_mut(&mut client)
186 .unwrap()
187 .set_id(user_id.to_proto())
188 .override_authenticate(move |cx| {
189 cx.spawn(|_| async move {
190 let access_token = "the-token".to_string();
191 Ok(Credentials {
192 user_id: user_id.to_proto(),
193 access_token,
194 })
195 })
196 })
197 .override_establish_connection(move |credentials, cx| {
198 assert_eq!(credentials.user_id, user_id.0 as u64);
199 assert_eq!(credentials.access_token, "the-token");
200
201 let server = server.clone();
202 let db = db.clone();
203 let connection_killers = connection_killers.clone();
204 let forbid_connections = forbid_connections.clone();
205 let client_name = client_name.clone();
206 cx.spawn(move |cx| async move {
207 if forbid_connections.load(SeqCst) {
208 Err(EstablishConnectionError::other(anyhow!(
209 "server is forbidding connections"
210 )))
211 } else {
212 let (client_conn, server_conn, killed) =
213 Connection::in_memory(cx.background_executor().clone());
214 let (connection_id_tx, connection_id_rx) = oneshot::channel();
215 let user = db
216 .get_user_by_id(user_id)
217 .await
218 .expect("retrieving user failed")
219 .unwrap();
220 cx.background_executor()
221 .spawn(server.handle_connection(
222 server_conn,
223 client_name,
224 user,
225 None,
226 Some(connection_id_tx),
227 Executor::Deterministic(cx.background_executor().clone()),
228 ))
229 .detach();
230 let connection_id = connection_id_rx.await.unwrap();
231 connection_killers
232 .lock()
233 .insert(connection_id.into(), killed);
234 Ok(client_conn)
235 }
236 })
237 });
238
239 let fs = FakeFs::new(cx.executor());
240 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
241 let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx));
242 let mut language_registry = LanguageRegistry::test();
243 language_registry.set_executor(cx.executor());
244 let app_state = Arc::new(workspace::AppState {
245 client: client.clone(),
246 user_store: user_store.clone(),
247 workspace_store,
248 languages: Arc::new(language_registry),
249 fs: fs.clone(),
250 build_window_options: |_, _, _| Default::default(),
251 node_runtime: FakeNodeRuntime::new(),
252 });
253
254 cx.update(|cx| {
255 theme::init(theme::LoadThemes::JustBase, cx);
256 Project::init(&client, cx);
257 client::init(&client, cx);
258 language::init(cx);
259 editor::init(cx);
260 workspace::init(app_state.clone(), cx);
261 call::init(client.clone(), user_store.clone(), cx);
262 channel::init(&client, user_store.clone(), cx);
263 notifications::init(client.clone(), user_store, cx);
264 collab_ui::init(&app_state, cx);
265 file_finder::init(cx);
266 menu::init();
267 settings::KeymapFile::load_asset("keymaps/default.json", cx).unwrap();
268 });
269
270 client
271 .authenticate_and_connect(false, &cx.to_async())
272 .await
273 .unwrap();
274
275 let client = TestClient {
276 app_state,
277 username: name.to_string(),
278 channel_store: cx.read(ChannelStore::global).clone(),
279 notification_store: cx.read(NotificationStore::global).clone(),
280 state: Default::default(),
281 };
282 client.wait_for_current_user(cx).await;
283 client
284 }
285
286 pub fn disconnect_client(&self, peer_id: PeerId) {
287 self.connection_killers
288 .lock()
289 .remove(&peer_id)
290 .unwrap()
291 .store(true, SeqCst);
292 }
293
294 pub fn simulate_long_connection_interruption(
295 &self,
296 peer_id: PeerId,
297 deterministic: BackgroundExecutor,
298 ) {
299 self.forbid_connections();
300 self.disconnect_client(peer_id);
301 deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
302 self.allow_connections();
303 deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
304 deterministic.run_until_parked();
305 }
306
307 pub fn forbid_connections(&self) {
308 self.forbid_connections.store(true, SeqCst);
309 }
310
311 pub fn allow_connections(&self) {
312 self.forbid_connections.store(false, SeqCst);
313 }
314
315 pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
316 for ix in 1..clients.len() {
317 let (left, right) = clients.split_at_mut(ix);
318 let (client_a, cx_a) = left.last_mut().unwrap();
319 for (client_b, cx_b) in right {
320 client_a
321 .app_state
322 .user_store
323 .update(*cx_a, |store, cx| {
324 store.request_contact(client_b.user_id().unwrap(), cx)
325 })
326 .await
327 .unwrap();
328 cx_a.executor().run_until_parked();
329 client_b
330 .app_state
331 .user_store
332 .update(*cx_b, |store, cx| {
333 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
334 })
335 .await
336 .unwrap();
337 }
338 }
339 }
340
341 pub async fn make_channel(
342 &self,
343 channel: &str,
344 parent: Option<u64>,
345 admin: (&TestClient, &mut TestAppContext),
346 members: &mut [(&TestClient, &mut TestAppContext)],
347 ) -> u64 {
348 let (_, admin_cx) = admin;
349 let channel_id = admin_cx
350 .read(ChannelStore::global)
351 .update(admin_cx, |channel_store, cx| {
352 channel_store.create_channel(channel, parent, cx)
353 })
354 .await
355 .unwrap();
356
357 for (member_client, member_cx) in members {
358 admin_cx
359 .read(ChannelStore::global)
360 .update(admin_cx, |channel_store, cx| {
361 channel_store.invite_member(
362 channel_id,
363 member_client.user_id().unwrap(),
364 ChannelRole::Member,
365 cx,
366 )
367 })
368 .await
369 .unwrap();
370
371 admin_cx.executor().run_until_parked();
372
373 member_cx
374 .read(ChannelStore::global)
375 .update(*member_cx, |channels, cx| {
376 channels.respond_to_channel_invite(channel_id, true, cx)
377 })
378 .await
379 .unwrap();
380 }
381
382 channel_id
383 }
384
385 pub async fn make_public_channel(
386 &self,
387 channel: &str,
388 client: &TestClient,
389 cx: &mut TestAppContext,
390 ) -> u64 {
391 let channel_id = self
392 .make_channel(channel, None, (client, cx), &mut [])
393 .await;
394
395 client
396 .channel_store()
397 .update(cx, |channel_store, cx| {
398 channel_store.set_channel_visibility(
399 channel_id,
400 proto::ChannelVisibility::Public,
401 cx,
402 )
403 })
404 .await
405 .unwrap();
406
407 channel_id
408 }
409
410 pub async fn make_channel_tree(
411 &self,
412 channels: &[(&str, Option<&str>)],
413 creator: (&TestClient, &mut TestAppContext),
414 ) -> Vec<u64> {
415 let mut observed_channels = HashMap::default();
416 let mut result = Vec::new();
417 for (channel, parent) in channels {
418 let id;
419 if let Some(parent) = parent {
420 if let Some(parent_id) = observed_channels.get(parent) {
421 id = self
422 .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
423 .await;
424 } else {
425 panic!(
426 "Edge {}->{} referenced before {} was created",
427 parent, channel, parent
428 )
429 }
430 } else {
431 id = self
432 .make_channel(channel, None, (creator.0, creator.1), &mut [])
433 .await;
434 }
435
436 observed_channels.insert(channel, id);
437 result.push(id);
438 }
439
440 result
441 }
442
443 pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
444 self.make_contacts(clients).await;
445
446 let (left, right) = clients.split_at_mut(1);
447 let (_client_a, cx_a) = &mut left[0];
448 let active_call_a = cx_a.read(ActiveCall::global);
449
450 for (client_b, cx_b) in right {
451 let user_id_b = client_b.current_user_id(*cx_b).to_proto();
452 active_call_a
453 .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
454 .await
455 .unwrap();
456
457 cx_b.executor().run_until_parked();
458 let active_call_b = cx_b.read(ActiveCall::global);
459 active_call_b
460 .update(*cx_b, |call, cx| call.accept_incoming(cx))
461 .await
462 .unwrap();
463 }
464 }
465
466 pub async fn build_app_state(
467 test_db: &TestDb,
468 fake_server: &live_kit_client::TestServer,
469 ) -> Arc<AppState> {
470 Arc::new(AppState {
471 db: test_db.db().clone(),
472 live_kit_client: Some(Arc::new(fake_server.create_api_client())),
473 config: Config {
474 http_port: 0,
475 database_url: "".into(),
476 database_max_connections: 0,
477 api_token: "".into(),
478 invite_link_prefix: "".into(),
479 live_kit_server: None,
480 live_kit_key: None,
481 live_kit_secret: None,
482 rust_log: None,
483 log_json: None,
484 zed_environment: "test".into(),
485 },
486 })
487 }
488}
489
490impl Deref for TestServer {
491 type Target = Server;
492
493 fn deref(&self) -> &Self::Target {
494 &self.server
495 }
496}
497
498impl Drop for TestServer {
499 fn drop(&mut self) {
500 self.server.teardown();
501 self.test_live_kit_server.teardown().unwrap();
502 }
503}
504
505impl Deref for TestClient {
506 type Target = Arc<Client>;
507
508 fn deref(&self) -> &Self::Target {
509 &self.app_state.client
510 }
511}
512
513impl TestClient {
514 pub fn fs(&self) -> &FakeFs {
515 self.app_state.fs.as_fake()
516 }
517
518 pub fn channel_store(&self) -> &Model<ChannelStore> {
519 &self.channel_store
520 }
521
522 pub fn notification_store(&self) -> &Model<NotificationStore> {
523 &self.notification_store
524 }
525
526 pub fn user_store(&self) -> &Model<UserStore> {
527 &self.app_state.user_store
528 }
529
530 pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
531 &self.app_state.languages
532 }
533
534 pub fn client(&self) -> &Arc<Client> {
535 &self.app_state.client
536 }
537
538 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
539 UserId::from_proto(
540 self.app_state
541 .user_store
542 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
543 )
544 }
545
546 pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
547 let mut authed_user = self
548 .app_state
549 .user_store
550 .read_with(cx, |user_store, _| user_store.watch_current_user());
551 while authed_user.next().await.unwrap().is_none() {}
552 }
553
554 pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
555 self.app_state
556 .user_store
557 .update(cx, |store, _| store.clear_contacts())
558 .await;
559 }
560
561 pub fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<Model<Project>>> + 'a {
562 Ref::map(self.state.borrow(), |state| &state.local_projects)
563 }
564
565 pub fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<Model<Project>>> + 'a {
566 Ref::map(self.state.borrow(), |state| &state.remote_projects)
567 }
568
569 pub fn local_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<Model<Project>>> + 'a {
570 RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
571 }
572
573 pub fn remote_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<Model<Project>>> + 'a {
574 RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
575 }
576
577 pub fn buffers_for_project<'a>(
578 &'a self,
579 project: &Model<Project>,
580 ) -> impl DerefMut<Target = HashSet<Model<language::Buffer>>> + 'a {
581 RefMut::map(self.state.borrow_mut(), |state| {
582 state.buffers.entry(project.clone()).or_default()
583 })
584 }
585
586 pub fn buffers<'a>(
587 &'a self,
588 ) -> impl DerefMut<Target = HashMap<Model<Project>, HashSet<Model<language::Buffer>>>> + 'a
589 {
590 RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
591 }
592
593 pub fn channel_buffers<'a>(
594 &'a self,
595 ) -> impl DerefMut<Target = HashSet<Model<ChannelBuffer>>> + 'a {
596 RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
597 }
598
599 pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
600 self.app_state
601 .user_store
602 .read_with(cx, |store, _| ContactsSummary {
603 current: store
604 .contacts()
605 .iter()
606 .map(|contact| contact.user.github_login.clone())
607 .collect(),
608 outgoing_requests: store
609 .outgoing_contact_requests()
610 .iter()
611 .map(|user| user.github_login.clone())
612 .collect(),
613 incoming_requests: store
614 .incoming_contact_requests()
615 .iter()
616 .map(|user| user.github_login.clone())
617 .collect(),
618 })
619 }
620
621 pub async fn build_local_project(
622 &self,
623 root_path: impl AsRef<Path>,
624 cx: &mut TestAppContext,
625 ) -> (Model<Project>, WorktreeId) {
626 let project = self.build_empty_local_project(cx);
627 let (worktree, _) = project
628 .update(cx, |p, cx| {
629 p.find_or_create_local_worktree(root_path, true, cx)
630 })
631 .await
632 .unwrap();
633 worktree
634 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
635 .await;
636 (project, worktree.read_with(cx, |tree, _| tree.id()))
637 }
638
639 pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Model<Project> {
640 self.fs()
641 .insert_tree(
642 "/a",
643 json!({
644 "1.txt": "one\none\none",
645 "2.js": "function two() { return 2; }",
646 "3.rs": "mod test",
647 }),
648 )
649 .await;
650 self.build_local_project("/a", cx).await.0
651 }
652
653 pub async fn host_workspace(
654 &self,
655 workspace: &View<Workspace>,
656 channel_id: u64,
657 cx: &mut VisualTestContext,
658 ) {
659 cx.update(|cx| {
660 let active_call = ActiveCall::global(cx);
661 active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
662 })
663 .await
664 .unwrap();
665 cx.update(|cx| {
666 let active_call = ActiveCall::global(cx);
667 let project = workspace.read(cx).project().clone();
668 active_call.update(cx, |call, cx| call.share_project(project, cx))
669 })
670 .await
671 .unwrap();
672 cx.executor().run_until_parked();
673 }
674
675 pub async fn join_workspace<'a>(
676 &'a self,
677 channel_id: u64,
678 cx: &'a mut TestAppContext,
679 ) -> (View<Workspace>, &'a mut VisualTestContext) {
680 cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
681 .await
682 .unwrap();
683 cx.run_until_parked();
684
685 self.active_workspace(cx)
686 }
687
688 pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Model<Project> {
689 cx.update(|cx| {
690 Project::local(
691 self.client().clone(),
692 self.app_state.node_runtime.clone(),
693 self.app_state.user_store.clone(),
694 self.app_state.languages.clone(),
695 self.app_state.fs.clone(),
696 cx,
697 )
698 })
699 }
700
701 pub async fn build_remote_project(
702 &self,
703 host_project_id: u64,
704 guest_cx: &mut TestAppContext,
705 ) -> Model<Project> {
706 let active_call = guest_cx.read(ActiveCall::global);
707 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
708 room.update(guest_cx, |room, cx| {
709 room.join_project(
710 host_project_id,
711 self.app_state.languages.clone(),
712 self.app_state.fs.clone(),
713 cx,
714 )
715 })
716 .await
717 .unwrap()
718 }
719
720 pub fn build_workspace<'a>(
721 &'a self,
722 project: &Model<Project>,
723 cx: &'a mut TestAppContext,
724 ) -> (View<Workspace>, &'a mut VisualTestContext) {
725 cx.add_window_view(|cx| {
726 cx.activate_window();
727 Workspace::new(0, project.clone(), self.app_state.clone(), cx)
728 })
729 }
730
731 pub async fn build_test_workspace<'a>(
732 &'a self,
733 cx: &'a mut TestAppContext,
734 ) -> (View<Workspace>, &'a mut VisualTestContext) {
735 let project = self.build_test_project(cx).await;
736 cx.add_window_view(|cx| {
737 cx.activate_window();
738 Workspace::new(0, project.clone(), self.app_state.clone(), cx)
739 })
740 }
741
742 pub fn active_workspace<'a>(
743 &'a self,
744 cx: &'a mut TestAppContext,
745 ) -> (View<Workspace>, &'a mut VisualTestContext) {
746 let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
747
748 let view = window.root_view(cx).unwrap();
749 let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
750 // it might be nice to try and cleanup these at the end of each test.
751 (view, cx)
752 }
753}
754
755impl Drop for TestClient {
756 fn drop(&mut self) {
757 self.app_state.client.teardown();
758 }
759}