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 = 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(SemanticVersion::default(), 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 .await
434 .unwrap();
435
436 TestClient {
437 app_state,
438 username: "dev-server".to_string(),
439 channel_store: cx.read(ChannelStore::global).clone(),
440 notification_store: cx.read(NotificationStore::global).clone(),
441 state: Default::default(),
442 }
443 }
444
445 pub fn disconnect_client(&self, peer_id: PeerId) {
446 self.connection_killers
447 .lock()
448 .remove(&peer_id)
449 .unwrap()
450 .store(true, SeqCst);
451 }
452
453 pub fn simulate_long_connection_interruption(
454 &self,
455 peer_id: PeerId,
456 deterministic: BackgroundExecutor,
457 ) {
458 self.forbid_connections();
459 self.disconnect_client(peer_id);
460 deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
461 self.allow_connections();
462 deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
463 deterministic.run_until_parked();
464 }
465
466 pub fn forbid_connections(&self) {
467 self.forbid_connections.store(true, SeqCst);
468 }
469
470 pub fn allow_connections(&self) {
471 self.forbid_connections.store(false, SeqCst);
472 }
473
474 pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
475 for ix in 1..clients.len() {
476 let (left, right) = clients.split_at_mut(ix);
477 let (client_a, cx_a) = left.last_mut().unwrap();
478 for (client_b, cx_b) in right {
479 client_a
480 .app_state
481 .user_store
482 .update(*cx_a, |store, cx| {
483 store.request_contact(client_b.user_id().unwrap(), cx)
484 })
485 .await
486 .unwrap();
487 cx_a.executor().run_until_parked();
488 client_b
489 .app_state
490 .user_store
491 .update(*cx_b, |store, cx| {
492 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
493 })
494 .await
495 .unwrap();
496 }
497 }
498 }
499
500 pub async fn make_channel(
501 &self,
502 channel: &str,
503 parent: Option<ChannelId>,
504 admin: (&TestClient, &mut TestAppContext),
505 members: &mut [(&TestClient, &mut TestAppContext)],
506 ) -> ChannelId {
507 let (_, admin_cx) = admin;
508 let channel_id = admin_cx
509 .read(ChannelStore::global)
510 .update(admin_cx, |channel_store, cx| {
511 channel_store.create_channel(channel, parent, cx)
512 })
513 .await
514 .unwrap();
515
516 for (member_client, member_cx) in members {
517 admin_cx
518 .read(ChannelStore::global)
519 .update(admin_cx, |channel_store, cx| {
520 channel_store.invite_member(
521 channel_id,
522 member_client.user_id().unwrap(),
523 ChannelRole::Member,
524 cx,
525 )
526 })
527 .await
528 .unwrap();
529
530 admin_cx.executor().run_until_parked();
531
532 member_cx
533 .read(ChannelStore::global)
534 .update(*member_cx, |channels, cx| {
535 channels.respond_to_channel_invite(channel_id, true, cx)
536 })
537 .await
538 .unwrap();
539 }
540
541 channel_id
542 }
543
544 pub async fn make_public_channel(
545 &self,
546 channel: &str,
547 client: &TestClient,
548 cx: &mut TestAppContext,
549 ) -> ChannelId {
550 let channel_id = self
551 .make_channel(channel, None, (client, cx), &mut [])
552 .await;
553
554 client
555 .channel_store()
556 .update(cx, |channel_store, cx| {
557 channel_store.set_channel_visibility(
558 channel_id,
559 proto::ChannelVisibility::Public,
560 cx,
561 )
562 })
563 .await
564 .unwrap();
565
566 channel_id
567 }
568
569 pub async fn make_channel_tree(
570 &self,
571 channels: &[(&str, Option<&str>)],
572 creator: (&TestClient, &mut TestAppContext),
573 ) -> Vec<ChannelId> {
574 let mut observed_channels = HashMap::default();
575 let mut result = Vec::new();
576 for (channel, parent) in channels {
577 let id;
578 if let Some(parent) = parent {
579 if let Some(parent_id) = observed_channels.get(parent) {
580 id = self
581 .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
582 .await;
583 } else {
584 panic!(
585 "Edge {}->{} referenced before {} was created",
586 parent, channel, parent
587 )
588 }
589 } else {
590 id = self
591 .make_channel(channel, None, (creator.0, creator.1), &mut [])
592 .await;
593 }
594
595 observed_channels.insert(channel, id);
596 result.push(id);
597 }
598
599 result
600 }
601
602 pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
603 self.make_contacts(clients).await;
604
605 let (left, right) = clients.split_at_mut(1);
606 let (_client_a, cx_a) = &mut left[0];
607 let active_call_a = cx_a.read(ActiveCall::global);
608
609 for (client_b, cx_b) in right {
610 let user_id_b = client_b.current_user_id(cx_b).to_proto();
611 active_call_a
612 .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
613 .await
614 .unwrap();
615
616 cx_b.executor().run_until_parked();
617 let active_call_b = cx_b.read(ActiveCall::global);
618 active_call_b
619 .update(*cx_b, |call, cx| call.accept_incoming(cx))
620 .await
621 .unwrap();
622 }
623 }
624
625 pub async fn build_app_state(
626 test_db: &TestDb,
627 live_kit_test_server: &live_kit_client::TestServer,
628 executor: Executor,
629 ) -> Arc<AppState> {
630 Arc::new(AppState {
631 db: test_db.db().clone(),
632 live_kit_client: Some(Arc::new(live_kit_test_server.create_api_client())),
633 blob_store_client: None,
634 rate_limiter: Arc::new(RateLimiter::new(test_db.db().clone())),
635 executor,
636 clickhouse_client: None,
637 config: Config {
638 http_port: 0,
639 database_url: "".into(),
640 database_max_connections: 0,
641 api_token: "".into(),
642 invite_link_prefix: "".into(),
643 live_kit_server: None,
644 live_kit_key: None,
645 live_kit_secret: None,
646 rust_log: None,
647 log_json: None,
648 zed_environment: "test".into(),
649 blob_store_url: None,
650 blob_store_region: None,
651 blob_store_access_key: None,
652 blob_store_secret_key: None,
653 blob_store_bucket: None,
654 openai_api_key: None,
655 google_ai_api_key: None,
656 anthropic_api_key: None,
657 clickhouse_url: None,
658 clickhouse_user: None,
659 clickhouse_password: None,
660 clickhouse_database: None,
661 zed_client_checksum_seed: None,
662 slack_panics_webhook: None,
663 auto_join_channel_id: None,
664 migrations_path: None,
665 seed_path: None,
666 supermaven_admin_api_key: None,
667 },
668 })
669 }
670}
671
672impl Deref for TestServer {
673 type Target = Server;
674
675 fn deref(&self) -> &Self::Target {
676 &self.server
677 }
678}
679
680impl Drop for TestServer {
681 fn drop(&mut self) {
682 self.server.teardown();
683 self.test_live_kit_server.teardown().unwrap();
684 }
685}
686
687impl Deref for TestClient {
688 type Target = Arc<Client>;
689
690 fn deref(&self) -> &Self::Target {
691 &self.app_state.client
692 }
693}
694
695impl TestClient {
696 pub fn fs(&self) -> &FakeFs {
697 self.app_state.fs.as_fake()
698 }
699
700 pub fn channel_store(&self) -> &Model<ChannelStore> {
701 &self.channel_store
702 }
703
704 pub fn notification_store(&self) -> &Model<NotificationStore> {
705 &self.notification_store
706 }
707
708 pub fn user_store(&self) -> &Model<UserStore> {
709 &self.app_state.user_store
710 }
711
712 pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
713 &self.app_state.languages
714 }
715
716 pub fn client(&self) -> &Arc<Client> {
717 &self.app_state.client
718 }
719
720 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
721 UserId::from_proto(
722 self.app_state
723 .user_store
724 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
725 )
726 }
727
728 pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
729 let mut authed_user = self
730 .app_state
731 .user_store
732 .read_with(cx, |user_store, _| user_store.watch_current_user());
733 while authed_user.next().await.unwrap().is_none() {}
734 }
735
736 pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
737 self.app_state
738 .user_store
739 .update(cx, |store, _| store.clear_contacts())
740 .await;
741 }
742
743 pub fn local_projects(&self) -> impl Deref<Target = Vec<Model<Project>>> + '_ {
744 Ref::map(self.state.borrow(), |state| &state.local_projects)
745 }
746
747 pub fn dev_server_projects(&self) -> impl Deref<Target = Vec<Model<Project>>> + '_ {
748 Ref::map(self.state.borrow(), |state| &state.dev_server_projects)
749 }
750
751 pub fn local_projects_mut(&self) -> impl DerefMut<Target = Vec<Model<Project>>> + '_ {
752 RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
753 }
754
755 pub fn dev_server_projects_mut(&self) -> impl DerefMut<Target = Vec<Model<Project>>> + '_ {
756 RefMut::map(self.state.borrow_mut(), |state| {
757 &mut state.dev_server_projects
758 })
759 }
760
761 pub fn buffers_for_project<'a>(
762 &'a self,
763 project: &Model<Project>,
764 ) -> impl DerefMut<Target = HashSet<Model<language::Buffer>>> + 'a {
765 RefMut::map(self.state.borrow_mut(), |state| {
766 state.buffers.entry(project.clone()).or_default()
767 })
768 }
769
770 pub fn buffers(
771 &self,
772 ) -> impl DerefMut<Target = HashMap<Model<Project>, HashSet<Model<language::Buffer>>>> + '_
773 {
774 RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
775 }
776
777 pub fn channel_buffers(&self) -> impl DerefMut<Target = HashSet<Model<ChannelBuffer>>> + '_ {
778 RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
779 }
780
781 pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
782 self.app_state
783 .user_store
784 .read_with(cx, |store, _| ContactsSummary {
785 current: store
786 .contacts()
787 .iter()
788 .map(|contact| contact.user.github_login.clone())
789 .collect(),
790 outgoing_requests: store
791 .outgoing_contact_requests()
792 .iter()
793 .map(|user| user.github_login.clone())
794 .collect(),
795 incoming_requests: store
796 .incoming_contact_requests()
797 .iter()
798 .map(|user| user.github_login.clone())
799 .collect(),
800 })
801 }
802
803 pub async fn build_local_project(
804 &self,
805 root_path: impl AsRef<Path>,
806 cx: &mut TestAppContext,
807 ) -> (Model<Project>, WorktreeId) {
808 let project = self.build_empty_local_project(cx);
809 let (worktree, _) = project
810 .update(cx, |p, cx| {
811 p.find_or_create_local_worktree(root_path, true, cx)
812 })
813 .await
814 .unwrap();
815 worktree
816 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
817 .await;
818 (project, worktree.read_with(cx, |tree, _| tree.id()))
819 }
820
821 pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Model<Project> {
822 self.fs()
823 .insert_tree(
824 "/a",
825 json!({
826 "1.txt": "one\none\none",
827 "2.js": "function two() { return 2; }",
828 "3.rs": "mod test",
829 }),
830 )
831 .await;
832 self.build_local_project("/a", cx).await.0
833 }
834
835 pub async fn host_workspace(
836 &self,
837 workspace: &View<Workspace>,
838 channel_id: ChannelId,
839 cx: &mut VisualTestContext,
840 ) {
841 cx.update(|cx| {
842 let active_call = ActiveCall::global(cx);
843 active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
844 })
845 .await
846 .unwrap();
847 cx.update(|cx| {
848 let active_call = ActiveCall::global(cx);
849 let project = workspace.read(cx).project().clone();
850 active_call.update(cx, |call, cx| call.share_project(project, cx))
851 })
852 .await
853 .unwrap();
854 cx.executor().run_until_parked();
855 }
856
857 pub async fn join_workspace<'a>(
858 &'a self,
859 channel_id: ChannelId,
860 cx: &'a mut TestAppContext,
861 ) -> (View<Workspace>, &'a mut VisualTestContext) {
862 cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
863 .await
864 .unwrap();
865 cx.run_until_parked();
866
867 self.active_workspace(cx)
868 }
869
870 pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Model<Project> {
871 cx.update(|cx| {
872 Project::local(
873 self.client().clone(),
874 self.app_state.node_runtime.clone(),
875 self.app_state.user_store.clone(),
876 self.app_state.languages.clone(),
877 self.app_state.fs.clone(),
878 cx,
879 )
880 })
881 }
882
883 pub async fn build_dev_server_project(
884 &self,
885 host_project_id: u64,
886 guest_cx: &mut TestAppContext,
887 ) -> Model<Project> {
888 let active_call = guest_cx.read(ActiveCall::global);
889 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
890 room.update(guest_cx, |room, cx| {
891 room.join_project(
892 host_project_id,
893 self.app_state.languages.clone(),
894 self.app_state.fs.clone(),
895 cx,
896 )
897 })
898 .await
899 .unwrap()
900 }
901
902 pub fn build_workspace<'a>(
903 &'a self,
904 project: &Model<Project>,
905 cx: &'a mut TestAppContext,
906 ) -> (View<Workspace>, &'a mut VisualTestContext) {
907 cx.add_window_view(|cx| {
908 cx.activate_window();
909 Workspace::new(None, project.clone(), self.app_state.clone(), cx)
910 })
911 }
912
913 pub async fn build_test_workspace<'a>(
914 &'a self,
915 cx: &'a mut TestAppContext,
916 ) -> (View<Workspace>, &'a mut VisualTestContext) {
917 let project = self.build_test_project(cx).await;
918 cx.add_window_view(|cx| {
919 cx.activate_window();
920 Workspace::new(None, project.clone(), self.app_state.clone(), cx)
921 })
922 }
923
924 pub fn active_workspace<'a>(
925 &'a self,
926 cx: &'a mut TestAppContext,
927 ) -> (View<Workspace>, &'a mut VisualTestContext) {
928 let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
929
930 let view = window.root_view(cx).unwrap();
931 let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
932 // it might be nice to try and cleanup these at the end of each test.
933 (view, cx)
934 }
935}
936
937pub fn open_channel_notes(
938 channel_id: ChannelId,
939 cx: &mut VisualTestContext,
940) -> Task<anyhow::Result<View<ChannelView>>> {
941 let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
942 let view = window.root_view(cx).unwrap();
943
944 cx.update(|cx| ChannelView::open(channel_id, None, view.clone(), cx))
945}
946
947impl Drop for TestClient {
948 fn drop(&mut self) {
949 self.app_state.client.teardown();
950 }
951}