test_server.rs

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