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