test_server.rs

  1use crate::{
  2    auth::split_dev_server_token,
  3    db::{tests::TestDb, NewUserParams, UserId},
  4    executor::Executor,
  5    rpc::{Principal, Server, ZedVersion, CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
  6    AppState, Config, RateLimiter,
  7};
  8use anyhow::anyhow;
  9use call::ActiveCall;
 10use channel::{ChannelBuffer, ChannelStore};
 11use client::{
 12    self, proto::PeerId, ChannelId, Client, Connection, Credentials, EstablishConnectionError,
 13    UserStore,
 14};
 15use clock::FakeSystemClock;
 16use collab_ui::channel_view::ChannelView;
 17use collections::{HashMap, HashSet};
 18use fs::FakeFs;
 19use futures::{channel::oneshot, StreamExt as _};
 20use git::GitHostingProviderRegistry;
 21use gpui::{BackgroundExecutor, Context, Model, Task, TestAppContext, View, VisualTestContext};
 22use http::FakeHttpClient;
 23use language::LanguageRegistry;
 24use node_runtime::FakeNodeRuntime;
 25use notifications::NotificationStore;
 26use parking_lot::Mutex;
 27use project::{Project, WorktreeId};
 28use rpc::{
 29    proto::{self, ChannelRole},
 30    RECEIVE_TIMEOUT,
 31};
 32use semantic_version::SemanticVersion;
 33use serde_json::json;
 34use settings::SettingsStore;
 35use std::{
 36    cell::{Ref, RefCell, RefMut},
 37    env,
 38    ops::{Deref, DerefMut},
 39    path::Path,
 40    sync::{
 41        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
 42        Arc,
 43    },
 44};
 45use workspace::{Workspace, WorkspaceStore};
 46
 47pub struct TestServer {
 48    pub app_state: Arc<AppState>,
 49    pub test_live_kit_server: Arc<live_kit_client::TestServer>,
 50    server: Arc<Server>,
 51    next_github_user_id: i32,
 52    connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
 53    forbid_connections: Arc<AtomicBool>,
 54    _test_db: TestDb,
 55}
 56
 57pub struct TestClient {
 58    pub username: String,
 59    pub app_state: Arc<workspace::AppState>,
 60    channel_store: Model<ChannelStore>,
 61    notification_store: Model<NotificationStore>,
 62    state: RefCell<TestClientState>,
 63}
 64
 65#[derive(Default)]
 66struct TestClientState {
 67    local_projects: Vec<Model<Project>>,
 68    dev_server_projects: Vec<Model<Project>>,
 69    buffers: HashMap<Model<Project>, HashSet<Model<language::Buffer>>>,
 70    channel_buffers: HashSet<Model<ChannelBuffer>>,
 71}
 72
 73pub struct ContactsSummary {
 74    pub current: Vec<String>,
 75    pub outgoing_requests: Vec<String>,
 76    pub incoming_requests: Vec<String>,
 77}
 78
 79impl TestServer {
 80    pub async fn start(deterministic: BackgroundExecutor) -> Self {
 81        static NEXT_LIVE_KIT_SERVER_ID: AtomicUsize = AtomicUsize::new(0);
 82
 83        let use_postgres = env::var("USE_POSTGRES").ok();
 84        let use_postgres = use_postgres.as_deref();
 85        let test_db = if use_postgres == Some("true") || use_postgres == Some("1") {
 86            TestDb::postgres(deterministic.clone())
 87        } else {
 88            TestDb::sqlite(deterministic.clone())
 89        };
 90        let live_kit_server_id = NEXT_LIVE_KIT_SERVER_ID.fetch_add(1, SeqCst);
 91        let live_kit_server = live_kit_client::TestServer::create(
 92            format!("http://livekit.{}.test", live_kit_server_id),
 93            format!("devkey-{}", live_kit_server_id),
 94            format!("secret-{}", live_kit_server_id),
 95            deterministic.clone(),
 96        )
 97        .unwrap();
 98        let executor = Executor::Deterministic(deterministic.clone());
 99        let app_state = Self::build_app_state(&test_db, &live_kit_server, executor.clone()).await;
100        let epoch = app_state
101            .db
102            .create_server(&app_state.config.zed_environment)
103            .await
104            .unwrap();
105        let server = Server::new(epoch, app_state.clone());
106        server.start().await.unwrap();
107        // Advance clock to ensure the server's cleanup task is finished.
108        deterministic.advance_clock(CLEANUP_TIMEOUT);
109        Self {
110            app_state,
111            server,
112            connection_killers: Default::default(),
113            forbid_connections: Default::default(),
114            next_github_user_id: 0,
115            _test_db: test_db,
116            test_live_kit_server: live_kit_server,
117        }
118    }
119
120    pub async fn start2(
121        cx_a: &mut TestAppContext,
122        cx_b: &mut TestAppContext,
123    ) -> (TestServer, TestClient, TestClient, ChannelId) {
124        let mut server = Self::start(cx_a.executor()).await;
125        let client_a = server.create_client(cx_a, "user_a").await;
126        let client_b = server.create_client(cx_b, "user_b").await;
127        let channel_id = server
128            .make_channel(
129                "test-channel",
130                None,
131                (&client_a, cx_a),
132                &mut [(&client_b, cx_b)],
133            )
134            .await;
135        cx_a.run_until_parked();
136
137        (server, client_a, client_b, channel_id)
138    }
139
140    pub async fn start1(cx: &mut TestAppContext) -> (TestServer, TestClient) {
141        let mut server = Self::start(cx.executor().clone()).await;
142        let client = server.create_client(cx, "user_a").await;
143        (server, client)
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(SemanticVersion::default(), 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::User {
204                        user_id: user_id.to_proto(),
205                        access_token,
206                    })
207                })
208            })
209            .override_establish_connection(move |credentials, cx| {
210                assert_eq!(
211                    credentials,
212                    &Credentials::User {
213                        user_id: user_id.0 as u64,
214                        access_token: "the-token".into()
215                    }
216                );
217
218                let server = server.clone();
219                let db = db.clone();
220                let connection_killers = connection_killers.clone();
221                let forbid_connections = forbid_connections.clone();
222                let client_name = client_name.clone();
223                cx.spawn(move |cx| async move {
224                    if forbid_connections.load(SeqCst) {
225                        Err(EstablishConnectionError::other(anyhow!(
226                            "server is forbidding connections"
227                        )))
228                    } else {
229                        let (client_conn, server_conn, killed) =
230                            Connection::in_memory(cx.background_executor().clone());
231                        let (connection_id_tx, connection_id_rx) = oneshot::channel();
232                        let user = db
233                            .get_user_by_id(user_id)
234                            .await
235                            .expect("retrieving user failed")
236                            .unwrap();
237                        cx.background_executor()
238                            .spawn(server.handle_connection(
239                                server_conn,
240                                client_name,
241                                Principal::User(user),
242                                ZedVersion(SemanticVersion::new(1, 0, 0)),
243                                Some(connection_id_tx),
244                                Executor::Deterministic(cx.background_executor().clone()),
245                            ))
246                            .detach();
247                        let connection_id = connection_id_rx.await.map_err(|e| {
248                            EstablishConnectionError::Other(anyhow!(
249                                "{} (is server shutting down?)",
250                                e
251                            ))
252                        })?;
253                        connection_killers
254                            .lock()
255                            .insert(connection_id.into(), killed);
256                        Ok(client_conn)
257                    }
258                })
259            });
260
261        let git_hosting_provider_registry =
262            cx.update(|cx| GitHostingProviderRegistry::default_global(cx));
263        git_hosting_provider_registry
264            .register_hosting_provider(Arc::new(git_hosting_providers::Github));
265
266        let fs = FakeFs::new(cx.executor());
267        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
268        let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx));
269        let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
270        let app_state = Arc::new(workspace::AppState {
271            client: client.clone(),
272            user_store: user_store.clone(),
273            workspace_store,
274            languages: language_registry,
275            fs: fs.clone(),
276            build_window_options: |_, _| Default::default(),
277            node_runtime: FakeNodeRuntime::new(),
278        });
279
280        let os_keymap = "keymaps/default-macos.json";
281
282        cx.update(|cx| {
283            theme::init(theme::LoadThemes::JustBase, cx);
284            Project::init(&client, cx);
285            client::init(&client, cx);
286            language::init(cx);
287            editor::init(cx);
288            workspace::init(app_state.clone(), cx);
289            call::init(client.clone(), user_store.clone(), cx);
290            channel::init(&client, user_store.clone(), cx);
291            notifications::init(client.clone(), user_store, cx);
292            collab_ui::init(&app_state, cx);
293            file_finder::init(cx);
294            menu::init();
295            dev_server_projects::init(client.clone(), cx);
296            settings::KeymapFile::load_asset(os_keymap, cx).unwrap();
297        });
298
299        client
300            .authenticate_and_connect(false, &cx.to_async())
301            .await
302            .unwrap();
303
304        let client = TestClient {
305            app_state,
306            username: name.to_string(),
307            channel_store: cx.read(ChannelStore::global).clone(),
308            notification_store: cx.read(NotificationStore::global).clone(),
309            state: Default::default(),
310        };
311        client.wait_for_current_user(cx).await;
312        client
313    }
314
315    pub async fn create_dev_server(
316        &self,
317        access_token: String,
318        cx: &mut TestAppContext,
319    ) -> TestClient {
320        cx.update(|cx| {
321            if cx.has_global::<SettingsStore>() {
322                panic!("Same cx used to create two test clients")
323            }
324            let settings = SettingsStore::test(cx);
325            cx.set_global(settings);
326            release_channel::init(SemanticVersion::default(), cx);
327            client::init_settings(cx);
328        });
329        let (dev_server_id, _) = split_dev_server_token(&access_token).unwrap();
330
331        let clock = Arc::new(FakeSystemClock::default());
332        let http = FakeHttpClient::with_404_response();
333        let mut client = cx.update(|cx| Client::new(clock, http.clone(), cx));
334        let server = self.server.clone();
335        let db = self.app_state.db.clone();
336        let connection_killers = self.connection_killers.clone();
337        let forbid_connections = self.forbid_connections.clone();
338        Arc::get_mut(&mut client)
339            .unwrap()
340            .set_id(1)
341            .set_dev_server_token(client::DevServerToken(access_token.clone()))
342            .override_establish_connection(move |credentials, cx| {
343                assert_eq!(
344                    credentials,
345                    &Credentials::DevServer {
346                        token: client::DevServerToken(access_token.to_string())
347                    }
348                );
349
350                let server = server.clone();
351                let db = db.clone();
352                let connection_killers = connection_killers.clone();
353                let forbid_connections = forbid_connections.clone();
354                cx.spawn(move |cx| async move {
355                    if forbid_connections.load(SeqCst) {
356                        Err(EstablishConnectionError::other(anyhow!(
357                            "server is forbidding connections"
358                        )))
359                    } else {
360                        let (client_conn, server_conn, killed) =
361                            Connection::in_memory(cx.background_executor().clone());
362                        let (connection_id_tx, connection_id_rx) = oneshot::channel();
363                        let dev_server = db
364                            .get_dev_server(dev_server_id)
365                            .await
366                            .expect("retrieving dev_server failed");
367                        cx.background_executor()
368                            .spawn(server.handle_connection(
369                                server_conn,
370                                "dev-server".to_string(),
371                                Principal::DevServer(dev_server),
372                                ZedVersion(SemanticVersion::new(1, 0, 0)),
373                                Some(connection_id_tx),
374                                Executor::Deterministic(cx.background_executor().clone()),
375                            ))
376                            .detach();
377                        let connection_id = connection_id_rx.await.map_err(|e| {
378                            EstablishConnectionError::Other(anyhow!(
379                                "{} (is server shutting down?)",
380                                e
381                            ))
382                        })?;
383                        connection_killers
384                            .lock()
385                            .insert(connection_id.into(), killed);
386                        Ok(client_conn)
387                    }
388                })
389            });
390
391        let fs = FakeFs::new(cx.executor());
392        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
393        let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx));
394        let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
395        let app_state = Arc::new(workspace::AppState {
396            client: client.clone(),
397            user_store: user_store.clone(),
398            workspace_store,
399            languages: language_registry,
400            fs: fs.clone(),
401            build_window_options: |_, _| Default::default(),
402            node_runtime: FakeNodeRuntime::new(),
403        });
404
405        cx.update(|cx| {
406            theme::init(theme::LoadThemes::JustBase, cx);
407            Project::init(&client, cx);
408            client::init(&client, cx);
409            language::init(cx);
410            editor::init(cx);
411            workspace::init(app_state.clone(), cx);
412            call::init(client.clone(), user_store.clone(), cx);
413            channel::init(&client, user_store.clone(), cx);
414            notifications::init(client.clone(), user_store, cx);
415            collab_ui::init(&app_state, cx);
416            file_finder::init(cx);
417            menu::init();
418            headless::init(
419                client.clone(),
420                headless::AppState {
421                    languages: app_state.languages.clone(),
422                    user_store: app_state.user_store.clone(),
423                    fs: fs.clone(),
424                    node_runtime: app_state.node_runtime.clone(),
425                },
426                cx,
427            )
428        })
429        .await
430        .unwrap();
431
432        TestClient {
433            app_state,
434            username: "dev-server".to_string(),
435            channel_store: cx.read(ChannelStore::global).clone(),
436            notification_store: cx.read(NotificationStore::global).clone(),
437            state: Default::default(),
438        }
439    }
440
441    pub fn disconnect_client(&self, peer_id: PeerId) {
442        self.connection_killers
443            .lock()
444            .remove(&peer_id)
445            .unwrap()
446            .store(true, SeqCst);
447    }
448
449    pub fn simulate_long_connection_interruption(
450        &self,
451        peer_id: PeerId,
452        deterministic: BackgroundExecutor,
453    ) {
454        self.forbid_connections();
455        self.disconnect_client(peer_id);
456        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
457        self.allow_connections();
458        deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
459        deterministic.run_until_parked();
460    }
461
462    pub fn forbid_connections(&self) {
463        self.forbid_connections.store(true, SeqCst);
464    }
465
466    pub fn allow_connections(&self) {
467        self.forbid_connections.store(false, SeqCst);
468    }
469
470    pub async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
471        for ix in 1..clients.len() {
472            let (left, right) = clients.split_at_mut(ix);
473            let (client_a, cx_a) = left.last_mut().unwrap();
474            for (client_b, cx_b) in right {
475                client_a
476                    .app_state
477                    .user_store
478                    .update(*cx_a, |store, cx| {
479                        store.request_contact(client_b.user_id().unwrap(), cx)
480                    })
481                    .await
482                    .unwrap();
483                cx_a.executor().run_until_parked();
484                client_b
485                    .app_state
486                    .user_store
487                    .update(*cx_b, |store, cx| {
488                        store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
489                    })
490                    .await
491                    .unwrap();
492            }
493        }
494    }
495
496    pub async fn make_channel(
497        &self,
498        channel: &str,
499        parent: Option<ChannelId>,
500        admin: (&TestClient, &mut TestAppContext),
501        members: &mut [(&TestClient, &mut TestAppContext)],
502    ) -> ChannelId {
503        let (_, admin_cx) = admin;
504        let channel_id = admin_cx
505            .read(ChannelStore::global)
506            .update(admin_cx, |channel_store, cx| {
507                channel_store.create_channel(channel, parent, cx)
508            })
509            .await
510            .unwrap();
511
512        for (member_client, member_cx) in members {
513            admin_cx
514                .read(ChannelStore::global)
515                .update(admin_cx, |channel_store, cx| {
516                    channel_store.invite_member(
517                        channel_id,
518                        member_client.user_id().unwrap(),
519                        ChannelRole::Member,
520                        cx,
521                    )
522                })
523                .await
524                .unwrap();
525
526            admin_cx.executor().run_until_parked();
527
528            member_cx
529                .read(ChannelStore::global)
530                .update(*member_cx, |channels, cx| {
531                    channels.respond_to_channel_invite(channel_id, true, cx)
532                })
533                .await
534                .unwrap();
535        }
536
537        channel_id
538    }
539
540    pub async fn make_public_channel(
541        &self,
542        channel: &str,
543        client: &TestClient,
544        cx: &mut TestAppContext,
545    ) -> ChannelId {
546        let channel_id = self
547            .make_channel(channel, None, (client, cx), &mut [])
548            .await;
549
550        client
551            .channel_store()
552            .update(cx, |channel_store, cx| {
553                channel_store.set_channel_visibility(
554                    channel_id,
555                    proto::ChannelVisibility::Public,
556                    cx,
557                )
558            })
559            .await
560            .unwrap();
561
562        channel_id
563    }
564
565    pub async fn make_channel_tree(
566        &self,
567        channels: &[(&str, Option<&str>)],
568        creator: (&TestClient, &mut TestAppContext),
569    ) -> Vec<ChannelId> {
570        let mut observed_channels = HashMap::default();
571        let mut result = Vec::new();
572        for (channel, parent) in channels {
573            let id;
574            if let Some(parent) = parent {
575                if let Some(parent_id) = observed_channels.get(parent) {
576                    id = self
577                        .make_channel(channel, Some(*parent_id), (creator.0, creator.1), &mut [])
578                        .await;
579                } else {
580                    panic!(
581                        "Edge {}->{} referenced before {} was created",
582                        parent, channel, parent
583                    )
584                }
585            } else {
586                id = self
587                    .make_channel(channel, None, (creator.0, creator.1), &mut [])
588                    .await;
589            }
590
591            observed_channels.insert(channel, id);
592            result.push(id);
593        }
594
595        result
596    }
597
598    pub async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
599        self.make_contacts(clients).await;
600
601        let (left, right) = clients.split_at_mut(1);
602        let (_client_a, cx_a) = &mut left[0];
603        let active_call_a = cx_a.read(ActiveCall::global);
604
605        for (client_b, cx_b) in right {
606            let user_id_b = client_b.current_user_id(cx_b).to_proto();
607            active_call_a
608                .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
609                .await
610                .unwrap();
611
612            cx_b.executor().run_until_parked();
613            let active_call_b = cx_b.read(ActiveCall::global);
614            active_call_b
615                .update(*cx_b, |call, cx| call.accept_incoming(cx))
616                .await
617                .unwrap();
618        }
619    }
620
621    pub async fn build_app_state(
622        test_db: &TestDb,
623        live_kit_test_server: &live_kit_client::TestServer,
624        executor: Executor,
625    ) -> Arc<AppState> {
626        Arc::new(AppState {
627            db: test_db.db().clone(),
628            live_kit_client: Some(Arc::new(live_kit_test_server.create_api_client())),
629            blob_store_client: None,
630            rate_limiter: Arc::new(RateLimiter::new(test_db.db().clone())),
631            executor,
632            clickhouse_client: None,
633            config: Config {
634                http_port: 0,
635                database_url: "".into(),
636                database_max_connections: 0,
637                api_token: "".into(),
638                invite_link_prefix: "".into(),
639                live_kit_server: None,
640                live_kit_key: None,
641                live_kit_secret: None,
642                rust_log: None,
643                log_json: None,
644                zed_environment: "test".into(),
645                blob_store_url: None,
646                blob_store_region: None,
647                blob_store_access_key: None,
648                blob_store_secret_key: None,
649                blob_store_bucket: None,
650                openai_api_key: None,
651                google_ai_api_key: None,
652                anthropic_api_key: None,
653                clickhouse_url: None,
654                clickhouse_user: None,
655                clickhouse_password: None,
656                clickhouse_database: None,
657                zed_client_checksum_seed: None,
658                slack_panics_webhook: None,
659                auto_join_channel_id: None,
660                migrations_path: None,
661                seed_path: None,
662                supermaven_admin_api_key: None,
663            },
664        })
665    }
666}
667
668impl Deref for TestServer {
669    type Target = Server;
670
671    fn deref(&self) -> &Self::Target {
672        &self.server
673    }
674}
675
676impl Drop for TestServer {
677    fn drop(&mut self) {
678        self.server.teardown();
679        self.test_live_kit_server.teardown().unwrap();
680    }
681}
682
683impl Deref for TestClient {
684    type Target = Arc<Client>;
685
686    fn deref(&self) -> &Self::Target {
687        &self.app_state.client
688    }
689}
690
691impl TestClient {
692    pub fn fs(&self) -> &FakeFs {
693        self.app_state.fs.as_fake()
694    }
695
696    pub fn channel_store(&self) -> &Model<ChannelStore> {
697        &self.channel_store
698    }
699
700    pub fn notification_store(&self) -> &Model<NotificationStore> {
701        &self.notification_store
702    }
703
704    pub fn user_store(&self) -> &Model<UserStore> {
705        &self.app_state.user_store
706    }
707
708    pub fn language_registry(&self) -> &Arc<LanguageRegistry> {
709        &self.app_state.languages
710    }
711
712    pub fn client(&self) -> &Arc<Client> {
713        &self.app_state.client
714    }
715
716    pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
717        UserId::from_proto(
718            self.app_state
719                .user_store
720                .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
721        )
722    }
723
724    pub async fn wait_for_current_user(&self, cx: &TestAppContext) {
725        let mut authed_user = self
726            .app_state
727            .user_store
728            .read_with(cx, |user_store, _| user_store.watch_current_user());
729        while authed_user.next().await.unwrap().is_none() {}
730    }
731
732    pub async fn clear_contacts(&self, cx: &mut TestAppContext) {
733        self.app_state
734            .user_store
735            .update(cx, |store, _| store.clear_contacts())
736            .await;
737    }
738
739    pub fn local_projects(&self) -> impl Deref<Target = Vec<Model<Project>>> + '_ {
740        Ref::map(self.state.borrow(), |state| &state.local_projects)
741    }
742
743    pub fn dev_server_projects(&self) -> impl Deref<Target = Vec<Model<Project>>> + '_ {
744        Ref::map(self.state.borrow(), |state| &state.dev_server_projects)
745    }
746
747    pub fn local_projects_mut(&self) -> impl DerefMut<Target = Vec<Model<Project>>> + '_ {
748        RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
749    }
750
751    pub fn dev_server_projects_mut(&self) -> impl DerefMut<Target = Vec<Model<Project>>> + '_ {
752        RefMut::map(self.state.borrow_mut(), |state| {
753            &mut state.dev_server_projects
754        })
755    }
756
757    pub fn buffers_for_project<'a>(
758        &'a self,
759        project: &Model<Project>,
760    ) -> impl DerefMut<Target = HashSet<Model<language::Buffer>>> + 'a {
761        RefMut::map(self.state.borrow_mut(), |state| {
762            state.buffers.entry(project.clone()).or_default()
763        })
764    }
765
766    pub fn buffers(
767        &self,
768    ) -> impl DerefMut<Target = HashMap<Model<Project>, HashSet<Model<language::Buffer>>>> + '_
769    {
770        RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
771    }
772
773    pub fn channel_buffers(&self) -> impl DerefMut<Target = HashSet<Model<ChannelBuffer>>> + '_ {
774        RefMut::map(self.state.borrow_mut(), |state| &mut state.channel_buffers)
775    }
776
777    pub fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
778        self.app_state
779            .user_store
780            .read_with(cx, |store, _| ContactsSummary {
781                current: store
782                    .contacts()
783                    .iter()
784                    .map(|contact| contact.user.github_login.clone())
785                    .collect(),
786                outgoing_requests: store
787                    .outgoing_contact_requests()
788                    .iter()
789                    .map(|user| user.github_login.clone())
790                    .collect(),
791                incoming_requests: store
792                    .incoming_contact_requests()
793                    .iter()
794                    .map(|user| user.github_login.clone())
795                    .collect(),
796            })
797    }
798
799    pub async fn build_local_project(
800        &self,
801        root_path: impl AsRef<Path>,
802        cx: &mut TestAppContext,
803    ) -> (Model<Project>, WorktreeId) {
804        let project = self.build_empty_local_project(cx);
805        let (worktree, _) = project
806            .update(cx, |p, cx| {
807                p.find_or_create_local_worktree(root_path, true, cx)
808            })
809            .await
810            .unwrap();
811        worktree
812            .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
813            .await;
814        (project, worktree.read_with(cx, |tree, _| tree.id()))
815    }
816
817    pub async fn build_test_project(&self, cx: &mut TestAppContext) -> Model<Project> {
818        self.fs()
819            .insert_tree(
820                "/a",
821                json!({
822                    "1.txt": "one\none\none",
823                    "2.js": "function two() { return 2; }",
824                    "3.rs": "mod test",
825                }),
826            )
827            .await;
828        self.build_local_project("/a", cx).await.0
829    }
830
831    pub async fn host_workspace(
832        &self,
833        workspace: &View<Workspace>,
834        channel_id: ChannelId,
835        cx: &mut VisualTestContext,
836    ) {
837        cx.update(|cx| {
838            let active_call = ActiveCall::global(cx);
839            active_call.update(cx, |call, cx| call.join_channel(channel_id, cx))
840        })
841        .await
842        .unwrap();
843        cx.update(|cx| {
844            let active_call = ActiveCall::global(cx);
845            let project = workspace.read(cx).project().clone();
846            active_call.update(cx, |call, cx| call.share_project(project, cx))
847        })
848        .await
849        .unwrap();
850        cx.executor().run_until_parked();
851    }
852
853    pub async fn join_workspace<'a>(
854        &'a self,
855        channel_id: ChannelId,
856        cx: &'a mut TestAppContext,
857    ) -> (View<Workspace>, &'a mut VisualTestContext) {
858        cx.update(|cx| workspace::join_channel(channel_id, self.app_state.clone(), None, cx))
859            .await
860            .unwrap();
861        cx.run_until_parked();
862
863        self.active_workspace(cx)
864    }
865
866    pub fn build_empty_local_project(&self, cx: &mut TestAppContext) -> Model<Project> {
867        cx.update(|cx| {
868            Project::local(
869                self.client().clone(),
870                self.app_state.node_runtime.clone(),
871                self.app_state.user_store.clone(),
872                self.app_state.languages.clone(),
873                self.app_state.fs.clone(),
874                cx,
875            )
876        })
877    }
878
879    pub async fn build_dev_server_project(
880        &self,
881        host_project_id: u64,
882        guest_cx: &mut TestAppContext,
883    ) -> Model<Project> {
884        let active_call = guest_cx.read(ActiveCall::global);
885        let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
886        room.update(guest_cx, |room, cx| {
887            room.join_project(
888                host_project_id,
889                self.app_state.languages.clone(),
890                self.app_state.fs.clone(),
891                cx,
892            )
893        })
894        .await
895        .unwrap()
896    }
897
898    pub fn build_workspace<'a>(
899        &'a self,
900        project: &Model<Project>,
901        cx: &'a mut TestAppContext,
902    ) -> (View<Workspace>, &'a mut VisualTestContext) {
903        cx.add_window_view(|cx| {
904            cx.activate_window();
905            Workspace::new(None, project.clone(), self.app_state.clone(), cx)
906        })
907    }
908
909    pub async fn build_test_workspace<'a>(
910        &'a self,
911        cx: &'a mut TestAppContext,
912    ) -> (View<Workspace>, &'a mut VisualTestContext) {
913        let project = self.build_test_project(cx).await;
914        cx.add_window_view(|cx| {
915            cx.activate_window();
916            Workspace::new(None, project.clone(), self.app_state.clone(), cx)
917        })
918    }
919
920    pub fn active_workspace<'a>(
921        &'a self,
922        cx: &'a mut TestAppContext,
923    ) -> (View<Workspace>, &'a mut VisualTestContext) {
924        let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
925
926        let view = window.root_view(cx).unwrap();
927        let cx = VisualTestContext::from_window(*window.deref(), cx).as_mut();
928        // it might be nice to try and cleanup these at the end of each test.
929        (view, cx)
930    }
931}
932
933pub fn open_channel_notes(
934    channel_id: ChannelId,
935    cx: &mut VisualTestContext,
936) -> Task<anyhow::Result<View<ChannelView>>> {
937    let window = cx.update(|cx| cx.active_window().unwrap().downcast::<Workspace>().unwrap());
938    let view = window.root_view(cx).unwrap();
939
940    cx.update(|cx| ChannelView::open(channel_id, None, view.clone(), cx))
941}
942
943impl Drop for TestClient {
944    fn drop(&mut self) {
945        self.app_state.client.teardown();
946    }
947}