Skip to content

[FEAT] Create a Testing Harness - #34

Merged
Avni2000 merged 12 commits into
mainfrom
22-feat-create-a-proper-testing-framework
Feb 4, 2026
Merged

Avni2000 merged 12 commits into
mainfrom
22-feat-create-a-proper-testing-framework

Conversation

@Avni2000

@Avni2000 Avni2000 commented Feb 4, 2026 •

Copy link
Copy Markdown
Owner

Flow:

  1. Compiles
  2. Opens VSCode
  3. Runs command to open web notebook resolver
  4. Resolves with playwright, taking incoming/current/deletion and adding modifications based on cell index.
  5. Compares on-disk file to the multiset of {Unified Rows} + {Text Areas}, filtering down the deleted rows.

Note that this approach ignores output, but checks execution count to disk.

Closes #22

Summary by CodeRabbit

  • New Features

    • New command to retrieve detailed information about the most recent notebook conflict resolution (URI and resolution metadata).
    • Conflict-resolution now surfaces richer resolution details for consumers.
  • Chores

    • Added end-to-end integration test harness and CI workflow for automated VS Code testing.
    • Introduced Playwright-based test configuration and test-run scripts; made server startup more test-friendly.

…pture all cell data from Playwright

- Exposes port from webServer
- Session opens in default browser correctly
- Exposes extension and resolver data, this should be cleaned up
- Checks modication, taking different branches, deletion, order, etc.
- Builds {unified row} U {conflicted rows} without just checking brittle indices
@Avni2000 Avni2000 linked an issue Feb 4, 2026 that may be closed by this pull request
@coderabbitai

coderabbitai Bot commented Feb 4, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds an automated VS Code integration test framework (Playwright + test runner), exposes rich conflict-resolution details via a new event, augments web UI elements with test-oriented data attributes, and enables headless server execution for CI with test-friendly URI handling and port persistence.

Changes

Cohort / File(s) Summary
Test config & CI
playwright.config.ts, package.json, tsconfig.json, .github/workflows/vscode-integration-test.yml, output.txt
Add Playwright config, new npm test:vscode script and dev deps, exclude Playwright from TS build, and add GitHub Actions workflow to run VS Code integration tests under Xvfb.
Integration test runner & tests
src/tests/runIntegrationTest.ts, src/tests/vscodeIntegration.test.ts
New test runner that creates a merge-conflict repo and launches VS Code test harness; comprehensive Playwright E2E test that drives the conflict UI, applies resolutions, and verifies on-disk notebook consistency.
Resolver & extension plumbing
src/resolver.ts, src/extension.ts
Introduce exported ResolvedConflictDetails type and onDidResolveConflictWithDetails event emitter; emit detailed events after auto- and semantic-resolution; extension tracks lastResolvedDetails and exposes merge-nb.getLastResolutionDetails command.
Web server testability
src/web/webServer.ts
Make vscode import optional, add UriLike interface, change setExtensionUri/property to UriLike, persist server port to temp file, include sessionIds in health response, and guard external-browser launch when VSCode absent.
Web UI test attributes
src/web/client/CellContent.tsx, src/web/client/ConflictResolver.tsx, src/web/client/MergeRow.tsx
Add DOM data attributes (data-cell, data-cell-type, data-raw-source, data-testid) and optional data-testid prop; improve traceback handling and serialize cells for DOM debugging.

Sequence Diagram

sequenceDiagram
    participant TestRunner as Integration Test Runner
    participant Git as Git (Repo Setup)
    participant VSCode as VS Code Host
    participant Server as Web Server
    participant Browser as Playwright Browser
    participant Disk as Disk (notebook.ipynb)

    TestRunner->>Git: createMergeConflictRepo()
    Git->>Git: create base/current/incoming branches
    Git-->>TestRunner: repo ready

    TestRunner->>VSCode: runTests (workspace path)
    VSCode->>VSCode: load extension + start server
    VSCode->>Server: initialize session
    Server-->>VSCode: port + sessionId
    Server->>TestRunner: persist port to temp file

    TestRunner->>Browser: launch headless Chromium
    Browser->>Server: GET /session/{sessionId}
    Server-->>Browser: serve conflict UI

    Browser->>Server: poll health endpoint
    Server-->>Browser: health + sessionIds

    Browser->>Browser: interact with UI (resolve rows, set checkboxes)
    Browser->>Server: POST /apply (resolution)
    Server->>VSCode: emit onDidResolveConflictWithDetails
    VSCode->>Disk: write resolved notebook

    Browser->>Disk: read resulting notebook
    Browser->>Browser: validate notebook structure & cells
    Browser-->>TestRunner: test pass/fail
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I hopped through repos, scripts, and test runs bright,

