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 invite_link_prefix: "".into(),
469 live_kit_server: None,
470 live_kit_key: None,
471 live_kit_secret: None,
472 rust_log: None,
473 log_json: None,
474 zed_environment: "test".into(),
475 },
476 })
477 }
478}
479
480impl Deref for TestServer {
481 type Target = Server;
482
483 fn deref(&self) -> &Self::Target {
484 &self.server
485 }
486}
487
488impl Drop for TestServer {
489 fn drop(&mut self) {
490 self.server.teardown();
491 self.test_live_kit_server.teardown().unwrap();
492 }
493}
494
495impl Deref for TestClient {
496 type Target = Arc<Client>;
497
498 fn deref(&self) -> &Self::Target {
499 &self.app_state.client
500 }
501}
502
503impl TestClient {
504 pub fn fs(&self) -> &FakeFs {
505 self.app_state.fs.as_fake()
506 }
507
508 pub fn channel_store(&self) -> &Model<ChannelStore> {
509 &self.channel_store
510 }
511
512 pub fn notification_store(&self) -> &Model<NotificationStore> {
513 &self.notification_store
514 }
515
516 pub fn user_store(&self) -> &Model<UserStore> {
517 &self.app_state.user_store
518 }
519
520 pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
521 &self.app_state.languages
522 }
523
524 pub fn client(&self) -> &Arc<Client> {
525 &self.app_state.client
526 }
527
528 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
529 UserId::from_proto(
530 self.app_state
531 .user_store
532 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
533 )
534 }
535
536 pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
537 let mut authed_user = self
538 .app_state
539 .user_store
540 .read_with(cx, |user_store, _| user_store.watch_current_user());
541 while authed_user.next().await.unwrap().is_none() {}
542 }
543
544 pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
545 self.app_state
546 .user_store
547 .update(cx, |store, _| store.clear_contacts())
548 .await;
549 }
550
551 pub fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<Model<Project>>> + 'a {
552 Ref::map(self.state.borrow(), |state| &state.local_projects)
553 }
554
555 pub fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<Model<Project>>> + 'a {
556 Ref::map(self.state.borrow(), |state| &state.remote_projects)
557 }
558
559 pub fn local_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<Model<Project>>> + 'a {
560 RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
561 }
562
563 pub fn remote_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<Model<Project>>> + 'a {
564 RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
565 }
566
567 pub fn buffers_for_project<'a>(
568 &'a self,
569 project: &Model<Project>,
570 ) -> impl DerefMut<Target = HashSet<Model<language::Buffer>>> + 'a {
571 RefMut::map(self.state.borrow_mut(), |state| {
572 state.buffers.entry(project.clone()).or_default()
573 })
574 }
575
576 pub fn buffers<'a>(
577 &'a self,
578 ) -> impl DerefMut<Target = HashMap<Model<Project>, HashSet<Model<language::Buffer>>>> + 'a
579 {
580 RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
581 }
582
583 pub fn channel_buffers<'a>(
584 &'a self,
585 ) -> impl DerefMut<Target = HashSet<Model<ChannelBuffer>>> + 'a {
586 RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
587 }
588
589 pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
590 self.app_state
591 .user_store
592 .read_with(cx, |store, _| ContactsSummary {
593 current: store
594 .contacts()
595 .iter()
596 .map(|contact| contact.user.github_login.clone())
597 .collect(),
598 outgoing_requests: store
599 .outgoing_contact_requests()
600 .iter()
601 .map(|user| user.github_login.clone())
602 .collect(),
603 incoming_requests: store
604 .incoming_contact_requests()
605 .iter()
606 .map(|user| user.github_login.clone())
607 .collect(),
608 })
609 }
610
611 pub async fn build_local_project(
612 &self,
613 root_path: impl AsRef<Path>,
614 cx: &mut TestAppContext,
615 ) -> (Model<Project>, WorktreeId) {
616 let project = self.build_empty_local_project(cx);
617 let (worktree, _) = project
618 .update(cx, |p, cx| {
619 p.find_or_create_local_worktree(root_path, true, cx)
620 })
621 .await
622 .unwrap();
623 worktree
624 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
625 .await;
626 (project, worktree.read_with(cx, |tree, _| tree.id()))
627 }
628
629 pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Model<Project> {
630 self.fs()
631 .insert_tree(
632 "/a",
633 json!({
634 "1.txt": "one\none\none",
635 "2.js": "function two() { return 2; }",
636 "3.rs": "mod test",
637 }),
638 )
639 .await;
640 self.build_local_project("/a", cx).await.0
641 }
642
643 pub async fn host_workspace(
644 &self,
645 workspace: &View<Workspace>,
646 channel_id: u64,
647 cx: &mut VisualTestContext,
648 ) {
649 cx.update(|cx| {
650 let active_call = ActiveCall::global(cx);
651 active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
652 })
653 .await
654 .unwrap();
655 cx.update(|cx| {
656 let active_call = ActiveCall::global(cx);
657 let project = workspace.read(cx).project().clone();
658 active_call.update(cx, |call, cx| call.share_project(project, cx))
659 })
660 .await
661 .unwrap();
662 cx.executor().run_until_parked();
663 }
664
665 pub async fn join_workspace<'a>(
666 &'a self,
667 channel_id: u64,
668 cx: &'a mut TestAppContext,
669 ) -> (View<Workspace>, &'a mut VisualTestContext) {
670 cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
671 .await
672 .unwrap();
673 cx.run_until_parked();
674
675 self.active_workspace(cx)
676 }
677
678 pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Model<Project> {
679 cx.update(|cx| {
680 Project::local(
681 self.client().clone(),
682 self.app_state.node_runtime.clone(),
683 self.app_state.user_store.clone(),
684 self.app_state.languages.clone(),
685 self.app_state.fs.clone(),
686 cx,
687 )
688 })
689 }
690
691 pub async fn build_remote_project(
692 &self,
693 host_project_id: u64,
694 guest_cx: &mut TestAppContext,
695 ) -> Model<Project> {
696 let active_call = guest_cx.read(ActiveCall::global);
697 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
698 room.update(guest_cx, |room, cx| {
699 room.join_project(
700 host_project_id,
701 self.app_state.languages.clone(),
702 self.app_state.fs.clone(),
703 cx,
704 )
705 })
706 .await
707 .unwrap()
708 }
709
710 pub fn build_workspace<'a>(
711 &'a self,
712 project: &Model<Project>,
713 cx: &'a mut TestAppContext,
714 ) -> (View<Workspace>, &'a mut VisualTestContext) {
715 cx.add_window_view(|cx| {
716 cx.activate_window();
717 Workspace::new(0, project.clone(), self.app_state.clone(), cx)
718 })
719 }
720
721 pub async fn build_test_workspace<'a>(
722 &'a self,
723 cx: &'a mut TestAppContext,
724 ) -> (View<Workspace>, &'a mut VisualTestContext) {
725 let project = self.build_test_project(cx).await;
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 fn active_workspace<'a>(
733 &'a self,
734 cx: &'a mut TestAppContext,
735 ) -> (View<Workspace>, &'a mut VisualTestContext) {
736 let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
737
738 let view = window.root_view(cx).unwrap();
739 let cx = Box::new(VisualTestContext::from_window(*window.deref(), cx));
740 // it might be nice to try and cleanup these at the end of each test.
741 (view, Box::leak(cx))
742 }
743}
744
745impl Drop for TestClient {
746 fn drop(&mut self) {
747 self.app_state.client.teardown();
748 }
749}