-
Notifications
You must be signed in to change notification settings - Fork 5
test: add comprehensive unit test suite with vitest #51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Add 301 unit tests covering pure utility functions with focus on security-critical sanitization and complex frequency transformation logic. Test coverage includes: - sanitize.ts: XSS prevention, HTML stripping, whitespace normalization - frequencyTransform.ts: All daily/weekly/biweekly/monthly/quarterly patterns - parameterUtils.ts: Date normalization, autoScheduled parsing, validation - constants.ts: Relative date parsing, priority validation, payload cleaning - cache.ts: LRU eviction, TTL expiry, pattern-based invalidation - ToolRegistry/ToolConfigurator: Preset counts, custom config parsing Setup: - vitest.config.ts with coverage targets for src/utils and src/tools - tests/setup.ts mocking logger to silence console output during tests Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
This PR introduces a Vitest configuration and a new, comprehensive unit test suite targeting core utility modules and tool configuration behavior, with a focus on deterministic, security‑sensitive, and branching logic.
Changes:
- Add
vitest.config.tswith custom test discovery, setup file, coverage include/exclude, and a 10s test timeout. - Add new unit tests for tool configuration/registry, sanitization, parameter utilities, frequency transformation, constants, and cache behavior under
tests/unit/*.test.ts. - Add a shared Vitest setup file that mocks the logger to suppress console output during tests.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
vitest.config.ts |
Configures Vitest test discovery, setup, coverage targeting src/utils and src/tools, and a global timeout; note that the include glob currently excludes existing *.spec.ts tests. |
tests/unit/toolConfiguration.test.ts |
Adds unit tests covering ToolRegistry (tool registration, presets, custom configs) and ToolConfigurator (preset validation, custom config parsing/validation, behavior of static helpers). |
tests/unit/sanitize.test.ts |
Adds detailed tests for text sanitization (XSS stripping, HTML removal, whitespace/unicode normalization, length limits) and higher‑level APIs sanitizeCommentContent, sanitizeDescription, and sanitizeName. |
tests/unit/parameterUtils.test.ts |
Tests normalizeDueDateForApi, parseTaskArgs, validateRequiredParams, sanitizeStringParams, workspace/search/project parsing, defaults handling, type validation, and workspace validation. |
tests/unit/frequencyTransform.test.ts |
Adds extensive coverage for transformFrequencyToApiString, validateFrequencyObject, and isValidFrequencyObject across daily/weekly/biweekly/monthly/quarterly/yearly/custom patterns and error cases. |
tests/unit/constants.test.ts |
Tests parseFilterDate handling of relative and absolute dates, priority validation helpers, minimal payload creation, and null/undefined conversion utilities. |
tests/unit/cache.test.ts |
Provides thorough tests for SimpleCache covering TTL expiration, LRU eviction/promotion, pattern‑based invalidation, withCache behavior, stats, cleanup, destroy, and auto‑cleanup. |
tests/setup.ts |
Global Vitest setup that mocks the logger module to silence logging during tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
vitest.config.ts
Outdated
|
|
||
| export default defineConfig({ | ||
| test: { | ||
| include: ['tests/**/*.test.ts'], |
Copilot
AI
Jan 25, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The include pattern here is restricted to tests/**/*.test.ts, which means all existing *.spec.ts test files under tests/ (e.g., tests/cache.spec.ts, tests/handlers.*.spec.ts) will no longer be discovered or executed by Vitest. To avoid silently dropping the current test suite, broaden the pattern to also match *.spec.ts (for example by using a glob that includes both .test.ts and .spec.ts, or by adding a second include entry).
| include: ['tests/**/*.test.ts'], | |
| include: ['tests/**/*.{test,spec}.ts'], |
PR Review: Comprehensive Unit Test Suite with VitestOverall AssessmentVerdict: ✅ Excellent Addition with Minor Suggestions This PR adds a well-structured and comprehensive test suite covering 301 tests across 6 critical utility modules. The focus on testing pure functions (particularly security-critical sanitization) demonstrates strong engineering discipline. The tests are well-organized, thorough, and follow best practices. Strengths 💪1. Excellent Test Organization
2. Security-First Approach 🔒
3. Smart Testing Strategy
4. Comprehensive Edge Case Coverage
5. Proper Test Configuration
Issues & Suggestions 🔍Critical IssuesNone identified - No blocking issues found. High Priority Suggestions1. Test Setup: Path Traversal Issue (tests/setup.ts:7)The relative path ../src/ assumes the setup file location. Consider using path aliases configured in vitest.config.ts for robustness. 2. Cache Test: Fragile Timing (cache.test.ts:285-300)The auto-cleanup test relies on internal timing (TTL/2 = 30s). If cleanup logic changes, the test breaks. Consider advancing timers by a full TTL cycle (60s) instead of assuming 30s intervals. 3. Missing Edge Case TestsA. Script Tag Regex Edge Case it('handles script tags with string literals containing closing tags', () => {
expect(sanitizeTextContent('<script>var x = "</script>"; alert(1);</script>')).toBe('');
});B. autoScheduled Parameter Edge Cases Medium Priority4. Error Message ValidationTests verify errors are thrown but don't validate messages. Consider using .toThrow(/pattern/) to ensure user-facing errors are clear and include documentation links. 5. Redundant Logger MockingtoolConfiguration.test.ts mocks logger twice (in file and via setup.ts). Remove redundant mock. Code Quality Assessment 📊Adherence to CLAUDE.md Guidelines✅ Excellent - Tests align with project conventions and focus on utility layer TypeScript Usage✅ Strong - Proper typing with appropriate use of generics and type assertions Best Practices✅ Followed - Single responsibility, descriptive names, proper setup/teardown, test isolation Security Review 🔒XSS Prevention Tests✅ Comprehensive - Covers script tags, HTML stripping, event handlers, nested tags Minor Gaps (potentially out of scope)The sanitization doesn't test for:
Note: These may be handled by Motion API. Test Coverage 📈What's Covered✅ sanitize, cache, frequencyTransform, parameterUtils, constants, tool configuration What's Missing (for follow-up PRs)
Final Recommendations 📝Before Merging
Post-Merge Follow-ups
ConclusionRecommendation: Approve with minor fixes ✅ This is a high-quality PR that significantly improves test coverage and code reliability. The focus on pure functions and security-critical code demonstrates excellent engineering judgment. The suggested changes are mostly non-blocking enhancements. Great work! 🎉 |
Critical fixes: - Include *.spec.ts files in vitest config to run 60 existing tests - Fix logger mocking to use console.error spy instead of module mock Improvements: - Add edge case test for script tags with nested closing tags - Add numeric edge case tests for autoScheduled parameter (0, 1, -1) - Fix fragile cache auto-cleanup test to use full TTL cycle - Remove redundant logger mocks from toolConfiguration test All 361 tests now pass (301 new + 60 existing). Addresses feedback from: - Copilot: Include pattern excludes existing tests - Claude bot: Test setup, edge cases, timing assumptions Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Pull Request Review: Comprehensive Unit Test SuiteOverall Assessment: Excellent work! ✅ This PR adds 301 well-structured unit tests with strong coverage of edge cases and security scenarios. The test suite demonstrates thoughtful testing practices and focuses appropriately on pure functions. Grade: A- (91/100) 🎯 Strengths
🔴 Critical Issues1. XSS Vulnerability Acceptance (sanitize.test.ts:73)// Edge case: script content contains "</script>" in a string
// This is acceptable behavior - the attack is still neutralized
expect(result).toContain('alert');Problem: The test accepts that // This could bypass sanitization:
<script>var x = "</script>"; alert(1);</script>Recommendation: Either fix the sanitization regex or clearly document this as a known limitation with mitigation strategies. 2. Unclear Numeric
|
| File | Score | Critical Issues | Coverage Quality |
|---|---|---|---|
| sanitize.test.ts | 9/10 | 1 | Excellent XSS focus |
| cache.test.ts | 8.5/10 | 0 | Strong LRU/TTL coverage |
| constants.test.ts | 8/10 | 0 | Good, missing edge cases |
| frequencyTransform.test.ts | 9.5/10 | 0 | Exceptional completeness |
| parameterUtils.test.ts | 9/10 | 1 | Very comprehensive |
| toolConfiguration.test.ts | 9/10 | 1 | Excellent config testing |
✅ Approval Status
APPROVED with recommendations - This is a high-quality test suite that significantly improves the codebase. The critical issues are manageable and primarily involve documentation clarity rather than fundamental flaws. The tests follow best practices and demonstrate a strong understanding of edge cases and security concerns.
Before Merge Checklist
- Address or document the XSS regex limitation
- Clarify numeric
autoScheduledbehavior in docs/code - Consider adding warning for invalid tool configs
- Verify tests pass in CI
Great work on this comprehensive test suite! The focus on pure functions and security-critical code is exactly the right approach.
Review conducted using repository's CLAUDE.md guidelines and MCP architecture patterns.
Security enhancements: - Document XSS regex limitation with script tag nested strings - Add test for img onerror XSS vector - Add test for HTML entity encoding (not decoded) - Add path traversal security tests for custom tool configs - Add malicious property name tests (__proto__, constructor) Edge case coverage: - Add numeric autoScheduled tests (0, 1, -1) - Add date overflow behavior tests (Feb 30, month 13) - Add leap year date handling tests - Document JSDoc for autoScheduled parameter behavior Configuration: - Verify ToolConfigurator already logs ERROR/WARN for invalid configs All 367 tests pass (301 new + 60 existing + 6 additional). Addresses feedback from Claude bot review: - Critical: XSS vulnerability documentation - Minor: Missing security tests, date validation gaps - Clarity: autoScheduled numeric behavior documentation Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Code Review: Comprehensive Unit Test SuiteOverviewThis PR adds 301 unit tests across 6 test files, focusing on pure utility functions. The testing approach is well-designed, prioritizing security-critical sanitization functions and complex logic. ✅ Strengths1. Excellent Test Coverage
2. Clean Test Organization
3. Strong Security Testing
4. Documentation Quality
5. Test Setup Configuration
|
🔍 Issues & Concerns1. Critical: Missing Dependencies Recommendation: The PR test plan shows all tests pass, but ensure CI workflow includes dependency installation. Add documentation about running npm install before testing locally. 2. Security: Documented Regex Limitation While safe (no execution context remains), this deserves attention:
3. Date Overflow Behavior Recommendation: Either implement strict validation to reject invalid dates, or explicitly document this as intended pass-through behavior. 4. Type Safety Concerns Recommendation: While testing runtime safety is good, consider strengthening type signatures where possible. 5. Test Completeness
Recommendation: Acceptable for this PR. Consider a follow-up PR for integration tests. |
📊 Analysis SummaryTest Coverage Quality
Performance Considerations
Security Assessment Strong Points:
Concerns:
Overall Security: Good for current scope, with documented limitations |
📝 Recommendations SummaryMust Fix Before Merge
Should Consider
Nice to Have
🎉 ConclusionThis is a high-quality PR that adds significant value:
The testing approach (pure functions first, avoiding fragile mocks) is pragmatic and will create a solid foundation for future testing efforts. Recommendation: Approve with minor comments - The issues noted are mostly documentation and future enhancements. The core testing work is excellent. 📚 Additional NotesThe PR aligns well with the CLAUDE.md guidelines:
Great work on building a comprehensive test suite! 🚀 |
Summary
Test Coverage
sanitize.test.tsfrequencyTransform.test.tsparameterUtils.test.tsconstants.test.tscache.test.tstoolConfiguration.test.tsKey Testing Principles
Test Plan
npm testnpm run type-check🤖 Generated with Claude Code