1use crate::{
2 auth::split_dev_server_token,
3 db::{tests::TestDb, NewUserParams, UserId},
4 executor::Executor,
5 rpc::{Principal, Server, ZedVersion, CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
6 AppState, Config, RateLimiter,
7};
8use anyhow::anyhow;
9use call::ActiveCall;
10use channel::{ChannelBuffer, ChannelStore};
11use client::{
12 self, proto::PeerId, ChannelId, Client, Connection, Credentials, EstablishConnectionError,
13 UserStore,
14};
15use clock::FakeSystemClock;
16use collab_ui::channel_view::ChannelView;
17use collections::{HashMap, HashSet};
18use fs::FakeFs;
19use futures::{channel::oneshot, StreamExt as _};
20use git::GitHostingProviderRegistry;
21use gpui::{BackgroundExecutor, Context, Model, Task, TestAppContext, View, VisualTestContext};
22use language::LanguageRegistry;
23use node_runtime::FakeNodeRuntime;
24use notifications::NotificationStore;
25use parking_lot::Mutex;
26use project::{Project, WorktreeId};
27use rpc::{
28 proto::{self, ChannelRole},
29 RECEIVE_TIMEOUT,
30};
31use semantic_version::SemanticVersion;
32use serde_json::json;
33use settings::SettingsStore;
34use std::{
35 cell::{Ref, RefCell, RefMut},
36 env,
37 ops::{Deref, DerefMut},
38 path::Path,
39 sync::{
40 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
41 Arc,
42 },
43};
44use util::http::FakeHttpClient;
45use workspace::{Workspace, WorkspaceId, WorkspaceStore};
46
47pub struct TestServer {
48 pub app_state: Arc<AppState>,
49 pub test_live_kit_server: Arc<live_kit_client::TestServer>,
50 server: Arc<Server>,
51 next_github_user_id: i32,
52 connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
53 forbid_connections: Arc<AtomicBool>,
54 _test_db: TestDb,
55}
56
57pub struct TestClient {
58 pub username: String,
59 pub app_state: Arc<workspace::AppState>,
60 channel_store: Model<ChannelStore>,
61 notification_store: Model<NotificationStore>,
62 state: RefCell<TestClientState>,
63}
64
65#[derive(Default)]
66struct TestClientState {
67 local_projects: Vec<Model<Project>>,
68 dev_server_projects: Vec<Model<Project>>,
69 buffers: HashMap<Model<Project>, HashSet<Model<language::Buffer>>>,
70 channel_buffers: HashSet<Model<ChannelBuffer>>,
71}
72
73pub struct ContactsSummary {
74 pub current: Vec<String>,
75 pub outgoing_requests: Vec<String>,
76 pub incoming_requests: Vec<String>,
77}
78
79impl TestServer {
80 pub async fn start(deterministic: BackgroundExecutor) -> Self {
81 static NEXT_LIVE_KIT_SERVER_ID: AtomicUsize = AtomicUsize::new(0);
82
83 let use_postgres = env::var("USE_POSTGRES").ok();
84 let use_postgres = use_postgres.as_deref();
85 let test_db = if use_postgres == Some("true") || use_postgres == Some("1") {
86 TestDb::postgres(deterministic.clone())
87 } else {
88 TestDb::sqlite(deterministic.clone())
89 };
90 let live_kit_server_id = NEXT_LIVE_KIT_SERVER_ID.fetch_add(1, SeqCst);
91 let live_kit_server = live_kit_client::TestServer::create(
92 format!("http://livekit.{}.test", live_kit_server_id),
93 format!("devkey-{}", live_kit_server_id),
94 format!("secret-{}", live_kit_server_id),
95 deterministic.clone(),
96 )
97 .unwrap();
98 let executor = Executor::Deterministic(deterministic.clone());
99 let app_state = Self::build_app_state(&test_db, &live_kit_server, executor.clone()).await;
100 let epoch = app_state
101 .db
102 .create_server(&app_state.config.zed_environment)
103 .await
104 .unwrap();
105 let server = Server::new(epoch, app_state.clone());
106 server.start().await.unwrap();
107 // Advance clock to ensure the server's cleanup task is finished.
108 deterministic.advance_clock(CLEANUP_TIMEOUT);
109 Self {
110 app_state,
111 server,
112 connection_killers: Default::default(),
113 forbid_connections: Default::default(),
114 next_github_user_id: 0,
115 _test_db: test_db,
116 test_live_kit_server: live_kit_server,
117 }
118 }
119
120 pub async fn start2(
121 cx_a: &mut TestAppContext,
122 cx_b: &mut TestAppContext,
123 ) -> (TestServer, TestClient, TestClient, ChannelId) {
124 let mut server = Self::start(cx_a.executor()).await;
125 let client_a = server.create_client(cx_a, "user_a").await;
126 let client_b = server.create_client(cx_b, "user_b").await;
127 let channel_id = server
128 .make_channel(
129 "test-channel",
130 None,
131 (&client_a, cx_a),
132 &mut [(&client_b, cx_b)],
133 )
134 .await;
135 cx_a.run_until_parked();
136
137 (server, client_a, client_b, channel_id)
138 }
139
140 pub async fn start1(cx: &mut TestAppContext) -> (TestServer, TestClient) {
141 let mut server = Self::start(cx.executor().clone()).await;
142 let client = server.create_client(cx, "user_a").await;
143 (server, client)
144 }
145
146 pub async fn reset(&self) {
147 self.app_state.db.reset();
148 let epoch = self
149 .app_state
150 .db
151 .create_server(&self.app_state.config.zed_environment)
152 .await
153 .unwrap();
154 self.server.reset(epoch);
155 }
156
157 pub async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
158 cx.update(|cx| {
159 if cx.has_global::<SettingsStore>() {
160 panic!("Same cx used to create two test clients")
161 }
162 let settings = SettingsStore::test(cx);
163 cx.set_global(settings);
164 release_channel::init("0.0.0", cx);
165 client::init_settings(cx);
166 });
167
168 let clock = Arc::new(FakeSystemClock::default());
169 let http = FakeHttpClient::with_404_response();
170 let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
171 {
172 user.id
173 } else {
174 let github_user_id = self.next_github_user_id;
175 self.next_github_user_id += 1;
176 self.app_state
177 .db
178 .create_user(
179 &format!("{name}@example.com"),
180 false,
181 NewUserParams {
182 github_login: name.into(),
183 github_user_id,
184 },
185 )
186 .await
187 .expect("creating user failed")
188 .user_id
189 };
190 let client_name = name.to_string();
191 let mut client = cx.update(|cx| Client::new(clock, http.clone(), cx));
192 let server = self.server.clone();
193 let db = self.app_state.db.clone();
194 let connection_killers = self.connection_killers.clone();
195 let forbid_connections = self.forbid_connections.clone();
196
197 Arc::get_mut(&mut client)
198 .unwrap()
199 .set_id(user_id.to_proto())
200 .override_authenticate(move |cx| {
201 cx.spawn(|_| async move {
202 let access_token = "the-token".to_string();
203 Ok(Credentials::User {
204 user_id: user_id.to_proto(),
205 access_token,
206 })
207 })
208 })
209 .override_establish_connection(move |credentials, cx| {
210 assert_eq!(
211 credentials,
212 &Credentials::User {
213 user_id: user_id.0 as u64,
214 access_token: "the-token".into()
215 }
216 );
217
218 let server = server.clone();
219 let db = db.clone();
220 let connection_killers = connection_killers.clone();
221 let forbid_connections = forbid_connections.clone();
222 let client_name = client_name.clone();
223 cx.spawn(move |cx| async move {
224 if forbid_connections.load(SeqCst) {
225 Err(EstablishConnectionError::other(anyhow!(
226 "server is forbidding connections"
227 )))
228 } else {
229 let (client_conn, server_conn, killed) =
230 Connection::in_memory(cx.background_executor().clone());
231 let (connection_id_tx, connection_id_rx) = oneshot::channel();
232 let user = db
233 .get_user_by_id(user_id)
234 .await
235 .expect("retrieving user failed")
236 .unwrap();
237 cx.background_executor()
238 .spawn(server.handle_connection(
239 server_conn,
240 client_name,
241 Principal::User(user),
242 ZedVersion(SemanticVersion::new(1, 0, 0)),
243 Some(connection_id_tx),
244 Executor::Deterministic(cx.background_executor().clone()),
245 ))
246 .detach();
247 let connection_id = connection_id_rx.await.map_err(|e| {
248 EstablishConnectionError::Other(anyhow!(
249 "{} (is server shutting down?)",
250 e
251 ))
252 })?;
253 connection_killers
254 .lock()
255 .insert(connection_id.into(), killed);
256 Ok(client_conn)
257 }
258 })
259 });
260
261 let git_hosting_provider_registry =
262 cx.update(|cx| GitHostingProviderRegistry::default_global(cx));
263 git_hosting_provider_registry
264 .register_hosting_provider(Arc::new(git_hosting_providers::Github));
265
266 let fs = FakeFs::new(cx.executor());
267 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
268 let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx));
269 let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
270 let app_state = Arc::new(workspace::AppState {
271 client: client.clone(),
272 user_store: user_store.clone(),
273 workspace_store,
274 languages: language_registry,
275 fs: fs.clone(),
276 build_window_options: |_, _| Default::default(),
277 node_runtime: FakeNodeRuntime::new(),
278 });
279
280 let os_keymap = if cfg!(target_os = "linux") {
281 "keymaps/default-linux.json"
282 } else {
283 "keymaps/default-macos.json"
284 };
285
286 cx.update(|cx| {
287 theme::init(theme::LoadThemes::JustBase, cx);
288 Project::init(&client, cx);
289 client::init(&client, cx);
290 language::init(cx);
291 editor::init(cx);
292 workspace::init(app_state.clone(), cx);
293 call::init(client.clone(), user_store.clone(), cx);
294 channel::init(&client, user_store.clone(), cx);
295 notifications::init(client.clone(), user_store, cx);
296 collab_ui::init(&app_state, cx);
297 file_finder::init(cx);
298 menu::init();
299 dev_server_projects::init(client.clone(), cx);
300 settings::KeymapFile::load_asset(os_keymap, cx).unwrap();
301 });
302
303 client
304 .authenticate_and_connect(false, &cx.to_async())
305 .await
306 .unwrap();
307
308 let client = TestClient {
309 app_state,
310 username: name.to_string(),
311 channel_store: cx.read(ChannelStore::global).clone(),
312 notification_store: cx.read(NotificationStore::global).clone(),
313 state: Default::default(),
314 };
315 client.wait_for_current_user(cx).await;
316 client
317 }
318
319 pub async fn create_dev_server(
320 &self,
321 access_token: String,
322 cx: &mut TestAppContext,
323 ) -> TestClient {
324 cx.update(|cx| {
325 if cx.has_global::<SettingsStore>() {
326 panic!("Same cx used to create two test clients")
327 }
328 let settings = SettingsStore::test(cx);
329 cx.set_global(settings);
330 release_channel::init("0.0.0", cx);
331 client::init_settings(cx);
332 });
333 let (dev_server_id, _) = split_dev_server_token(&access_token).unwrap();
334
335 let clock = Arc::new(FakeSystemClock::default());
336 let http = FakeHttpClient::with_404_response();
337 let mut client = cx.update(|cx| Client::new(clock, http.clone(), cx));
338 let server = self.server.clone();
339 let db = self.app_state.db.clone();
340 let connection_killers = self.connection_killers.clone();
341 let forbid_connections = self.forbid_connections.clone();
342 Arc::get_mut(&mut client)
343 .unwrap()
344 .set_id(1)
345 .set_dev_server_token(client::DevServerToken(access_token.clone()))
346 .override_establish_connection(move |credentials, cx| {
347 assert_eq!(
348 credentials,
349 &Credentials::DevServer {
350 token: client::DevServerToken(access_token.to_string())
351 }
352 );
353
354 let server = server.clone();
355 let db = db.clone();
356 let connection_killers = connection_killers.clone();
357 let forbid_connections = forbid_connections.clone();
358 cx.spawn(move |cx| async move {
359 if forbid_connections.load(SeqCst) {
360 Err(EstablishConnectionError::other(anyhow!(
361 "server is forbidding connections"
362 )))
363 } else {
364 let (client_conn, server_conn, killed) =
365 Connection::in_memory(cx.background_executor().clone());
366 let (connection_id_tx, connection_id_rx) = oneshot::channel();
367 let dev_server = db
368 .get_dev_server(dev_server_id)
369 .await
370 .expect("retrieving dev_server failed");
371 cx.background_executor()
372 .spawn(server.handle_connection(
373 server_conn,
374 "dev-server".to_string(),
375 Principal::DevServer(dev_server),
376 ZedVersion(SemanticVersion::new(1, 0, 0)),
377 Some(connection_id_tx),
378 Executor::Deterministic(cx.background_executor().clone()),
379 ))
380 .detach();
381 let connection_id = connection_id_rx.await.map_err(|e| {
382 EstablishConnectionError::Other(anyhow!(
383 "{} (is server shutting down?)",
384 e
385 ))
386 })?;
387 connection_killers
388 .lock()
389 .insert(connection_id.into(), killed);
390 Ok(client_conn)
391 }
392 })
393 });
394
395 let fs = FakeFs::new(cx.executor());
396 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
397 let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx));
398 let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
399 let app_state = Arc::new(workspace::AppState {
400 client: client.clone(),
401 user_store: user_store.clone(),
402 workspace_store,
403 languages: language_registry,
404 fs: fs.clone(),
405 build_window_options: |_, _| Default::default(),
406 node_runtime: FakeNodeRuntime::new(),
407 });
408
409 cx.update(|cx| {
410 theme::init(theme::LoadThemes::JustBase, cx);
411 Project::init(&client, cx);
412 client::init(&client, cx);
413 language::init(cx);
414 editor::init(cx);
415 workspace::init(app_state.clone(), cx);
416 call::init(client.clone(), user_store.clone(), cx);
417 channel::init(&client, user_store.clone(), cx);
418 notifications::init(client.clone(), user_store, cx);
419 collab_ui::init(&app_state, cx);
420 file_finder::init(cx);
421 menu::init();
422 headless::init(
423 client.clone(),
424 headless::AppState {
425 languages: app_state.languages.clone(),
426 user_store: app_state.user_store.clone(),
427 fs: fs.clone(),
428 node_runtime: app_state.node_runtime.clone(),
429 },
430 cx,
431 );
432 });
433
434 TestClient {
435 app_state,
436 username: "dev-server".to_string(),
437 channel_store: cx.read(ChannelStore::global).clone(),
438 notification_store: cx.read(NotificationStore::global).clone(),
439 state: Default::default(),
440 }
441 }
442
443 pub fn disconnect_client(&self, peer_id: PeerId) {
444 self.connection_killers
445 .lock()
446 .remove(&peer_id)
447 .unwrap()
448 .store(true, SeqCst);
449 }
450
451 pub fn simulate_long_connection_interruption(
452 &self,
453 peer_id: PeerId,
454 deterministic: BackgroundExecutor,
455 ) {
456 self.forbid_connections();
457 self.disconnect_client(peer_id);
458 deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
459 self.allow_connections();
460 deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
461 deterministic.run_until_parked();
462 }
463
464 pub fn forbid_connections(&self) {
465 self.forbid_connections.store(true, SeqCst);
466 }
467
468 pub fn allow_connections(&self) {
469 self.forbid_connections.store(false, SeqCst);
470 }
471
472 pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
473 for ix in 1..clients.len() {
474 let (left, right) = clients.split_at_mut(ix);
475 let (client_a, cx_a) = left.last_mut().unwrap();
476 for (client_b, cx_b) in right {
477 client_a
478 .app_state
479 .user_store
480 .update(*cx_a, |store, cx| {
481 store.request_contact(client_b.user_id().unwrap(), cx)
482 })
483 .await
484 .unwrap();
485 cx_a.executor().run_until_parked();
486 client_b
487 .app_state
488 .user_store
489 .update(*cx_b, |store, cx| {
490 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
491 })
492 .await
493 .unwrap();
494 }
495 }
496 }
497
498 pub async fn make_channel(
499 &self,
500 channel: &str,
501 parent: Option<ChannelId>,
502 admin: (&TestClient, &mut TestAppContext),
503 members: &mut [(&TestClient, &mut TestAppContext)],
504 ) -> ChannelId {
505 let (_, admin_cx) = admin;
506 let channel_id = admin_cx
507 .read(ChannelStore::global)
508 .update(admin_cx, |channel_store, cx| {
509 channel_store.create_channel(channel, parent, cx)
510 })
511 .await
512 .unwrap();
513
514 for (member_client, member_cx) in members {
515 admin_cx
516 .read(ChannelStore::global)
517 .update(admin_cx, |channel_store, cx| {
518 channel_store.invite_member(
519 channel_id,
520 member_client.user_id().unwrap(),
521 ChannelRole::Member,
522 cx,
523 )
524 })
525 .await
526 .unwrap();
527
528 admin_cx.executor().run_until_parked();
529
530 member_cx
531 .read(ChannelStore::global)
532 .update(*member_cx, |channels, cx| {
533 channels.respond_to_channel_invite(channel_id, true, cx)
534 })
535 .await
536 .unwrap();
537 }
538
539 channel_id
540 }
541
542 pub async fn make_public_channel(
543 &self,
544 channel: &str,
545 client: &TestClient,
546 cx: &mut TestAppContext,
547 ) -> ChannelId {
548 let channel_id = self
549 .make_channel(channel, None, (client, cx), &mut [])
550 .await;
551
552 client
553 .channel_store()
554 .update(cx, |channel_store, cx| {
555 channel_store.set_channel_visibility(
556 channel_id,
557 proto::ChannelVisibility::Public,
558 cx,
559 )
560 })
561 .await
562 .unwrap();
563
564 channel_id
565 }
566
567 pub async fn make_channel_tree(
568 &self,
569 channels: &[(&str, Option<&str>)],
570 creator: (&TestClient, &mut TestAppContext),
571 ) -> Vec<ChannelId> {
572 let mut observed_channels = HashMap::default();
573 let mut result = Vec::new();
574 for (channel, parent) in channels {
575 let id;
576 if let Some(parent) = parent {
577 if let Some(parent_id) = observed_channels.get(parent) {
578 id = self
579 .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
580 .await;
581 } else {
582 panic!(
583 "Edge {}->{} referenced before {} was created",
584 parent, channel, parent
585 )
586 }
587 } else {
588 id = self
589 .make_channel(channel, None, (creator.0, creator.1), &mut [])
590 .await;
591 }
592
593 observed_channels.insert(channel, id);
594 result.push(id);
595 }
596
597 result
598 }
599
600 pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
601 self.make_contacts(clients).await;
602
603 let (left, right) = clients.split_at_mut(1);
604 let (_client_a, cx_a) = &mut left[0];
605 let active_call_a = cx_a.read(ActiveCall::global);
606
607 for (client_b, cx_b) in right {
608 let user_id_b = client_b.current_user_id(cx_b).to_proto();
609 active_call_a
610 .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
611 .await
612 .unwrap();
613
614 cx_b.executor().run_until_parked();
615 let active_call_b = cx_b.read(ActiveCall::global);
616 active_call_b
617 .update(*cx_b, |call, cx| call.accept_incoming(cx))
618 .await
619 .unwrap();
620 }
621 }
622
623 pub async fn build_app_state(
624 test_db: &TestDb,
625 live_kit_test_server: &live_kit_client::TestServer,
626 executor: Executor,
627 ) -> Arc<AppState> {
628 Arc::new(AppState {
629 db: test_db.db().clone(),
630 live_kit_client: Some(Arc::new(live_kit_test_server.create_api_client())),
631 blob_store_client: None,
632 rate_limiter: Arc::new(RateLimiter::new(test_db.db().clone())),
633 executor,
634 clickhouse_client: None,
635 config: Config {
636 http_port: 0,
637 database_url: "".into(),
638 database_max_connections: 0,
639 api_token: "".into(),
640 invite_link_prefix: "".into(),
641 live_kit_server: None,
642 live_kit_key: None,
643 live_kit_secret: None,
644 rust_log: None,
645 log_json: None,
646 zed_environment: "test".into(),
647 blob_store_url: None,
648 blob_store_region: None,
649 blob_store_access_key: None,
650 blob_store_secret_key: None,
651 blob_store_bucket: None,
652 openai_api_key: None,
653 google_ai_api_key: None,
654 anthropic_api_key: None,
655 clickhouse_url: None,
656 clickhouse_user: None,
657 clickhouse_password: None,
658 clickhouse_database: None,
659 zed_client_checksum_seed: None,
660 slack_panics_webhook: None,
661 auto_join_channel_id: None,
662 migrations_path: None,
663 seed_path: None,
664 supermaven_admin_api_key: None,
665 },
666 })
667 }
668}
669
670impl Deref for TestServer {
671 type Target = Server;
672
673 fn deref(&self) -> &Self::Target {
674 &self.server
675 }
676}
677
678impl Drop for TestServer {
679 fn drop(&mut self) {
680 self.server.teardown();
681 self.test_live_kit_server.teardown().unwrap();
682 }
683}
684
685impl Deref for TestClient {
686 type Target = Arc<Client>;
687
688 fn deref(&self) -> &Self::Target {
689 &self.app_state.client
690 }
691}
692
693impl TestClient {
694 pub fn fs(&self) -> &FakeFs {
695 self.app_state.fs.as_fake()
696 }
697
698 pub fn channel_store(&self) -> &Model<ChannelStore> {
699 &self.channel_store
700 }
701
702 pub fn notification_store(&self) -> &Model<NotificationStore> {
703 &self.notification_store
704 }
705
706 pub fn user_store(&self) -> &Model<UserStore> {
707 &self.app_state.user_store
708 }
709
710 pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
711 &self.app_state.languages
712 }
713
714 pub fn client(&self) -> &Arc<Client> {
715 &self.app_state.client
716 }
717
718 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
719 UserId::from_proto(
720 self.app_state
721 .user_store
722 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
723 )
724 }
725
726 pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
727 let mut authed_user = self
728 .app_state
729 .user_store
730 .read_with(cx, |user_store, _| user_store.watch_current_user());
731 while authed_user.next().await.unwrap().is_none() {}
732 }
733
734 pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
735 self.app_state
736 .user_store
737 .update(cx, |store, _| store.clear_contacts())
738 .await;
739 }
740
741 pub fn local_projects(&self) -> impl Deref<Target = Vec<Model<Project>>> + '_ {
742 Ref::map(self.state.borrow(), |state| &state.local_projects)
743 }
744
745 pub fn dev_server_projects(&self) -> impl Deref<Target = Vec<Model<Project>>> + '_ {
746 Ref::map(self.state.borrow(), |state| &state.dev_server_projects)
747 }
748
749 pub fn local_projects_mut(&self) -> impl DerefMut<Target = Vec<Model<Project>>> + '_ {
750 RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
751 }
752
753 pub fn dev_server_projects_mut(&self) -> impl DerefMut<Target = Vec<Model<Project>>> + '_ {
754 RefMut::map(self.state.borrow_mut(), |state| {
755 &mut state.dev_server_projects
756 })
757 }
758
759 pub fn buffers_for_project<'a>(
760 &'a self,
761 project: &Model<Project>,
762 ) -> impl DerefMut<Target = HashSet<Model<language::Buffer>>> + 'a {
763 RefMut::map(self.state.borrow_mut(), |state| {
764 state.buffers.entry(project.clone()).or_default()
765 })
766 }
767
768 pub fn buffers(
769 &self,
770 ) -> impl DerefMut<Target = HashMap<Model<Project>, HashSet<Model<language::Buffer>>>> + '_
771 {
772 RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
773 }
774
775 pub fn channel_buffers(&self) -> impl DerefMut<Target = HashSet<Model<ChannelBuffer>>> + '_ {
776 RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
777 }
778
779 pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
780 self.app_state
781 .user_store
782 .read_with(cx, |store, _| ContactsSummary {
783 current: store
784 .contacts()
785 .iter()
786 .map(|contact| contact.user.github_login.clone())
787 .collect(),
788 outgoing_requests: store
789 .outgoing_contact_requests()
790 .iter()
791 .map(|user| user.github_login.clone())
792 .collect(),
793 incoming_requests: store
794 .incoming_contact_requests()
795 .iter()
796 .map(|user| user.github_login.clone())
797 .collect(),
798 })
799 }
800
801 pub async fn build_local_project(
802 &self,
803 root_path: impl AsRef<Path>,
804 cx: &mut TestAppContext,
805 ) -> (Model<Project>, WorktreeId) {
806 let project = self.build_empty_local_project(cx);
807 let (worktree, _) = project
808 .update(cx, |p, cx| {
809 p.find_or_create_local_worktree(root_path, true, cx)
810 })
811 .await
812 .unwrap();
813 worktree
814 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
815 .await;
816 (project, worktree.read_with(cx, |tree, _| tree.id()))
817 }
818
819 pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Model<Project> {
820 self.fs()
821 .insert_tree(
822 "/a",
823 json!({
824 "1.txt": "one\none\none",
825 "2.js": "function two() { return 2; }",
826 "3.rs": "mod test",
827 }),
828 )
829 .await;
830 self.build_local_project("/a", cx).await.0
831 }
832
833 pub async fn host_workspace(
834 &self,
835 workspace: &View<Workspace>,
836 channel_id: ChannelId,
837 cx: &mut VisualTestContext,
838 ) {
839 cx.update(|cx| {
840 let active_call = ActiveCall::global(cx);
841 active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
842 })
843 .await
844 .unwrap();
845 cx.update(|cx| {
846 let active_call = ActiveCall::global(cx);
847 let project = workspace.read(cx).project().clone();
848 active_call.update(cx, |call, cx| call.share_project(project, cx))
849 })
850 .await
851 .unwrap();
852 cx.executor().run_until_parked();
853 }
854
855 pub async fn join_workspace<'a>(
856 &'a self,
857 channel_id: ChannelId,
858 cx: &'a mut TestAppContext,
859 ) -> (View<Workspace>, &'a mut VisualTestContext) {
860 cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
861 .await
862 .unwrap();
863 cx.run_until_parked();
864
865 self.active_workspace(cx)
866 }
867
868 pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Model<Project> {
869 cx.update(|cx| {
870 Project::local(
871 self.client().clone(),
872 self.app_state.node_runtime.clone(),
873 self.app_state.user_store.clone(),
874 self.app_state.languages.clone(),
875 self.app_state.fs.clone(),
876 cx,
877 )
878 })
879 }
880
881 pub async fn build_dev_server_project(
882 &self,
883 host_project_id: u64,
884 guest_cx: &mut TestAppContext,
885 ) -> Model<Project> {
886 let active_call = guest_cx.read(ActiveCall::global);
887 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
888 room.update(guest_cx, |room, cx| {
889 room.join_project(
890 host_project_id,
891 self.app_state.languages.clone(),
892 self.app_state.fs.clone(),
893 cx,
894 )
895 })
896 .await
897 .unwrap()
898 }
899
900 pub fn build_workspace<'a>(
901 &'a self,
902 project: &Model<Project>,
903 cx: &'a mut TestAppContext,
904 ) -> (View<Workspace>, &'a mut VisualTestContext) {
905 cx.add_window_view(|cx| {
906 cx.activate_window();
907 Workspace::new(
908 WorkspaceId::default(),
909 project.clone(),
910 self.app_state.clone(),
911 cx,
912 )
913 })
914 }
915
916 pub async fn build_test_workspace<'a>(
917 &'a self,
918 cx: &'a mut TestAppContext,
919 ) -> (View<Workspace>, &'a mut VisualTestContext) {
920 let project = self.build_test_project(cx).await;
921 cx.add_window_view(|cx| {
922 cx.activate_window();
923 Workspace::new(
924 WorkspaceId::default(),
925 project.clone(),
926 self.app_state.clone(),
927 cx,
928 )
929 })
930 }
931
932 pub fn active_workspace<'a>(
933 &'a self,
934 cx: &'a mut TestAppContext,
935 ) -> (View<Workspace>, &'a mut VisualTestContext) {
936 let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
937
938 let view = window.root_view(cx).unwrap();
939 let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
940 // it might be nice to try and cleanup these at the end of each test.
941 (view, cx)
942 }
943}
944
945pub fn open_channel_notes(
946 channel_id: ChannelId,
947 cx: &mut VisualTestContext,
948) -> Task<anyhow::Result<View<ChannelView>>> {
949 let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
950 let view = window.root_view(cx).unwrap();
951
952 cx.update(|cx| ChannelView::open(channel_id, None, view.clone(), cx))
953}
954
955impl Drop for TestClient {
956 fn drop(&mut self) {
957 self.app_state.client.teardown();
958 }
959}