Testing
This guide covers testing strategies and tools used in the TradeX platform.
Testing Philosophy
Section titled “Testing Philosophy”- Unit Tests: Test individual components in isolation
- Integration Tests: Test service interactions
- End-to-End Tests: Test complete workflows
- Performance Tests: Test system performance under load
Go Services
Section titled “Go Services”Unit Tests
Section titled “Unit Tests”cd apps/marketdata-service
# Run all testsgo test ./...
# Run specific testgo test ./internal/service/trade
# Run with coveragego test -cover ./...Integration Tests
Section titled “Integration Tests”# Run integration tests (requires infrastructure)go test -tags=integration ./...Example Test
Section titled “Example Test”func TestTradeService_GetRecentTrades(t *testing.T) { // Setup repo := mock.NewTradeRepository() service := trade.NewService(repo, logger, nil)
// Execute trades, err := service.GetRecentTrades(ctx, "BTCUSDT-PERP", 10)
// Assert assert.NoError(t, err) assert.Len(t, trades, 10)}TypeScript Services
Section titled “TypeScript Services”Unit Tests
Section titled “Unit Tests”cd apps/order-service
# Run testsbun test
# Run with coveragebun test --coverageExample Test
Section titled “Example Test”import { describe, it, expect } from 'bun:test';
describe('OrderService', () => { it('should create order', async () => { const service = new OrderService(); const order = await service.createOrder({ instrumentId: '...', side: 'buy', type: 'limit', quantity: 10, price: 50000 });
expect(order).toBeDefined(); expect(order.status).toBe('accepted'); });});Python Services
Section titled “Python Services”Unit Tests
Section titled “Unit Tests”cd apps/auth-service
# Run testsuv run pytest
# Run with coverageuv run pytest --cov=app --cov-report=htmlExample Test
Section titled “Example Test”import pytestfrom app.services.auth_service import AuthService
def test_login_success(): service = AuthService() result = service.login("user@example.com", "password")
assert result.success is True assert result.token is not NoneIntegration Testing
Section titled “Integration Testing”Test Infrastructure
Section titled “Test Infrastructure”Use Docker Compose for test infrastructure:
version: '3.8'services: postgres-test: image: postgres:14 environment: POSTGRES_DB: tradex_testService Integration Tests
Section titled “Service Integration Tests”describe('Order Service Integration', () => { beforeAll(async () => { // Start test infrastructure await startTestInfra(); });
afterAll(async () => { // Stop test infrastructure await stopTestInfra(); });
it('should process order end-to-end', async () => { // Test complete order flow });});End-to-End Testing
Section titled “End-to-End Testing”Test Scenarios
Section titled “Test Scenarios”- User Registration and Login
- Order Placement and Execution
- Market Data Subscription
- Wallet Operations
E2E Test Framework
Section titled “E2E Test Framework”describe('E2E: Order Flow', () => { it('should place and execute order', async () => { // 1. Authenticate const token = await login();
// 2. Place order const order = await placeOrder(token, { symbol: 'BTCUSDT-PERP', side: 'buy', quantity: 1, price: 50000 });
// 3. Wait for execution await waitForOrderExecution(order.id);
// 4. Verify trade const trades = await getTrades(token); expect(trades).toContainEqual( expect.objectContaining({ orderId: order.id }) ); });});Performance Testing
Section titled “Performance Testing”Load Testing
Section titled “Load Testing”Use tools like:
- k6: Load testing tool
- Apache Bench: HTTP load testing
- JMeter: Comprehensive load testing
Example k6 Test
Section titled “Example k6 Test”import http from 'k6/http';import { check } from 'k6';
export const options = { vus: 10, duration: '30s',};
export default function () { const res = http.get('http://localhost:8080/v1/trades?symbol=BTCUSDT-PERP'); check(res, { 'status is 200': (r) => r.status === 200, 'response time < 100ms': (r) => r.timings.duration < 100, });}Mocking
Section titled “Mocking”Go Services
Section titled “Go Services”// Mock repositorytype MockTradeRepository struct { trades []*Trade}
func (m *MockTradeRepository) GetRecentTrades(ctx context.Context, symbol string, limit int) ([]*Trade, error) { return m.trades[:limit], nil}TypeScript Services
Section titled “TypeScript Services”// Mock serviceconst mockWalletService = { getBalance: jest.fn().mockResolvedValue({ available: 1000 }), holdBalance: jest.fn().mockResolvedValue({ success: true })};Test Data
Section titled “Test Data”Fixtures
Section titled “Fixtures”Create reusable test data:
export const testInstruments = { btcPerp: { id: 'test-btc-perp', symbol: 'BTCUSDT-PERP', status: 'active' }};Database Seeding
Section titled “Database Seeding”# Seed test databun run seed:testContinuous Integration
Section titled “Continuous Integration”GitHub Actions Example
Section titled “GitHub Actions Example”name: Tests
on: [push, pull_request]
jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 - run: bun install - run: bun testBest Practices
Section titled “Best Practices”- Test Isolation: Each test should be independent
- Cleanup: Clean up test data after tests
- Fast Tests: Keep unit tests fast (< 1s)
- Clear Assertions: Use descriptive assertion messages
- Test Coverage: Aim for > 80% coverage