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