-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path300-testing.mdc
More file actions
1452 lines (1135 loc) · 34.7 KB
/
Copy path300-testing.mdc
File metadata and controls
1452 lines (1135 loc) · 34.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: Testing Strategies & Best Practices
description: Comprehensive testing guide covering unit, integration, E2E, test frameworks, patterns, and CI/CD integration
priority: 300
alwaysApply: false
files:
include:
- "**/*.test.ts"
- "**/*.test.js"
- "**/*.test.py"
- "**/*.test.go"
- "**/*.spec.ts"
- "**/*.spec.js"
- "**/test_*.py"
- "**/*_test.go"
- "**/jest.config.js"
- "**/pytest.ini"
- "**/vitest.config.ts"
---
# Testing Strategies & Best Practices
**Audience**: engineers writing and reviewing tests across languages and frameworks
**Goal**: Create reliable, maintainable test suites that provide fast feedback and high confidence
## Testing Philosophy (Core Principles)
**Core Principles:**
- **"Test pyramid, not test ice cream cone"** - More unit tests, fewer integration tests, minimal E2E tests
- **"Fast feedback loop"** - Tests should run quickly and fail fast with clear error messages
- **"Tests are documentation"** - Tests describe how code should behave, make them readable
- **"Isolation is essential"** - Tests should be independent, repeatable, and not depend on each other
- **"Quality over quantity"** - 80% coverage is good, but meaningful tests matter more than coverage percentage
- **"Test behavior, not implementation"** - Test what the code does, not how it does it
- **"Fail fast, fail clearly"** - Tests should fail with actionable error messages
- **"Maintainability matters"** - Tests should be easy to update when requirements change
**Applying Testing Principles:**
```typescript
// BAD: Testing implementation, unclear, slow
it('test1', () => {
const result = service.process();
expect(result).toBeTruthy();
});
// GOOD: Testing behavior, clear, fast
it('should calculate total price with 10% discount', () => {
// Arrange
const cart = new ShoppingCart();
cart.addItem({ id: '1', price: 100 });
cart.addItem({ id: '2', price: 50 });
// Act
const total = cart.calculateTotal(0.1);
// Assert
expect(total).toBe(135); // (100 + 50) * 0.9
});
```
## Guiding Principles
1. **Test Pyramid**: More unit tests, fewer integration tests, minimal E2E tests
2. **Fast Feedback**: Tests should run quickly and fail fast
3. **Isolation**: Tests should be independent and repeatable
4. **Clarity**: Tests are documentation - make them readable
5. **Coverage**: Aim for 80%+ coverage, but quality > quantity
---
## Test Pyramid
```
E2E Tests (Few)
- Slow, brittle, expensive
- Test critical user journeys
E2E - 5-10% of tests
Integration Tests (Some)
Integration - Medium speed
- Test component interactions
- 20-30% of tests
Unit Tests (Many)
Unit - Fast, focused, reliable
- Test individual functions/classes
- 60-70% of tests
```
---
## Unit Testing
### Jest (JavaScript/TypeScript)
#### Basic Test Structure
```typescript
// user.test.ts
import { describe, it, expect, beforeEach, afterEach } from '@jest/globals';
import { UserService } from './user-service';
describe('UserService', () => {
let userService: UserService;
beforeEach(() => {
userService = new UserService();
});
afterEach(() => {
jest.clearAllMocks();
});
describe('createUser', () => {
it('should create a user with valid data', () => {
const userData = { name: 'John', email: 'john@acme.com' };
const user = userService.createUser(userData);
expect(user).toMatchObject(userData);
expect(user.id).toBeDefined();
expect(user.createdAt).toBeInstanceOf(Date);
});
it('should throw error for invalid email', () => {
const userData = { name: 'John', email: 'invalid' };
expect(() => userService.createUser(userData)).toThrow('Invalid email');
});
it('should hash the password', () => {
const userData = { name: 'John', email: 'john@acme.com', password: 'secret' };
const user = userService.createUser(userData);
expect(user.password).not.toBe('secret');
expect(user.password).toMatch(/^hashed_/);
});
});
});
```
#### Table-Driven Tests
```typescript
// GOOD - Test multiple cases efficiently
describe('calculateDiscount', () => {
it.each([
[100, 0.1, 10],
[200, 0.2, 40],
[500, 0.15, 75],
[0, 0.5, 0],
])('should calculate discount for amount %d with rate %d', (amount, rate, expected) => {
expect(calculateDiscount(amount, rate)).toBe(expected);
});
});
```
#### Mocking
```typescript
import { jest } from '@jest/globals';
import { UserService } from './user-service';
import { EmailService } from './email-service';
// Mock external dependencies
jest.mock('./email-service');
describe('UserService with mocks', () => {
let userService: UserService;
let emailService: jest.Mocked<EmailService>;
beforeEach(() => {
emailService = new EmailService() as jest.Mocked<EmailService>;
userService = new UserService(emailService);
});
it('should send welcome email on user creation', async () => {
emailService.sendWelcome.mockResolvedValue(true);
await userService.createUser({ name: 'John', email: 'john@acme.com' });
expect(emailService.sendWelcome).toHaveBeenCalledTimes(1);
expect(emailService.sendWelcome).toHaveBeenCalledWith('john@acme.com');
});
it('should handle email sending failure', async () => {
emailService.sendWelcome.mockRejectedValue(new Error('SMTP error'));
await expect(
userService.createUser({ name: 'John', email: 'john@acme.com' })
).rejects.toThrow('Failed to send welcome email');
});
});
```
#### Spy on Functions
```typescript
import { jest } from '@jest/globals';
describe('Spy examples', () => {
it('should spy on console.log', () => {
const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation();
myFunction();
expect(consoleLogSpy).toHaveBeenCalledWith('Expected message');
consoleLogSpy.mockRestore();
});
it('should spy on class method', () => {
const service = new UserService();
const validateSpy = jest.spyOn(service, 'validateEmail');
service.createUser({ name: 'John', email: 'john@acme.com' });
expect(validateSpy).toHaveBeenCalledWith('john@acme.com');
});
});
```
---
### pytest (Python)
#### Basic Test Structure
```python
# test_user_service.py
import pytest
from datetime import datetime
from user_service import UserService, ValidationError
class TestUserService:
@pytest.fixture
def user_service(self):
"""Fixture to create UserService instance."""
return UserService()
def test_create_user_with_valid_data(self, user_service):
"""Should create user with valid data."""
user_data = {"name": "John", "email": "john@acme.com"}
user = user_service.create_user(user_data)
assert user["name"] == "John"
assert user["email"] == "john@acme.com"
assert "id" in user
assert isinstance(user["created_at"], datetime)
def test_create_user_with_invalid_email(self, user_service):
"""Should raise ValidationError for invalid email."""
user_data = {"name": "John", "email": "invalid"}
with pytest.raises(ValidationError, match="Invalid email"):
user_service.create_user(user_data)
def test_password_is_hashed(self, user_service):
"""Should hash the password."""
user_data = {"name": "John", "email": "john@acme.com", "password": "secret"}
user = user_service.create_user(user_data)
assert user["password"] != "secret"
assert user["password"].startswith("hashed_")
```
#### Parametrized Tests
```python
# GOOD - Test multiple cases efficiently
import pytest
@pytest.mark.parametrize("amount,rate,expected", [
(100, 0.1, 10),
(200, 0.2, 40),
(500, 0.15, 75),
(0, 0.5, 0),
])
def test_calculate_discount(amount, rate, expected):
"""Should calculate discount correctly."""
assert calculate_discount(amount, rate) == expected
```
#### Mocking with pytest
```python
from unittest.mock import Mock, patch
import pytest
class TestUserServiceWithMocks:
@pytest.fixture
def email_service_mock(self):
"""Mock email service."""
return Mock()
@pytest.fixture
def user_service(self, email_service_mock):
"""User service with mocked email service."""
return UserService(email_service=email_service_mock)
def test_send_welcome_email_on_creation(self, user_service, email_service_mock):
"""Should send welcome email on user creation."""
email_service_mock.send_welcome.return_value = True
user_service.create_user({"name": "John", "email": "john@acme.com"})
email_service_mock.send_welcome.assert_called_once_with("john@acme.com")
def test_handle_email_sending_failure(self, user_service, email_service_mock):
"""Should handle email sending failure."""
email_service_mock.send_welcome.side_effect = Exception("SMTP error")
with pytest.raises(Exception, match="Failed to send welcome email"):
user_service.create_user({"name": "John", "email": "john@acme.com"})
@patch('user_service.datetime')
def test_created_at_timestamp(self, datetime_mock, user_service):
"""Should use current timestamp for created_at."""
fixed_time = datetime(2024, 1, 1, 12, 0, 0)
datetime_mock.now.return_value = fixed_time
user = user_service.create_user({"name": "John", "email": "john@acme.com"})
assert user["created_at"] == fixed_time
```
#### Testing Automation with tox
`tox` automates testing across multiple Python versions and environments:
**Installation:**
```bash
uv add --dev tox
# or
pip install tox
```
**Basic Usage:**
```bash
# Run all test environments
tox
# Run specific environment
tox -e py312 # Python 3.12
tox -e py313 # Python 3.13
tox -e lint # Linting checks
tox -e format # Formatting checks
# List available environments
tox -l
# Run in parallel (faster)
tox -p auto
```
**Configuration (tox.ini):**
```ini
[tox]
envlist = py312,py313,lint,format,security
isolated_build = true
[testenv]
deps =
pytest>=7.0
pytest-cov
commands =
pytest --cov=src --cov-report=html
[testenv:lint]
deps =
ruff>=0.1.0
black>=23.0.0
isort>=5.13.0
commands =
ruff check .
black --check .
isort --check-only .
[testenv:format]
deps =
black>=23.0.0
isort>=5.13.0
commands =
black .
isort .
[testenv:security]
deps =
bandit>=1.7.0
commands =
bandit -r src -ll
```
**Configuration (pyproject.toml):**
```toml
[tool.tox]
legacy_tox_ini = """
[tox]
envlist = py312,py313,lint,format
[testenv]
deps = pytest
commands = pytest
[testenv:lint]
deps = ruff,black,isort
commands = ruff check . && black --check . && isort --check-only .
"""
```
**Benefits:**
- Test across multiple Python versions automatically
- Isolated environments prevent dependency conflicts
- Run linting, formatting, and security checks consistently
- Same commands work locally and in CI/CD
- Parallel execution speeds up test runs
**CI/CD Integration:**
```yaml
# GitHub Actions example
- name: Run tox
run: |
pip install tox
tox -p auto
```
---
### Go Testing
#### Basic Test Structure
```go
// user_test.go
package user
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCreateUser(t *testing.T) {
service := NewUserService()
t.Run("should create user with valid data", func(t *testing.T) {
userData := UserData{
Name: "John",
Email: "john@acme.com",
}
user, err := service.CreateUser(userData)
require.NoError(t, err)
assert.Equal(t, "John", user.Name)
assert.Equal(t, "john@acme.com", user.Email)
assert.NotEmpty(t, user.ID)
assert.NotZero(t, user.CreatedAt)
})
t.Run("should return error for invalid email", func(t *testing.T) {
userData := UserData{
Name: "John",
Email: "invalid",
}
_, err := service.CreateUser(userData)
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid email")
})
}
```
#### Table-Driven Tests
```go
// GOOD - Idiomatic Go testing
func TestCalculateDiscount(t *testing.T) {
tests := []struct {
name string
amount float64
rate float64
expected float64
}{
{"10% off 100", 100, 0.1, 10},
{"20% off 200", 200, 0.2, 40},
{"15% off 500", 500, 0.15, 75},
{"50% off 0", 0, 0.5, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := CalculateDiscount(tt.amount, tt.rate)
assert.Equal(t, tt.expected, result)
})
}
}
```
#### Mocking with Interfaces
```go
// Define interface for dependency
type EmailService interface {
SendWelcome(email string) error
}
// Mock implementation
type MockEmailService struct {
SendWelcomeCalled bool
SendWelcomeError error
}
func (m *MockEmailService) SendWelcome(email string) error {
m.SendWelcomeCalled = true
return m.SendWelcomeError
}
// Test with mock
func TestCreateUserSendsWelcomeEmail(t *testing.T) {
mockEmail := &MockEmailService{}
service := NewUserService(mockEmail)
_, err := service.CreateUser(UserData{
Name: "John",
Email: "john@acme.com",
})
require.NoError(t, err)
assert.True(t, mockEmail.SendWelcomeCalled)
}
```
---
## Integration Testing
### Database Integration Tests
#### PostgreSQL with Testcontainers (Node.js)
```typescript
import { GenericContainer, StartedTestContainer } from 'testcontainers';
import { Client } from 'pg';
describe('UserRepository Integration', () => {
let container: StartedTestContainer;
let client: Client;
beforeAll(async () => {
// Start PostgreSQL container
container = await new GenericContainer('postgres:16-alpine')
.withEnvironment({ POSTGRES_PASSWORD: 'test' })
.withExposedPorts(5432)
.start();
// Connect to container
client = new Client({
host: container.getHost(),
port: container.getMappedPort(5432),
user: 'postgres',
password: 'test',
database: 'postgres',
});
await client.connect();
// Run migrations
await client.query(`
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100) UNIQUE
)
`);
}, 60000);
afterAll(async () => {
await client.end();
await container.stop();
});
it('should insert and retrieve user', async () => {
const repo = new UserRepository(client);
const created = await repo.create({ name: 'John', email: 'john@acme.com' });
const retrieved = await repo.findById(created.id);
expect(retrieved).toMatchObject({
name: 'John',
email: 'john@acme.com',
});
});
});
```
#### Python with pytest-postgresql
```python
import pytest
from user_repository import UserRepository
@pytest.fixture
def user_repository(postgresql):
"""Create user repository with test database."""
# postgresql fixture from pytest-postgresql
cursor = postgresql.cursor()
cursor.execute("""
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100) UNIQUE
)
""")
postgresql.commit()
return UserRepository(postgresql)
def test_insert_and_retrieve_user(user_repository):
"""Should insert and retrieve user."""
created = user_repository.create({"name": "John", "email": "john@acme.com"})
retrieved = user_repository.find_by_id(created["id"])
assert retrieved["name"] == "John"
assert retrieved["email"] == "john@acme.com"
```
### API Integration Tests
#### FastAPI (Python)
```python
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_create_user_endpoint():
"""Should create user via API."""
response = client.post(
"/api/users",
json={"name": "John", "email": "john@acme.com"}
)
assert response.status_code == 201
data = response.json()
assert data["name"] == "John"
assert data["email"] == "john@acme.com"
assert "id" in data
def test_get_user_endpoint():
"""Should retrieve user by ID."""
# Create user first
create_response = client.post(
"/api/users",
json={"name": "Jane", "email": "jane@acme.com"}
)
user_id = create_response.json()["id"]
# Retrieve user
response = client.get(f"/api/users/{user_id}")
assert response.status_code == 200
data = response.json()
assert data["name"] == "Jane"
def test_get_nonexistent_user_returns_404():
"""Should return 404 for nonexistent user."""
response = client.get("/api/users/99999")
assert response.status_code == 404
```
#### Express (Node.js)
```typescript
import request from 'supertest';
import { app } from './app';
describe('User API Integration', () => {
describe('POST /api/users', () => {
it('should create user', async () => {
const response = await request(app)
.post('/api/users')
.send({ name: 'John', email: 'john@acme.com' })
.expect(201);
expect(response.body).toMatchObject({
name: 'John',
email: 'john@acme.com',
});
expect(response.body.id).toBeDefined();
});
it('should return 400 for invalid data', async () => {
await request(app)
.post('/api/users')
.send({ name: 'John' }) // Missing email
.expect(400);
});
});
describe('GET /api/users/:id', () => {
it('should retrieve user by ID', async () => {
// Create user first
const createResponse = await request(app)
.post('/api/users')
.send({ name: 'Jane', email: 'jane@acme.com' });
const userId = createResponse.body.id;
// Retrieve user
const response = await request(app)
.get(`/api/users/${userId}`)
.expect(200);
expect(response.body.name).toBe('Jane');
});
it('should return 404 for nonexistent user', async () => {
await request(app)
.get('/api/users/99999')
.expect(404);
});
});
});
```
---
## End-to-End (E2E) Testing
### Playwright (Modern, Recommended)
```typescript
// e2e/user-flow.spec.ts
import { test, expect } from '@playwright/test';
test.describe('User Registration Flow', () => {
test('should allow user to register and login', async ({ page }) => {
// Navigate to registration page
await page.goto('https://app.acme.com/register');
// Fill registration form
await page.fill('[name="name"]', 'John Doe');
await page.fill('[name="email"]', 'john@acme.com');
await page.fill('[name="password"]', 'SecurePassword123!');
await page.fill('[name="confirmPassword"]', 'SecurePassword123!');
// Submit form
await page.click('button[type="submit"]');
// Wait for success message
await expect(page.locator('.success-message')).toContainText(
'Registration successful'
);
// Should redirect to dashboard
await expect(page).toHaveURL(/.*\/dashboard/);
// Verify user is logged in
await expect(page.locator('.user-profile')).toContainText('John Doe');
});
test('should show error for duplicate email', async ({ page }) => {
await page.goto('https://app.acme.com/register');
await page.fill('[name="email"]', 'existing@acme.com');
await page.fill('[name="password"]', 'password123');
await page.click('button[type="submit"]');
await expect(page.locator('.error-message')).toContainText(
'Email already exists'
);
});
});
// Visual regression testing
test('homepage should look correct', async ({ page }) => {
await page.goto('https://app.acme.com');
await expect(page).toHaveScreenshot('homepage.png');
});
```
### Playwright Configuration
```typescript
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
{ name: 'Mobile Chrome', use: { ...devices['Pixel 5'] } },
{ name: 'Mobile Safari', use: { ...devices['iPhone 12'] } },
],
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
});
```
---
## Test Coverage
### Jest Coverage
```json
{
"jest": {
"collectCoverage": true,
"coverageDirectory": "coverage",
"coverageReporters": ["text", "lcov", "html"],
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": 80
}
},
"collectCoverageFrom": [
"src/**/*.{js,ts}",
"!src/**/*.test.{js,ts}",
"!src/**/*.spec.{js,ts}"
]
}
}
```
### pytest Coverage
```ini
# pytest.ini
[pytest]
addopts =
--cov=src
--cov-report=html
--cov-report=term-missing
--cov-fail-under=80
```
### Go Coverage
```bash
# Run tests with coverage
go test -cover ./...
# Generate coverage report
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out -o coverage.html
# Coverage threshold check
go test -coverprofile=coverage.out ./... && \
go tool cover -func=coverage.out | grep total | awk '{if ($3+0 < 80) exit 1}'
```
---
## CI/CD Integration
### GitHub Actions - Full Test Suite
```yaml
name: Test Suite
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
checks: write
jobs:
unit-tests:
name: Unit Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run unit tests
run: npm run test:unit -- --coverage
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
files: ./coverage/lcov.info
integration-tests:
name: Integration Tests
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_PASSWORD: test
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run integration tests
run: npm run test:integration
env:
DATABASE_URL: postgresql://postgres:test@localhost:5432/test
e2e-tests:
name: E2E Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Install Playwright
run: npx playwright install --with-deps
- name: Run E2E tests
run: npm run test:e2e
- name: Upload Playwright report
uses: actions/upload-artifact@v3
if: always()
with:
name: playwright-report
path: playwright-report/
retention-days: 30
```
---
## Advanced Testing Patterns