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