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