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