Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

Merge branch 'main' into randomized-tests-operation-script

Max Brunsfeld9c25d37dfc91
diff --cc crates/collab/src/tests/randomized_integration_tests.rs
index 01a744427ec,e0170f6648e..e44e52196d2
--- a/crates/collab/src/tests/randomized_integration_tests.rs
+++ b/crates/collab/src/tests/randomized_integration_tests.rs
@@@ -19,18 -18,13 +19,19 @@@ use rand::
distributions::{Alphanumeric, DistString},
prelude::*,
};
+use serde::{Deserialize, Serialize};
+ use settings::Settings;
use std::{
env,
- ffi::OsStr,
+ ops::Range,
path::{Path, PathBuf},
- sync::Arc,
+ rc::Rc,
+ sync::{
+ atomic::{AtomicBool, Ordering::SeqCst},
+ Arc,
+ },
};
+use util::ResultExt;
#[gpui::test(iterations = 100)]
async fn test_random_collaboration(
@@@ -876,1031 -1169,42 +905,1049 @@@ async fn apply_client_operation
.await
.map_err(|err| anyhow!("search request failed: {:?}", err))
});
- if rng.lock().gen_bool(0.3) {
- log::info!("{}: detaching search request", client.username);
+ if detach {
cx.update(|cx| search.detach_and_log_err(cx));
} else {
- buffers.extend(search.await?.into_keys());
+ search.await?;
}
}
- _ => {
- buffer.update(cx, |buffer, cx| {
- log::info!(
- "{}: updating buffer {} ({:?})",
- client.username,
- buffer.remote_id(),
- buffer.file().unwrap().full_path(cx)
- );
- if rng.lock().gen_bool(0.7) {
- buffer.randomly_edit(&mut *rng.lock(), 5, cx);
- } else {
- buffer.randomly_undo_redo(&mut *rng.lock(), cx);
+
- ClientOperation::CreateFsEntry { path, is_dir } => {
++ ClientOperation::WriteFsEntry {
++ path,
++ is_dir,
++ content,
++ } => {
+ client
+ .fs
+ .metadata(&path.parent().unwrap())
+ .await?
+ .ok_or(TestError::Inapplicable)?;
+
- log::info!(
- "{}: creating {} at {:?}",
- client.username,
- if is_dir { "dir" } else { "file" },
- path
- );
-
+ if is_dir {
++ log::info!("{}: creating dir at {:?}", client.username, path);
+ client.fs.create_dir(&path).await.unwrap();
+ } else {
++ let exists = client.fs.metadata(&path).await?.is_some();
++ let verb = if exists { "updating" } else { "creating" };
++ log::info!("{}: {} file at {:?}", verb, client.username, path);
++
+ client
+ .fs
- .create_file(&path, Default::default())
++ .save(&path, &content.as_str().into(), fs::LineEnding::Unix)
+ .await
+ .unwrap();
+ }
+ }
+
+ ClientOperation::WriteGitIndex {
+ repo_path,
+ contents,
+ } => {
+ if !client
+ .fs
+ .metadata(&repo_path)
+ .await?
+ .map_or(false, |m| m.is_dir)
+ {
+ Err(TestError::Inapplicable)?;
+ }
+
+ log::info!(
+ "{}: writing git index for repo {:?}: {:?}",
+ client.username,
+ repo_path,
+ contents
+ );
+
+ let dot_git_dir = repo_path.join(".git");
+ let contents = contents
+ .iter()
+ .map(|(path, contents)| (path.as_path(), contents.clone()))
+ .collect::<Vec<_>>();
+ if client.fs.metadata(&dot_git_dir).await?.is_none() {
+ client.fs.create_dir(&dot_git_dir).await?;
+ }
+ client.fs.set_index_for_repo(&dot_git_dir, &contents).await;
+ }
+ }
+ Ok(())
+}
+
+struct TestPlan {
+ rng: StdRng,
+ replay: bool,
+ stored_operations: Vec<(StoredOperation, Arc<AtomicBool>)>,
+ max_operations: usize,
+ operation_ix: usize,
+ users: Vec<UserTestPlan>,
+ next_batch_id: usize,
+ allow_server_restarts: bool,
+ allow_client_reconnection: bool,
+ allow_client_disconnection: bool,
+}
+
+struct UserTestPlan {
+ user_id: UserId,
+ username: String,
+ next_root_id: usize,
+ operation_ix: usize,
+ online: bool,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(untagged)]
+enum StoredOperation {
+ Server(Operation),
+ Client {
+ user_id: UserId,
+ batch_id: usize,
+ operation: ClientOperation,
+ },
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+enum Operation {
+ AddConnection {
+ user_id: UserId,
+ },
+ RemoveConnection {
+ user_id: UserId,
+ },
+ BounceConnection {
+ user_id: UserId,
+ },
+ RestartServer,
+ MutateClients {
+ batch_id: usize,
+ #[serde(skip_serializing)]
+ #[serde(skip_deserializing)]
+ user_ids: Vec<UserId>,
+ quiesce: bool,
+ },
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+enum ClientOperation {
+ AcceptIncomingCall,
+ RejectIncomingCall,
+ LeaveCall,
+ InviteContactToCall {
+ user_id: UserId,
+ },
+ OpenLocalProject {
+ first_root_name: String,
+ },
+ OpenRemoteProject {
+ host_id: UserId,
+ first_root_name: String,
+ },
+ AddWorktreeToProject {
+ project_root_name: String,
+ new_root_path: PathBuf,
+ },
+ CloseRemoteProject {
+ project_root_name: String,
+ },
+ OpenBuffer {
+ project_root_name: String,
+ is_local: bool,
+ full_path: PathBuf,
+ },
+ SearchProject {
+ project_root_name: String,
+ is_local: bool,
+ query: String,
+ detach: bool,
+ },
+ EditBuffer {
+ project_root_name: String,
+ is_local: bool,
+ full_path: PathBuf,
+ edits: Vec<(Range<usize>, Arc<str>)>,
+ },
+ CloseBuffer {
+ project_root_name: String,
+ is_local: bool,
+ full_path: PathBuf,
+ },
+ SaveBuffer {
+ project_root_name: String,
+ is_local: bool,
+ full_path: PathBuf,
+ detach: bool,
+ },
+ RequestLspDataInBuffer {
+ project_root_name: String,
+ is_local: bool,
+ full_path: PathBuf,
+ offset: usize,
+ kind: LspRequestKind,
+ detach: bool,
+ },
+ CreateWorktreeEntry {
+ project_root_name: String,
+ is_local: bool,
+ full_path: PathBuf,
+ is_dir: bool,
+ },
- CreateFsEntry {
++ WriteFsEntry {
+ path: PathBuf,
+ is_dir: bool,
++ content: String,
+ },
+ WriteGitIndex {
+ repo_path: PathBuf,
+ contents: Vec<(PathBuf, String)>,
+ },
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+enum LspRequestKind {
+ Rename,
+ Completion,
+ CodeAction,
+ Definition,
+ Highlights,
+}
+
+enum TestError {
+ Inapplicable,
+ Other(anyhow::Error),
+}
+
+impl From<anyhow::Error> for TestError {
+ fn from(value: anyhow::Error) -> Self {
+ Self::Other(value)
+ }
+}
+
+impl TestPlan {
+ fn new(mut rng: StdRng, users: Vec<UserTestPlan>, max_operations: usize) -> Self {
+ Self {
+ replay: false,
+ allow_server_restarts: rng.gen_bool(0.7),
+ allow_client_reconnection: rng.gen_bool(0.7),
+ allow_client_disconnection: rng.gen_bool(0.1),
+ stored_operations: Vec::new(),
+ operation_ix: 0,
+ next_batch_id: 0,
+ max_operations,
+ users,
+ rng,
+ }
+ }
+
+ fn load(&mut self, path: &Path) {
+ let json = std::fs::read_to_string(path).unwrap();
+ self.replay = true;
+ let stored_operations: Vec<StoredOperation> = serde_json::from_str(&json).unwrap();
+ self.stored_operations = stored_operations
+ .iter()
+ .cloned()
+ .enumerate()
+ .map(|(i, mut operation)| {
+ if let StoredOperation::Server(Operation::MutateClients {
+ batch_id: current_batch_id,
+ user_ids,
+ ..
+ }) = &mut operation
+ {
+ assert!(user_ids.is_empty());
+ user_ids.extend(stored_operations[i + 1..].iter().filter_map(|operation| {
+ if let StoredOperation::Client {
+ user_id, batch_id, ..
+ } = operation
+ {
+ if batch_id == current_batch_id {
+ return Some(user_id);
+ }
+ }
+ None
+ }));
+ user_ids.sort_unstable();
}
- });
+ (operation, Arc::new(AtomicBool::new(false)))
+ })
+ .collect()
+ }
+
+ fn save(&mut self, path: &Path) {
+ // Format each operation as one line
+ let mut json = Vec::new();
+ json.push(b'[');
+ for (operation, skipped) in &self.stored_operations {
+ if skipped.load(SeqCst) {
+ continue;
+ }
+ if json.len() > 1 {
+ json.push(b',');
+ }
+ json.extend_from_slice(b"\n ");
+ serde_json::to_writer(&mut json, operation).unwrap();
}
+ json.extend_from_slice(b"\n]\n");
+ std::fs::write(path, &json).unwrap();
}
- Ok(())
+ fn next_server_operation(
+ &mut self,
+ clients: &[(Rc<TestClient>, TestAppContext)],
+ ) -> Option<(Operation, Arc<AtomicBool>)> {
+ if self.replay {
+ while let Some(stored_operation) = self.stored_operations.get(self.operation_ix) {
+ self.operation_ix += 1;
+ if let (StoredOperation::Server(operation), skipped) = stored_operation {
+ return Some((operation.clone(), skipped.clone()));
+ }
+ }
+ None
+ } else {
+ let operation = self.generate_server_operation(clients)?;
+ let skipped = Arc::new(AtomicBool::new(false));
+ self.stored_operations
+ .push((StoredOperation::Server(operation.clone()), skipped.clone()));
+ Some((operation, skipped))
+ }
+ }
+
+ fn next_client_operation(
+ &mut self,
+ client: &TestClient,
+ current_batch_id: usize,
+ cx: &TestAppContext,
+ ) -> Option<(ClientOperation, Arc<AtomicBool>)> {
+ let current_user_id = client.current_user_id(cx);
+ let user_ix = self
+ .users
+ .iter()
+ .position(|user| user.user_id == current_user_id)
+ .unwrap();
+ let user_plan = &mut self.users[user_ix];
+
+ if self.replay {
+ while let Some(stored_operation) = self.stored_operations.get(user_plan.operation_ix) {
+ user_plan.operation_ix += 1;
+ if let (
+ StoredOperation::Client {
+ user_id, operation, ..
+ },
+ skipped,
+ ) = stored_operation
+ {
+ if user_id == &current_user_id {
+ return Some((operation.clone(), skipped.clone()));
+ }
+ }
+ }
+ None
+ } else {
+ let operation = self.generate_client_operation(current_user_id, client, cx)?;
+ let skipped = Arc::new(AtomicBool::new(false));
+ self.stored_operations.push((
+ StoredOperation::Client {
+ user_id: current_user_id,
+ batch_id: current_batch_id,
+ operation: operation.clone(),
+ },
+ skipped.clone(),
+ ));
+ Some((operation, skipped))
+ }
+ }
+
+ fn generate_server_operation(
+ &mut self,
+ clients: &[(Rc<TestClient>, TestAppContext)],
+ ) -> Option<Operation> {
+ if self.operation_ix == self.max_operations {
+ return None;
+ }
+
+ Some(loop {
+ break match self.rng.gen_range(0..100) {
+ 0..=29 if clients.len() < self.users.len() => {
+ let user = self
+ .users
+ .iter()
+ .filter(|u| !u.online)
+ .choose(&mut self.rng)
+ .unwrap();
+ self.operation_ix += 1;
+ Operation::AddConnection {
+ user_id: user.user_id,
+ }
+ }
+ 30..=34 if clients.len() > 1 && self.allow_client_disconnection => {
+ let (client, cx) = &clients[self.rng.gen_range(0..clients.len())];
+ let user_id = client.current_user_id(cx);
+ self.operation_ix += 1;
+ Operation::RemoveConnection { user_id }
+ }
+ 35..=39 if clients.len() > 1 && self.allow_client_reconnection => {
+ let (client, cx) = &clients[self.rng.gen_range(0..clients.len())];
+ let user_id = client.current_user_id(cx);
+ self.operation_ix += 1;
+ Operation::BounceConnection { user_id }
+ }
+ 40..=44 if self.allow_server_restarts && clients.len() > 1 => {
+ self.operation_ix += 1;
+ Operation::RestartServer
+ }
+ _ if !clients.is_empty() => {
+ let count = self
+ .rng
+ .gen_range(1..10)
+ .min(self.max_operations - self.operation_ix);
+ let batch_id = util::post_inc(&mut self.next_batch_id);
+ let mut user_ids = (0..count)
+ .map(|_| {
+ let ix = self.rng.gen_range(0..clients.len());
+ let (client, cx) = &clients[ix];
+ client.current_user_id(cx)
+ })
+ .collect::<Vec<_>>();
+ user_ids.sort_unstable();
+ Operation::MutateClients {
+ user_ids,
+ batch_id,
+ quiesce: self.rng.gen_bool(0.7),
+ }
+ }
+ _ => continue,
+ };
+ })
+ }
+
+ fn generate_client_operation(
+ &mut self,
+ user_id: UserId,
+ client: &TestClient,
+ cx: &TestAppContext,
+ ) -> Option<ClientOperation> {
+ if self.operation_ix == self.max_operations {
+ return None;
+ }
+
+ let executor = cx.background();
+ self.operation_ix += 1;
+ let call = cx.read(ActiveCall::global);
+ Some(loop {
+ match self.rng.gen_range(0..100_u32) {
+ // Mutate the call
+ 0..=29 => {
+ // Respond to an incoming call
+ if call.read_with(cx, |call, _| call.incoming().borrow().is_some()) {
+ break if self.rng.gen_bool(0.7) {
+ ClientOperation::AcceptIncomingCall
+ } else {
+ ClientOperation::RejectIncomingCall
+ };
+ }
+
+ match self.rng.gen_range(0..100_u32) {
+ // Invite a contact to the current call
+ 0..=70 => {
+ let available_contacts =
+ client.user_store.read_with(cx, |user_store, _| {
+ user_store
+ .contacts()
+ .iter()
+ .filter(|contact| contact.online && !contact.busy)
+ .cloned()
+ .collect::<Vec<_>>()
+ });
+ if !available_contacts.is_empty() {
+ let contact = available_contacts.choose(&mut self.rng).unwrap();
+ break ClientOperation::InviteContactToCall {
+ user_id: UserId(contact.user.id as i32),
+ };
+ }
+ }
+
+ // Leave the current call
+ 71.. => {
+ if self.allow_client_disconnection
+ && call.read_with(cx, |call, _| call.room().is_some())
+ {
+ break ClientOperation::LeaveCall;
+ }
+ }
+ }
+ }
+
+ // Mutate projects
+ 30..=59 => match self.rng.gen_range(0..100_u32) {
+ // Open a new project
+ 0..=70 => {
+ // Open a remote project
+ if let Some(room) = call.read_with(cx, |call, _| call.room().cloned()) {
+ let existing_remote_project_ids = cx.read(|cx| {
+ client
+ .remote_projects()
+ .iter()
+ .map(|p| p.read(cx).remote_id().unwrap())
+ .collect::<Vec<_>>()
+ });
+ let new_remote_projects = room.read_with(cx, |room, _| {
+ room.remote_participants()
+ .values()
+ .flat_map(|participant| {
+ participant.projects.iter().filter_map(|project| {
+ if existing_remote_project_ids.contains(&project.id) {
+ None
+ } else {
+ Some((
+ UserId::from_proto(participant.user.id),
+ project.worktree_root_names[0].clone(),
+ ))
+ }
+ })
+ })
+ .collect::<Vec<_>>()
+ });
+ if !new_remote_projects.is_empty() {
+ let (host_id, first_root_name) =
+ new_remote_projects.choose(&mut self.rng).unwrap().clone();
+ break ClientOperation::OpenRemoteProject {
+ host_id,
+ first_root_name,
+ };
+ }
+ }
+ // Open a local project
+ else {
+ let first_root_name = self.next_root_dir_name(user_id);
+ break ClientOperation::OpenLocalProject { first_root_name };
+ }
+ }
+
+ // Close a remote project
+ 71..=80 => {
+ if !client.remote_projects().is_empty() {
+ let project = client
+ .remote_projects()
+ .choose(&mut self.rng)
+ .unwrap()
+ .clone();
+ let first_root_name = root_name_for_project(&project, cx);
+ break ClientOperation::CloseRemoteProject {
+ project_root_name: first_root_name,
+ };
+ }
+ }
+
+ // Mutate project worktrees
+ 81.. => match self.rng.gen_range(0..100_u32) {
+ // Add a worktree to a local project
+ 0..=50 => {
+ let Some(project) = client
+ .local_projects()
+ .choose(&mut self.rng)
+ .cloned() else { continue };
+ let project_root_name = root_name_for_project(&project, cx);
+ let mut paths = executor.block(client.fs.paths());
+ paths.remove(0);
+ let new_root_path = if paths.is_empty() || self.rng.gen() {
+ Path::new("/").join(&self.next_root_dir_name(user_id))
+ } else {
+ paths.choose(&mut self.rng).unwrap().clone()
+ };
+ break ClientOperation::AddWorktreeToProject {
+ project_root_name,
+ new_root_path,
+ };
+ }
+
+ // Add an entry to a worktree
+ _ => {
+ let Some(project) = choose_random_project(client, &mut self.rng) else { continue };
+ let project_root_name = root_name_for_project(&project, cx);
+ let is_local = project.read_with(cx, |project, _| project.is_local());
+ let worktree = project.read_with(cx, |project, cx| {
+ project
+ .worktrees(cx)
+ .filter(|worktree| {
+ let worktree = worktree.read(cx);
+ worktree.is_visible()
+ && worktree.entries(false).any(|e| e.is_file())
+ && worktree.root_entry().map_or(false, |e| e.is_dir())
+ })
+ .choose(&mut self.rng)
+ });
+ let Some(worktree) = worktree else { continue };
+ let is_dir = self.rng.gen::<bool>();
+ let mut full_path =
+ worktree.read_with(cx, |w, _| PathBuf::from(w.root_name()));
+ full_path.push(gen_file_name(&mut self.rng));
+ if !is_dir {
+ full_path.set_extension("rs");
+ }
+ break ClientOperation::CreateWorktreeEntry {
+ project_root_name,
+ is_local,
+ full_path,
+ is_dir,
+ };
+ }
+ },
+ },
+
+ // Query and mutate buffers
+ 60..=90 => {
+ let Some(project) = choose_random_project(client, &mut self.rng) else { continue };
+ let project_root_name = root_name_for_project(&project, cx);
+ let is_local = project.read_with(cx, |project, _| project.is_local());
+
+ match self.rng.gen_range(0..100_u32) {
+ // Manipulate an existing buffer
+ 0..=70 => {
+ let Some(buffer) = client
+ .buffers_for_project(&project)
+ .iter()
+ .choose(&mut self.rng)
+ .cloned() else { continue };
+
+ let full_path = buffer
+ .read_with(cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
+
+ match self.rng.gen_range(0..100_u32) {
+ // Close the buffer
+ 0..=15 => {
+ break ClientOperation::CloseBuffer {
+ project_root_name,
+ is_local,
+ full_path,
+ };
+ }
+ // Save the buffer
+ 16..=29 if buffer.read_with(cx, |b, _| b.is_dirty()) => {
+ let detach = self.rng.gen_bool(0.3);
+ break ClientOperation::SaveBuffer {
+ project_root_name,
+ is_local,
+ full_path,
+ detach,
+ };
+ }
+ // Edit the buffer
+ 30..=69 => {
+ let edits = buffer.read_with(cx, |buffer, _| {
+ buffer.get_random_edits(&mut self.rng, 3)
+ });
+ break ClientOperation::EditBuffer {
+ project_root_name,
+ is_local,
+ full_path,
+ edits,
+ };
+ }
+ // Make an LSP request
+ _ => {
+ let offset = buffer.read_with(cx, |buffer, _| {
+ buffer.clip_offset(
+ self.rng.gen_range(0..=buffer.len()),
+ language::Bias::Left,
+ )
+ });
+ let detach = self.rng.gen();
+ break ClientOperation::RequestLspDataInBuffer {
+ project_root_name,
+ full_path,
+ offset,
+ is_local,
+ kind: match self.rng.gen_range(0..5_u32) {
+ 0 => LspRequestKind::Rename,
+ 1 => LspRequestKind::Highlights,
+ 2 => LspRequestKind::Definition,
+ 3 => LspRequestKind::CodeAction,
+ 4.. => LspRequestKind::Completion,
+ },
+ detach,
+ };
+ }
+ }
+ }
+
+ 71..=80 => {
+ let query = self.rng.gen_range('a'..='z').to_string();
+ let detach = self.rng.gen_bool(0.3);
+ break ClientOperation::SearchProject {
+ project_root_name,
+ is_local,
+ query,
+ detach,
+ };
+ }
+
+ // Open a buffer
+ 81.. => {
+ let worktree = project.read_with(cx, |project, cx| {
+ project
+ .worktrees(cx)
+ .filter(|worktree| {
+ let worktree = worktree.read(cx);
+ worktree.is_visible()
+ && worktree.entries(false).any(|e| e.is_file())
+ })
+ .choose(&mut self.rng)
+ });
+ let Some(worktree) = worktree else { continue };
+ let full_path = worktree.read_with(cx, |worktree, _| {
+ let entry = worktree
+ .entries(false)
+ .filter(|e| e.is_file())
+ .choose(&mut self.rng)
+ .unwrap();
+ if entry.path.as_ref() == Path::new("") {
+ Path::new(worktree.root_name()).into()
+ } else {
+ Path::new(worktree.root_name()).join(&entry.path)
+ }
+ });
+ break ClientOperation::OpenBuffer {
+ project_root_name,
+ is_local,
+ full_path,
+ };
+ }
+ }
+ }
+
+ // Update a git index
+ 91..=95 => {
+ let repo_path = executor
+ .block(client.fs.directories())
+ .choose(&mut self.rng)
+ .unwrap()
+ .clone();
+
+ let mut file_paths = executor
+ .block(client.fs.files())
+ .into_iter()
+ .filter(|path| path.starts_with(&repo_path))
+ .collect::<Vec<_>>();
+ let count = self.rng.gen_range(0..=file_paths.len());
+ file_paths.shuffle(&mut self.rng);
+ file_paths.truncate(count);
+
+ let mut contents = Vec::new();
+ for abs_child_file_path in &file_paths {
+ let child_file_path = abs_child_file_path
+ .strip_prefix(&repo_path)
+ .unwrap()
+ .to_path_buf();
+ let new_base = Alphanumeric.sample_string(&mut self.rng, 16);
+ contents.push((child_file_path, new_base));
+ }
+
+ break ClientOperation::WriteGitIndex {
+ repo_path,
+ contents,
+ };
+ }
+
- // Create a file or directory
++ // Create or update a file or directory
+ 96.. => {
+ let is_dir = self.rng.gen::<bool>();
- let mut path = cx
- .background()
- .block(client.fs.directories())
- .choose(&mut self.rng)
- .unwrap()
- .clone();
- path.push(gen_file_name(&mut self.rng));
- if !is_dir {
- path.set_extension("rs");
++ let content;
++ let mut path;
++ let dir_paths = cx.background().block(client.fs.directories());
++
++ if is_dir {
++ content = String::new();
++ path = dir_paths.choose(&mut self.rng).unwrap().clone();
++ path.push(gen_file_name(&mut self.rng));
++ } else {
++ content = Alphanumeric.sample_string(&mut self.rng, 16);
++
++ // Create a new file or overwrite an existing file
++ let file_paths = cx.background().block(client.fs.files());
++ if file_paths.is_empty() || self.rng.gen_bool(0.5) {
++ path = dir_paths.choose(&mut self.rng).unwrap().clone();
++ path.push(gen_file_name(&mut self.rng));
++ path.set_extension("rs");
++ } else {
++ path = file_paths.choose(&mut self.rng).unwrap().clone()
++ };
+ }
- break ClientOperation::CreateFsEntry { path, is_dir };
++ break ClientOperation::WriteFsEntry {
++ path,
++ is_dir,
++ content,
++ };
+ }
+ }
+ })
+ }
+
+ fn next_root_dir_name(&mut self, user_id: UserId) -> String {
+ let user_ix = self
+ .users
+ .iter()
+ .position(|user| user.user_id == user_id)
+ .unwrap();
+ let root_id = util::post_inc(&mut self.users[user_ix].next_root_id);
+ format!("dir-{user_id}-{root_id}")
+ }
+
+ fn user(&mut self, user_id: UserId) -> &mut UserTestPlan {
+ let ix = self
+ .users
+ .iter()
+ .position(|user| user.user_id == user_id)
+ .unwrap();
+ &mut self.users[ix]
+ }
}
-fn choose_random_project(
- client: &mut TestClient,
- rng: &Mutex<StdRng>,
+async fn simulate_client(
+ client: Rc<TestClient>,
+ mut operation_rx: futures::channel::mpsc::UnboundedReceiver<usize>,
+ plan: Arc<Mutex<TestPlan>>,
+ mut cx: TestAppContext,
+) {
+ // Setup language server
+ let mut language = Language::new(
+ LanguageConfig {
+ name: "Rust".into(),
+ path_suffixes: vec!["rs".to_string()],
+ ..Default::default()
+ },
+ None,
+ );
+ let _fake_language_servers = language
+ .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
+ name: "the-fake-language-server",
+ capabilities: lsp::LanguageServer::full_capabilities(),
+ initializer: Some(Box::new({
+ let plan = plan.clone();
+ let fs = client.fs.clone();
+ move |fake_server: &mut FakeLanguageServer| {
+ fake_server.handle_request::<lsp::request::Completion, _, _>(
+ |_, _| async move {
+ Ok(Some(lsp::CompletionResponse::Array(vec![
+ lsp::CompletionItem {
+ text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
+ range: lsp::Range::new(
+ lsp::Position::new(0, 0),
+ lsp::Position::new(0, 0),
+ ),
+ new_text: "the-new-text".to_string(),
+ })),
+ ..Default::default()
+ },
+ ])))
+ },
+ );
+
+ fake_server.handle_request::<lsp::request::CodeActionRequest, _, _>(
+ |_, _| async move {
+ Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
+ lsp::CodeAction {
+ title: "the-code-action".to_string(),
+ ..Default::default()
+ },
+ )]))
+ },
+ );
+
+ fake_server.handle_request::<lsp::request::PrepareRenameRequest, _, _>(
+ |params, _| async move {
+ Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
+ params.position,
+ params.position,
+ ))))
+ },
+ );
+
+ fake_server.handle_request::<lsp::request::GotoDefinition, _, _>({
+ let fs = fs.clone();
+ let plan = plan.clone();
+ move |_, _| {
+ let fs = fs.clone();
+ let plan = plan.clone();
+ async move {
+ let files = fs.files().await;
+ let count = plan.lock().rng.gen_range::<usize, _>(1..3);
+ let files = (0..count)
+ .map(|_| files.choose(&mut plan.lock().rng).unwrap())
+ .collect::<Vec<_>>();
+ log::info!("LSP: Returning definitions in files {:?}", &files);
+ Ok(Some(lsp::GotoDefinitionResponse::Array(
+ files
+ .into_iter()
+ .map(|file| lsp::Location {
+ uri: lsp::Url::from_file_path(file).unwrap(),
+ range: Default::default(),
+ })
+ .collect(),
+ )))
+ }
+ }
+ });
+
+ fake_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>({
+ let plan = plan.clone();
+ move |_, _| {
+ let mut highlights = Vec::new();
+ let highlight_count = plan.lock().rng.gen_range(1..=5);
+ for _ in 0..highlight_count {
+ let start_row = plan.lock().rng.gen_range(0..100);
+ let start_column = plan.lock().rng.gen_range(0..100);
+ let start = PointUtf16::new(start_row, start_column);
+ let end_row = plan.lock().rng.gen_range(0..100);
+ let end_column = plan.lock().rng.gen_range(0..100);
+ let end = PointUtf16::new(end_row, end_column);
+ let range = if start > end { end..start } else { start..end };
+ highlights.push(lsp::DocumentHighlight {
+ range: range_to_lsp(range.clone()),
+ kind: Some(lsp::DocumentHighlightKind::READ),
+ });
+ }
+ highlights.sort_unstable_by_key(|highlight| {
+ (highlight.range.start, highlight.range.end)
+ });
+ async move { Ok(Some(highlights)) }
+ }
+ });
+ }
+ })),
+ ..Default::default()
+ }))
+ .await;
+ client.language_registry.add(Arc::new(language));
+
+ while let Some(batch_id) = operation_rx.next().await {
+ let Some((operation, skipped)) = plan.lock().next_client_operation(&client, batch_id, &cx) else { break };
+ match apply_client_operation(&client, operation, &mut cx).await {
+ Ok(()) => {}
+ Err(TestError::Inapplicable) => skipped.store(true, SeqCst),
+ Err(TestError::Other(error)) => {
+ log::error!("{} error: {}", client.username, error);
+ }
+ }
+ cx.background().simulate_random_delay().await;
+ }
+ log::info!("{}: done", client.username);
+}
+
+fn buffer_for_full_path(
+ client: &TestClient,
+ project: &ModelHandle<Project>,
+ full_path: &PathBuf,
+ cx: &TestAppContext,
+) -> Option<ModelHandle<language::Buffer>> {
+ client
+ .buffers_for_project(project)
+ .iter()
+ .find(|buffer| {
+ buffer.read_with(cx, |buffer, cx| {
+ buffer.file().unwrap().full_path(cx) == *full_path
+ })
+ })
+ .cloned()
+}
+
+fn project_for_root_name(
+ client: &TestClient,
+ root_name: &str,
+ cx: &TestAppContext,
) -> Option<ModelHandle<Project>> {
+ if let Some(ix) = project_ix_for_root_name(&*client.local_projects(), root_name, cx) {
+ return Some(client.local_projects()[ix].clone());
+ }
+ if let Some(ix) = project_ix_for_root_name(&*client.remote_projects(), root_name, cx) {
+ return Some(client.remote_projects()[ix].clone());
+ }
+ None
+}
+
+fn project_ix_for_root_name(
+ projects: &[ModelHandle<Project>],
+ root_name: &str,
+ cx: &TestAppContext,
+) -> Option<usize> {
+ projects.iter().position(|project| {
+ project.read_with(cx, |project, cx| {
+ let worktree = project.visible_worktrees(cx).next().unwrap();
+ worktree.read(cx).root_name() == root_name
+ })
+ })
+}
+
+fn root_name_for_project(project: &ModelHandle<Project>, cx: &TestAppContext) -> String {
+ project.read_with(cx, |project, cx| {
+ project
+ .visible_worktrees(cx)
+ .next()
+ .unwrap()
+ .read(cx)
+ .root_name()
+ .to_string()
+ })
+}
+
+fn project_path_for_full_path(
+ project: &ModelHandle<Project>,
+ full_path: &Path,
+ cx: &TestAppContext,
+) -> Option<ProjectPath> {
+ let mut components = full_path.components();
+ let root_name = components.next().unwrap().as_os_str().to_str().unwrap();
+ let path = components.as_path().into();
+ let worktree_id = project.read_with(cx, |project, cx| {
+ project.worktrees(cx).find_map(|worktree| {
+ let worktree = worktree.read(cx);
+ if worktree.root_name() == root_name {
+ Some(worktree.id())
+ } else {
+ None
+ }
+ })
+ })?;
+ Some(ProjectPath { worktree_id, path })
+}
+
+async fn ensure_project_shared(
+ project: &ModelHandle<Project>,
+ client: &TestClient,
+ cx: &mut TestAppContext,
+) {
+ let first_root_name = root_name_for_project(project, cx);
+ let active_call = cx.read(ActiveCall::global);
+ if active_call.read_with(cx, |call, _| call.room().is_some())
+ && project.read_with(cx, |project, _| project.is_local() && !project.is_shared())
+ {
+ match active_call
+ .update(cx, |call, cx| call.share_project(project.clone(), cx))
+ .await
+ {
+ Ok(project_id) => {
+ log::info!(
+ "{}: shared project {} with id {}",
+ client.username,
+ first_root_name,
+ project_id
+ );
+ }
+ Err(error) => {
+ log::error!(
+ "{}: error sharing project {}: {:?}",
+ client.username,
+ first_root_name,
+ error
+ );
+ }
+ }
+ }
+}
+
+fn choose_random_project(client: &TestClient, rng: &mut StdRng) -> Option<ModelHandle<Project>> {
client
- .local_projects
+ .local_projects()
.iter()
- .chain(&client.remote_projects)
- .choose(&mut *rng.lock())
+ .chain(client.remote_projects().iter())
+ .choose(rng)
.cloned()
}
@@@ -1913,15 -1217,14 +1960,27 @@@ fn gen_file_name(rng: &mut StdRng) -> S
name
}
+fn path_env_var(name: &str) -> Option<PathBuf> {
+ let value = env::var(name).ok()?;
+ let mut path = PathBuf::from(value);
+ if path.is_relative() {
+ let mut abs_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ abs_path.pop();
+ abs_path.pop();
+ abs_path.push(path);
+ path = abs_path
+ }
+ Some(path)
+}
++
+ async fn child_file_paths(client: &TestClient, dir_path: &Path) -> Vec<PathBuf> {
+ let mut child_paths = client.fs.read_dir(dir_path).await.unwrap();
+ let mut child_file_paths = Vec::new();
+ while let Some(child_path) = child_paths.next().await {
+ let child_path = child_path.unwrap();
+ if client.fs.is_file(&child_path).await {
+ child_file_paths.push(child_path);
+ }
+ }
+ child_file_paths
+ }