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