Skip to content

test: add unit tests for shell-substitution.js parser - #2495

Merged
affaan-m merged 2 commits into
affaan-m:mainfrom
nankingjing:test-shell-parser
Jul 26, 2026
Merged

affaan-m merged 2 commits into
affaan-m:mainfrom
nankingjing:test-shell-parser

Conversation

@nankingjing

Copy link
Copy Markdown
Contributor

What

Adds unit tests for scripts/lib/shell-substitution.js, which had no test coverage. This shared parser powers the destructive-bash and dev-server PreToolUse hooks (scripts/hooks/gateguard-fact-force.js, scripts/hooks/pre-bash-dev-server-block.js), so its correctness is security-relevant: it's how those hooks peer inside $(...)/backticks, (...) subshells, and { ...; } brace groups to catch commands that would otherwise slip past segment-splitting.

Coverage

tests/lib/shell-substitution.test.js exercises all three exported functions (39 assertions):

  • extractCommandSubstitutions — $() and backtick bodies, multiple/ordered bodies, recursive nesting ($() inside $() and inside backticks), single-quote literalness vs. double-quote permissiveness, empty-body/null/undefined guards.
  • extractSubshellGroups — plain (...) bodies, nesting, skipping $()/backtick spans, single- and double-quoted parens treated as literal.
  • extractBraceGroups — { ...; } bodies, nesting, the reserved-word boundary rules (space required after {; { must follow a boundary; } closes only after a boundary), and skipping quoted/substituted spans.

Each function also has a security-relevant case asserting a rm -rf-style command is surfaced when hidden inside that construct.

How verified

  • Ran the new file directly (node tests/lib/shell-substitution.test.js) against the current shell-substitution.js: 39 passed, 0 failed.
  • Ran it through the repo harness (node tests/run-all.js) to confirm discovery via the tests/**/*.test.js glob and that the Results: Passed: N, Failed: N line is parsed into the aggregate.

Test style, test() helper, and results line match the existing suite (mirrors tests/lib/shell-split.test.js and tests/lib/transcript-context.test.js). No source behavior is changed — tests only.

@nankingjing
nankingjing requested a review from affaan-m as a code owner July 10, 2026 15:21
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: fb6c76e7-94f9-4f9f-b6d7-dbacdeaf73a7

📥 Commits

Reviewing files that changed from the base of the PR and between ff791c9 and c0fc91e.

📒 Files selected for processing (1)
  • tests/lib/shell-substitution.test.js
📜 Recent review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: Greptile Review
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}

📄 CodeRabbit inference engine (.cursor/rules/common-coding-style.md)

**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}: Always create new objects, never mutate existing ones. Use immutable patterns to prevent hidden side effects and enable safe concurrency
Organize code into many small files (200-400 lines typical, 800 lines max) organized by feature/domain rather than by type
Always handle errors explicitly at every level and never silently swallow errors
Always validate all user input before processing at system boundaries
Use schema-based validation where available
Fail fast with clear error messages when validation fails
Never trust external data (API responses, user input, file content)
Ensure code is readable and well-named
Keep functions small (less than 50 lines)
Keep files focused (less than 800 lines)
Avoid deep nesting (more than 4 levels)
Do not use hardcoded values; use constants or configuration instead

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

No hardcoded secrets (API keys, passwords, tokens) - validate before any commit

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}: All user inputs must be validated
Enable CSRF protection on all state-changing endpoints
Verify authentication and authorization for all protected endpoints
Implement rate limiting on all endpoints to prevent abuse
Ensure error messages do not leak sensitive data in responses

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,sql}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Use parameterized queries to prevent SQL injection

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,html,php,java,cs,rb,go}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Implement XSS prevention by sanitizing HTML output

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp,properties,yml,yaml,json,env,config}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

NEVER hardcode secrets in source code - ALWAYS use environment variables or a secret manager

Files:

  • tests/lib/shell-substitution.test.js
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-coding-style.md)

