test_server.rs

  1use crate::{
  2    db::{tests::TestDb, NewUserParams, UserId},
  3    executor::Executor,
  4    rpc::{Principal, Server, ZedVersion, CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
  5    AppState, Config, RateLimiter,
  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;
 22use notifications::NotificationStore;
 23use parking_lot::Mutex;
 24use project::{Project, WorktreeId};
 25use rpc::{
 26    proto::{self, ChannelRole},
 27    RECEIVE_TIMEOUT,
 28};
 29use semantic_version::SemanticVersion;
 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;
 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 executor = Executor::Deterministic(deterministic.clone());
 97        let app_state = Self::build_app_state(&test_db, &live_kit_server, executor.clone()).await;
 98        let epoch = app_state
 99            .db
100            .create_server(&app_state.config.zed_environment)
101            .await
102            .unwrap();
103        let server = Server::new(epoch, app_state.clone());
104        server.start().await.unwrap();
105        // Advance clock to ensure the server's cleanup task is finished.
106        deterministic.advance_clock(CLEANUP_TIMEOUT);
107        Self {
108            app_state,
109            server,
110            connection_killers: Default::default(),
111            forbid_connections: Default::default(),
112            next_github_user_id: 0,
113            _test_db: test_db,
114            test_live_kit_server: live_kit_server,
115        }
116    }
117
118    pub async fn start2(
119        cx_a: &mut TestAppContext,
120        cx_b: &mut TestAppContext,
121    ) -> (TestServer, TestClient, TestClient, ChannelId) {
122        let mut server = Self::start(cx_a.executor()).await;
123        let client_a = server.create_client(cx_a, "user_a").await;
124        let client_b = server.create_client(cx_b, "user_b").await;
125        let channel_id = server
126            .make_channel(
127                "test-channel",
128                None,
129                (&client_a, cx_a),
130                &mut [(&client_b, cx_b)],
131            )
132            .await;
133        cx_a.run_until_parked();
134
135        (server, client_a, client_b, channel_id)
136    }
137
138    pub async fn start1(cx: &mut TestAppContext) -> TestClient {
139        let mut server = Self::start(cx.executor().clone()).await;
140        server.create_client(cx, "user_a").await
141    }
142
143    pub async fn reset(&self) {
144        self.app_state.db.reset();
145        let epoch = self
146            .app_state
147            .db
148            .create_server(&self.app_state.config.zed_environment)
149            .await
150            .unwrap();
151        self.server.reset(epoch);
152    }
153
154    pub async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
155        cx.update(|cx| {
156            if cx.has_global::<SettingsStore>() {
157                panic!("Same cx used to create two test clients")
158            }
159            let settings = SettingsStore::test(cx);
160            cx.set_global(settings);
161            release_channel::init("0.0.0", cx);
162            client::init_settings(cx);
163        });
164
165        let clock = Arc::new(FakeSystemClock::default());
166        let http = FakeHttpClient::with_404_response();
167        let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
168        {
169            user.id
170        } else {
171            let github_user_id = self.next_github_user_id;
172            self.next_github_user_id += 1;
173            self.app_state
174                .db
175                .create_user(
176                    &format!("{name}@example.com"),
177                    false,
178                    NewUserParams {
179                        github_login: name.into(),
180                        github_user_id,
181                    },
182                )
183                .await
184                .expect("creating user failed")
185                .user_id
186        };
187        let client_name = name.to_string();
188        let mut client = cx.update(|cx| Client::new(clock, http.clone(), cx));
189        let server = self.server.clone();
190        let db = self.app_state.db.clone();
191        let connection_killers = self.connection_killers.clone();
192        let forbid_connections = self.forbid_connections.clone();
193
194        Arc::get_mut(&mut client)
195            .unwrap()
196            .set_id(user_id.to_proto())
197            .override_authenticate(move |cx| {
198                cx.spawn(|_| async move {
199                    let access_token = "the-token".to_string();
200                    Ok(Credentials::User {
201                        user_id: user_id.to_proto(),
202                        access_token,
203                    })
204                })
205            })
206            .override_establish_connection(move |credentials, cx| {
207                assert_eq!(
208                    credentials,
209                    &Credentials::User {
210                        user_id: user_id.0 as u64,
211                        access_token: "the-token".into()
212                    }
213                );
214
215                let server = server.clone();
216                let db = db.clone();
217                let connection_killers = connection_killers.clone();
218                let forbid_connections = forbid_connections.clone();
219                let client_name = client_name.clone();
220                cx.spawn(move |cx| async move {
221                    if forbid_connections.load(SeqCst) {
222                        Err(EstablishConnectionError::other(anyhow!(
223                            "server is forbidding connections"
224                        )))
225                    } else {
226                        let (client_conn, server_conn, killed) =
227                            Connection::in_memory(cx.background_executor().clone());
228                        let (connection_id_tx, connection_id_rx) = oneshot::channel();
229                        let user = db
230                            .get_user_by_id(user_id)
231                            .await
232                            .expect("retrieving user failed")
233                            .unwrap();
234                        cx.background_executor()
235                            .spawn(server.handle_connection(
236                                server_conn,
237                                client_name,
238                                Principal::User(user),
239                                ZedVersion(SemanticVersion::new(1, 0, 0)),
240                                Some(connection_id_tx),
241                                Executor::Deterministic(cx.background_executor().clone()),
242                            ))
243                            .detach();
244                        let connection_id = connection_id_rx.await.map_err(|e| {
245                            EstablishConnectionError::Other(anyhow!(
246                                "{} (is server shutting down?)",
247                                e
248                            ))
249                        })?;
250                        connection_killers
251                            .lock()
252                            .insert(connection_id.into(), killed);
253                        Ok(client_conn)
254                    }
255                })
256            });
257
258        let fs = FakeFs::new(cx.executor());
259        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
260        let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx));
261        let language_registry = Arc::new(LanguageRegistry::test(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: 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        live_kit_test_server: &live_kit_client::TestServer,
487        executor: Executor,
488    ) -> Arc<AppState> {
489        Arc::new(AppState {
490            db: test_db.db().clone(),
491            live_kit_client: Some(Arc::new(live_kit_test_server.create_api_client())),
492            blob_store_client: None,
493            rate_limiter: Arc::new(RateLimiter::new(test_db.db().clone())),
494            executor,
495            clickhouse_client: None,
496            config: Config {
497                http_port: 0,
498                database_url: "".into(),
499                database_max_connections: 0,
500                api_token: "".into(),
501                invite_link_prefix: "".into(),
502                live_kit_server: None,
503                live_kit_key: None,
504                live_kit_secret: None,
505                rust_log: None,
506                log_json: None,
507                zed_environment: "test".into(),
508                blob_store_url: None,
509                blob_store_region: None,
510                blob_store_access_key: None,
511                blob_store_secret_key: None,
512                blob_store_bucket: None,
513                openai_api_key: None,
514                google_ai_api_key: None,
515                clickhouse_url: None,
516                clickhouse_user: None,
517                clickhouse_password: None,
518                clickhouse_database: None,
519                zed_client_checksum_seed: None,
520                slack_panics_webhook: None,
521                auto_join_channel_id: None,
522                migrations_path: None,
523                seed_path: None,
524            },
525        })
526    }
527}
528
529impl Deref for TestServer {
530    type Target = Server;
531
532    fn deref(&self) -> &Self::Target {
533        &self.server
534    }
535}
536
537impl Drop for TestServer {
538    fn drop(&mut self) {
539        self.server.teardown();
540        self.test_live_kit_server.teardown().unwrap();
541    }
542}
543
544impl Deref for TestClient {
545    type Target = Arc<Client>;
546
547    fn deref(&self) -> &Self::Target {
548        &self.app_state.client
549    }
550}
551
552impl TestClient {
553    pub fn fs(&self) -> &FakeFs {
554        self.app_state.fs.as_fake()
555    }
556
557    pub fn channel_store(&self) -> &Model<ChannelStore> {
558        &self.channel_store
559    }
560
561    pub fn notification_store(&self) -> &Model<NotificationStore> {
562        &self.notification_store
563    }
564
565    pub fn user_store(&self) -> &Model<UserStore> {
566        &self.app_state.user_store
567    }
568
569    pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
570        &self.app_state.languages
571    }
572
573    pub fn client(&self) -> &Arc<Client> {
574        &self.app_state.client
575    }
576
577    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
578        UserId::from_proto(
579            self.app_state
580                .user_store
581                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
582        )
583    }
584
585    pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
586        let mut authed_user = self
587            .app_state
588            .user_store
589            .read_with(cx, |user_store, _| user_store.watch_current_user());
590        while authed_user.next().await.unwrap().is_none() {}
591    }
592
593    pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
594        self.app_state
595            .user_store
596            .update(cx, |store, _| store.clear_contacts())
597            .await;
598    }
599
600    pub fn local_projects(&self) -> impl Deref<Target = Vec<Model<Project>>> + '_ {
601        Ref::map(self.state.borrow(), |state| &state.local_projects)
602    }
603
604    pub fn remote_projects(&self) -> impl Deref<Target = Vec<Model<Project>>> + '_ {
605        Ref::map(self.state.borrow(), |state| &state.remote_projects)
606    }
607
608    pub fn local_projects_mut(&self) -> impl DerefMut<Target = Vec<Model<Project>>> + '_ {
609        RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
610    }
611
612    pub fn remote_projects_mut(&self) -> impl DerefMut<Target = Vec<Model<Project>>> + '_ {
613        RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
614    }
615
616    pub fn buffers_for_project<'a>(
617        &'a self,
618        project: &Model<Project>,
619    ) -> impl DerefMut<Target = HashSet<Model<language::Buffer>>> + 'a {
620        RefMut::map(self.state.borrow_mut(), |state| {
621            state.buffers.entry(project.clone()).or_default()
622        })
623    }
624
625    pub fn buffers(
626        &self,
627    ) -> impl DerefMut<Target = HashMap<Model<Project>, HashSet<Model<language::Buffer>>>> + '_
628    {
629        RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
630    }
631
632    pub fn channel_buffers(&self) -> impl DerefMut<Target = HashSet<Model<ChannelBuffer>>> + '_ {
633        RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
634    }
635
636    pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
637        self.app_state
638            .user_store
639            .read_with(cx, |store, _| ContactsSummary {
640                current: store
641                    .contacts()
642                    .iter()
643                    .map(|contact| contact.user.github_login.clone())
644                    .collect(),
645                outgoing_requests: store
646                    .outgoing_contact_requests()
647                    .iter()
648                    .map(|user| user.github_login.clone())
649                    .collect(),
650                incoming_requests: store
651                    .incoming_contact_requests()
652                    .iter()
653                    .map(|user| user.github_login.clone())
654                    .collect(),
655            })
656    }
657
658    pub async fn build_local_project(
659        &self,
660        root_path: impl AsRef<Path>,
661        cx: &mut TestAppContext,
662    ) -> (Model<Project>, WorktreeId) {
663        let project = self.build_empty_local_project(cx);
664        let (worktree, _) = project
665            .update(cx, |p, cx| {
666                p.find_or_create_local_worktree(root_path, true, cx)
667            })
668            .await
669            .unwrap();
670        worktree
671            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
672            .await;
673        (project, worktree.read_with(cx, |tree, _| tree.id()))
674    }
675
676    pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Model<Project> {
677        self.fs()
678            .insert_tree(
679                "/a",
680                json!({
681                    "1.txt": "one\none\none",
682                    "2.js": "function two() { return 2; }",
683                    "3.rs": "mod test",
684                }),
685            )
686            .await;
687        self.build_local_project("/a", cx).await.0
688    }
689
690    pub async fn host_workspace(
691        &self,
692        workspace: &View<Workspace>,
693        channel_id: ChannelId,
694        cx: &mut VisualTestContext,
695    ) {
696        cx.update(|cx| {
697            let active_call = ActiveCall::global(cx);
698            active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
699        })
700        .await
701        .unwrap();
702        cx.update(|cx| {
703            let active_call = ActiveCall::global(cx);
704            let project = workspace.read(cx).project().clone();
705            active_call.update(cx, |call, cx| call.share_project(project, cx))
706        })
707        .await
708        .unwrap();
709        cx.executor().run_until_parked();
710    }
711
712    pub async fn join_workspace<'a>(
713        &'a self,
714        channel_id: ChannelId,
715        cx: &'a mut TestAppContext,
716    ) -> (View<Workspace>, &'a mut VisualTestContext) {
717        cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
718            .await
719            .unwrap();
720        cx.run_until_parked();
721
722        self.active_workspace(cx)
723    }
724
725    pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Model<Project> {
726        cx.update(|cx| {
727            Project::local(
728                self.client().clone(),
729                self.app_state.node_runtime.clone(),
730                self.app_state.user_store.clone(),
731                self.app_state.languages.clone(),
732                self.app_state.fs.clone(),
733                cx,
734            )
735        })
736    }
737
738    pub async fn build_remote_project(
739        &self,
740        host_project_id: u64,
741        guest_cx: &mut TestAppContext,
742    ) -> Model<Project> {
743        let active_call = guest_cx.read(ActiveCall::global);
744        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
745        room.update(guest_cx, |room, cx| {
746            room.join_project(
747                host_project_id,
748                self.app_state.languages.clone(),
749                self.app_state.fs.clone(),
750                cx,
751            )
752        })
753        .await
754        .unwrap()
755    }
756
757    pub fn build_workspace<'a>(
758        &'a self,
759        project: &Model<Project>,
760        cx: &'a mut TestAppContext,
761    ) -> (View<Workspace>, &'a mut VisualTestContext) {
762        cx.add_window_view(|cx| {
763            cx.activate_window();
764            Workspace::new(
765                WorkspaceId::default(),
766                project.clone(),
767                self.app_state.clone(),
768                cx,
769            )
770        })
771    }
772
773    pub async fn build_test_workspace<'a>(
774        &'a self,
775        cx: &'a mut TestAppContext,
776    ) -> (View<Workspace>, &'a mut VisualTestContext) {
777        let project = self.build_test_project(cx).await;
778        cx.add_window_view(|cx| {
779            cx.activate_window();
780            Workspace::new(
781                WorkspaceId::default(),
782                project.clone(),
783                self.app_state.clone(),
784                cx,
785            )
786        })
787    }
788
789    pub fn active_workspace<'a>(
790        &'a self,
791        cx: &'a mut TestAppContext,
792    ) -> (View<Workspace>, &'a mut VisualTestContext) {
793        let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
794
795        let view = window.root_view(cx).unwrap();
796        let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
797        // it might be nice to try and cleanup these at the end of each test.
798        (view, cx)
799    }
800}
801
802pub fn open_channel_notes(
803    channel_id: ChannelId,
804    cx: &mut VisualTestContext,
805) -> Task<anyhow::Result<View<ChannelView>>> {
806    let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
807    let view = window.root_view(cx).unwrap();
808
809    cx.update(|cx| ChannelView::open(channel_id, None, view.clone(), cx))
810}
811
812impl Drop for TestClient {
813    fn drop(&mut self) {
814        self.app_state.client.teardown();
815    }
816}