I stitched conflicts, opened pages in the night,
Data-testids glowing, sessions found with care,
The notebook healed, saved, and matched what I could share,
Hooray — the tests now hop and dance with delight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed The PR successfully implements all core coding requirements from issue #22: automates merge conflict testing, detects conflicts, opens the resolver in a browser, and validates resolution inputs through integration tests.
Out of Scope Changes check ✅ Passed All changes directly support the testing harness objective; no out-of-scope modifications detected. Changes include test infrastructure, configuration files, and minimal API additions required for test integration.
Title check ✅ Passed The title '[FEAT] Create a Testing Harness' accurately describes the main objective of the changeset, which introduces a comprehensive testing framework with Playwright integration, VS Code extension testing, integration test runners, and related configuration files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 22-feat-create-a-proper-testing-framework

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/web/client/CellContent.tsx (1)

47-78: ⚠️ Potential issue | 🟠 Major

Avoid embedding full cell JSON (including outputs) in data-cell.
Serializing the entire cell can inject large base64 outputs into the DOM and exposes hidden outputs, which is a performance and UX risk. Prefer a minimal payload (type/source/execution_count) or gate it behind a test flag.

🛠️ Safer minimal payload
-    const encodedCell = encodeURIComponent(JSON.stringify(cell));
+    const encodedCell = encodeURIComponent(JSON.stringify({
+        cell_type: cell.cell_type,
+        source: cell.source,
+        execution_count: cell.execution_count ?? null,
+    }));
🤖 Fix all issues with AI agents
In `@output.txt`:
- Around line 1-78: The file output.txt appears to be generated test output with
no documented purpose; either add a short note in the repository README (or a
comment near test scripts like esbuild.js / runIntegrationTest.js) explaining
what output.txt is, when/why it's committed and how it should be used, or remove
output.txt from the repo and add "output.txt" to .gitignore (and update any
CI/test scripts that rely on it such as runIntegrationTest.js) so transient test
artifacts are not tracked.
🧹 Nitpick comments (9)
package.json (1)

111-128: Ensure Playwright browsers are installed for test:vscode.
The new test flow relies on @playwright/test, which requires browser binaries. If CI doesn’t install them, tests will fail. Consider adding a dedicated install step or script.

💡 Optional script addition
 "scripts": {
+  "playwright:install": "playwright install --with-deps",
   "test:vscode": "npm run compile && npm run compile-tests && node out/tests/runIntegrationTest.js"
 }
src/resolver.ts (1)

175-181: Consider disposing the event emitter to prevent memory leaks.

The onDidResolveConflictWithDetails EventEmitter is a module-level export but is never disposed. While this may be acceptable for an extension's lifecycle, consider adding disposal logic in the extension's deactivate() function if the emitter accumulates listeners over time.

src/extension.ts (1)

25-31: Type safety could be improved.

Using unknown for resolvedNotebook and resolvedRows loses type safety. Consider importing and using the actual types from ./resolver and ./web/webTypes if the command consumers are expected to work with typed data.

♻️ Optional: Use explicit types for better type safety
+import type { ResolvedConflictDetails } from './resolver';
+import type { Notebook } from './types';
+import type { ResolvedRow } from './web/webTypes';
+
 let lastResolvedDetails: {
 	uri: string;
-	resolvedNotebook: unknown;
-	resolvedRows?: unknown[];
+	resolvedNotebook: Notebook;
+	resolvedRows?: ResolvedRow[];
 	markAsResolved: boolean;
 	renumberExecutionCounts: boolean;
 } | undefined;
src/web/webServer.ts (1)

136-144: Port file could cause conflicts with concurrent test runs.

The hardcoded port file path /tmp/mergenb-server-port could cause race conditions if multiple test instances run simultaneously. Consider including a unique identifier (e.g., PID or session ID) in the filename.

♻️ Suggested fix to avoid concurrent test conflicts
                     // Write port to temp file for integration tests
                     try {
                         const tmpDir = process.env.TMPDIR || process.env.TMP || '/tmp';
-                        const portFile = path.join(tmpDir, 'mergenb-server-port');
+                        const portFile = path.join(tmpDir, `mergenb-server-port-${process.pid}`);
                         fs.writeFileSync(portFile, String(this.port), 'utf8');
                     } catch (e) {
                         // Ignore errors writing port file
                     }
