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