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