test_server.rs

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