new_process_modal.rs

  1use dap::DapRegistry;
  2use gpui::{BackgroundExecutor, TestAppContext, VisualTestContext};
  3use project::{FakeFs, Project};
  4use serde_json::json;
  5use std::sync::Arc;
  6use std::sync::atomic::{AtomicBool, Ordering};
  7use task::{DebugRequest, DebugScenario, LaunchRequest, TaskContext, VariableName, ZedDebugConfig};
  8use util::path;
  9
 10// use crate::new_process_modal::NewProcessMode;
 11use crate::tests::{init_test, init_test_workspace};
 12
 13#[gpui::test]
 14async fn test_debug_session_substitutes_variables_and_relativizes_paths(
 15    executor: BackgroundExecutor,
 16    cx: &mut TestAppContext,
 17) {
 18    init_test(cx);
 19
 20    let fs = FakeFs::new(executor.clone());
 21    fs.insert_tree(
 22        path!("/project"),
 23        json!({
 24            "main.rs": "fn main() {}"
 25        }),
 26    )
 27    .await;
 28
 29    let project = Project::test(fs, [path!("/project").as_ref()], cx).await;
 30    let workspace = init_test_workspace(&project, cx).await;
 31    let cx = &mut VisualTestContext::from_window(*workspace, cx);
 32
 33    let test_variables = vec![(
 34        VariableName::WorktreeRoot,
 35        path!("/test/worktree/path").to_string(),
 36    )]
 37    .into_iter()
 38    .collect();
 39
 40    let task_context = TaskContext {
 41        cwd: None,
 42        task_variables: test_variables,
 43        project_env: Default::default(),
 44    };
 45
 46    let home_dir = paths::home_dir();
 47
 48    let test_cases: Vec<(&'static str, &'static str)> = vec![
 49        // Absolute path - should not be relativized
 50        (
 51            path!("/absolute/path/to/program"),
 52            path!("/absolute/path/to/program"),
 53        ),
 54        // Relative path - should be prefixed with worktree root
 55        (
 56            format!(".{0}src{0}program", std::path::MAIN_SEPARATOR).leak(),
 57            path!("/test/worktree/path/src/program"),
 58        ),
 59        // Home directory path - should be expanded to full home directory path
 60        (
 61            format!("~{0}src{0}program", std::path::MAIN_SEPARATOR).leak(),
 62            home_dir
 63                .join("src")
 64                .join("program")
 65                .to_string_lossy()
 66                .to_string()
 67                .leak(),
 68        ),
 69        // Path with $ZED_WORKTREE_ROOT - should be substituted without double appending
 70        (
 71            format!(
 72                "$ZED_WORKTREE_ROOT{0}src{0}program",
 73                std::path::MAIN_SEPARATOR
 74            )
 75            .leak(),
 76            path!("/test/worktree/path/src/program"),
 77        ),
 78    ];
 79
 80    let called_launch = Arc::new(AtomicBool::new(false));
 81
 82    for (input_path, expected_path) in test_cases {
 83        let _subscription = project::debugger::test::intercept_debug_sessions(cx, {
 84            let called_launch = called_launch.clone();
 85            move |client| {
 86                client.on_request::<dap::requests::Launch, _>({
 87                    let called_launch = called_launch.clone();
 88
 89                    move |_, args| {
 90                        let config = args.raw.as_object().unwrap();
 91
 92                        assert_eq!(
 93                            config["program"].as_str().unwrap(),
 94                            expected_path,
 95                            "Program path was not correctly substituted for input: {}",
 96                            input_path
 97                        );
 98
 99                        assert_eq!(
100                            config["cwd"].as_str().unwrap(),
101                            expected_path,
102                            "CWD path was not correctly substituted for input: {}",
103                            input_path
104                        );
105
106                        let expected_other_field = if input_path.contains("$ZED_WORKTREE_ROOT") {
107                            input_path
108                                .replace("$ZED_WORKTREE_ROOT", &path!("/test/worktree/path"))
109                                .to_owned()
110                        } else {
111                            input_path.to_string()
112                        };
113
114                        assert_eq!(
115                            config["otherField"].as_str().unwrap(),
116                            &expected_other_field,
117                            "Other field was incorrectly modified for input: {}",
118                            input_path
119                        );
120
121                        called_launch.store(true, Ordering::SeqCst);
122
123                        Ok(())
124                    }
125                });
126            }
127        });
128
129        let scenario = DebugScenario {
130            adapter: "fake-adapter".into(),
131            label: "test-debug-session".into(),
132            build: None,
133            config: json!({
134                "request": "launch",
135                "program": input_path,
136                "cwd": input_path,
137                "otherField": input_path
138            }),
139            tcp_connection: None,
140        };
141
142        workspace
143            .update(cx, |workspace, window, cx| {
144                workspace.start_debug_session(scenario, task_context.clone(), None, window, cx)
145            })
146            .unwrap();
147
148        cx.run_until_parked();
149
150        assert!(called_launch.load(Ordering::SeqCst));
151        called_launch.store(false, Ordering::SeqCst);
152    }
153}
154
155// #[gpui::test]
156// async fn test_save_debug_scenario_to_file(executor: BackgroundExecutor, cx: &mut TestAppContext) {
157//     init_test(cx);
158
159//     let fs = FakeFs::new(executor.clone());
160//     fs.insert_tree(
161//         path!("/project"),
162//         json!({
163//             "main.rs": "fn main() {}"
164//         }),
165//     )
166//     .await;
167
168//     let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
169//     let workspace = init_test_workspace(&project, cx).await;
170//     let cx = &mut VisualTestContext::from_window(*workspace, cx);
171
172//     workspace
173//         .update(cx, |workspace, window, cx| {
174//             crate::new_process_modal::NewProcessModal::show(
175//                 workspace,
176//                 window,
177//                 NewProcessMode::Debug,
178//                 None,
179//                 cx,
180//             );
181//         })
182//         .unwrap();
183
184//     cx.run_until_parked();
185
186//     let modal = workspace
187//         .update(cx, |workspace, _, cx| {
188//             workspace.active_modal::<crate::new_process_modal::NewProcessModal>(cx)
189//         })
190//         .unwrap()
191//         .expect("Modal should be active");
192
193//     modal.update_in(cx, |modal, window, cx| {
194//         modal.set_configure("/project/main", "/project", false, window, cx);
195//         modal.save_scenario(window, cx);
196//     });
197
198//     cx.executor().run_until_parked();
199
200//     let debug_json_content = fs
201//         .load(path!("/project/.zed/debug.json").as_ref())
202//         .await
203//         .expect("debug.json should exist");
204
205//     let expected_content = vec![
206//         "[",
207//         "  {",
208//         r#"    "adapter": "fake-adapter","#,
209//         r#"    "label": "main (fake-adapter)","#,
210//         r#"    "request": "launch","#,
211//         r#"    "program": "/project/main","#,
212//         r#"    "cwd": "/project","#,
213//         r#"    "args": [],"#,
214//         r#"    "env": {}"#,
215//         "  }",
216//         "]",
217//     ];
218
219//     let actual_lines: Vec<&str> = debug_json_content.lines().collect();
220//     pretty_assertions::assert_eq!(expected_content, actual_lines);
221
222//     modal.update_in(cx, |modal, window, cx| {
223//         modal.set_configure("/project/other", "/project", true, window, cx);
224//         modal.save_scenario(window, cx);
225//     });
226
227//     cx.executor().run_until_parked();
228
229//     let debug_json_content = fs
230//         .load(path!("/project/.zed/debug.json").as_ref())
231//         .await
232//         .expect("debug.json should exist after second save");
233
234//     let expected_content = vec![
235//         "[",
236//         "  {",
237//         r#"    "adapter": "fake-adapter","#,
238//         r#"    "label": "main (fake-adapter)","#,
239//         r#"    "request": "launch","#,
240//         r#"    "program": "/project/main","#,
241//         r#"    "cwd": "/project","#,
242//         r#"    "args": [],"#,
243//         r#"    "env": {}"#,
244//         "  },",
245//         "  {",
246//         r#"    "adapter": "fake-adapter","#,
247//         r#"    "label": "other (fake-adapter)","#,
248//         r#"    "request": "launch","#,
249//         r#"    "program": "/project/other","#,
250//         r#"    "cwd": "/project","#,
251//         r#"    "args": [],"#,
252//         r#"    "env": {}"#,
253//         "  }",
254//         "]",
255//     ];
256
257//     let actual_lines: Vec<&str> = debug_json_content.lines().collect();
258//     pretty_assertions::assert_eq!(expected_content, actual_lines);
259// }
260
261#[gpui::test]
262async fn test_dap_adapter_config_conversion_and_validation(cx: &mut TestAppContext) {
263    init_test(cx);
264
265    let mut expected_adapters = vec![
266        "CodeLLDB",
267        "Debugpy",
268        "PHP",
269        "JavaScript",
270        "Ruby",
271        "Delve",
272        "GDB",
273        "fake-adapter",
274    ];
275
276    let adapter_names = cx.update(|cx| {
277        let registry = DapRegistry::global(cx);
278        registry.enumerate_adapters()
279    });
280
281    let zed_config = ZedDebugConfig {
282        label: "test_debug_session".into(),
283        adapter: "test_adapter".into(),
284        request: DebugRequest::Launch(LaunchRequest {
285            program: "test_program".into(),
286            cwd: None,
287            args: vec![],
288            env: Default::default(),
289        }),
290        stop_on_entry: Some(true),
291    };
292
293    for adapter_name in adapter_names {
294        let adapter_str = adapter_name.to_string();
295        if let Some(pos) = expected_adapters.iter().position(|&x| x == adapter_str) {
296            expected_adapters.remove(pos);
297        }
298
299        let adapter = cx
300            .update(|cx| {
301                let registry = DapRegistry::global(cx);
302                registry.adapter(adapter_name.as_ref())
303            })
304            .unwrap_or_else(|| panic!("Adapter {} should exist", adapter_name));
305
306        let mut adapter_specific_config = zed_config.clone();
307        adapter_specific_config.adapter = adapter_name.to_string().into();
308
309        let debug_scenario = adapter
310            .config_from_zed_format(adapter_specific_config)
311            .unwrap_or_else(|_| {
312                panic!(
313                    "Adapter {} should successfully convert from Zed format",
314                    adapter_name
315                )
316            });
317
318        assert!(
319            debug_scenario.config.is_object(),
320            "Adapter {} should produce a JSON object for config",
321            adapter_name
322        );
323
324        let request_type = adapter
325            .request_kind(&debug_scenario.config)
326            .unwrap_or_else(|_| {
327                panic!(
328                    "Adapter {} should validate the config successfully",
329                    adapter_name
330                )
331            });
332
333        match request_type {
334            dap::StartDebuggingRequestArgumentsRequest::Launch => {}
335            dap::StartDebuggingRequestArgumentsRequest::Attach => {
336                panic!(
337                    "Expected Launch request but got Attach for adapter {}",
338                    adapter_name
339                );
340            }
341        }
342    }
343
344    assert!(
345        expected_adapters.is_empty(),
346        "The following expected adapters were not found in the registry: {:?}",
347        expected_adapters
348    );
349}