test_server.rs

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