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