nb-cli 0.0.9

A command-line tool for reading, writing, and executing Jupyter notebooks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
mod test_helpers;

use std::fs;
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;

/// Helper struct to manage test environment
struct TestEnv {
    temp_dir: TempDir,
    binary_path: PathBuf,
    venv_path_env: String,
    venv_root: PathBuf,
}

impl TestEnv {
    fn new() -> Option<Self> {
        // Setup venv and check if execution tests can run
        let venv_root = test_helpers::setup_execution_venv()?;
        let venv_path_env = test_helpers::setup_venv_environment()?;

        let temp_dir = TempDir::new().expect("Failed to create temp directory");
        let binary_path = env!("CARGO_BIN_EXE_nb").into();

        Some(Self {
            temp_dir,
            binary_path,
            venv_path_env,
            venv_root,
        })
    }

    fn notebook_path(&self, name: &str) -> PathBuf {
        self.temp_dir.path().join(name)
    }

    /// Copy a fixture notebook to the test environment
    fn copy_fixture(&self, fixture_name: &str, dest_name: &str) -> PathBuf {
        let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("fixtures")
            .join(fixture_name);
        let dest_path = self.notebook_path(dest_name);
        fs::copy(&fixture_path, &dest_path)
            .unwrap_or_else(|_| panic!("Failed to copy fixture {}", fixture_name));
        dest_path
    }

    /// Copy an entire fixture directory (with subdirectories) to the test environment
    fn copy_fixture_dir(&self, fixture_subdir: &str, dest_name: &str) -> PathBuf {
        let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("fixtures")
            .join(fixture_subdir);
        let dest_path = self.notebook_path(dest_name);

        fn copy_dir_recursive(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
            fs::create_dir_all(dst)?;
            for entry in fs::read_dir(src)? {
                let entry = entry?;
                let ty = entry.file_type()?;
                let src_path = entry.path();
                let dst_path = dst.join(entry.file_name());
                if ty.is_dir() {
                    copy_dir_recursive(&src_path, &dst_path)?;
                } else {
                    fs::copy(&src_path, &dst_path)?;
                }
            }
            Ok(())
        }

        copy_dir_recursive(&fixture_path, &dest_path)
            .unwrap_or_else(|_| panic!("Failed to copy fixture directory {}", fixture_subdir));
        dest_path
    }

    fn run(&self, args: &[&str]) -> CommandResult {
        let output = Command::new(&self.binary_path)
            .args(args)
            .current_dir(self.temp_dir.path())
            .env("PATH", &self.venv_path_env)
            .env("VIRTUAL_ENV", &self.venv_root)
            .env_remove("PYTHONHOME") // Remove if set, as it conflicts with venv
            .output()
            .expect("Failed to execute command");

        CommandResult {
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            success: output.status.success(),
        }
    }
}

struct CommandResult {
    stdout: String,
    stderr: String,
    success: bool,
}

impl CommandResult {
    fn assert_success(self) -> Self {
        if !self.success {
            panic!(
                "Command failed:\nStderr: {}\nStdout: {}",
                self.stderr, self.stdout
            );
        }
        self
    }

    fn assert_failure(self) -> Self {
        if self.success {
            panic!(
                "Expected command to fail but it succeeded:\nStdout: {}\nStderr: {}",
                self.stdout, self.stderr
            );
        }
        self
    }
}

// ==================== EXECUTION TESTS ====================

#[test]
fn test_execute_single_cell() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    let result = env
        .run(&["execute", nb_path.to_str().unwrap(), "--cell-index", "0"])
        .assert_success();

    // Execute now returns notebook markdown on stdout
    assert!(
        test_helpers::parse_notebook_header(&result.stdout).is_some(),
        "Execute stdout should contain @@notebook header"
    );
}

#[test]
fn test_execute_cell_with_output() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    // Execute entire notebook so cell 2 can print the result
    let exec_result = env
        .run(&["execute", nb_path.to_str().unwrap()])
        .assert_success();

    // Verify output directly in execute stdout
    let outputs = test_helpers::parse_outputs(&exec_result.stdout);
    assert!(
        !outputs.is_empty(),
        "Execute stdout should contain @@output sentinels"
    );
    assert!(
        exec_result.stdout.contains("Result: 52"),
        "Execute stdout should contain the print output"
    );

    // Persistence check: verify via nb read that outputs were saved
    let result = env
        .run(&["read", nb_path.to_str().unwrap(), "--cell-index", "2"])
        .assert_success();

    let cells = test_helpers::parse_cells(&result.stdout);
    assert_eq!(cells.len(), 1);
    assert_eq!(cells[0].get_str("cell_type"), Some("code"));

    let read_outputs = test_helpers::parse_outputs(&result.stdout);
    assert!(
        !read_outputs.is_empty(),
        "Cell should have outputs after execution"
    );

    assert!(result.stdout.contains("Result: 52"));
}

