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