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