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