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 = cx.new(|cx| CloudUserStore::new(client.cloud_client(), cx));
286 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
287 let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
288 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
289 let app_state = Arc::new(workspace::AppState {
290 client: client.clone(),
291 user_store: user_store.clone(),
292 cloud_user_store,
293 workspace_store,
294 languages: language_registry,
295 fs: fs.clone(),
296 build_window_options: |_, _| Default::default(),
297 node_runtime: NodeRuntime::unavailable(),
298 session,
299 });
300
301 let os_keymap = "keymaps/default-macos.json";
302
303 cx.update(|cx| {
304 theme::init(theme::LoadThemes::JustBase, cx);
305 Project::init(&client, cx);
306 client::init(&client, cx);
307 language::init(cx);
308 editor::init(cx);
309 workspace::init(app_state.clone(), cx);
310 call::init(client.clone(), user_store.clone(), cx);
311 channel::init(&client, user_store.clone(), cx);
312 notifications::init(client.clone(), user_store, cx);
313 collab_ui::init(&app_state, cx);
314 file_finder::init(cx);
315 menu::init();
316 cx.bind_keys(
317 settings::KeymapFile::load_asset_allow_partial_failure(os_keymap, cx).unwrap(),
318 );
319 language_model::LanguageModelRegistry::test(cx);
320 assistant_context::init(client.clone(), cx);
321 agent_settings::init(cx);
322 });
323
324 client
325 .authenticate_and_connect(false, &cx.to_async())
326 .await
327 .into_response()
328 .unwrap();
329
330 let client = TestClient {
331 app_state,
332 username: name.to_string(),
333 channel_store: cx.read(ChannelStore::global).clone(),
334 notification_store: cx.read(NotificationStore::global).clone(),
335 state: Default::default(),
336 };
337 client.wait_for_current_user(cx).await;
338 client
339 }
340
341 pub fn disconnect_client(&self, peer_id: PeerId) {
342 self.connection_killers
343 .lock()
344 .remove(&peer_id)
345 .unwrap()
346 .store(true, SeqCst);
347 }
348
349 pub fn simulate_long_connection_interruption(
350 &self,
351 peer_id: PeerId,
352 deterministic: BackgroundExecutor,
353 ) {
354 self.forbid_connections();
355 self.disconnect_client(peer_id);
356 deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
357 self.allow_connections();
358 deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
359 deterministic.run_until_parked();
360 }
361
362 pub fn forbid_connections(&self) {
363 self.forbid_connections.store(true, SeqCst);
364 }
365
366 pub fn allow_connections(&self) {
367 self.forbid_connections.store(false, SeqCst);
368 }
369
370 pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
371 for ix in 1..clients.len() {
372 let (left, right) = clients.split_at_mut(ix);
373 let (client_a, cx_a) = left.last_mut().unwrap();
374 for (client_b, cx_b) in right {
375 client_a
376 .app_state
377 .user_store
378 .update(*cx_a, |store, cx| {
379 store.request_contact(client_b.user_id().unwrap(), cx)
380 })
381 .await
382 .unwrap();
383 cx_a.executor().run_until_parked();
384 client_b
385 .app_state
386 .user_store
387 .update(*cx_b, |store, cx| {
388 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
389 })
390 .await
391 .unwrap();
392 }
393 }
394 }
395
396 pub async fn make_channel(
397 &self,
398 channel: &str,
399 parent: Option<ChannelId>,
400 admin: (&TestClient, &mut TestAppContext),
401 members: &mut [(&TestClient, &mut TestAppContext)],
402 ) -> ChannelId {
403 let (_, admin_cx) = admin;
404 let channel_id = admin_cx
405 .read(ChannelStore::global)
406 .update(admin_cx, |channel_store, cx| {
407 channel_store.create_channel(channel, parent, cx)
408 })
409 .await
410 .unwrap();
411
412 for (member_client, member_cx) in members {
413 admin_cx
414 .read(ChannelStore::global)
415 .update(admin_cx, |channel_store, cx| {
416 channel_store.invite_member(
417 channel_id,
418 member_client.user_id().unwrap(),
419 ChannelRole::Member,
420 cx,
421 )
422 })
423 .await
424 .unwrap();
425
426 admin_cx.executor().run_until_parked();
427
428 member_cx
429 .read(ChannelStore::global)
430 .update(*member_cx, |channels, cx| {
431 channels.respond_to_channel_invite(channel_id, true, cx)
432 })
433 .await
434 .unwrap();
435 }
436
437 channel_id
438 }
439
440 pub async fn make_public_channel(
441 &self,
442 channel: &str,
443 client: &TestClient,
444 cx: &mut TestAppContext,
445 ) -> ChannelId {
446 let channel_id = self
447 .make_channel(channel, None, (client, cx), &mut [])
448 .await;
449
450 client
451 .channel_store()
452 .update(cx, |channel_store, cx| {
453 channel_store.set_channel_visibility(
454 channel_id,
455 proto::ChannelVisibility::Public,
456 cx,
457 )
458 })
459 .await
460 .unwrap();
461
462 channel_id
463 }
464
465 pub async fn make_channel_tree(
466 &self,
467 channels: &[(&str, Option<&str>)],
468 creator: (&TestClient, &mut TestAppContext),
469 ) -> Vec<ChannelId> {
470 let mut observed_channels = HashMap::default();
471 let mut result = Vec::new();
472 for (channel, parent) in channels {
473 let id;
474 if let Some(parent) = parent {
475 if let Some(parent_id) = observed_channels.get(parent) {
476 id = self
477 .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
478 .await;
479 } else {
480 panic!(
481 "Edge {}->{} referenced before {} was created",
482 parent, channel, parent
483 )
484 }
485 } else {
486 id = self
487 .make_channel(channel, None, (creator.0, creator.1), &mut [])
488 .await;
489 }
490
491 observed_channels.insert(channel, id);
492 result.push(id);
493 }
494
495 result
496 }
497
498 pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
499 self.make_contacts(clients).await;
500
501 let (left, right) = clients.split_at_mut(1);
502 let (_client_a, cx_a) = &mut left[0];
503 let active_call_a = cx_a.read(ActiveCall::global);
504
505 for (client_b, cx_b) in right {
506 let user_id_b = client_b.current_user_id(cx_b).to_proto();
507 active_call_a
508 .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
509 .await
510 .unwrap();
511
512 cx_b.executor().run_until_parked();
513 let active_call_b = cx_b.read(ActiveCall::global);
514 active_call_b
515 .update(*cx_b, |call, cx| call.accept_incoming(cx))
516 .await
517 .unwrap();
518 }
519 }
520
521 pub async fn build_app_state(
522 test_db: &TestDb,
523 livekit_test_server: &LivekitTestServer,
524 executor: Executor,
525 ) -> Arc<AppState> {
526 Arc::new(AppState {
527 db: test_db.db().clone(),
528 llm_db: None,
529 livekit_client: Some(Arc::new(livekit_test_server.create_api_client())),
530 blob_store_client: None,
531 real_stripe_client: None,
532 stripe_client: Some(Arc::new(FakeStripeClient::new())),
533 stripe_billing: None,
534 executor,
535 kinesis_client: None,
536 config: Config {
537 http_port: 0,
538 database_url: "".into(),
539 database_max_connections: 0,
540 api_token: "".into(),
541 invite_link_prefix: "".into(),
542 livekit_server: None,
543 livekit_key: None,
544 livekit_secret: None,
545 llm_database_url: None,
546 llm_database_max_connections: None,
547 llm_database_migrations_path: None,
548 llm_api_secret: None,
549 rust_log: None,
550 log_json: None,
551 zed_environment: "test".into(),
552 blob_store_url: None,
553 blob_store_region: None,
554 blob_store_access_key: None,
555 blob_store_secret_key: None,
556 blob_store_bucket: None,
557 openai_api_key: None,
558 google_ai_api_key: None,
559 anthropic_api_key: None,
560 anthropic_staff_api_key: None,
561 llm_closed_beta_model_name: None,
562 prediction_api_url: None,
563 prediction_api_key: None,
564 prediction_model: None,
565 zed_client_checksum_seed: None,
566 slack_panics_webhook: None,
567 auto_join_channel_id: None,
568 migrations_path: None,
569 seed_path: None,
570 stripe_api_key: None,
571 supermaven_admin_api_key: None,
572 user_backfiller_github_access_token: None,
573 kinesis_region: None,
574 kinesis_stream: None,
575 kinesis_access_key: None,
576 kinesis_secret_key: None,
577 },
578 })
579 }
580}
581
582impl Deref for TestServer {
583 type Target = Server;
584
585 fn deref(&self) -> &Self::Target {
586 &self.server
587 }
588}
589
590impl Drop for TestServer {
591 fn drop(&mut self) {
592 self.server.teardown();
593 self.test_livekit_server.teardown().unwrap();
594 }
595}
596
597impl Deref for TestClient {
598 type Target = Arc<Client>;
599
600 fn deref(&self) -> &Self::Target {
601 &self.app_state.client
602 }
603}
604
605impl TestClient {
606 pub fn fs(&self) -> Arc<FakeFs> {
607 self.app_state.fs.as_fake()
608 }
609
610 pub fn channel_store(&self) -> &Entity<ChannelStore> {
611 &self.channel_store
612 }
613
614 pub fn notification_store(&self) -> &Entity<NotificationStore> {
615 &self.notification_store
616 }
617
618 pub fn user_store(&self) -> &Entity<UserStore> {
619 &self.app_state.user_store
620 }
621
622 pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
623 &self.app_state.languages
624 }
625
626 pub fn client(&self) -> &Arc<Client> {
627 &self.app_state.client
628 }
629
630 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
631 UserId::from_proto(
632 self.app_state
633 .user_store
634 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
635 )
636 }
637
638 pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
639 let mut authed_user = self
640 .app_state
641 .user_store
642 .read_with(cx, |user_store, _| user_store.watch_current_user());
643 while authed_user.next().await.unwrap().is_none() {}
644 }
645
646 pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
647 self.app_state
648 .user_store
649 .update(cx, |store, _| store.clear_contacts())
650 .await;
651 }
652
653 pub fn local_projects(&self) -> impl Deref<Target = Vec<Entity<Project>>> + '_ {
654 Ref::map(self.state.borrow(), |state| &state.local_projects)
655 }
656
657 pub fn dev_server_projects(&self) -> impl Deref<Target = Vec<Entity<Project>>> + '_ {
658 Ref::map(self.state.borrow(), |state| &state.dev_server_projects)
659 }
660
661 pub fn local_projects_mut(&self) -> impl DerefMut<Target = Vec<Entity<Project>>> + '_ {
662 RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
663 }
664
665 pub fn dev_server_projects_mut(&self) -> impl DerefMut<Target = Vec<Entity<Project>>> + '_ {
666 RefMut::map(self.state.borrow_mut(), |state| {
667 &mut state.dev_server_projects
668 })
669 }
670
671 pub fn buffers_for_project<'a>(
672 &'a self,
673 project: &Entity<Project>,
674 ) -> impl DerefMut<Target = HashSet<Entity<language::Buffer>>> + 'a {
675 RefMut::map(self.state.borrow_mut(), |state| {
676 state.buffers.entry(project.clone()).or_default()
677 })
678 }
679
680 pub fn buffers(
681 &self,
682 ) -> impl DerefMut<Target = HashMap<Entity<Project>, HashSet<Entity<language::Buffer>>>> + '_
683 {
684 RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
685 }
686
687 pub fn channel_buffers(&self) -> impl DerefMut<Target = HashSet<Entity<ChannelBuffer>>> + '_ {
688 RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
689 }
690
691 pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
692 self.app_state
693 .user_store
694 .read_with(cx, |store, _| ContactsSummary {
695 current: store
696 .contacts()
697 .iter()
698 .map(|contact| contact.user.github_login.clone())
699 .collect(),
700 outgoing_requests: store
701 .outgoing_contact_requests()
702 .iter()
703 .map(|user| user.github_login.clone())
704 .collect(),
705 incoming_requests: store
706 .incoming_contact_requests()
707 .iter()
708 .map(|user| user.github_login.clone())
709 .collect(),
710 })
711 }
712
713 pub async fn build_local_project(
714 &self,
715 root_path: impl AsRef<Path>,
716 cx: &mut TestAppContext,
717 ) -> (Entity<Project>, WorktreeId) {
718 let project = self.build_empty_local_project(cx);
719 let (worktree, _) = project
720 .update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
721 .await
722 .unwrap();
723 worktree
724 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
725 .await;
726 cx.run_until_parked();
727 (project, worktree.read_with(cx, |tree, _| tree.id()))
728 }
729
730 pub async fn build_ssh_project(
731 &self,
732 root_path: impl AsRef<Path>,
733 ssh: Entity<SshRemoteClient>,
734 cx: &mut TestAppContext,
735 ) -> (Entity<Project>, WorktreeId) {
736 let project = cx.update(|cx| {
737 Project::ssh(
738 ssh,
739 self.client().clone(),
740 self.app_state.node_runtime.clone(),
741 self.app_state.user_store.clone(),
742 self.app_state.languages.clone(),
743 self.app_state.fs.clone(),
744 cx,
745 )
746 });
747 let (worktree, _) = project
748 .update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
749 .await
750 .unwrap();
751 (project, worktree.read_with(cx, |tree, _| tree.id()))
752 }
753
754 pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Entity<Project> {
755 self.fs()
756 .insert_tree(
757 path!("/a"),
758 json!({
759 "1.txt": "one\none\none",
760 "2.js": "function two() { return 2; }",
761 "3.rs": "mod test",
762 }),
763 )
764 .await;
765 self.build_local_project(path!("/a"), cx).await.0
766 }
767
768 pub async fn host_workspace(
769 &self,
770 workspace: &Entity<Workspace>,
771 channel_id: ChannelId,
772 cx: &mut VisualTestContext,
773 ) {
774 cx.update(|_, cx| {
775 let active_call = ActiveCall::global(cx);
776 active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
777 })
778 .await
779 .unwrap();
780 cx.update(|_, cx| {
781 let active_call = ActiveCall::global(cx);
782 let project = workspace.read(cx).project().clone();
783 active_call.update(cx, |call, cx| call.share_project(project, cx))
784 })
785 .await
786 .unwrap();
787 cx.executor().run_until_parked();
788 }
789
790 pub async fn join_workspace<'a>(
791 &'a self,
792 channel_id: ChannelId,
793 cx: &'a mut TestAppContext,
794 ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
795 cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
796 .await
797 .unwrap();
798 cx.run_until_parked();
799
800 self.active_workspace(cx)
801 }
802
803 pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Entity<Project> {
804 cx.update(|cx| {
805 Project::local(
806 self.client().clone(),
807 self.app_state.node_runtime.clone(),
808 self.app_state.user_store.clone(),
809 self.app_state.languages.clone(),
810 self.app_state.fs.clone(),
811 None,
812 cx,
813 )
814 })
815 }
816
817 pub async fn join_remote_project(
818 &self,
819 host_project_id: u64,
820 guest_cx: &mut TestAppContext,
821 ) -> Entity<Project> {
822 let active_call = guest_cx.read(ActiveCall::global);
823 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
824 room.update(guest_cx, |room, cx| {
825 room.join_project(
826 host_project_id,
827 self.app_state.languages.clone(),
828 self.app_state.fs.clone(),
829 cx,
830 )
831 })
832 .await
833 .unwrap()
834 }
835
836 pub fn build_workspace<'a>(
837 &'a self,
838 project: &Entity<Project>,
839 cx: &'a mut TestAppContext,
840 ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
841 cx.add_window_view(|window, cx| {
842 window.activate_window();
843 Workspace::new(None, project.clone(), self.app_state.clone(), window, cx)
844 })
845 }
846
847 pub async fn build_test_workspace<'a>(
848 &'a self,
849 cx: &'a mut TestAppContext,
850 ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
851 let project = self.build_test_project(cx).await;
852 cx.add_window_view(|window, cx| {
853 window.activate_window();
854 Workspace::new(None, project.clone(), self.app_state.clone(), window, cx)
855 })
856 }
857
858 pub fn active_workspace<'a>(
859 &'a self,
860 cx: &'a mut TestAppContext,
861 ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
862 let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
863
864 let entity = window.root(cx).unwrap();
865 let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
866 // it might be nice to try and cleanup these at the end of each test.
867 (entity, cx)
868 }
869}
870
871pub fn open_channel_notes(
872 channel_id: ChannelId,
873 cx: &mut VisualTestContext,
874) -> Task<anyhow::Result<Entity<ChannelView>>> {
875 let window = cx.update(|_, cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
876 let entity = window.root(cx).unwrap();
877
878 cx.update(|window, cx| ChannelView::open(channel_id, None, entity.clone(), window, cx))
879}
880
881impl Drop for TestClient {
882 fn drop(&mut self) {
883 self.app_state.client.teardown();
884 }
885}