**/*.{ts,tsx,js,jsx}: Use spread operator for immutable updates in TypeScript/JavaScript instead of direct mutation
Use async/await with try-catch for error handling in TypeScript/JavaScript
Use Zod for schema-based input validation in TypeScript/JavaScript
No console.log statements in production code; use proper logging libraries instead

**/*.{ts,tsx,js,jsx}: Auto-format JavaScript/TypeScript files using Prettier after edit
Warn about console.log statements in edited files
Check all modified files for console.log statements before session ends

**/*.{ts,tsx,js,jsx}: Use the ApiResponse interface pattern with generic type parameter: interface ApiResponse<T> { success: boolean; data?: T; error?: string; meta?: { total: number; page: number; limit: number; } }
Implement custom React hooks following the pattern: export a named function with use prefix, generic type parameters, and proper useEffect cleanup for side effects

**/*.{ts,tsx,js,jsx}: Never hardcode secrets; always use environment variables for sensitive credentials like API keys
Throw an error when required environment variables are not configured to fail fast and ensure security prerequisites are met

Use Playwright as the E2E testing framework for critical user flows in TypeScript/JavaScript

Files:

  • tests/lib/shell-substitution.test.js
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{test,spec}.{js,ts,jsx,tsx}: Write tests before implementation (test-driven development); target 80%+ coverage
Achieve minimum 80% test coverage across all three layers: Unit, Integration, and E2E
Use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts,jsx,tsx}: Always create new objects and never mutate in place; return new copies instead
Keep files between 200–400 lines typical, with a maximum of 800 lines
Extract helpers when a file exceeds 200 lines
Handle errors explicitly at every level; never swallow errors silently
Validate all user input before processing; use schema-based validation where available
Never trust external data (API responses, file content, query params); always validate
All user inputs must be validated and sanitized
Error messages must be scrubbed of sensitive internals
Use readable, well-named identifiers in all code
Keep functions under 50 lines
Keep files under 800 lines
Avoid nesting deeper than 4 levels
Implement comprehensive error handling in all code
Do not hardcode values; use constants or environment configuration instead
Do not use in-place mutation; always return new objects or state

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,json,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Do not hardcode secrets, API keys, passwords, or tokens

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts}: Use parameterized queries for all database writes (no string interpolation)
Auth/authz must be checked server-side for every sensitive path
Rate limiting must be applied to all public endpoints

Files:

  • tests/lib/shell-substitution.test.js
