test_server.rs

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