test_server.rs

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