Skip to content

Commit dd46b3e

Browse files
Feature: Sandboxes Monitoring - 2 - Testing Infrastructure (#138)
- [ ] 1: API/State Layer #137 - [ ] 2: **THIS PR** Builds upon the API/State Management layer to provide comprehensive test coverage for all utility functions and data processing logic. Integrates unit tests into the CI pipeline for early regression detection. ## Key Features **Comprehensive Unit Test Coverage (104 tests)** - **Chart utilities** (25 tests) - Data transformation, axis calculations, tooltip formatting - **Formatting functions** (47 tests) - Date/time/number formatting across locales and formats - **Sandboxes utilities** (17 tests) - Metrics processing and transformation logic - **Team metrics calculations** (15 tests) - Step calculations and aggregation algorithms **Development & Load Testing** - `burst.test.ts` - Tests system behavior under sudden load spikes - `traffic.test.ts` - Tests sustained traffic patterns and performance - Configurable test scenarios for different usage patterns **GitHub Actions CI Integration** - Dedicated `unit-tests` job that runs before integration tests - Minimal environment setup (no external services required) - Fast feedback loop (~1 second execution time) - Cost-efficient CI pipeline (integration tests only run if unit tests pass) **Test Infrastructure** - Supporting UI components needed for testing (chart-utils, tooltips) - Proper test isolation and mocking strategies - Enhanced test documentation and examples ## Test Coverage Architecture ### CI Pipeline Flow ```mermaid graph LR subgraph "GitHub Actions" Push[Push/PR] --> UnitTests["Unit Tests<br/>104 tests<br/>~1s execution"] UnitTests --> |"✅ Pass"| IntegrationTests["Integration Tests<br/>~30s execution"] UnitTests --> |"❌ Fail"| Stop[❌ Stop Pipeline] IntegrationTests --> |"✅ Pass"| Success[✅ All Tests Pass] IntegrationTests --> |"❌ Fail"| Fail[❌ Integration Failure] end subgraph "Test Categories" UnitTests --> ChartUtils["Chart Utils (25)"] UnitTests --> Formatting["Formatting (47)"] UnitTests --> Sandboxes["Sandboxes (17)"] UnitTests --> Metrics["Team Metrics (15)"] end style UnitTests fill:#e1f5fe style IntegrationTests fill:#e8f5e9 style Success fill:#c8e6c9 style Fail fill:#ffcdd2 style Stop fill:#ffcdd2 ``` ### Test Coverage Map ```mermaid graph TB subgraph "Utility Functions Tested" subgraph "Chart Utilities" CalcAvg["calculateAverage()"] CalcMedian["calculateMedian()"] CalcCentralTendency["calculateCentralTendency()"] CalcYAxis["calculateYAxisMax()"] FillZeros["fillMetricsWithZeros()"] TransformData["transformMetricsToLineData()"] CreateSeries["createChartSeries()"] end subgraph "Formatting Functions" FormatNumber["formatNumber()"] FormatBytes["formatBytes()"] FormatDuration["formatDuration()"] FormatDate["formatChartTimestamp*()"] FormatCompact["formatCompactNumber()"] FormatDecimal["formatDecimal()"] FormatPercentage["formatPercentage()"] end subgraph "Data Processing" TransformMetrics["transformMetricsToClientMetrics()"] CalcStep["calculateStepForDuration()"] FillTeamMetrics["fillTeamMetricsWithZeros()"] end end subgraph "Test Files" ChartTests["chart-utils.test.ts<br/>25 tests"] FormatTests["formatting.test.ts<br/>47 tests"] SandboxTests["sandboxes.test.ts<br/>17 tests"] MetricsTests["team-metrics-step.test.ts<br/>15 tests"] end ChartTests --> CalcAvg ChartTests --> CalcMedian ChartTests --> CalcCentralTendency ChartTests --> CalcYAxis ChartTests --> FillZeros ChartTests --> TransformData ChartTests --> CreateSeries FormatTests --> FormatNumber FormatTests --> FormatBytes FormatTests --> FormatDuration FormatTests --> FormatDate FormatTests --> FormatCompact FormatTests --> FormatDecimal FormatTests --> FormatPercentage SandboxTests --> TransformMetrics SandboxTests --> CalcStep MetricsTests --> FillTeamMetrics style ChartTests fill:#e1f5fe style FormatTests fill:#fff3e0 style SandboxTests fill:#e8f5e9 style MetricsTests fill:#f3e5f5 ``` ## Technical Implementation **Test Architecture** - Vitest as the test runner with TypeScript support - Tests focus on pure functions and data transformations - Mock data generation for consistent test scenarios - Comprehensive edge case coverage (empty data, boundary conditions, timezone handling) **Key Test Files** - `src/__test__/unit/chart-utils.test.ts` - Chart calculation logic - `src/__test__/unit/formatting.test.ts` - All formatting utilities - `src/__test__/unit/sandboxes.test.ts` - Data transformation functions - `src/__test__/unit/team-metrics-step.test.ts` - Time interval calculations - `src/__test__/development/` - Load and performance testing **CI Pipeline Enhancements** - Unit tests run first for fast feedback - Integration tests depend on unit test success - Parallel test execution for optimal performance - Clear separation of test types and responsibilities --- *This PR provides comprehensive test coverage for the API/State Management layer. All 104 unit tests pass and are integrated into CI. The testing infrastructure validates that all utility functions work correctly and provides confidence for further development. Requires PR1 (API layer) to be merged first.*
1 parent fde3cd6 commit dd46b3e

File tree

14 files changed

+2438
-807
lines changed

14 files changed

+2438
-807
lines changed

.github/workflows/test.yml

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,31 @@ on:
77
branches: [main]
88

99
jobs:
10+
unit-tests:
11+
name: Unit Tests
12+
runs-on: ubuntu-latest
13+
14+
# unit tests don't need environment variables - they test pure functions
15+
16+
steps:
17+
- name: Checkout code
18+
uses: actions/checkout@v4
19+
20+
- name: Setup Bun
21+
uses: oven-sh/setup-bun@v1
22+
with:
23+
bun-version: 1.2.20
24+
25+
- name: Install dependencies
26+
run: bun install
27+
28+
- name: Run unit tests
29+
run: bun test:unit
30+
1031
integration-tests:
1132
name: Integration Tests
1233
runs-on: ubuntu-latest
34+
needs: unit-tests # run after unit tests pass
1335

1436
# these are placeholders which is fine for integration tests
1537
env:
@@ -35,7 +57,7 @@ jobs:
3557
- name: Setup Bun
3658
uses: oven-sh/setup-bun@v1
3759
with:
38-
bun-version: latest
60+
bun-version: 1.2.20
3961

4062
- name: Install dependencies
4163
run: bun install

package.json

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,32 +11,31 @@
1111
"lint": "next lint",
1212
"lint:fix": "next lint --fix",
1313
"format": "prettier --write .",
14-
"<<<<<< Development Tools": "",
14+
"prebuild": "bun scripts:check-app-env",
15+
"<<<<<<< Development Tools": "",
1516
"scan:local": "bunx react-scan@latest localhost:3000",
16-
"<<<<<< Database": "",
17+
"<<<<<<< Database": "",
1718
"db:migrations:create": "bun run scripts:create-migration",
1819
"db:migrations:apply": "bun run scripts:apply-migrations",
19-
"<<<<<< Gen": "",
20+
"<<<<<<< Gen": "",
2021
"generate:infra": "bunx openapi-typescript ./spec/openapi.yaml -o ./src/types/infra-api.d.ts",
2122
"generate:supabase": "bunx supabase@latest gen types typescript --schema public > src/types/database.types.ts --project-id $SUPABASE_PROJECT_ID",
22-
"<<<<<< Scripts": "",
23+
"<<<<<<< Scripts": "",
2324
"scripts:check-app-env": "bun scripts/check-app-env.ts",
2425
"scripts:check-e2e-env": "bun scripts/check-e2e-env.ts",
2526
"scripts:check-all-env": "bun scripts:check-app-env && bun scripts:check-e2e-env",
2627
"scripts:create-migration": "bun scripts/create-migration.ts",
27-
"<<<<<< Development": "",
28+
"<<<<<<< Development": "",
2829
"shad": "bunx shadcn@canary",
29-
"prebuild": "bun scripts:check-app-env",
30-
"<<<<<< Testing": "",
30+
"test:development:traffic": "vitest run src/__test__/development/traffic.test.ts",
31+
"<<<<<<< Testing": "",
3132
"test:run": "bun scripts:check-all-env && vitest run",
3233
"test:integration": "bun scripts:check-app-env && vitest run src/__test__/integration/",
33-
"test:unit": "bun scripts:check-app-env && vitest run src/__test__/unit/",
34+
"test:unit": "vitest run src/__test__/unit/",
3435
"test:e2e": "bun scripts:check-all-env && vitest run src/__test__/e2e/",
3536
"test:watch": "bun scripts:check-all-env && vitest",
3637
"test:ui": "bun scripts:check-all-env && vitest --ui",
37-
"test:ui:integration": "bun scripts:check-app-env && vitest --ui src/__test__/integration/",
38-
"test:development:burst": "vitest run src/__test__/development/burst.test.ts",
39-
"test:development:traffic": "vitest run src/__test__/development/traffic.test.ts"
38+
"test:ui:integration": "bun scripts:check-app-env && vitest --ui src/__test__/integration/"
4039
},
4140
"dependencies": {
4241
"@fumadocs/mdx-remote": "^1.2.0",

src/__test__/README.md

Lines changed: 60 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,43 @@
11
# Testing Strategy
22

3-
This project uses a comprehensive testing strategy with different types of tests for different purposes. This README explains the current state of testing and how to extend it.
4-
53
## Current Test Types
64

5+
### Unit Tests
6+
7+
Unit tests are the most granular tests that verify individual functions, components, or modules work correctly in isolation. These tests are fast, focused, and should be the foundation of our testing pyramid.
8+
9+
**Location:** `src/__test__/unit/`
10+
11+
**Naming Convention:** Unit test files should follow the pattern `[module-name].test.[ext]`
12+
- For testing `src/lib/utils/formatting.ts`, create `src/__test__/unit/formatting.test.ts`
13+
- For testing `src/ui/primitives/button.tsx`, create `src/__test__/unit/button.test.tsx`
14+
- Group related tests in the same file when they test the same module
15+
16+
**Run with:**
17+
- All unit tests: `bun test:unit`
18+
- All tests: `bun test:run`
19+
- Watch mode: `bun test:watch`
20+
- Specific file: `bun test src/__test__/unit/formatting.test.ts`
21+
22+
**Examples:**
23+
- `src/__test__/unit/formatting.test.ts` for testing formatting utilities
24+
- `src/__test__/unit/auth-utils.test.ts` for testing authentication utilities
25+
- `src/__test__/unit/button.test.tsx` for testing button component
26+
27+
**Benefits of Centralized Unit Tests:**
28+
- All unit tests in one location for easy discovery
29+
- Clear separation between test types
30+
- Consistent test organization
31+
- Easy to run all unit tests at once
32+
33+
**What to Unit Test:**
34+
- Pure utility functions (e.g., formatters, validators, parsers)
35+
- Business logic functions
36+
- React hooks
37+
- Component rendering and behavior
38+
- Data transformations
39+
- Error handling edge cases
40+
741
### Integration Tests
842

943
Integration tests verify that different parts of the application work together correctly, but they use mocks for external dependencies like databases and APIs. These tests are fast, reliable, and don't require external services to be running.
@@ -18,10 +52,6 @@ The integration tests use a dummy environment set in `vitest.config.ts` which pr
1852
- Integration tests run the `scripts:check-app-env` script before execution to ensure all required application environment variables are set.
1953
- This is configured in `package.json`: `"test:integration": "bun scripts:check-app-env && vitest run src/__test__/integration/"`
2054

21-
**Examples:**
22-
- Authentication tests in `src/__test__/integration/auth.test.ts`
23-
- Middleware tests in `src/__test__/integration/middleware.test.ts`
24-
2555
### End-to-End (E2E) Tests
2656

2757
**Current Status:** E2E tests are not yet implemented. There is a placeholder file at `src/__test__/e2e/placeholder.test.ts`.
@@ -42,9 +72,6 @@ Development tests are specialized tests designed to assist with feature developm
4272

4373
**Purpose:** These tests spawn real resources (like sandboxes) that can be observed in the dashboard while developing features, eliminating the need to manually manage test resources.
4474

45-
**Examples:**
46-
- `metrics.test.ts`: Spawns stressed sandboxes in batches to test dashboard performance and metrics visualization
47-
4875
**Environment Setup:**
4976
To run development tests, you must create a `.env.test` file with the required environment variables:
5077
```bash
@@ -60,11 +87,22 @@ TEST_E2B_TEMPLATE=base # optional, defaults to 'base'
6087

6188
### Locally
6289

63-
To run all tests:
90+
To run all tests (unit, integration, and E2E):
6491
```bash
6592
bun test:run
6693
```
6794

95+
To run tests in watch mode (great for development):
96+
```bash
97+
bun test:watch
98+
```
99+
100+
To run only unit tests:
101+
```bash
102+
bun test:unit
103+
bun test src/__test__/unit/formatting.test.ts # specific unit test file
104+
```
105+
68106
To run only integration tests:
69107
```bash
70108
bun test:integration
@@ -77,7 +115,10 @@ bun test:e2e
77115

78116
### In CI/CD
79117

80-
Currently, only integration tests are configured to run in CI/CD:
118+
Currently, unit and integration tests are configured to run in CI/CD:
119+
- **Unit tests** are run from `src/__test__/unit/`
120+
- **Integration tests** are run from `src/__test__/integration/`
121+
- Both use the `.test.` naming convention for automatic discovery
81122

82123
(See [`.github/workflows/test.yml`](.github/workflows/test.yml))
83124

@@ -121,9 +162,12 @@ To start implementing E2E tests:
121162

122163
## Best Practices
123164

124-
1. **Write integration tests for most functionality**: They're faster and more reliable.
125-
2. **Use E2E tests for critical paths**: Focus on key user journeys like authentication, payment, etc.
126-
3. **Keep E2E tests minimal**: They're slower and more brittle, so use them sparingly.
127-
4. **Use test data**: Create and clean up test data in your E2E tests to avoid polluting your development/production environment.
128-
5. **Skip E2E tests if environment variables are missing**: This allows the tests to be run in environments without the necessary credentials.
165+
1. **Start with unit tests**: Write unit tests for all utility functions, pure logic, and isolated components.
166+
2. **Organize tests by type**: Keep unit tests in `src/__test__/unit/`, integration tests in `src/__test__/integration/`.
167+
3. **Write integration tests for feature flows**: Test how different parts work together, but mock external dependencies.
168+
4. **Use E2E tests for critical paths**: Focus on key user journeys like authentication, payment, etc.
169+
5. **Keep E2E tests minimal**: They're slower and more brittle, so use them sparingly.
170+
6. **Use test data**: Create and clean up test data in your E2E tests to avoid polluting your development/production environment.
171+
7. **Skip E2E tests if environment variables are missing**: This allows the tests to be run in environments without the necessary credentials.
172+
8. **Follow the naming convention**: Always use `.test.` in the filename for all test files.
129173

0 commit comments

Comments
 (0)