**/*.{jsx,tsx,js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

HTML output must be sanitized where applicable

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Required environment variables must be validated at startup

Files:

  • tests/lib/shell-substitution.test.js

📝 Walkthrough

Summary by CodeRabbit

  • Tests
    • Added a new test suite covering shell substitution handling, subshell grouping, and brace-group extraction.
    • Verifies quoting rules (single vs. double quotes), correct behavior for empty/null inputs, and safe handling of escaped $()/backticks.
    • Includes nested/recursive extraction scenarios and confirms result ordering for outer vs. inner constructs.
    • Adds security-oriented assertions to ensure command-like substrings are preserved in the extracted content.
    • Uses a lightweight pass/fail runner with a summary and non-zero exit on failures.

Walkthrough

Adds a standalone test suite for the three shell extraction helpers, covering quoting, escaping, nesting, boundaries, risky command bodies, pass/fail reporting, and process exit status.

Changes

Shell substitution tests

Layer / File(s) Summary
Command substitution coverage
tests/lib/shell-substitution.test.js
Adds the test harness and assertions for $() and backtick extraction, quoting, escaping, ordering, empty inputs, nesting, and risky command bodies.
Subshell and brace-group coverage
tests/lib/shell-substitution.test.js
Tests subshell and brace-group extraction, nesting, boundaries, quoting, embedded substitutions, risky command bodies, and final exit reporting.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: affaan-m

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Title check ✅ Passed The title clearly summarizes the main change: adding unit tests for the shell-substitution parser.
Description check ✅ Passed The description is directly about the added shell-substitution tests and their coverage.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


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.

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/lib/shell-substitution.test.js`:
- Around line 10-24: Replace the direct console.log calls throughout the test
runner with the project’s approved test-output or logging mechanism, preserving
all success, failure, and summary messages. Update test() to report the caught
error with its stack trace when available, while retaining a useful fallback for
errors without one.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 88711af2-aefd-4a8f-8345-5c3479ca3dfb

📥 Commits

Reviewing files that changed from the base of the PR and between 4092795 and 364c068.

📒 Files selected for processing (1)
  • tests/lib/shell-substitution.test.js
📜 Review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: CodeRabbit / Review
  • GitHub Check: Greptile Review
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}

📄 CodeRabbit inference engine (.cursor/rules/common-coding-style.md)

**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}: Always create new objects, never mutate existing ones. Use immutable patterns to prevent hidden side effects and enable safe concurrency
Organize code into many small files (200-400 lines typical, 800 lines max) organized by feature/domain rather than by type
Always handle errors explicitly at every level and never silently swallow errors
Always validate all user input before processing at system boundaries
Use schema-based validation where available
Fail fast with clear error messages when validation fails
Never trust external data (API responses, user input, file content)
Ensure code is readable and well-named
Keep functions small (less than 50 lines)
Keep files focused (less than 800 lines)
Avoid deep nesting (more than 4 levels)
Do not use hardcoded values; use constants or configuration instead

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

No hardcoded secrets (API keys, passwords, tokens) - validate before any commit

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}: All user inputs must be validated
Enable CSRF protection on all state-changing endpoints
Verify authentication and authorization for all protected endpoints
Implement rate limiting on all endpoints to prevent abuse
Ensure error messages do not leak sensitive data in responses

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,sql}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Use parameterized queries to prevent SQL injection

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,html,php,java,cs,rb,go}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Implement XSS prevention by sanitizing HTML output

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp,properties,yml,yaml,json,env,config}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

NEVER hardcode secrets in source code - ALWAYS use environment variables or a secret manager

Files:

  • tests/lib/shell-substitution.test.js
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-coding-style.md)

**/*.{ts,tsx,js,jsx}: Use spread operator for immutable updates in TypeScript/JavaScript instead of direct mutation
Use async/await with try-catch for error handling in TypeScript/JavaScript
Use Zod for schema-based input validation in TypeScript/JavaScript
No console.log statements in production code; use proper logging libraries instead

**/*.{ts,tsx,js,jsx}: Auto-format JavaScript/TypeScript files using Prettier after edit
Warn about console.log statements in edited files
Check all modified files for console.log statements before session ends

**/*.{ts,tsx,js,jsx}: Use the ApiResponse interface pattern with generic type parameter: interface ApiResponse<T> { success: boolean; data?: T; error?: string; meta?: { total: number; page: number; limit: number; } }
Implement custom React hooks following the pattern: export a named function with use prefix, generic type parameters, and proper useEffect cleanup for side effects

