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