1use crate::{
2 db::{NewUserParams, TestDb, UserId},
3 executor::Executor,
4 rpc::{Server, CLEANUP_TIMEOUT},
5 AppState,
6};
7use anyhow::anyhow;
8use call::ActiveCall;
9use client::{
10 self, proto::PeerId, ChannelStore, Client, Connection, Credentials, EstablishConnectionError,
11 UserStore,
12};
13use collections::{HashMap, HashSet};
14use fs::FakeFs;
15use futures::{channel::oneshot, StreamExt as _};
16use gpui::{
17 elements::*, executor::Deterministic, AnyElement, Entity, ModelHandle, TestAppContext, View,
18 ViewContext, ViewHandle, WeakViewHandle,
19};
20use language::LanguageRegistry;
21use parking_lot::Mutex;
22use project::{Project, WorktreeId};
23use settings::SettingsStore;
24use std::{
25 cell::{Ref, RefCell, RefMut},
26 env,
27 ops::{Deref, DerefMut},
28 path::Path,
29 sync::{
30 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
31 Arc,
32 },
33};
34use util::http::FakeHttpClient;
35use workspace::Workspace;
36
37mod channel_tests;
38mod integration_tests;
39mod randomized_integration_tests;
40
41struct TestServer {
42 app_state: Arc<AppState>,
43 server: Arc<Server>,
44 connection_killers: Arc<Mutex<HashMap<PeerId, Arc<AtomicBool>>>>,
45 forbid_connections: Arc<AtomicBool>,
46 _test_db: TestDb,
47 test_live_kit_server: Arc<live_kit_client::TestServer>,
48}
49
50impl TestServer {
51 async fn start(deterministic: &Arc<Deterministic>) -> Self {
52 static NEXT_LIVE_KIT_SERVER_ID: AtomicUsize = AtomicUsize::new(0);
53
54 let use_postgres = env::var("USE_POSTGRES").ok();
55 let use_postgres = use_postgres.as_deref();
56 let test_db = if use_postgres == Some("true") || use_postgres == Some("1") {
57 TestDb::postgres(deterministic.build_background())
58 } else {
59 TestDb::sqlite(deterministic.build_background())
60 };
61 let live_kit_server_id = NEXT_LIVE_KIT_SERVER_ID.fetch_add(1, SeqCst);
62 let live_kit_server = live_kit_client::TestServer::create(
63 format!("http://livekit.{}.test", live_kit_server_id),
64 format!("devkey-{}", live_kit_server_id),
65 format!("secret-{}", live_kit_server_id),
66 deterministic.build_background(),
67 )
68 .unwrap();
69 let app_state = Self::build_app_state(&test_db, &live_kit_server).await;
70 let epoch = app_state
71 .db
72 .create_server(&app_state.config.zed_environment)
73 .await
74 .unwrap();
75 let server = Server::new(
76 epoch,
77 app_state.clone(),
78 Executor::Deterministic(deterministic.build_background()),
79 );
80 server.start().await.unwrap();
81 // Advance clock to ensure the server's cleanup task is finished.
82 deterministic.advance_clock(CLEANUP_TIMEOUT);
83 Self {
84 app_state,
85 server,
86 connection_killers: Default::default(),
87 forbid_connections: Default::default(),
88 _test_db: test_db,
89 test_live_kit_server: live_kit_server,
90 }
91 }
92
93 async fn reset(&self) {
94 self.app_state.db.reset();
95 let epoch = self
96 .app_state
97 .db
98 .create_server(&self.app_state.config.zed_environment)
99 .await
100 .unwrap();
101 self.server.reset(epoch);
102 }
103
104 async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
105 cx.update(|cx| {
106 cx.set_global(SettingsStore::test(cx));
107 });
108
109 let http = FakeHttpClient::with_404_response();
110 let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
111 {
112 user.id
113 } else {
114 self.app_state
115 .db
116 .create_user(
117 &format!("{name}@example.com"),
118 false,
119 NewUserParams {
120 github_login: name.into(),
121 github_user_id: 0,
122 invite_count: 0,
123 },
124 )
125 .await
126 .expect("creating user failed")
127 .user_id
128 };
129 let client_name = name.to_string();
130 let mut client = cx.read(|cx| Client::new(http.clone(), cx));
131 let server = self.server.clone();
132 let db = self.app_state.db.clone();
133 let connection_killers = self.connection_killers.clone();
134 let forbid_connections = self.forbid_connections.clone();
135
136 Arc::get_mut(&mut client)
137 .unwrap()
138 .set_id(user_id.0 as usize)
139 .override_authenticate(move |cx| {
140 cx.spawn(|_| async move {
141 let access_token = "the-token".to_string();
142 Ok(Credentials {
143 user_id: user_id.0 as u64,
144 access_token,
145 })
146 })
147 })
148 .override_establish_connection(move |credentials, cx| {
149 assert_eq!(credentials.user_id, user_id.0 as u64);
150 assert_eq!(credentials.access_token, "the-token");
151
152 let server = server.clone();
153 let db = db.clone();
154 let connection_killers = connection_killers.clone();
155 let forbid_connections = forbid_connections.clone();
156 let client_name = client_name.clone();
157 cx.spawn(move |cx| async move {
158 if forbid_connections.load(SeqCst) {
159 Err(EstablishConnectionError::other(anyhow!(
160 "server is forbidding connections"
161 )))
162 } else {
163 let (client_conn, server_conn, killed) =
164 Connection::in_memory(cx.background());
165 let (connection_id_tx, connection_id_rx) = oneshot::channel();
166 let user = db
167 .get_user_by_id(user_id)
168 .await
169 .expect("retrieving user failed")
170 .unwrap();
171 cx.background()
172 .spawn(server.handle_connection(
173 server_conn,
174 client_name,
175 user,
176 Some(connection_id_tx),
177 Executor::Deterministic(cx.background()),
178 ))
179 .detach();
180 let connection_id = connection_id_rx.await.unwrap();
181 connection_killers
182 .lock()
183 .insert(connection_id.into(), killed);
184 Ok(client_conn)
185 }
186 })
187 });
188
189 let fs = FakeFs::new(cx.background());
190 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
191 let channel_store =
192 cx.add_model(|cx| ChannelStore::new(client.clone(), user_store.clone(), cx));
193 let app_state = Arc::new(workspace::AppState {
194 client: client.clone(),
195 user_store: user_store.clone(),
196 languages: Arc::new(LanguageRegistry::test()),
197 fs: fs.clone(),
198 build_window_options: |_, _, _| Default::default(),
199 initialize_workspace: |_, _, _, _| unimplemented!(),
200 background_actions: || &[],
201 });
202
203 cx.update(|cx| {
204 theme::init((), cx);
205 Project::init(&client, cx);
206 client::init(&client, cx);
207 language::init(cx);
208 editor::init_settings(cx);
209 workspace::init(app_state.clone(), cx);
210 audio::init((), cx);
211 call::init(client.clone(), user_store.clone(), cx);
212 });
213
214 client
215 .authenticate_and_connect(false, &cx.to_async())
216 .await
217 .unwrap();
218
219 let client = TestClient {
220 client,
221 username: name.to_string(),
222 state: Default::default(),
223 user_store,
224 channel_store,
225 fs,
226 language_registry: Arc::new(LanguageRegistry::test()),
227 };
228 client.wait_for_current_user(cx).await;
229 client
230 }
231
232 fn disconnect_client(&self, peer_id: PeerId) {
233 self.connection_killers
234 .lock()
235 .remove(&peer_id)
236 .unwrap()
237 .store(true, SeqCst);
238 }
239
240 fn forbid_connections(&self) {
241 self.forbid_connections.store(true, SeqCst);
242 }
243
244 fn allow_connections(&self) {
245 self.forbid_connections.store(false, SeqCst);
246 }
247
248 async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
249 for ix in 1..clients.len() {
250 let (left, right) = clients.split_at_mut(ix);
251 let (client_a, cx_a) = left.last_mut().unwrap();
252 for (client_b, cx_b) in right {
253 client_a
254 .user_store
255 .update(*cx_a, |store, cx| {
256 store.request_contact(client_b.user_id().unwrap(), cx)
257 })
258 .await
259 .unwrap();
260 cx_a.foreground().run_until_parked();
261 client_b
262 .user_store
263 .update(*cx_b, |store, cx| {
264 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
265 })
266 .await
267 .unwrap();
268 }
269 }
270 }
271
272 async fn create_room(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
273 self.make_contacts(clients).await;
274
275 let (left, right) = clients.split_at_mut(1);
276 let (_client_a, cx_a) = &mut left[0];
277 let active_call_a = cx_a.read(ActiveCall::global);
278
279 for (client_b, cx_b) in right {
280 let user_id_b = client_b.current_user_id(*cx_b).to_proto();
281 active_call_a
282 .update(*cx_a, |call, cx| call.invite(user_id_b, None, cx))
283 .await
284 .unwrap();
285
286 cx_b.foreground().run_until_parked();
287 let active_call_b = cx_b.read(ActiveCall::global);
288 active_call_b
289 .update(*cx_b, |call, cx| call.accept_incoming(cx))
290 .await
291 .unwrap();
292 }
293 }
294
295 async fn build_app_state(
296 test_db: &TestDb,
297 fake_server: &live_kit_client::TestServer,
298 ) -> Arc<AppState> {
299 Arc::new(AppState {
300 db: test_db.db().clone(),
301 live_kit_client: Some(Arc::new(fake_server.create_api_client())),
302 config: Default::default(),
303 })
304 }
305}
306
307impl Deref for TestServer {
308 type Target = Server;
309
310 fn deref(&self) -> &Self::Target {
311 &self.server
312 }
313}
314
315impl Drop for TestServer {
316 fn drop(&mut self) {
317 self.server.teardown();
318 self.test_live_kit_server.teardown().unwrap();
319 }
320}
321
322struct TestClient {
323 client: Arc<Client>,
324 username: String,
325 state: RefCell<TestClientState>,
326 pub user_store: ModelHandle<UserStore>,
327 pub channel_store: ModelHandle<ChannelStore>,
328 language_registry: Arc<LanguageRegistry>,
329 fs: Arc<FakeFs>,
330}
331
332#[derive(Default)]
333struct TestClientState {
334 local_projects: Vec<ModelHandle<Project>>,
335 remote_projects: Vec<ModelHandle<Project>>,
336 buffers: HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>,
337}
338
339impl Deref for TestClient {
340 type Target = Arc<Client>;
341
342 fn deref(&self) -> &Self::Target {
343 &self.client
344 }
345}
346
347struct ContactsSummary {
348 pub current: Vec<String>,
349 pub outgoing_requests: Vec<String>,
350 pub incoming_requests: Vec<String>,
351}
352
353impl TestClient {
354 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
355 UserId::from_proto(
356 self.user_store
357 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
358 )
359 }
360
361 async fn wait_for_current_user(&self, cx: &TestAppContext) {
362 let mut authed_user = self
363 .user_store
364 .read_with(cx, |user_store, _| user_store.watch_current_user());
365 while authed_user.next().await.unwrap().is_none() {}
366 }
367
368 async fn clear_contacts(&self, cx: &mut TestAppContext) {
369 self.user_store
370 .update(cx, |store, _| store.clear_contacts())
371 .await;
372 }
373
374 fn local_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
375 Ref::map(self.state.borrow(), |state| &state.local_projects)
376 }
377
378 fn remote_projects<'a>(&'a self) -> impl Deref<Target = Vec<ModelHandle<Project>>> + 'a {
379 Ref::map(self.state.borrow(), |state| &state.remote_projects)
380 }
381
382 fn local_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
383 RefMut::map(self.state.borrow_mut(), |state| &mut state.local_projects)
384 }
385
386 fn remote_projects_mut<'a>(&'a self) -> impl DerefMut<Target = Vec<ModelHandle<Project>>> + 'a {
387 RefMut::map(self.state.borrow_mut(), |state| &mut state.remote_projects)
388 }
389
390 fn buffers_for_project<'a>(
391 &'a self,
392 project: &ModelHandle<Project>,
393 ) -> impl DerefMut<Target = HashSet<ModelHandle<language::Buffer>>> + 'a {
394 RefMut::map(self.state.borrow_mut(), |state| {
395 state.buffers.entry(project.clone()).or_default()
396 })
397 }
398
399 fn buffers<'a>(
400 &'a self,
401 ) -> impl DerefMut<Target = HashMap<ModelHandle<Project>, HashSet<ModelHandle<language::Buffer>>>> + 'a
402 {
403 RefMut::map(self.state.borrow_mut(), |state| &mut state.buffers)
404 }
405
406 fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
407 self.user_store.read_with(cx, |store, _| ContactsSummary {
408 current: store
409 .contacts()
410 .iter()
411 .map(|contact| contact.user.github_login.clone())
412 .collect(),
413 outgoing_requests: store
414 .outgoing_contact_requests()
415 .iter()
416 .map(|user| user.github_login.clone())
417 .collect(),
418 incoming_requests: store
419 .incoming_contact_requests()
420 .iter()
421 .map(|user| user.github_login.clone())
422 .collect(),
423 })
424 }
425
426 async fn build_local_project(
427 &self,
428 root_path: impl AsRef<Path>,
429 cx: &mut TestAppContext,
430 ) -> (ModelHandle<Project>, WorktreeId) {
431 let project = cx.update(|cx| {
432 Project::local(
433 self.client.clone(),
434 self.user_store.clone(),
435 self.language_registry.clone(),
436 self.fs.clone(),
437 cx,
438 )
439 });
440 let (worktree, _) = project
441 .update(cx, |p, cx| {
442 p.find_or_create_local_worktree(root_path, true, cx)
443 })
444 .await
445 .unwrap();
446 worktree
447 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
448 .await;
449 (project, worktree.read_with(cx, |tree, _| tree.id()))
450 }
451
452 async fn build_remote_project(
453 &self,
454 host_project_id: u64,
455 guest_cx: &mut TestAppContext,
456 ) -> ModelHandle<Project> {
457 let active_call = guest_cx.read(ActiveCall::global);
458 let room = active_call.read_with(guest_cx, |call, _| call.room().unwrap().clone());
459 room.update(guest_cx, |room, cx| {
460 room.join_project(
461 host_project_id,
462 self.language_registry.clone(),
463 self.fs.clone(),
464 cx,
465 )
466 })
467 .await
468 .unwrap()
469 }
470
471 fn build_workspace(
472 &self,
473 project: &ModelHandle<Project>,
474 cx: &mut TestAppContext,
475 ) -> ViewHandle<Workspace> {
476 struct WorkspaceContainer {
477 workspace: Option<WeakViewHandle<Workspace>>,
478 }
479
480 impl Entity for WorkspaceContainer {
481 type Event = ();
482 }
483
484 impl View for WorkspaceContainer {
485 fn ui_name() -> &'static str {
486 "WorkspaceContainer"
487 }
488
489 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
490 if let Some(workspace) = self
491 .workspace
492 .as_ref()
493 .and_then(|workspace| workspace.upgrade(cx))
494 {
495 ChildView::new(&workspace, cx).into_any()
496 } else {
497 Empty::new().into_any()
498 }
499 }
500 }
501
502 // We use a workspace container so that we don't need to remove the window in order to
503 // drop the workspace and we can use a ViewHandle instead.
504 let (window_id, container) = cx.add_window(|_| WorkspaceContainer { workspace: None });
505 let workspace = cx.add_view(window_id, |cx| Workspace::test_new(project.clone(), cx));
506 container.update(cx, |container, cx| {
507 container.workspace = Some(workspace.downgrade());
508 cx.notify();
509 });
510 workspace
511 }
512}
513
514impl Drop for TestClient {
515 fn drop(&mut self) {
516 self.client.teardown();
517 }
518}