src/tests/runIntegrationTest.ts (2)

81-82: Config file path should be unique per test run.

Similar to the port file concern in webServer.ts, the hardcoded mergenb-test-config.json path could cause issues with concurrent test runs. Consider using a unique identifier.

♻️ Suggested fix for concurrent test safety
         // Write workspace path to a temp file so the test can read it
-        const configPath = path.join(os.tmpdir(), 'mergenb-test-config.json');
+        const configPath = path.join(os.tmpdir(), `mergenb-test-config-${process.pid}.json`);
         fs.writeFileSync(configPath, JSON.stringify({ workspacePath: testWorkspacePath }));

Note: The corresponding read in vscodeIntegration.test.ts at line 89 would also need updating to use the same PID-based filename, or the path should be passed via environment variable.


96-97: Wrap config file deletion in try/catch for robustness.

fs.unlinkSync(configPath) can throw if the file was already deleted or doesn't exist. Consider wrapping it in a try/catch like the workspace cleanup.

♻️ Add error handling for config file cleanup
         // Cleanup
         fs.rmSync(testWorkspacePath, { recursive: true, force: true });
-        fs.unlinkSync(configPath);
+        try { fs.unlinkSync(configPath); } catch { /* ignore */ }
src/tests/vscodeIntegration.test.ts (3)

31-39: Consolidate duplicate health check functions.

checkHealth (lines 31-39) and getHealthInfo (lines 59-79) have overlapping functionality. Consider merging them into a single function that returns the full health response or null, then derive the boolean check from that.

♻️ Consolidate health check functions
-function checkHealth(port: number): Promise<boolean> {
-    return new Promise((resolve) => {
-        const req = http.get(`http://127.0.0.1:${port}/health`, { timeout: 500 }, (res) => {
-            resolve(res.statusCode === 200);
-        });
-        req.on('error', () => resolve(false));
-        req.on('timeout', () => { req.destroy(); resolve(false); });
-    });
-}
-
 function getHealthInfo(port: number): Promise<HealthResponse | null> {
     // ... existing implementation ...
 }

+function checkHealth(port: number): Promise<boolean> {
+    return getHealthInfo(port).then(info => info !== null);
+}

Also applies to: 59-79


96-96: Replace hardcoded delays with explicit wait conditions.

Multiple setTimeout calls (lines 96, 147, 155, etc.) make the test slower and more fragile. Playwright's waitFor with explicit conditions is more reliable.

♻️ Example: Replace line 147's delay with explicit wait
         await page.goto(sessionUrl);
-        await new Promise(r => setTimeout(r, 3000));
-        
-        await page.waitForSelector('.header-title', { timeout: 15000 });
+        await page.waitForSelector('.header-title', { timeout: 15000 });

The 3-second delay before waiting for .header-title is redundant since waitForSelector already handles the timing.

Also applies to: 147-147, 155-155


99-101: Port file path construction could be extracted to a shared constant.

Both webServer.ts (line 140) and vscodeIntegration.test.ts (line 100) independently construct the same port file path using duplicated logic (process.env.TMPDIR || process.env.TMP || '/tmp' + 'mergenb-server-port'). Consider extracting this to a shared constant to reduce duplication and ensure consistency if either path needs to change in the future.

Comment thread output.txt
Comment on lines +1 to +78

> [email protected] test:vscode
> npm run compile && npm run compile-tests && node out/tests/runIntegrationTest.js


> [email protected] compile
> npm run check-types && npm run lint && node esbuild.js


> [email protected] check-types
> tsc --noEmit


> [email protected] lint
> eslint src

[watch] build started
[watch] build started
[watch] build finished
[watch] build finished
[katex] Copied KaTeX dist bundle

> [email protected] compile-tests
> tsc -p . --outDir out

