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