**/*.{ts,tsx,js,jsx}: Never hardcode secrets; always use environment variables for sensitive credentials like API keys
Throw an error when required environment variables are not configured to fail fast and ensure security prerequisites are met

Use Playwright as the E2E testing framework for critical user flows in TypeScript/JavaScript

Files:

  • tests/lib/shell-substitution.test.js
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{test,spec}.{js,ts,jsx,tsx}: Write tests before implementation (test-driven development); target 80%+ coverage
Achieve minimum 80% test coverage across all three layers: Unit, Integration, and E2E
Use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts,jsx,tsx}: Always create new objects and never mutate in place; return new copies instead
Keep files between 200–400 lines typical, with a maximum of 800 lines
Extract helpers when a file exceeds 200 lines
Handle errors explicitly at every level; never swallow errors silently
Validate all user input before processing; use schema-based validation where available
Never trust external data (API responses, file content, query params); always validate
All user inputs must be validated and sanitized
Error messages must be scrubbed of sensitive internals
Use readable, well-named identifiers in all code
Keep functions under 50 lines
Keep files under 800 lines
Avoid nesting deeper than 4 levels
Implement comprehensive error handling in all code
Do not hardcode values; use constants or environment configuration instead
Do not use in-place mutation; always return new objects or state

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,json,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Do not hardcode secrets, API keys, passwords, or tokens

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts}: Use parameterized queries for all database writes (no string interpolation)
Auth/authz must be checked server-side for every sensitive path
Rate limiting must be applied to all public endpoints

Files:

  • tests/lib/shell-substitution.test.js
**/*.{jsx,tsx,js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

HTML output must be sanitized where applicable

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Required environment variables must be validated at startup

Files:

  • tests/lib/shell-substitution.test.js
🔇 Additional comments (4)
tests/lib/shell-substitution.test.js (4)

26-87: LGTM!


89-130: LGTM!


132-158: LGTM!

Also applies to: 163-181


159-161: 🎯 Functional Correctness

} handling is correct in this case.

Comment thread tests/lib/shell-substitution.test.js Resolved
@greptile-apps