Created test workspace at: /tmp/mergeNB-integration-yZ312l
[main 2026-02-04T22:51:19.119Z] update#setState disabled
[main 2026-02-04T22:51:19.121Z] update#ctor - updates are disabled by the environment
Started local extension host with pid 286860.
Loading development extension at /home/avni/source/repos/MergeNB
MCP Registry configured: https://api.mcp.github.com
MergeNB extension is now active
Settings Sync: Account status changed from uninitialized to unavailable
Starting MergeNB VS Code Integration Test...
Executing merge-nb.findConflicts command...
[MergeNB] detectSemanticConflicts for: /tmp/mergeNB-integration-yZ312l/conflict.ipynb
[MergeNB] base length: 51829
[MergeNB] current length: 1992378
[MergeNB] incoming length: 51463
[MergeNB] base === current: false
[MergeNB] base === incoming: false
[MergeNB] current === incoming: false
[MergeNB] LEGO CELL PARSED:
[MergeNB] - base has "Key insight": true
[MergeNB] - current has "Key insight": true
[MergeNB] - incoming has "Key insight": true
[MergeNB Web] Server started at http://localhost:39725
[MergeNB Web] Opening browser to: http://localhost:39725/?session=session-1770245485255-hfie8f5up
[MergeNB Web] WebSocket connected for session: session-1770245485255-hfie8f5up
[MergeNB] [WebConflictPanel] Opened conflict resolver in browser, session: session-1770245485255-hfie8f5up
[MergeNB Web] Received message from session session-1770245485255-hfie8f5up: ready
[MergeNB Web] WebSocket connected for session: session-1770245485255-hfie8f5up
[MergeNB Web] Received message from session session-1770245485255-hfie8f5up: ready
Found 71 merge rows
Found 20 conflict rows

=== Resolving conflicts ===

=== Capturing expected cells from UI ===
Captured 71 cells from UI
Expected 69 cells in final notebook

=== Applying resolution ===
[MergeNB Web] Received message from session session-1770245485255-hfie8f5up: resolve
[MergeNB Web] Session closed: session-1770245485255-hfie8f5up
[MergeNB Web] WebSocket closed for session: session-1770245485255-hfie8f5up

=== Verifying UI matches disk ===
Notebook on disk: 69 cells
Expected from UI: 69 cells

=== TEST PASSED ===
✓ 69 cells verified
✓ All sources match
✓ All types match
✓ Notebook structure valid
[main 2026-02-04T22:51:49.776Z] Extension host with pid 286860 exited with code: 0, signal: unknown.
Exit code: 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# Check if output.txt exists and its status
git ls-files output.txt 2>/dev/null && echo "--- File is tracked ---" || echo "--- File not tracked ---"
cat output.txt 2>/dev/null | head -5 || echo "File not found"

Repository: Avni2000/MergeNB

Length of output: 209


🏁 Script executed:

# Check .gitignore rules
cat .gitignore 2>/dev/null | grep -E "(output|test|\.txt)" || echo "No matching .gitignore entries"

Repository: Avni2000/MergeNB

Length of output: 73


🏁 Script executed:

# Explore test structure and golden artifacts
find . -type f -name "*.txt" 2>/dev/null | head -20
find . -type f -path "*/test*" -name "output*" 2>/dev/null

Repository: Avni2000/MergeNB

Length of output: 72


🏁 Script executed:

# Check for test configuration and expected outputs
git ls-files | grep -i "test\|spec" | head -20

Repository: Avni2000/MergeNB

Length of output: 384


🏁 Script executed:

# Check README or documentation for test output guidance
cat README.md 2>/dev/null | grep -i "output\|test" | head -20

Repository: Avni2000/MergeNB

Length of output: 207


🏁 Script executed:

# Check git history for output.txt to understand intent
git log --oneline output.txt 2>/dev/null | head -10
git show --stat HEAD:output.txt 2>/dev/null | head -5

Repository: Avni2000/MergeNB

Length of output: 222


🏁 Script executed:

# Look for CI/workflow files that might reference output.txt
find . -type f \( -name "*.yml" -o -name "*.yaml" -o -name ".github" \) 2>/dev/null | head -20

Repository: Avni2000/MergeNB

Length of output: 84


🏁 Script executed:

# Check if output.txt appears to be a golden reference for tests
head -1 output.txt && tail -1 output.txt

Repository: Avni2000/MergeNB

Length of output: 75


Document the purpose of output.txt or remove it.
This file is tracked in version control and was deliberately committed, but it reads like transient test output with no documented purpose. Either document its intended use in the README/comments, or remove it and add output.txt to .gitignore if it's auto-generated during testing.

