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