greptile-apps Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds tests/lib/shell-substitution.test.js, providing the first unit-test coverage for the three parser functions in scripts/lib/shell-substitution.js — extractCommandSubstitutions, extractSubshellGroups, and extractBraceGroups — which back the destructive-bash and dev-server PreToolUse security hooks.

  • extractCommandSubstitutions (19 tests): covers $() and backtick extraction, quoting semantics, escape handling (\$(...) / \`), and recursive nesting.
  • extractSubshellGroups (13 tests): covers plain (...) bodies, $() / backtick skip logic, and both single- and double-quote literalness.
  • extractBraceGroups (14 tests): covers { ...; } reserved-word boundary rules, skipping of $() / backtick / subshell spans inside the body, and null/undefined guards.

Confidence Score: 5/5

Tests-only change; no source code is modified and every assertion has been verified to match the current implementation behaviour.

The new file adds unit tests for an existing parser without touching any production code. All 46 test assertions are accurate against the source, the results-line format correctly integrates with run-all.js, and the escaped-substitution and null/undefined guards requested in the prior review round are now present.

No files require special attention.

Important Files Changed

Filename Overview
tests/lib/shell-substitution.test.js New test file with 46 test cases (19 + 13 + 14) covering all three exported functions; assertions are accurate against the source implementation, the results-line format correctly matches run-all.js's /Passed:\s*(\d+)/ regex, and escape/quoting/nesting edge cases are verified.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[shell-substitution.test.js] --> B[extractCommandSubstitutions — 19 tests]
    A --> C[extractSubshellGroups — 13 tests]
    A --> D[extractBraceGroups — 14 tests]

    B --> B1[basics: dollar-paren & backtick extraction]
    B --> B2[guards: null / undefined / empty body]
    B --> B3[quoting: single-literal / double-permissive]
    B --> B4[escaping: backslash-dollar / backslash-backtick]
    B --> B5[nesting: recursive body discovery]
    B --> B6[security: rm-rf & curl-pipe-sh surfaced]

    C --> C1[basics: plain parens + nesting]
    C --> C2[guards: null / undefined]
    C --> C3[skips: dollar-paren & backtick spans bypassed]
    C --> C4[quotes: both kinds treated as literal]
    C --> C5[security: rm-rf inside subshell surfaced]

    D --> D1[basics: brace-group body + nesting]
    D --> D2[guards: null / undefined]
    D --> D3[reserved-word: space-after / boundary-before-open / boundary-before-close]
    D --> D4[skips: dollar-paren spans not treated as close]
    D --> D5[security: rm-rf inside brace group surfaced]
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A[shell-substitution.test.js] --> B[extractCommandSubstitutions — 19 tests]
    A --> C[extractSubshellGroups — 13 tests]
    A --> D[extractBraceGroups — 14 tests]

    B --> B1[basics: dollar-paren & backtick extraction]
    B --> B2[guards: null / undefined / empty body]
    B --> B3[quoting: single-literal / double-permissive]
    B --> B4[escaping: backslash-dollar / backslash-backtick]
    B --> B5[nesting: recursive body discovery]
    B --> B6[security: rm-rf & curl-pipe-sh surfaced]

    C --> C1[basics: plain parens + nesting]
    C --> C2[guards: null / undefined]
    C --> C3[skips: dollar-paren & backtick spans bypassed]
    C --> C4[quotes: both kinds treated as literal]
    C --> C5[security: rm-rf inside subshell surfaced]

    D --> D1[basics: brace-group body + nesting]
    D --> D2[guards: null / undefined]
    D --> D3[reserved-word: space-after / boundary-before-open / boundary-before-close]
    D --> D4[skips: dollar-paren spans not treated as close]
    D --> D5[security: rm-rf inside brace group surfaced]
Loading

Reviews (4): Last reviewed commit: "test(shell-substitution): cover guards a..." | Re-trigger Greptile

Comment thread tests/lib/shell-substitution.test.js Resolved
Comment thread tests/lib/shell-substitution.test.js Resolved

@daltino daltino left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This PR adds a comprehensive set of unit tests for shell-substitution.js. The test file follows a clear structure, leveraging assert for validations, and includes helpful output for debugging. While the contribution adds 181 lines without any deletions, it aligns with the repo's guidelines on testing strategies and improves coverage. Great enhancement!

@nankingjing

Copy link
Copy Markdown
Contributor Author

Added null-guard tests for subshell/brace extractors, and escaped-substitution tests so the security-sensitive path is covered. Branch: nankingjing/ECC:fix/shell-substitution-greptile-gaps

@nankingjing

Copy link
Copy Markdown
Contributor Author

Added null-guard tests for subshell/brace extractors, and escaped-substitution tests so the security-sensitive path is covered.

Branch: nankingjing/ECC:fix/shell-substitution-greptile-gaps

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/lib/shell-substitution.test.js`:
- Around line 12-24: Refactor the custom test runner around test so passed and
failed are no longer mutated shared variables. Have each test execution return
its success or failure result, then aggregate those results functionally with
Array.prototype.reduce while preserving the existing output and error reporting
behavior.
- Around line 31-33: Refactor the test around extractCommandSubstitutions into
explicit Arrange, Act, and Assert steps: assign the input command to a
descriptive variable, store the function result separately, then assert the
expected substitution. Preserve the existing test behavior and use a descriptive
test name that clearly states it extracts a command-substitution body.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 269d78ac-192a-410a-ab6b-226420c68b73

📥 Commits

Reviewing files that changed from the base of the PR and between cd6e4c4 and ff791c9.

📒 Files selected for processing (1)
  • tests/lib/shell-substitution.test.js
📜 Review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: Greptile Review
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}

📄 CodeRabbit inference engine (.cursor/rules/common-coding-style.md)

**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}: Always create new objects, never mutate existing ones. Use immutable patterns to prevent hidden side effects and enable safe concurrency
Organize code into many small files (200-400 lines typical, 800 lines max) organized by feature/domain rather than by type
Always handle errors explicitly at every level and never silently swallow errors
Always validate all user input before processing at system boundaries
Use schema-based validation where available
Fail fast with clear error messages when validation fails
Never trust external data (API responses, user input, file content)
Ensure code is readable and well-named
Keep functions small (less than 50 lines)
Keep files focused (less than 800 lines)
Avoid deep nesting (more than 4 levels)
Do not use hardcoded values; use constants or configuration instead

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

No hardcoded secrets (API keys, passwords, tokens) - validate before any commit

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}: All user inputs must be validated
Enable CSRF protection on all state-changing endpoints
Verify authentication and authorization for all protected endpoints
Implement rate limiting on all endpoints to prevent abuse
Ensure error messages do not leak sensitive data in responses

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,sql}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Use parameterized queries to prevent SQL injection

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,html,php,java,cs,rb,go}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Implement XSS prevention by sanitizing HTML output

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp,properties,yml,yaml,json,env,config}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

