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