test_server.rs

  1use anyhow::anyhow;
  2use call::ActiveCall;
  3use channel::{ChannelBuffer, ChannelStore};
  4use client::test::{make_get_authenticated_user_response, parse_authorization_header};
  5use client::{
  6    self, ChannelId, Client, Connection, Credentials, EstablishConnectionError, UserStore,
  7    proto::PeerId,
  8};
  9use clock::FakeSystemClock;
 10use collab::{
 11    AppState, Config,
 12    db::{NewUserParams, UserId},
 13    executor::Executor,
 14    rpc::{CLEANUP_TIMEOUT, Principal, RECONNECT_TIMEOUT, Server, ZedVersion},
 15};
 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 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        Arc,
 44        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
 45    },
 46};
 47use util::path;
 48use workspace::{MultiWorkspace, Workspace, WorkspaceStore};
 49
 50use livekit_client::test::TestServer as LivekitTestServer;
 51
 52use crate::db_tests::TestDb;
 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        const ACCESS_TOKEN: &str = "the-token";
166
167        let fs = FakeFs::new(cx.executor());
168
169        cx.update(|cx| {
170            gpui_tokio::init(cx);
171            if cx.has_global::<SettingsStore>() {
172                panic!("Same cx used to create two test clients")
173            }
174            let settings = SettingsStore::test(cx);
175            cx.set_global(settings);
176            release_channel::init(semver::Version::new(0, 0, 0), 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 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        client
251            .set_id(user_id.to_proto())
252            .override_authenticate(move |cx| {
253                cx.spawn(async move |_| {
254                    Ok(Credentials {
255                        user_id: user_id.to_proto(),
256                        access_token: ACCESS_TOKEN.into(),
257                    })
258                })
259            })
260            .override_establish_connection(move |credentials, cx| {
261                assert_eq!(
262                    credentials,
263                    &Credentials {
264                        user_id: user_id.0 as u64,
265                        access_token: ACCESS_TOKEN.into(),
266                    }
267                );
268
269                let server = server.clone();
270                let db = db.clone();
271                let connection_killers = connection_killers.clone();
272                let forbid_connections = forbid_connections.clone();
273                let client_name = client_name.clone();
274                cx.spawn(async move |cx| {
275                    if forbid_connections.load(SeqCst) {
276                        Err(EstablishConnectionError::other(anyhow!(
277                            "server is forbidding connections"
278                        )))
279                    } else {
280                        let (client_conn, server_conn, killed) =
281                            Connection::in_memory(cx.background_executor().clone());
282                        let (connection_id_tx, connection_id_rx) = oneshot::channel();
283                        let user = db
284                            .get_user_by_id(user_id)
285                            .await
286                            .map_err(|e| {
287                                EstablishConnectionError::Other(anyhow!(
288                                    "retrieving user failed: {}",
289                                    e
290                                ))
291                            })?
292                            .unwrap();
293                        cx.background_spawn(server.handle_connection(
294                            server_conn,
295                            client_name,
296                            Principal::User(user),
297                            ZedVersion(semver::Version::new(1, 0, 0)),
298                            Some("test".to_string()),
299                            None,
300                            None,
301                            None,
302                            Some(connection_id_tx),
303                            Executor::Deterministic(cx.background_executor().clone()),
304                            None,
305                        ))
306                        .detach();
307                        let connection_id = connection_id_rx.await.map_err(|e| {
308                            EstablishConnectionError::Other(anyhow!(
309                                "{} (is server shutting down?)",
310                                e
311                            ))
312                        })?;
313                        connection_killers
314                            .lock()
315                            .insert(connection_id.into(), killed);
316                        Ok(client_conn)
317                    }
318                })
319            });
320
321        let git_hosting_provider_registry = cx.update(GitHostingProviderRegistry::default_global);
322        git_hosting_provider_registry
323            .register_hosting_provider(Arc::new(git_hosting_providers::Github::public_instance()));
324
325        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
326        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
327        let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
328        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
329        let app_state = Arc::new(workspace::AppState {
330            client: client.clone(),
331            user_store: user_store.clone(),
332            workspace_store,
333            languages: language_registry,
334            fs: fs.clone(),
335            build_window_options: |_, _| Default::default(),
336            node_runtime: NodeRuntime::unavailable(),
337            session,
338        });
339
340        let os_keymap = "keymaps/default-macos.json";
341
342        cx.update(|cx| {
343            theme_settings::init(theme::LoadThemes::JustBase, cx);
344            Project::init(&client, cx);
345            client::init(&client, cx);
346            editor::init(cx);
347            workspace::init(app_state.clone(), cx);
348            call::init(client.clone(), user_store.clone(), cx);
349            channel::init(&client, user_store.clone(), cx);
350            notifications::init(client.clone(), user_store, cx);
351            collab_ui::init(&app_state, cx);
352            file_finder::init(cx);
353            menu::init();
354            cx.bind_keys(settings::KeymapFile::load_asset_cached(os_keymap, cx).unwrap());
355            language_model::LanguageModelRegistry::test(cx);
356        });
357
358        client
359            .connect(false, &cx.to_async())
360            .await
361            .into_response()
362            .unwrap();
363
364        let client = TestClient {
365            app_state,
366            username: name.to_string(),
367            channel_store: cx.read(ChannelStore::global),
368            notification_store: cx.read(NotificationStore::global),
369            state: Default::default(),
370        };
371        client.wait_for_current_user(cx).await;
372        client
373    }
374
375    pub fn disconnect_client(&self, peer_id: PeerId) {
376        self.connection_killers
377            .lock()
378            .remove(&peer_id)
379            .unwrap()
380            .store(true, SeqCst);
381    }
382
383    pub fn simulate_long_connection_interruption(
384        &self,
385        peer_id: PeerId,
386        deterministic: BackgroundExecutor,
387    ) {
388        self.forbid_connections();
389        self.disconnect_client(peer_id);
390        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
391        self.allow_connections();
392        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
393        deterministic.run_until_parked();
394    }
395
396    pub fn forbid_connections(&self) {
397        self.forbid_connections.store(true, SeqCst);
398    }
399
400    pub fn allow_connections(&self) {
401        self.forbid_connections.store(false, SeqCst);
402    }
403
404    pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
405        for ix in 1..clients.len() {
406            let (left, right) = clients.split_at_mut(ix);
407            let (client_a, cx_a) = left.last_mut().unwrap();
408            for (client_b, cx_b) in right {
409                client_a
410                    .app_state
411                    .user_store
412                    .update(*cx_a, |store, cx| {
413                        store.request_contact(client_b.user_id().unwrap(), cx)
414                    })
415                    .await
416                    .unwrap();
417                cx_a.executor().run_until_parked();
418                client_b
419                    .app_state
420                    .user_store
421                    .update(*cx_b, |store, cx| {
422                        store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
423                    })
424                    .await
425                    .unwrap();
426            }
427        }
428    }
429
430    pub async fn make_channel(
431        &self,
432        channel: &str,
433        parent: Option<ChannelId>,
434        admin: (&TestClient, &mut TestAppContext),
435        members: &mut [(&TestClient, &mut TestAppContext)],
436    ) -> ChannelId {
437        let (_, admin_cx) = admin;
438        let channel_id = admin_cx
439            .read(ChannelStore::global)
440            .update(admin_cx, |channel_store, cx| {
441                channel_store.create_channel(channel, parent, cx)
442            })
443            .await
444            .unwrap();
445
446        for (member_client, member_cx) in members {
447            admin_cx
448                .read(ChannelStore::global)
449                .update(admin_cx, |channel_store, cx| {
450                    channel_store.invite_member(
451                        channel_id,
452                        member_client.user_id().unwrap(),
453                        ChannelRole::Member,
454                        cx,
455                    )
456                })
457                .await
458                .unwrap();
459
460            admin_cx.executor().run_until_parked();
461
462            member_cx
463                .read(ChannelStore::global)
464                .update(*member_cx, |channels, cx| {
465                    channels.respond_to_channel_invite(channel_id, true, cx)
466                })
467                .await
468                .unwrap();
469        }
470
471        channel_id
472    }
473
474    pub async fn make_public_channel(
475        &self,
476        channel: &str,
477        client: &TestClient,
478        cx: &mut TestAppContext,
479    ) -> ChannelId {
480        let channel_id = self
481            .make_channel(channel, None, (client, cx), &mut [])
482            .await;
483
484        client
485            .channel_store()
486            .update(cx, |channel_store, cx| {
487                channel_store.set_channel_visibility(
488                    channel_id,
489                    proto::ChannelVisibility::Public,
490                    cx,
491                )
492            })
493            .await
494            .unwrap();
495
496        channel_id
497    }
498
499    pub async fn make_channel_tree(
500        &self,
501        channels: &[(&str, Option<&str>)],
502        creator: (&TestClient, &mut TestAppContext),
503    ) -> Vec<ChannelId> {
504        let mut observed_channels = HashMap::default();
505        let mut result = Vec::new();
506        for (channel, parent) in channels {
507            let id;
508            if let Some(parent) = parent {
509                if let Some(parent_id) = observed_channels.get(parent) {
510                    id = self
511                        .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
512                        .await;
513                } else {
514                    panic!(
515                        "Edge {}->{} referenced before {} was created",
516                        parent, channel, parent
517                    )
518                }
519            } else {
520                id = self
521                    .make_channel(channel, None, (creator.0, creator.1), &mut [])
522                    .await;
523            }
524
525            observed_channels.insert(channel, id);
526            result.push(id);
527        }
528
529        result
530    }
531
532    pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
533        self.make_contacts(clients).await;
534
535        let (left, right) = clients.split_at_mut(1);
536        let (_client_a, cx_a) = &mut left[0];
537        let active_call_a = cx_a.read(ActiveCall::global);
538
539        for (client_b, cx_b) in right {
540            let user_id_b = client_b.current_user_id(cx_b).to_proto();
541            active_call_a
542                .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
543                .await
544                .unwrap();
545
546            cx_b.executor().run_until_parked();
547            let active_call_b = cx_b.read(ActiveCall::global);
548            active_call_b
549                .update(*cx_b, |call, cx| call.accept_incoming(cx))
550                .await
551                .unwrap();
552        }
553    }
554
555    pub async fn build_app_state(
556        test_db: &TestDb,
557        livekit_test_server: &LivekitTestServer,
558        executor: Executor,
559    ) -> Arc<AppState> {
560        Arc::new(AppState {
561            db: test_db.db().clone(),
562            http_client: None,
563            livekit_client: Some(Arc::new(livekit_test_server.create_api_client())),
564            blob_store_client: None,
565            executor,
566            kinesis_client: None,
567            config: Config {
568                http_port: 0,
569                database_url: "".into(),
570                database_max_connections: 0,
571                api_token: "".into(),
572                livekit_server: None,
573                livekit_key: None,
574                livekit_secret: None,
575                rust_log: None,
576                log_json: None,
577                zed_environment: "test".into(),
578                blob_store_url: None,
579                blob_store_region: None,
580                blob_store_access_key: None,
581                blob_store_secret_key: None,
582                blob_store_bucket: None,
583                zed_client_checksum_seed: None,
584                seed_path: None,
585                kinesis_region: None,
586                kinesis_stream: None,
587                kinesis_access_key: None,
588                kinesis_secret_key: None,
589            },
590        })
591    }
592}
593
594impl Deref for TestServer {
595    type Target = Server;
596
597    fn deref(&self) -> &Self::Target {
598        &self.server
599    }
600}
601
602impl Drop for TestServer {
603    fn drop(&mut self) {
604        self.server.teardown();
605        self.test_livekit_server.teardown().unwrap();
606    }
607}
608
609impl Deref for TestClient {
610    type Target = Arc<Client>;
611
612    fn deref(&self) -> &Self::Target {
613        &self.app_state.client
614    }
615}
616
617impl TestClient {
618    pub fn fs(&self) -> Arc<FakeFs> {
619        self.app_state.fs.as_fake()
620    }
621
622    pub fn channel_store(&self) -> &Entity<ChannelStore> {
623        &self.channel_store
624    }
625
626    pub fn notification_store(&self) -> &Entity<NotificationStore> {
627        &self.notification_store
628    }
629
630    pub fn user_store(&self) -> &Entity<UserStore> {
631        &self.app_state.user_store
632    }
633
634    pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
635        &self.app_state.languages
636    }
637
638    pub fn client(&self) -> &Arc<Client> {
639        &self.app_state.client
640    }
641
642    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
643        UserId::from_proto(
644            self.app_state
645                .user_store
646                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
647        )
648    }
649
650    pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
651        let mut authed_user = self
652            .app_state
653            .user_store
654            .read_with(cx, |user_store, _| user_store.watch_current_user());
655        while authed_user.next().await.unwrap().is_none() {}
656    }
657
658    pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
659        self.app_state
660            .user_store
661            .update(cx, |store, _| store.clear_contacts())
662            .await;
663    }
664
665    pub fn local_projects(&self) -> impl Deref<Target = Vec<Entity<Project>>> + '_ {
666        Ref::map(self.state.borrow(), |state| &state.local_projects)
667    }
668
669    pub fn dev_server_projects(&self) -> impl Deref<Target = Vec<Entity<Project>>> + '_ {
670        Ref::map(self.state.borrow(), |state| &state.dev_server_projects)
671    }
672
673    pub fn local_projects_mut(&self) -> impl DerefMut<Target = Vec<Entity<Project>>> + '_ {
674        RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
675    }
676
677    pub fn dev_server_projects_mut(&self) -> impl DerefMut<Target = Vec<Entity<Project>>> + '_ {
678        RefMut::map(self.state.borrow_mut(), |state| {
679            &mut state.dev_server_projects
680        })
681    }
682
683    pub fn buffers_for_project<'a>(
684        &'a self,
685        project: &Entity<Project>,
686    ) -> impl DerefMut<Target = HashSet<Entity<language::Buffer>>> + 'a {
687        RefMut::map(self.state.borrow_mut(), |state| {
688            state.buffers.entry(project.clone()).or_default()
689        })
690    }
691
692    pub fn buffers(
693        &self,
694    ) -> impl DerefMut<Target = HashMap<Entity<Project>, HashSet<Entity<language::Buffer>>>> + '_
695    {
696        RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
697    }
698
699    pub fn channel_buffers(&self) -> impl DerefMut<Target = HashSet<Entity<ChannelBuffer>>> + '_ {
700        RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
701    }
702
703    pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
704        self.app_state
705            .user_store
706            .read_with(cx, |store, _| ContactsSummary {
707                current: store
708                    .contacts()
709                    .iter()
710                    .map(|contact| contact.user.github_login.clone().to_string())
711                    .collect(),
712                outgoing_requests: store
713                    .outgoing_contact_requests()
714                    .iter()
715                    .map(|user| user.github_login.clone().to_string())
716                    .collect(),
717                incoming_requests: store
718                    .incoming_contact_requests()
719                    .iter()
720                    .map(|user| user.github_login.clone().to_string())
721                    .collect(),
722            })
723    }
724
725    pub async fn build_local_project(
726        &self,
727        root_path: impl AsRef<Path>,
728        cx: &mut TestAppContext,
729    ) -> (Entity<Project>, WorktreeId) {
730        let project = self.build_empty_local_project(false, cx);
731        let (worktree, _) = project
732            .update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
733            .await
734            .unwrap();
735        worktree
736            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
737            .await;
738        cx.run_until_parked();
739        (project, worktree.read_with(cx, |tree, _| tree.id()))
740    }
741
742    pub async fn build_local_project_with_trust(
743        &self,
744        root_path: impl AsRef<Path>,
745        cx: &mut TestAppContext,
746    ) -> (Entity<Project>, WorktreeId) {
747        let project = self.build_empty_local_project(true, cx);
748        let (worktree, _) = project
749            .update(cx, |p, cx| p.find_or_create_worktree(root_path, true, cx))
750            .await
751            .unwrap();
752        worktree
753            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
754            .await;
755        cx.run_until_parked();
756        (project, worktree.read_with(cx, |tree, _| tree.id()))
757    }
758
759    pub async fn build_ssh_project(
760        &self,
761        root_path: impl AsRef<Path>,
762        ssh: Entity<RemoteClient>,
763        init_worktree_trust: bool,
764        cx: &mut TestAppContext,
765    ) -> (Entity<Project>, WorktreeId) {
766        let project = cx.update(|cx| {
767            Project::remote(
768                ssh,
769                self.client().clone(),
770                self.app_state.node_runtime.clone(),
771                self.app_state.user_store.clone(),
772                self.app_state.languages.clone(),
773                self.app_state.fs.clone(),
774                init_worktree_trust,
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, 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(
835        &self,
836        init_worktree_trust: bool,
837        cx: &mut TestAppContext,
838    ) -> Entity<Project> {
839        cx.update(|cx| {
840            Project::local(
841                self.client().clone(),
842                self.app_state.node_runtime.clone(),
843                self.app_state.user_store.clone(),
844                self.app_state.languages.clone(),
845                self.app_state.fs.clone(),
846                None,
847                project::LocalProjectFlags {
848                    init_worktree_trust,
849                    ..Default::default()
850                },
851                cx,
852            )
853        })
854    }
855
856    pub async fn join_remote_project(
857        &self,
858        host_project_id: u64,
859        guest_cx: &mut TestAppContext,
860    ) -> Entity<Project> {
861        let active_call = guest_cx.read(ActiveCall::global);
862        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
863        room.update(guest_cx, |room, cx| {
864            room.join_project(
865                host_project_id,
866                self.app_state.languages.clone(),
867                self.app_state.fs.clone(),
868                cx,
869            )
870        })
871        .await
872        .unwrap()
873    }
874
875    pub fn build_workspace<'a>(
876        &'a self,
877        project: &Entity<Project>,
878        cx: &'a mut TestAppContext,
879    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
880        let app_state = self.app_state.clone();
881        let project = project.clone();
882        let window = cx.add_window(|window, cx| {
883            window.activate_window();
884            let workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
885            MultiWorkspace::new(workspace, window, cx)
886        });
887        let cx = VisualTestContext::from_window(*window, cx).into_mut();
888        cx.run_until_parked();
889        let workspace = window
890            .read_with(cx, |mw, _| mw.workspace().clone())
891            .unwrap();
892        (workspace, cx)
893    }
894
895    pub async fn build_test_workspace<'a>(
896        &'a self,
897        cx: &'a mut TestAppContext,
898    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
899        let project = self.build_test_project(cx).await;
900        let app_state = self.app_state.clone();
901        let window = cx.add_window(|window, cx| {
902            window.activate_window();
903            let workspace = cx.new(|cx| Workspace::new(None, project, app_state, window, cx));
904            MultiWorkspace::new(workspace, window, cx)
905        });
906        let cx = VisualTestContext::from_window(*window, cx).into_mut();
907        let workspace = window
908            .read_with(cx, |mw, _| mw.workspace().clone())
909            .unwrap();
910        (workspace, cx)
911    }
912
913    pub fn active_workspace<'a>(
914        &'a self,
915        cx: &'a mut TestAppContext,
916    ) -> (Entity<Workspace>, &'a mut VisualTestContext) {
917        let window = cx.update(|cx| {
918            cx.active_window()
919                .unwrap()
920                .downcast::<MultiWorkspace>()
921                .unwrap()
922        });
923
924        let entity = window
925            .read_with(cx, |mw, _| mw.workspace().clone())
926            .unwrap();
927        let cx = VisualTestContext::from_window(*window.deref(), cx).into_mut();
928        // it might be nice to try and cleanup these at the end of each test.
929        (entity, cx)
930    }
931}
932
933pub fn open_channel_notes(
934    channel_id: ChannelId,
935    cx: &mut VisualTestContext,
936) -> Task<anyhow::Result<Entity<ChannelView>>> {
937    let window = cx.update(|_, cx| {
938        cx.active_window()
939            .unwrap()
940            .downcast::<MultiWorkspace>()
941            .unwrap()
942    });
943    let entity = window
944        .read_with(cx, |mw, _| mw.workspace().clone())
945        .unwrap();
946
947    cx.update(|window, cx| ChannelView::open(channel_id, None, entity.clone(), window, cx))
948}
949
950impl Drop for TestClient {
951    fn drop(&mut self) {
952        self.app_state.client.teardown();
953    }
954}