Repository navigation
[FEAT] Create a Testing Harness - #34
Conversation
…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
📝 WalkthroughWalkthroughAdds 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
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 | 🟠 MajorAvoid 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 fortest: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
onDidResolveConflictWithDetailsEventEmitter 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'sdeactivate()function if the emitter accumulates listeners over time.src/extension.ts (1)
25-31: Type safety could be improved.Using
unknownforresolvedNotebookandresolvedRowsloses type safety. Consider importing and using the actual types from./resolverand./web/webTypesif 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-portcould 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 hardcodedmergenb-test-config.jsonpath 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.tsat 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) andgetHealthInfo(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
setTimeoutcalls (lines 96, 147, 155, etc.) make the test slower and more fragile. Playwright'swaitForwith 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-titleis redundant sincewaitForSelectoralready 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) andvscodeIntegration.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.
|
|
||
| > [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 | ||
| [90m[main 2026-02-04T22:51:19.119Z][0m update#setState disabled | ||
| [90m[main 2026-02-04T22:51:19.121Z][0m 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 | ||
| [90m[main 2026-02-04T22:51:49.776Z][0m Extension host with pid 286860 exited with code: 0, signal: unknown. | ||
| Exit code: 0 |
There was a problem hiding this comment.
🧩 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/nullRepository: Avni2000/MergeNB
Length of output: 72
🏁 Script executed:
# Check for test configuration and expected outputs
git ls-files | grep -i "test\|spec" | head -20Repository: 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 -20Repository: 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 -5Repository: 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 -20Repository: 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.txtRepository: 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.
|
@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? |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 24085 🏁 Script executed: Length of output: 8017 🏁 Script executed: Length of output: 17113 🏁 Script executed: Length of output: 7208 🏁 Script executed: Length of output: 870 🏁 Script executed: Length of output: 7691 🏁 Script executed: Length of output: 4184 🏁 Script executed: Length of output: 5864 🏁 Script executed: Length of output: 2331 🏁 Script executed: Length of output: 0 🏁 Script executed: Length of output: 0 🏁 Script executed: Length of output: 11162 🏁 Script executed: Length of output: 2365 🏁 Script executed: Length of output: 836 🏁 Script executed: Length of output: 1539
🔴 Critical: Source Format Inconsistency Not DetectedProblem: Jupyter notebooks allow In resolver.ts (Line 328): source: resolvedContent.split(/(?<=\n)/) // ALWAYS an arrayIn resolver.ts (Line 338): cellToUse = currentCell || incomingCell || baseCell; // Keeps original formatResult: 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 🔴 Critical: Outputs Array Never Directly VerifiedYour 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:
🔴 Major: Expected Cells Read from ORIGINAL DataLine 316 in test: source: getCellSource(cell), // cell from data-cell attributeThe
🟡 Moderate: Cell Type Inference Could Be WrongYour 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 🟡 Moderate: Metadata Comparison is Fragileif (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 ImprovementsYou should add verification for:
// 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`);
}
}
// 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(', ')}`);
}
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: Length of output: 284 Summary: Test Has Significant Verification Gaps 🔍Your integration test looks comprehensive but has blind spots that could hide real bugs:
The Core ProblemYour test essentially checks: But it should check: Bottom line: The test will pass even if:
Would you like me to plan improvements to the test to close these gaps? I can help you add:
Let me know if you want to tackle this now or track it separately! 🐰💭 ✏️ Learnings added
🧠 Learnings used |
|
@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. |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain
🏁 Script executed: Length of output: 284
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:
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! 🐰 🧠 Learnings used |
Flow:
Note that this approach ignores output, but checks execution count to disk.
Closes #22
Summary by CodeRabbit
New Features
Chores