#[test]
fn test_execute_cell_by_id() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    // Execute cell-1 which doesn't depend on other cells
    let result = env
        .run(&["execute", nb_path.to_str().unwrap(), "--cell", "cell-1"])
        .assert_success();

    assert!(
        test_helpers::parse_notebook_header(&result.stdout).is_some(),
        "Execute stdout should contain @@notebook header"
    );
}

#[test]
fn test_execute_notebook_preserves_state() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    // Execute entire notebook to preserve state across cells
    let exec_result = env
        .run(&["execute", nb_path.to_str().unwrap()])
        .assert_success();

    // Verify output directly in execute stdout
    assert!(
        exec_result.stdout.contains("Result: 52"),
        "Execute stdout should contain the computed result"
    );

    // Persistence check: verify via nb read
    let result = env
        .run(&["read", nb_path.to_str().unwrap(), "--cell-index", "2"])
        .assert_success();

    assert!(result.stdout.contains("Result: 52"));
}

#[test]
fn test_execute_entire_notebook() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    let exec_result = env
        .run(&["execute", nb_path.to_str().unwrap()])
        .assert_success();

    // Parse cells directly from execute stdout and verify execution counts
    let cells = test_helpers::parse_cells(&exec_result.stdout);
    assert!(!cells.is_empty(), "Should have cells in execute stdout");

    let code_cells: Vec<_> = cells
        .iter()
        .filter(|c| c.get_str("cell_type") == Some("code"))
        .collect();
    assert!(!code_cells.is_empty(), "Should have code cells");

    for cell in &code_cells {
        assert!(
            cell.get_i64("execution_count").is_some(),
            "Code cell at index {:?} should have execution_count after full notebook execution",
            cell.get_i64("index")
        );
    }

    // Persistence check: verify via nb read
    let read_result = env
        .run(&["read", nb_path.to_str().unwrap()])
        .assert_success();

    let read_cells = test_helpers::parse_cells(&read_result.stdout);
    let read_code_cells: Vec<_> = read_cells
        .iter()
        .filter(|c| c.get_str("cell_type") == Some("code"))
        .collect();
    for cell in &read_code_cells {
        assert!(
            cell.get_i64("execution_count").is_some(),
            "Persisted code cell should have execution_count"
        );
    }
}

#[test]
fn test_execute_notebook_with_range() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    // Execute only cells 0-1
    env.run(&[
        "execute",
        nb_path.to_str().unwrap(),
        "--start",
        "0",
        "--end",
        "1",
    ])
    .assert_success();
}

#[test]
fn test_execute_with_error() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("with_error.ipynb", "test.ipynb");

    // Should fail without --allow-errors but still output notebook content
    let result = env
        .run(&["execute", nb_path.to_str().unwrap()])
        .assert_failure();

    // Verify partial results appear in stdout despite failure
    assert!(
        test_helpers::parse_notebook_header(&result.stdout).is_some(),
        "Failed execute should still output @@notebook header"
    );

    let outputs = test_helpers::parse_outputs(&result.stdout);
    assert!(
        !outputs.is_empty(),
        "Failed execute should include outputs (error or successful cells)"
    );
}

#[test]
fn test_execute_with_allow_errors() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("with_error.ipynb", "test.ipynb");

    // Execute with --allow-errors (still exits with error code but updates notebook)
    let result = env.run(&["execute", nb_path.to_str().unwrap(), "--allow-errors"]);

    // Stdout should contain notebook markdown with outputs from both cells
    assert!(
        test_helpers::parse_notebook_header(&result.stdout).is_some(),
        "Should have @@notebook header in stdout"
    );

    let cells = test_helpers::parse_cells(&result.stdout);
    let code_cells: Vec<_> = cells
        .iter()
        .filter(|c| c.get_str("cell_type") == Some("code"))
        .collect();
    assert!(
        !code_cells.is_empty(),
        "Should have code cells in execute output"
    );

    // First cell should have execution_count (it succeeded)
    assert!(
        code_cells[0].get_i64("execution_count").is_some(),
        "First code cell should have execution_count"
    );

    // Persistence check
    let read_result = env
        .run(&["read", nb_path.to_str().unwrap(), "--cell-index", "0"])
        .assert_success();

    assert!(read_result.stdout.contains("execution_count"));
}

#[test]
fn test_execute_with_timeout() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    // Execute with custom timeout
    env.run(&[
        "execute",
        nb_path.to_str().unwrap(),
        "--cell-index",
        "0",
        "--timeout",
        "60",
    ])
    .assert_success();
}

