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 http::FakeHttpClient;
23use language::LanguageRegistry;
24use node_runtime::FakeNodeRuntime;
25use notifications::NotificationStore;
26use parking_lot::Mutex;
27use project::{Project, WorktreeId};
28use rpc::{
29 proto::{self, ChannelRole},
30 RECEIVE_TIMEOUT,
31};
32use semantic_version::SemanticVersion;
33use serde_json::json;
34use settings::SettingsStore;
35use std::{
36 cell::{Ref, RefCell, RefMut},
37 env,
38 ops::{Deref, DerefMut},
39 path::Path,
40 sync::{
41 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
42 Arc,
43 },
44};
45use workspace::{Workspace, 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(SemanticVersion::default(), 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 = "keymaps/default-macos.json";
281
282 cx.update(|cx| {
283 theme::init(theme::LoadThemes::JustBase, cx);
284 Project::init(&client, cx);
285 client::init(&client, cx);
286 language::init(cx);
287 editor::init(cx);
288 workspace::init(app_state.clone(), cx);
289 call::init(client.clone(), user_store.clone(), cx);
290 channel::init(&client, user_store.clone(), cx);
291 notifications::init(client.clone(), user_store, cx);
292 collab_ui::init(&app_state, cx);
293 file_finder::init(cx);
294 menu::init();
295 dev_server_projects::init(client.clone(), cx);
296 settings::KeymapFile::load_asset(os_keymap, cx).unwrap();
297 assistant::FakeCompletionProvider::setup_test(cx);
298 assistant::context_store::init(&client);
299 });
300
301 client
302 .authenticate_and_connect(false, &cx.to_async())
303 .await
304 .unwrap();
305
306 let client = TestClient {
307 app_state,
308 username: name.to_string(),
309 channel_store: cx.read(ChannelStore::global).clone(),
310 notification_store: cx.read(NotificationStore::global).clone(),
311 state: Default::default(),
312 };
313 client.wait_for_current_user(cx).await;
314 client
315 }
316
317 pub async fn create_dev_server(
318 &self,
319 access_token: String,
320 cx: &mut TestAppContext,
321 ) -> TestClient {
322 cx.update(|cx| {
323 if cx.has_global::<SettingsStore>() {
324 panic!("Same cx used to create two test clients")
325 }
326 let settings = SettingsStore::test(cx);
327 cx.set_global(settings);
328 release_channel::init(SemanticVersion::default(), cx);
329 client::init_settings(cx);
330 });
331 let (dev_server_id, _) = split_dev_server_token(&access_token).unwrap();
332
333 let clock = Arc::new(FakeSystemClock::default());
334 let http = FakeHttpClient::with_404_response();
335 let mut client = cx.update(|cx| Client::new(clock, http.clone(), cx));
336 let server = self.server.clone();
337 let db = self.app_state.db.clone();
338 let connection_killers = self.connection_killers.clone();
339 let forbid_connections = self.forbid_connections.clone();
340 Arc::get_mut(&mut client)
341 .unwrap()
342 .set_id(1)
343 .set_dev_server_token(client::DevServerToken(access_token.clone()))
344 .override_establish_connection(move |credentials, cx| {
345 assert_eq!(
346 credentials,
347 &Credentials::DevServer {
348 token: client::DevServerToken(access_token.to_string())
349 }
350 );
351
352 let server = server.clone();
353 let db = db.clone();
354 let connection_killers = connection_killers.clone();
355 let forbid_connections = forbid_connections.clone();
356 cx.spawn(move |cx| async move {
357 if forbid_connections.load(SeqCst) {
358 Err(EstablishConnectionError::other(anyhow!(
359 "server is forbidding connections"
360 )))
361 } else {
362 let (client_conn, server_conn, killed) =
363 Connection::in_memory(cx.background_executor().clone());
364 let (connection_id_tx, connection_id_rx) = oneshot::channel();
365 let dev_server = db
366 .get_dev_server(dev_server_id)
367 .await
368 .expect("retrieving dev_server failed");
369 cx.background_executor()
370 .spawn(server.handle_connection(
371 server_conn,
372 "dev-server".to_string(),
373 Principal::DevServer(dev_server),
374 ZedVersion(SemanticVersion::new(1, 0, 0)),
375 Some(connection_id_tx),
376 Executor::Deterministic(cx.background_executor().clone()),
377 ))
378 .detach();
379 let connection_id = connection_id_rx.await.map_err(|e| {
380 EstablishConnectionError::Other(anyhow!(
381 "{} (is server shutting down?)",
382 e
383 ))
384 })?;
385 connection_killers
386 .lock()
387 .insert(connection_id.into(), killed);
388 Ok(client_conn)
389 }
390 })
391 });
392
393 let fs = FakeFs::new(cx.executor());
394 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
395 let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx));
396 let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
397 let app_state = Arc::new(workspace::AppState {
398 client: client.clone(),
399 user_store: user_store.clone(),
400 workspace_store,
401 languages: language_registry,
402 fs: fs.clone(),
403 build_window_options: |_, _| Default::default(),
404 node_runtime: FakeNodeRuntime::new(),
405 });
406
407 cx.update(|cx| {
408 theme::init(theme::LoadThemes::JustBase, cx);
409 Project::init(&client, cx);
410 client::init(&client, cx);
411 language::init(cx);
412 editor::init(cx);
413 workspace::init(app_state.clone(), cx);
414 call::init(client.clone(), user_store.clone(), cx);
415 channel::init(&client, user_store.clone(), cx);
416 notifications::init(client.clone(), user_store, cx);
417 collab_ui::init(&app_state, cx);
418 file_finder::init(cx);
419 menu::init();
420 headless::init(
421 client.clone(),
422 headless::AppState {
423 languages: app_state.languages.clone(),
424 user_store: app_state.user_store.clone(),
425 fs: fs.clone(),
426 node_runtime: app_state.node_runtime.clone(),
427 },
428 cx,
429 )
430 })
431 .await
432 .unwrap();
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| p.find_or_create_worktree(root_path, true, cx))
809 .await
810 .unwrap();
811 worktree
812 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
813 .await;
814 (project, worktree.read_with(cx, |tree, _| tree.id()))
815 }
816
817 pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Model<Project> {
818 self.fs()
819 .insert_tree(
820 "/a",
821 json!({
822 "1.txt": "one\none\none",
823 "2.js": "function two() { return 2; }",
824 "3.rs": "mod test",
825 }),
826 )
827 .await;
828 self.build_local_project("/a", cx).await.0
829 }
830
831 pub async fn host_workspace(
832 &self,
833 workspace: &View<Workspace>,
834 channel_id: ChannelId,
835 cx: &mut VisualTestContext,
836 ) {
837 cx.update(|cx| {
838 let active_call = ActiveCall::global(cx);
839 active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
840 })
841 .await
842 .unwrap();
843 cx.update(|cx| {
844 let active_call = ActiveCall::global(cx);
845 let project = workspace.read(cx).project().clone();
846 active_call.update(cx, |call, cx| call.share_project(project, cx))
847 })
848 .await
849 .unwrap();
850 cx.executor().run_until_parked();
851 }
852
853 pub async fn join_workspace<'a>(
854 &'a self,
855 channel_id: ChannelId,
856 cx: &'a mut TestAppContext,
857 ) -> (View<Workspace>, &'a mut VisualTestContext) {
858 cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
859 .await
860 .unwrap();
861 cx.run_until_parked();
862
863 self.active_workspace(cx)
864 }
865
866 pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Model<Project> {
867 cx.update(|cx| {
868 Project::local(
869 self.client().clone(),
870 self.app_state.node_runtime.clone(),
871 self.app_state.user_store.clone(),
872 self.app_state.languages.clone(),
873 self.app_state.fs.clone(),
874 cx,
875 )
876 })
877 }
878
879 pub async fn build_dev_server_project(
880 &self,
881 host_project_id: u64,
882 guest_cx: &mut TestAppContext,
883 ) -> Model<Project> {
884 let active_call = guest_cx.read(ActiveCall::global);
885 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
886 room.update(guest_cx, |room, cx| {
887 room.join_project(
888 host_project_id,
889 self.app_state.languages.clone(),
890 self.app_state.fs.clone(),
891 cx,
892 )
893 })
894 .await
895 .unwrap()
896 }
897
898 pub fn build_workspace<'a>(
899 &'a self,
900 project: &Model<Project>,
901 cx: &'a mut TestAppContext,
902 ) -> (View<Workspace>, &'a mut VisualTestContext) {
903 cx.add_window_view(|cx| {
904 cx.activate_window();
905 Workspace::new(None, project.clone(), self.app_state.clone(), cx)
906 })
907 }
908
909 pub async fn build_test_workspace<'a>(
910 &'a self,
911 cx: &'a mut TestAppContext,
912 ) -> (View<Workspace>, &'a mut VisualTestContext) {
913 let project = self.build_test_project(cx).await;
914 cx.add_window_view(|cx| {
915 cx.activate_window();
916 Workspace::new(None, project.clone(), self.app_state.clone(), cx)
917 })
918 }
919
920 pub fn active_workspace<'a>(
921 &'a self,
922 cx: &'a mut TestAppContext,
923 ) -> (View<Workspace>, &'a mut VisualTestContext) {
924 let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
925
926 let view = window.root_view(cx).unwrap();
927 let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
928 // it might be nice to try and cleanup these at the end of each test.
929 (view, cx)
930 }
931}
932
933pub fn open_channel_notes(
934 channel_id: ChannelId,
935 cx: &mut VisualTestContext,
936) -> Task<anyhow::Result<View<ChannelView>>> {
937 let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
938 let view = window.root_view(cx).unwrap();
939
940 cx.update(|cx| ChannelView::open(channel_id, None, view.clone(), cx))
941}
942
943impl Drop for TestClient {
944 fn drop(&mut self) {
945 self.app_state.client.teardown();
946 }
947}