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