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                slack_panics_webhook: None,
511            },
512        })
513    }
514}
515
516impl Deref for TestServer {
517    type Target = Server;
518
519    fn deref(&self) -> &Self::Target {
520        &self.server
521    }
522}
523
524impl Drop for TestServer {
525    fn drop(&mut self) {
526        self.server.teardown();
527        self.test_live_kit_server.teardown().unwrap();
528    }
529}
530
531impl Deref for TestClient {
532    type Target = Arc<Client>;
533
534    fn deref(&self) -> &Self::Target {
535        &self.app_state.client
536    }
537}
538
539impl TestClient {
540    pub fn fs(&self) -> &FakeFs {
541        self.app_state.fs.as_fake()
542    }
543
544    pub fn channel_store(&self) -> &Model<ChannelStore> {
545        &self.channel_store
546    }
547
548    pub fn notification_store(&self) -> &Model<NotificationStore> {
549        &self.notification_store
550    }
551
552    pub fn user_store(&self) -> &Model<UserStore> {
553        &self.app_state.user_store
554    }
555
556    pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
557        &self.app_state.languages
558    }
559
560    pub fn client(&self) -> &Arc<Client> {
561        &self.app_state.client
562    }
563
564    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
565        UserId::from_proto(
566            self.app_state
567                .user_store
568                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
569        )
570    }
571
572    pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
573        let mut authed_user = self
574            .app_state
575            .user_store
576            .read_with(cx, |user_store, _| user_store.watch_current_user());
577        while authed_user.next().await.unwrap().is_none() {}
578    }
579
580    pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
581        self.app_state
582            .user_store
583            .update(cx, |store, _| store.clear_contacts())
584            .await;
585    }
586
587    pub fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<Model<Project>>> + 'a {
588        Ref::map(self.state.borrow(), |state| &state.local_projects)
589    }
590
591    pub fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<Model<Project>>> + 'a {
592        Ref::map(self.state.borrow(), |state| &state.remote_projects)
593    }
594
595    pub fn local_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<Model<Project>>> + 'a {
596        RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
597    }
598
599    pub fn remote_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<Model<Project>>> + 'a {
600        RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
601    }
602
603    pub fn buffers_for_project<'a>(
604        &'a self,
605        project: &Model<Project>,
606    ) -> impl DerefMut<Target = HashSet<Model<language::Buffer>>> + 'a {
607        RefMut::map(self.state.borrow_mut(), |state| {
608            state.buffers.entry(project.clone()).or_default()
609        })
610    }
611
612    pub fn buffers<'a>(
613        &'a self,
614    ) -> impl DerefMut<Target = HashMap<Model<Project>, HashSet<Model<language::Buffer>>>> + 'a
615    {
616        RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
617    }
618
619    pub fn channel_buffers<'a>(
620        &'a self,
621    ) -> impl DerefMut<Target = HashSet<Model<ChannelBuffer>>> + 'a {
622        RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
623    }
624
625    pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
626        self.app_state
627            .user_store
628            .read_with(cx, |store, _| ContactsSummary {
629                current: store
630                    .contacts()
631                    .iter()
632                    .map(|contact| contact.user.github_login.clone())
633                    .collect(),
634                outgoing_requests: store
635                    .outgoing_contact_requests()
636                    .iter()
637                    .map(|user| user.github_login.clone())
638                    .collect(),
639                incoming_requests: store
640                    .incoming_contact_requests()
641                    .iter()
642                    .map(|user| user.github_login.clone())
643                    .collect(),
644            })
645    }
646
647    pub async fn build_local_project(
648        &self,
649        root_path: impl AsRef<Path>,
650        cx: &mut TestAppContext,
651    ) -> (Model<Project>, WorktreeId) {
652        let project = self.build_empty_local_project(cx);
653        let (worktree, _) = project
654            .update(cx, |p, cx| {
655                p.find_or_create_local_worktree(root_path, true, cx)
656            })
657            .await
658            .unwrap();
659        worktree
660            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
661            .await;
662        (project, worktree.read_with(cx, |tree, _| tree.id()))
663    }
664
665    pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Model<Project> {
666        self.fs()
667            .insert_tree(
668                "/a",
669                json!({
670                    "1.txt": "one\none\none",
671                    "2.js": "function two() { return 2; }",
672                    "3.rs": "mod test",
673                }),
674            )
675            .await;
676        self.build_local_project("/a", cx).await.0
677    }
678
679    pub async fn host_workspace(
680        &self,
681        workspace: &View<Workspace>,
682        channel_id: ChannelId,
683        cx: &mut VisualTestContext,
684    ) {
685        cx.update(|cx| {
686            let active_call = ActiveCall::global(cx);
687            active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
688        })
689        .await
690        .unwrap();
691        cx.update(|cx| {
692            let active_call = ActiveCall::global(cx);
693            let project = workspace.read(cx).project().clone();
694            active_call.update(cx, |call, cx| call.share_project(project, cx))
695        })
696        .await
697        .unwrap();
698        cx.executor().run_until_parked();
699    }
700
701    pub async fn join_workspace<'a>(
702        &'a self,
703        channel_id: ChannelId,
704        cx: &'a mut TestAppContext,
705    ) -> (View<Workspace>, &'a mut VisualTestContext) {
706        cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
707            .await
708            .unwrap();
709        cx.run_until_parked();
710
711        self.active_workspace(cx)
712    }
713
714    pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Model<Project> {
715        cx.update(|cx| {
716            Project::local(
717                self.client().clone(),
718                self.app_state.node_runtime.clone(),
719                self.app_state.user_store.clone(),
720                self.app_state.languages.clone(),
721                self.app_state.fs.clone(),
722                cx,
723            )
724        })
725    }
726
727    pub async fn build_remote_project(
728        &self,
729        host_project_id: u64,
730        guest_cx: &mut TestAppContext,
731    ) -> Model<Project> {
732        let active_call = guest_cx.read(ActiveCall::global);
733        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
734        room.update(guest_cx, |room, cx| {
735            room.join_project(
736                host_project_id,
737                self.app_state.languages.clone(),
738                self.app_state.fs.clone(),
739                cx,
740            )
741        })
742        .await
743        .unwrap()
744    }
745
746    pub fn build_workspace<'a>(
747        &'a self,
748        project: &Model<Project>,
749        cx: &'a mut TestAppContext,
750    ) -> (View<Workspace>, &'a mut VisualTestContext) {
751        cx.add_window_view(|cx| {
752            cx.activate_window();
753            Workspace::new(0, project.clone(), self.app_state.clone(), cx)
754        })
755    }
756
757    pub async fn build_test_workspace<'a>(
758        &'a self,
759        cx: &'a mut TestAppContext,
760    ) -> (View<Workspace>, &'a mut VisualTestContext) {
761        let project = self.build_test_project(cx).await;
762        cx.add_window_view(|cx| {
763            cx.activate_window();
764            Workspace::new(0, project.clone(), self.app_state.clone(), cx)
765        })
766    }
767
768    pub fn active_workspace<'a>(
769        &'a self,
770        cx: &'a mut TestAppContext,
771    ) -> (View<Workspace>, &'a mut VisualTestContext) {
772        let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
773
774        let view = window.root_view(cx).unwrap();
775        let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
776        // it might be nice to try and cleanup these at the end of each test.
777        (view, cx)
778    }
779}
780
781pub fn open_channel_notes(
782    channel_id: ChannelId,
783    cx: &mut VisualTestContext,
784) -> Task<anyhow::Result<View<ChannelView>>> {
785    let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
786    let view = window.root_view(cx).unwrap();
787
788    cx.update(|cx| ChannelView::open(channel_id, None, view.clone(), cx))
789}
790
791impl Drop for TestClient {
792    fn drop(&mut self) {
793        self.app_state.client.teardown();
794    }
795}