#[test]
fn test_execute_last_cell_with_negative_index() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.notebook_path("test.ipynb");

    // Create a notebook with independent cells
    env.run(&["create", nb_path.to_str().unwrap()])
        .assert_success();

    env.run(&[
        "cell",
        "add",
        nb_path.to_str().unwrap(),
        "--source",
        "x = 10",
    ])
    .assert_success();

    env.run(&[
        "cell",
        "add",
        nb_path.to_str().unwrap(),
        "--source",
        "result = 2 + 2",
    ])
    .assert_success();

    // Execute last cell using --cell-index -1 (space-separated style)
    // This tests that allow_negative_numbers is properly configured
    let result = env
        .run(&["execute", nb_path.to_str().unwrap(), "--cell-index", "-1"])
        .assert_success();

    // Execute stdout should contain notebook markdown
    assert!(
        test_helpers::parse_notebook_header(&result.stdout).is_some(),
        "Execute stdout should contain @@notebook header"
    );
}

#[test]
#[ignore] // Dry-run feature not available in unified execute command
fn test_execute_dry_run() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    // Execute with --dry-run
    env.run(&[
        "execute",
        nb_path.to_str().unwrap(),
        "--cell-index",
        "0",
        "--dry-run",
    ])
    .assert_success();

    // Verify notebook wasn't modified (no execution count)
    let result = env
        .run(&["read", nb_path.to_str().unwrap()])
        .assert_success();

    // Execution count should still be null for dry run
    assert!(result.stdout.contains("\"execution_count\": null"));
}

#[test]
fn test_execute_json_format() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    let result = env
        .run(&[
            "execute",
            nb_path.to_str().unwrap(),
            "--cell-index",
            "0",
            "--json",
        ])
        .assert_success();

    // Should output valid JSON with cells and summary
    let json: serde_json::Value =
        serde_json::from_str(&result.stdout).expect("Should output valid JSON");
    assert!(
        json.get("success").is_some(),
        "JSON should have success field"
    );
    assert!(json.get("cells").is_some(), "JSON should have cells array");
}

// ==================== WORKFLOW TESTS ====================

#[test]
fn test_workflow_create_add_execute() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.notebook_path("workflow.ipynb");

    // Create notebook
    env.run(&["create", nb_path.to_str().unwrap()])
        .assert_success();

    // Add cell with code
    env.run(&[
        "cell",
        "add",
        nb_path.to_str().unwrap(),
        "--source",
        "result = 2 + 2",
    ])
    .assert_success();

    // Add another cell that uses the result
    env.run(&[
        "cell",
        "add",
        nb_path.to_str().unwrap(),
        "--source",
        "print(f'Answer: {result}')",
    ])
    .assert_success();

    // Execute entire notebook to preserve state
    let exec_result = env
        .run(&["execute", nb_path.to_str().unwrap()])
        .assert_success();

    // Verify output directly in execute stdout
    assert!(
        exec_result.stdout.contains("Answer: 4"),
        "Execute stdout should contain the computed answer"
    );

    // Persistence check (cell index 2 because create adds an empty cell at index 0)
    let result = env
        .run(&["read", nb_path.to_str().unwrap(), "--cell-index", "2"])
        .assert_success();

    assert!(result.stdout.contains("Answer: 4"));
}

#[test]
fn test_workflow_modify_and_reexecute() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    // Execute notebook
    env.run(&["execute", nb_path.to_str().unwrap()])
        .assert_success();

    // Modify a cell
    env.run(&[
        "cell",
        "update",
        nb_path.to_str().unwrap(),
        "--cell-index",
        "0",
        "--source",
        "x = 100",
    ])
    .assert_success();

    // Re-execute the notebook
    let exec_result = env
        .run(&["execute", nb_path.to_str().unwrap()])
        .assert_success();

    // Verify the new value directly in execute stdout
    assert!(
        exec_result.stdout.contains("Result: 110"),
        "Execute stdout should show Result: 110 after modifying x to 100"
    );

    // Persistence check
    let result = env
        .run(&["read", nb_path.to_str().unwrap(), "--cell-index", "2"])
        .assert_success();

    assert!(result.stdout.contains("Result: 110"));
}

#[test]
fn test_execute_with_relative_paths() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    // Copy the entire subdir fixture (includes notebook and data/test.txt)
    let subdir_path = env.copy_fixture_dir("subdir", "subdir");
    let nb_path = subdir_path.join("with_relative_path.ipynb");

    // Execute notebook from parent directory (not from subdir)
    // This tests that relative paths in the notebook work correctly
    env.run(&["execute", nb_path.to_str().unwrap()])
        .assert_success();

    // Verify the file was loaded successfully
    let result = env
        .run(&["read", nb_path.to_str().unwrap(), "--cell-index", "0"])
        .assert_success();

    // Check that it loaded the file and printed the expected output
    assert!(result.stdout.contains("Hello from relative path!"));
}

