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