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