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, WorkspaceId, 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 language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
261        let app_state = Arc::new(workspace::AppState {
262            client: client.clone(),
263            user_store: user_store.clone(),
264            workspace_store,
265            languages: language_registry,
266            fs: fs.clone(),
267            build_window_options: |_, _| Default::default(),
268            node_runtime: FakeNodeRuntime::new(),
269        });
270
271        cx.update(|cx| {
272            theme::init(theme::LoadThemes::JustBase, cx);
273            Project::init(&client, cx);
274            client::init(&client, cx);
275            language::init(cx);
276            editor::init(cx);
277            workspace::init(app_state.clone(), cx);
278            call::init(client.clone(), user_store.clone(), cx);
279            channel::init(&client, user_store.clone(), cx);
280            notifications::init(client.clone(), user_store, cx);
281            collab_ui::init(&app_state, cx);
282            file_finder::init(cx);
283            menu::init();
284            settings::KeymapFile::load_asset("keymaps/default-macos.json", cx).unwrap();
285        });
286
287        client
288            .authenticate_and_connect(false, &cx.to_async())
289            .await
290            .unwrap();
291
292        let client = TestClient {
293            app_state,
294            username: name.to_string(),
295            channel_store: cx.read(ChannelStore::global).clone(),
296            notification_store: cx.read(NotificationStore::global).clone(),
297            state: Default::default(),
298        };
299        client.wait_for_current_user(cx).await;
300        client
301    }
302
303    pub fn disconnect_client(&self, peer_id: PeerId) {
304        self.connection_killers
305            .lock()
306            .remove(&peer_id)
307            .unwrap()
308            .store(true, SeqCst);
309    }
310
311    pub fn simulate_long_connection_interruption(
312        &self,
313        peer_id: PeerId,
314        deterministic: BackgroundExecutor,
315    ) {
316        self.forbid_connections();
317        self.disconnect_client(peer_id);
318        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
319        self.allow_connections();
320        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
321        deterministic.run_until_parked();
322    }
323
324    pub fn forbid_connections(&self) {
325        self.forbid_connections.store(true, SeqCst);
326    }
327
328    pub fn allow_connections(&self) {
329        self.forbid_connections.store(false, SeqCst);
330    }
331
332    pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
333        for ix in 1..clients.len() {
334            let (left, right) = clients.split_at_mut(ix);
335            let (client_a, cx_a) = left.last_mut().unwrap();
336            for (client_b, cx_b) in right {
337                client_a
338                    .app_state
339                    .user_store
340                    .update(*cx_a, |store, cx| {
341                        store.request_contact(client_b.user_id().unwrap(), cx)
342                    })
343                    .await
344                    .unwrap();
345                cx_a.executor().run_until_parked();
346                client_b
347                    .app_state
348                    .user_store
349                    .update(*cx_b, |store, cx| {
350                        store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
351                    })
352                    .await
353                    .unwrap();
354            }
355        }
356    }
357
358    pub async fn make_channel(
359        &self,
360        channel: &str,
361        parent: Option<ChannelId>,
362        admin: (&TestClient, &mut TestAppContext),
363        members: &mut [(&TestClient, &mut TestAppContext)],
364    ) -> ChannelId {
365        let (_, admin_cx) = admin;
366        let channel_id = admin_cx
367            .read(ChannelStore::global)
368            .update(admin_cx, |channel_store, cx| {
369                channel_store.create_channel(channel, parent, cx)
370            })
371            .await
372            .unwrap();
373
374        for (member_client, member_cx) in members {
375            admin_cx
376                .read(ChannelStore::global)
377                .update(admin_cx, |channel_store, cx| {
378                    channel_store.invite_member(
379                        channel_id,
380                        member_client.user_id().unwrap(),
381                        ChannelRole::Member,
382                        cx,
383                    )
384                })
385                .await
386                .unwrap();
387
388            admin_cx.executor().run_until_parked();
389
390            member_cx
391                .read(ChannelStore::global)
392                .update(*member_cx, |channels, cx| {
393                    channels.respond_to_channel_invite(channel_id, true, cx)
394                })
395                .await
396                .unwrap();
397        }
398
399        channel_id
400    }
401
402    pub async fn make_public_channel(
403        &self,
404        channel: &str,
405        client: &TestClient,
406        cx: &mut TestAppContext,
407    ) -> ChannelId {
408        let channel_id = self
409            .make_channel(channel, None, (client, cx), &mut [])
410            .await;
411
412        client
413            .channel_store()
414            .update(cx, |channel_store, cx| {
415                channel_store.set_channel_visibility(
416                    channel_id,
417                    proto::ChannelVisibility::Public,
418                    cx,
419                )
420            })
421            .await
422            .unwrap();
423
424        channel_id
425    }
426
427    pub async fn make_channel_tree(
428        &self,
429        channels: &[(&str, Option<&str>)],
430        creator: (&TestClient, &mut TestAppContext),
431    ) -> Vec<ChannelId> {
432        let mut observed_channels = HashMap::default();
433        let mut result = Vec::new();
434        for (channel, parent) in channels {
435            let id;
436            if let Some(parent) = parent {
437                if let Some(parent_id) = observed_channels.get(parent) {
438                    id = self
439                        .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
440                        .await;
441                } else {
442                    panic!(
443                        "Edge {}->{} referenced before {} was created",
444                        parent, channel, parent
445                    )
446                }
447            } else {
448                id = self
449                    .make_channel(channel, None, (creator.0, creator.1), &mut [])
450                    .await;
451            }
452
453            observed_channels.insert(channel, id);
454            result.push(id);
455        }
456
457        result
458    }
459
460    pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
461        self.make_contacts(clients).await;
462
463        let (left, right) = clients.split_at_mut(1);
464        let (_client_a, cx_a) = &mut left[0];
465        let active_call_a = cx_a.read(ActiveCall::global);
466
467        for (client_b, cx_b) in right {
468            let user_id_b = client_b.current_user_id(cx_b).to_proto();
469            active_call_a
470                .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
471                .await
472                .unwrap();
473
474            cx_b.executor().run_until_parked();
475            let active_call_b = cx_b.read(ActiveCall::global);
476            active_call_b
477                .update(*cx_b, |call, cx| call.accept_incoming(cx))
478                .await
479                .unwrap();
480        }
481    }
482
483    pub async fn build_app_state(
484        test_db: &TestDb,
485        fake_server: &live_kit_client::TestServer,
486    ) -> Arc<AppState> {
487        Arc::new(AppState {
488            db: test_db.db().clone(),
489            live_kit_client: Some(Arc::new(fake_server.create_api_client())),
490            blob_store_client: None,
491            clickhouse_client: None,
492            config: Config {
493                http_port: 0,
494                database_url: "".into(),
495                database_max_connections: 0,
496                api_token: "".into(),
497                invite_link_prefix: "".into(),
498                live_kit_server: None,
499                live_kit_key: None,
500                live_kit_secret: None,
501                rust_log: None,
502                log_json: None,
503                zed_environment: "test".into(),
504                blob_store_url: None,
505                blob_store_region: None,
506                blob_store_access_key: None,
507                blob_store_secret_key: None,
508                blob_store_bucket: None,
509                clickhouse_url: None,
510                clickhouse_user: None,
511                clickhouse_password: None,
512                clickhouse_database: None,
513                zed_client_checksum_seed: None,
514                slack_panics_webhook: None,
515                auto_join_channel_id: 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(
757                WorkspaceId::default(),
758                project.clone(),
759                self.app_state.clone(),
760                cx,
761            )
762        })
763    }
764
765    pub async fn build_test_workspace<'a>(
766        &'a self,
767        cx: &'a mut TestAppContext,
768    ) -> (View<Workspace>, &'a mut VisualTestContext) {
769        let project = self.build_test_project(cx).await;
770        cx.add_window_view(|cx| {
771            cx.activate_window();
772            Workspace::new(
773                WorkspaceId::default(),
774                project.clone(),
775                self.app_state.clone(),
776                cx,
777            )
778        })
779    }
780
781    pub fn active_workspace<'a>(
782        &'a self,
783        cx: &'a mut TestAppContext,
784    ) -> (View<Workspace>, &'a mut VisualTestContext) {
785        let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
786
787        let view = window.root_view(cx).unwrap();
788        let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
789        // it might be nice to try and cleanup these at the end of each test.
790        (view, cx)
791    }
792}
793
794pub fn open_channel_notes(
795    channel_id: ChannelId,
796    cx: &mut VisualTestContext,
797) -> Task<anyhow::Result<View<ChannelView>>> {
798    let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
799    let view = window.root_view(cx).unwrap();
800
801    cx.update(|cx| ChannelView::open(channel_id, None, view.clone(), cx))
802}
803
804impl Drop for TestClient {
805    fn drop(&mut self) {
806        self.app_state.client.teardown();
807    }
808}