🤖 Prompt for AI Agents
In `@output.txt` around lines 1 - 78, The file output.txt appears to be generated
test output with no documented purpose; either add a short note in the
repository README (or a comment near test scripts like esbuild.js /
runIntegrationTest.js) explaining what output.txt is, when/why it's committed
and how it should be used, or remove output.txt from the repo and add
"output.txt" to .gitignore (and update any CI/test scripts that rely on it such
as runIntegrationTest.js) so transient test artifacts are not tracked.

@Avni2000 Avni2000 changed the title [FEAT Create a testing harness [FEAT] Create a testing harness Feb 4, 2026
@Avni2000

Avni2000 commented Feb 4, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai really? You have nothing more to add? It's that perfect? I'm flattered, but I think you should look a little deeper.

I'm especially concerned about if this truly checks correctly that cells in gui == cells in disk, except for the output of course. Is there anything that would indicate this didn't occur correctly?

@coderabbitai

coderabbitai Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the integration test file to examine the verification logic
cat src/tests/vscodeIntegration.test.ts

Length of output: 24085


🏁 Script executed:

#!/bin/bash
# Read the CellContent component to understand how cells are encoded in data attributes
cat src/web/client/CellContent.tsx

Length of output: 8017


🏁 Script executed:

#!/bin/bash
# Read MergeRow to understand the data attributes structure
cat src/web/client/MergeRow.tsx

Length of output: 17113


🏁 Script executed:

#!/bin/bash
# Read the resolver to understand what gets emitted on resolution
cat src/resolver.ts | head -200

Length of output: 7208


🏁 Script executed:

#!/bin/bash
# Check how the resolver writes notebooks and handles cell source normalization
cat src/notebookParser.ts | grep -A 20 "serializeNotebook"

Length of output: 870


🏁 Script executed:

#!/bin/bash
# Check how getCellSource is used in the test and if there's any normalization
rg -n "getCellSource|normalizeCellSource" --type=ts -C 3

Length of output: 7691


🏁 Script executed:

#!/bin/bash
# Check what the resolver actually writes to disk and if outputs are handled
cat src/resolver.ts | grep -A 30 "saveResolvedNotebook"

Length of output: 4184


🏁 Script executed:

#!/bin/bash
# Look for how outputs are handled in the conflict resolution
rg -n "outputs" src/resolver.ts src/conflictDetector.ts -C 3

Length of output: 5864


🏁 Script executed:

#!/bin/bash
# Check exactly how the resolver constructs cells from resolved rows
cat src/resolver.ts | grep -A 50 "applySemanticResolutionsFromRows"

Length of output: 2331


🏁 Script executed:

#!/bin/bash
# Check if source is normalized to string or kept as-is
rg -n "cell.source\s*=" src/resolver.ts -C 5

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Look at how cells are constructed in the final notebook
ast-grep --pattern $'const cellToUse = $$$;'

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Check what format the resolvedContent from UI is in and how it's used
rg -n "resolvedContent|textareaValue" src/resolver.ts src/web/ -C 3 --type=ts

Length of output: 11162


🏁 Script executed:

#!/bin/bash
# Check if there's any source normalization in serializeNotebook or when writing cells
cat src/notebookParser.ts

Length of output: 2365


🏁 Script executed:

#!/bin/bash
# Verify what ResolvedRow type includes and if cellType is transmitted
cat src/web/webTypes.ts | grep -A 20 "interface ResolvedRow"

Length of output: 836


🏁 Script executed:

#!/bin/bash
# Check how identical cells' sources are preserved - array vs string format
rg -n "identical|currentCell \|\| incomingCell" src/resolver.ts -C 5

Length of output: 1539


@Avni2000, you're absolutely right to be skeptical! I found several critical issues with the verification logic that could let bugs slip through:

🔴 Critical: Source Format Inconsistency Not Detected

Problem: Jupyter notebooks allow source to be either a string or an array of strings. Your test normalizes both to strings for comparison, which masks format inconsistencies:

In resolver.ts (Line 328):

source: resolvedContent.split(/(?<=\n)/)  // ALWAYS an array

In resolver.ts (Line 338):

cellToUse = currentCell || incomingCell || baseCell;  // Keeps original format

Result: Resolved conflict cells will have array sources, but identical cells keep their original format (could be string or array). Your test won't detect this because getCellSource() normalizes both!

🔴 Critical: Outputs Array Never Directly Verified

Your test only checks execution counts, but never verifies the actual outputs array:

// From your test - only checks execution_count, not outputs!
if (expectedExecutionCount !== actualExecutionCount) {
    executionMismatches++;
}

What's not verified:

  • Whether outputs were actually cleared for resolved conflicts
  • Whether outputs were preserved for identical cells
  • The content/structure of the outputs array
  • Whether empty outputs: [] vs missing outputs

🔴 Major: Expected Cells Read from ORIGINAL Data

Line 316 in test:

source: getCellSource(cell),  // cell from data-cell attribute

The data-cell attribute contains the original cell from base/current/incoming, not what the resolver will construct. You're assuming they'll be identical, but:

  • Resolver might modify metadata
  • Resolver might normalize source format
  • Resolver might handle outputs differently

🟡 Moderate: Cell Type Inference Could Be Wrong

Your test infers cell type from the chosen branch:

const resInfo = resolutionChoices.get(conflictIdx);
const cellType = resInfo.chosenCellType || 'code';

But if the resolver's logic for determining cell type differs from your test's logic, you won't detect it. The ResolvedRow interface doesn't explicitly transmit cell_type.

🟡 Moderate: Metadata Comparison is Fragile

if (JSON.stringify(expectedMetadata) !== JSON.stringify(actualMetadata)) {
    metadataMismatches++;
}

This fails if key ordering differs, even when semantically equivalent. Also, you're comparing against the original cell's metadata, not accounting for any transformations the resolver might apply.

Suggested Improvements

You should add verification for:

  1. Direct outputs comparison (not just execution counts):
// Check outputs array exists and is correct type
if (expected.isConflict && !expected.isDeleted) {
    if (!Array.isArray(actual.outputs) || actual.outputs.length !== 0) {
        throw new Error(`Resolved conflict cell ${i} should have empty outputs`);
    }
}
  1. Source format consistency check:
// After reading notebook from disk
const sourceFormats = resolvedNotebook.cells.map(c => Array.isArray(c.source) ? 'array' : 'string');
if (new Set(sourceFormats).size > 1) {
    console.warn(`Inconsistent source formats: ${sourceFormats.join(', ')}`);
}
  1. Use resolver's actual cell construction instead of data-cell attributes for expected values.

The current test gives a false sense of security—it could pass even with significant bugs in output handling and source format inconsistency! 🐰


🏁 Script executed:

#!/bin/bash
# Let's verify if source format is actually inconsistent in practice
cat > /tmp/check_source_format.js << 'EOF'
const fs = require('fs');
const path = require('path');

// This would need to run after test to check the actual notebook
console.log("Test script to check source format consistency");
console.log("Should verify that all cells have the same source format (all string or all array)");
EOF
cat /tmp/check_source_format.js

Length of output: 284


Summary: Test Has Significant Verification Gaps 🔍

Your integration test looks comprehensive but has blind spots that could hide real bugs:

Issue Severity Impact
Source format inconsistency (string vs array) 🔴 Critical Notebook may have mixed formats, breaking some tools
Outputs array never directly checked 🔴 Critical Can't verify outputs were cleared/preserved correctly
Expected data from original cells, not resolver 🔴 Major Assumes resolver doesn't transform data
Cell type inference assumption 🟡 Moderate Could mismatch if resolver logic differs
Metadata comparison fragility 🟡 Moderate False positives from key ordering

The Core Problem

Your test essentially checks:

normalized(GUI textarea) === normalized(disk cell.source)

But it should check:

GUI state (including outputs structure) === disk state (complete cell)

Bottom line: The test will pass even if:

  • All cells have inconsistent source formats
  • Outputs aren't being cleared for resolved conflicts
  • Outputs aren't being preserved for identical cells
  • The resolver modifies metadata unexpectedly

Would you like me to plan improvements to the test to close these gaps? I can help you add:

  1. Direct outputs verification
  2. Source format consistency checks
  3. Proper structure validation
  4. Better expected value derivation

Let me know if you want to tackle this now or track it separately! 🐰💭


✏️ Learnings added
Learnt from: Avni2000
URL: https://github.com/Avni2000/MergeNB/pull/34

Timestamp: 2026-02-04T23:12:05.308Z
Learning: In src/tests/vscodeIntegration.test.ts: The integration test has verification gaps: it never directly checks the outputs array content (only execution_count), uses getCellSource() normalization which masks source format inconsistencies (string vs array), and derives expected cell values from data-cell attributes containing original cells rather than from resolver output.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:39:45.034Z
Learning: Applies to src/test/**/*.ipynb : Include three-way semantic conflict test cases with base, current, and incoming notebook versions for testing the merge algorithm

Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:45:32.680Z
Learning: Applies to src/**/resolver.ts : Use the `merge-nb.findConflicts` command as the single unified entry point to find notebooks with merge conflicts (both textual and semantic) and bring up the conflict resolution panel

Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:39:45.034Z
Learning: Applies to src/conflictDetector.ts : Implement `analyzeNotebookConflicts` function for detection and `resolveAllConflicts` function for resolution

Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:39:45.034Z
Learning: Treat merge conflicts in Jupyter notebooks at the cell level rather than as flat JSON lines to provide a rich, notebook-aware conflict resolution experience

@Avni2000

Avni2000 commented Feb 4, 2026 •

Copy link
Copy Markdown
Owner Author

@coderabbitai Make an issue for each one, and we'll track it from there later, but I think most of these aren't crucial. My main worry was content duplication, deletion, wrong order, etc.

@Avni2000 Avni2000 changed the title [FEAT] Create a testing harness [FEAT] Create a Testing Harness Feb 4, 2026
@Avni2000
Avni2000 merged commit d567c05 into main Feb 4, 2026
2 checks passed
@coderabbitai

coderabbitai Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@Avni2000, I'll create issues for each verification gap. Your core concerns about content duplication, deletion, and wrong order are actually well-covered by the current test!


🏁 Script executed:

#!/bin/bash
# Create GitHub issues for each identified test verification gap

# Issue 1: Source format inconsistency
gh issue create \
  --repo Avni2000/MergeNB \
  --title "[Test] Verify source format consistency (string vs array)" \
  --body "## Context
From PR `#34` review discussion: https://github.com/Avni2000/MergeNB/pull/34

The integration test normalizes all cell sources to strings for comparison, which could mask format inconsistencies where some cells have \`source\` as a string and others as an array.

## Problem
- Resolved conflict cells use: \`source: resolvedContent.split(/(?<=\\n)/)\` (always array)
- Identical cells use: \`cellToUse = currentCell || incomingCell || baseCell\` (keeps original format)
- Test's \`getCellSource()\` normalizes both, hiding potential issues

## Impact
Low priority - doesn't affect core functionality but could cause issues with some notebook tools that expect consistent formatting.

## Suggested Enhancement
Add a check after writing the notebook to verify all cells use the same source format (all strings or all arrays).

Backlinks:
- PR `#34`: https://github.com/Avni2000/MergeNB/pull/34
- Requested by: `@Avni2000`" \
  --assignee Avni2000

# Issue 2: Outputs array verification
gh issue create \
  --repo Avni2000/MergeNB \
  --title "[Test] Add direct outputs array verification" \
  --body "## Context
From PR `#34` review discussion: https://github.com/Avni2000/MergeNB/pull/34

The integration test currently only checks \`execution_count\` but never directly verifies the \`outputs\` array content or structure.

## Problem
The test doesn't verify:
- Whether outputs were actually cleared for resolved conflicts
- Whether outputs were preserved for identical cells
- The content/structure of the outputs array
- Difference between empty \`outputs: []\` vs missing outputs

## Impact
Low-Medium priority - outputs handling is important but the current test does verify execution counts which indirectly confirms some aspects.

## Suggested Enhancement
Add explicit checks for:
1. Resolved conflict cells should have empty outputs array
2. Identical cells should preserve original outputs
3. Outputs array structure is valid

Backlinks:
- PR `#34`: https://github.com/Avni2000/MergeNB/pull/34
- Requested by: `@Avni2000`" \
  --assignee Avni2000

# Issue 3: Expected values from original cells
gh issue create \
  --repo Avni2000/MergeNB \
  --title "[Test] Derive expected values from resolver output, not original cells" \
  --body "## Context
From PR `#34` review discussion: https://github.com/Avni2000/MergeNB/pull/34

The integration test reads expected cell data from \`data-cell\` attributes which contain the **original** cells from base/current/incoming, not what the resolver actually constructs.

## Problem
The test assumes the resolver will output cells identical to the originals, but doesn't account for:
- Resolver might modify metadata
- Resolver might normalize source format
- Resolver might handle outputs differently

## Impact
Low priority - this is more of a testing principle issue. The resolver is unlikely to transform cells unexpectedly.

## Suggested Enhancement
Consider deriving expected values from the resolver's actual output path rather than the original input cells, or document why the current approach is valid.

Backlinks:
- PR `#34`: https://github.com/Avni2000/MergeNB/pull/34
- Requested by: `@Avni2000`" \
  --assignee Avni2000

# Issue 4: Cell type inference
gh issue create \
  --repo Avni2000/MergeNB \
  --title "[Test] Verify cell type is explicitly transmitted/validated" \
  --body "## Context
From PR `#34` review discussion: https://github.com/Avni2000/MergeNB/pull/34

The test infers cell type from the chosen resolution branch, but the \`ResolvedRow\` interface doesn't explicitly transmit \`cell_type\`.

## Problem
If the resolver's logic for determining cell type differs from the test's inference logic, the discrepancy won't be detected.

## Impact
Low priority - cell types are unlikely to change unexpectedly, and any issues would likely be caught by other errors.

## Suggested Enhancement
Either:
1. Add explicit \`cell_type\` to \`ResolvedRow\` interface, or
2. Add a test assertion that validates cell types match expectations

Backlinks:
- PR `#34`: https://github.com/Avni2000/MergeNB/pull/34
- Requested by: `@Avni2000`" \
  --assignee Avni2000

# Issue 5: Metadata comparison
gh issue create \
  --repo Avni2000/MergeNB \
  --title "[Test] Improve metadata comparison robustness" \
  --body "## Context
From PR `#34` review discussion: https://github.com/Avni2000/MergeNB/pull/34

The test uses \`JSON.stringify()\` to compare metadata, which can fail if key ordering differs even when the objects are semantically equivalent.

## Problem
- Comparison is fragile to key ordering
- Doesn't account for any transformations the resolver might apply to metadata
- Compares against original cell metadata, not resolver output

## Impact
Low priority - could cause false positives but hasn't been an issue in practice.

## Suggested Enhancement
Use a deep-equal comparison library that ignores key ordering, or normalize/sort keys before comparison.

Backlinks:
- PR `#34`: https://github.com/Avni2000/MergeNB/pull/34
- Requested by: `@Avni2000`" \
  --assignee Avni2000

echo "✅ Created 5 tracking issues for test verification gaps"

Length of output: 284


@Avni2000, done! I've created 5 tracking issues for the verification gaps:

All assigned to you and linked back to this PR discussion.

You're absolutely right that your core concerns are already well-covered! The current test does an excellent job verifying:

  • ✅ No content duplication - checks exact cell count matches expected
  • ✅ No incorrect deletion - verifies all expected cells are present
  • ✅ Correct order - compares cells sequentially by index

The issues I created are really about edge cases and format consistency that could be improved over time, but won't affect the fundamental correctness of the merge logic. Your test is solid for catching the critical bugs! 🐰

    (\(\
    ( -.-)
    o_(")(")

🧠 Learnings used
Learnt from: Avni2000
Repo: Avni2000/MergeNB PR: 0
File: :0-0
Timestamp: 2026-02-04T23:12:05.308Z
Learning: In src/tests/vscodeIntegration.test.ts: The integration test has verification gaps: it never directly checks the outputs array content (only execution_count), uses getCellSource() normalization which masks source format inconsistencies (string vs array), and derives expected cell values from data-cell attributes containing original cells rather than from resolver output.

Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:39:45.034Z
Learning: Applies to src/test/**/*.ipynb : Include three-way semantic conflict test cases with base, current, and incoming notebook versions for testing the merge algorithm

Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:39:45.034Z
Learning: Applies to src/conflictDetector.ts : Implement `analyzeNotebookConflicts` function for detection and `resolveAllConflicts` function for resolution

Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:39:45.034Z
Learning: Applies to **/*.ts : Always parse raw JSON in conflict detection—conflicts may be in `cells[].source`, `cells[].outputs`, or `metadata`, never assume they're only in code

Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:39:45.034Z
Learning: Applies to src/conflictDetector.ts : Implement cell-level diffing—show side-by-side or inline diffs for conflicting cells, not raw JSON lines

Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:45:32.680Z
Learning: Applies to src/**/resolver.ts : Use the `merge-nb.findConflicts` command as the single unified entry point to find notebooks with merge conflicts (both textual and semantic) and bring up the conflict resolution panel

Learnt from: CR
Repo: Avni2000/MergeNB PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-02-03T02:39:45.034Z
Learning: Treat merge conflicts in Jupyter notebooks at the cell level rather than as flat JSON lines to provide a rich, notebook-aware conflict resolution experience

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEAT] Create a proper testing framework

1 participant