// ==================== OUTPUT FORMAT TESTS ====================

#[test]
fn test_execute_output_matches_read() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    // Execute notebook — stdout should be notebook markdown
    let exec_result = env
        .run(&["execute", nb_path.to_str().unwrap()])
        .assert_success();

    // Read the same notebook — stdout should match execute
    let read_result = env
        .run(&["read", nb_path.to_str().unwrap()])
        .assert_success();

    // Both should produce the same notebook markdown format
    // Compare sentinel structure (headers, cells, outputs) rather than byte-for-byte
    // since output dir paths may differ
    let exec_cells = test_helpers::parse_cells(&exec_result.stdout);
    let read_cells = test_helpers::parse_cells(&read_result.stdout);
    assert_eq!(
        exec_cells.len(),
        read_cells.len(),
        "Execute and read should produce the same number of cells"
    );

    let exec_outputs = test_helpers::parse_outputs(&exec_result.stdout);
    let read_outputs = test_helpers::parse_outputs(&read_result.stdout);
    assert_eq!(
        exec_outputs.len(),
        read_outputs.len(),
        "Execute and read should produce the same number of outputs"
    );

    // Verify output types match
    for (exec_out, read_out) in exec_outputs.iter().zip(read_outputs.iter()) {
        assert_eq!(
            exec_out.get_str("output_type"),
            read_out.get_str("output_type"),
            "Output types should match between execute and read"
        );
    }
}

#[test]
fn test_execute_error_shows_partial_results_and_error() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("with_error.ipynb", "test.ipynb");

    // Execute without --allow-errors: cell-1 (valid_code = 123) succeeds, cell-2 (undefined_variable) fails
    let result = env
        .run(&["execute", nb_path.to_str().unwrap()])
        .assert_failure();

    // Stdout should contain notebook markdown with partial results
    assert!(
        test_helpers::parse_notebook_header(&result.stdout).is_some(),
        "Should have @@notebook header despite failure"
    );

    // Cell-1 should have execution_count (it ran successfully)
    let cells = test_helpers::parse_cells(&result.stdout);
    let code_cells: Vec<_> = cells
        .iter()
        .filter(|c| c.get_str("cell_type") == Some("code"))
        .collect();
    assert!(
        code_cells.len() >= 2,
        "Should have at least 2 code cells in output"
    );
    assert!(
        code_cells[0].get_i64("execution_count").is_some(),
        "First code cell should have execution_count (it succeeded)"
    );

    // Cell-2 should have an error output
    let outputs = test_helpers::parse_outputs(&result.stdout);
    let error_outputs: Vec<_> = outputs
        .iter()
        .filter(|o| o.get_str("output_type") == Some("error"))
        .collect();
    assert!(
        !error_outputs.is_empty(),
        "Should have an error output from the failed cell"
    );
    assert_eq!(
        error_outputs[0].get_str("ename"),
        Some("NameError"),
        "Error should be a NameError"
    );

    // Persistence check: partial results should be saved
    let read_result = env
        .run(&["read", nb_path.to_str().unwrap()])
        .assert_success();

    let read_cells = test_helpers::parse_cells(&read_result.stdout);
    let read_code_cells: Vec<_> = read_cells
        .iter()
        .filter(|c| c.get_str("cell_type") == Some("code"))
        .collect();
    assert!(
        read_code_cells[0].get_i64("execution_count").is_some(),
        "Persisted first cell should have execution_count"
    );
}

#[test]
fn test_execute_json_includes_outputs() {
    let Some(env) = TestEnv::new() else {
        eprintln!("⚠️  Skipping test: execution environment not available");
        return;
    };

    let nb_path = env.copy_fixture("for_execution.ipynb", "test.ipynb");

    let result = env
        .run(&["execute", nb_path.to_str().unwrap(), "--json"])
        .assert_success();

    let json: serde_json::Value =
        serde_json::from_str(&result.stdout).expect("Should output valid JSON");

    // Verify summary fields
    assert_eq!(json["success"], true);
    assert!(json["executed_cells"].as_u64().unwrap() > 0);

    // Verify cells array has outputs
    let cells = json["cells"].as_array().expect("Should have cells array");
    let code_cells: Vec<_> = cells.iter().filter(|c| c["cell_type"] == "code").collect();

    // Last code cell (print) should have outputs
    let last_cell = code_cells.last().expect("Should have code cells");
    let outputs = last_cell["outputs"]
        .as_array()
        .expect("Last code cell should have outputs");
    assert!(!outputs.is_empty(), "Should have at least one output");

    // Verify the actual output content contains the computed result
    let output_text = serde_json::to_string(outputs).unwrap();
    assert!(
        output_text.contains("Result: 52"),
        "Output should contain 'Result: 52'"
    );
}