NEVER hardcode secrets in source code - ALWAYS use environment variables or a secret manager

Files:

  • tests/lib/shell-substitution.test.js
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-coding-style.md)

**/*.{ts,tsx,js,jsx}: Use spread operator for immutable updates in TypeScript/JavaScript instead of direct mutation
Use async/await with try-catch for error handling in TypeScript/JavaScript
Use Zod for schema-based input validation in TypeScript/JavaScript
No console.log statements in production code; use proper logging libraries instead

**/*.{ts,tsx,js,jsx}: Auto-format JavaScript/TypeScript files using Prettier after edit
Warn about console.log statements in edited files
Check all modified files for console.log statements before session ends

**/*.{ts,tsx,js,jsx}: Use the ApiResponse interface pattern with generic type parameter: interface ApiResponse<T> { success: boolean; data?: T; error?: string; meta?: { total: number; page: number; limit: number; } }
Implement custom React hooks following the pattern: export a named function with use prefix, generic type parameters, and proper useEffect cleanup for side effects

**/*.{ts,tsx,js,jsx}: Never hardcode secrets; always use environment variables for sensitive credentials like API keys
Throw an error when required environment variables are not configured to fail fast and ensure security prerequisites are met

Use Playwright as the E2E testing framework for critical user flows in TypeScript/JavaScript

Files:

  • tests/lib/shell-substitution.test.js
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{test,spec}.{js,ts,jsx,tsx}: Write tests before implementation (test-driven development); target 80%+ coverage
Achieve minimum 80% test coverage across all three layers: Unit, Integration, and E2E
Use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts,jsx,tsx}: Always create new objects and never mutate in place; return new copies instead
Keep files between 200–400 lines typical, with a maximum of 800 lines
Extract helpers when a file exceeds 200 lines
Handle errors explicitly at every level; never swallow errors silently
Validate all user input before processing; use schema-based validation where available
Never trust external data (API responses, file content, query params); always validate
All user inputs must be validated and sanitized
Error messages must be scrubbed of sensitive internals
Use readable, well-named identifiers in all code
Keep functions under 50 lines
Keep files under 800 lines
Avoid nesting deeper than 4 levels
Implement comprehensive error handling in all code
Do not hardcode values; use constants or environment configuration instead
Do not use in-place mutation; always return new objects or state

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,json,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Do not hardcode secrets, API keys, passwords, or tokens

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts}: Use parameterized queries for all database writes (no string interpolation)
Auth/authz must be checked server-side for every sensitive path
Rate limiting must be applied to all public endpoints

Files:

  • tests/lib/shell-substitution.test.js
**/*.{jsx,tsx,js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

HTML output must be sanitized where applicable

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Required environment variables must be validated at startup

Files:

  • tests/lib/shell-substitution.test.js
🔇 Additional comments (1)
tests/lib/shell-substitution.test.js (1)

10-24: console.log usage flagged per coding guidelines.

As per coding guidelines: "Warn about console.log statements in edited files" and "Check all modified files for console.log statements before session ends." This test runner uses console.log for output reporting. Please replace direct console.log calls with the project’s approved test-output or logging mechanism.

Source: Coding guidelines

Comment thread tests/lib/shell-substitution.test.js Resolved
Comment thread tests/lib/shell-substitution.test.js Resolved

@affaan-m affaan-m left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Verified against current main: 46 focused tests pass, the test is discovered by the existing run-all harness, merge-tree is clean, and coverage includes the escaped substitution/security cases missing from the duplicate PR. The remaining console.log thread was withdrawn because this matches the repository standalone test convention.

@affaan-m
affaan-m merged commit 19df41d into affaan-m:main Jul 26, 2026
2 checks passed
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.

3 participants