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