# Cartec API Tests

This directory contains test suites for the Cartec API.

## Test Files

### 1. `api.test.js` - Node.js Test Suite

Comprehensive test suite using native Node.js HTTP module.

**Features:**
- Health check validation
- Request validation tests
- GPS provider validation
- RUT validation
- Email validation
- OT creation tests

**Run:**
```bash
node test/api.test.js
```

**Requirements:**
- Node.js 12+
- API running on `localhost:3000`

---

### 2. `run_tests.sh` - Bash Test Script

Simple curl-based test script for quick validation.

**Features:**
- Health check
- GPS provider validation (all 5 providers)
- Invalid input rejection
- Email validation
- Vehicle validation
- OT creation attempt

**Run:**
```bash
./test/run_tests.sh
```

or

```bash
bash test/run_tests.sh
```

**Requirements:**
- bash
- curl
- API running on `localhost:3000`

---

## Test Scenarios

### 1. Health Check
Verifies the `/api/health` endpoint is responding correctly.

**Expected:** HTTP 200 with `{"status":"ok","timestamp":"..."}`

---

### 2. GPS Provider Validation
Tests all valid GPS providers:
- `gpsimple`
- `entel`
- `tattersall`
- `cemin`
- `carflex`

**Expected:** All should be accepted by validation

---

### 3. Invalid Input Rejection

Tests that invalid inputs are properly rejected:
- Invalid RUT format
- Invalid RUT checksum
- Invalid email format
- Invalid GPS provider
- Missing required fields
- Empty vehicle list

**Expected:** HTTP 400 with appropriate error messages

---

### 4. OT Creation

Attempts to create a valid OT.

**Note:** This test may not pass if:
- Database is not configured
- Technician RUT `98765432-1` doesn't exist
- Tables `orden_trabajo` and `vehiculos_ot` don't exist
- Stored procedure `prc_api_create_OT` is not installed

**Expected (if DB configured):** HTTP 201 with OT ID

---

## Before Running Tests

### 1. Ensure API is Running

```bash
sudo systemctl status cartec-api
```

If not running:
```bash
sudo systemctl start cartec-api
```

### 2. Check API is Responding

```bash
curl http://localhost:3000/api/health
```

### 3. Database Setup (for full OT creation test)

Ensure these exist:

```sql
-- Check tables
SHOW TABLES LIKE 'orden_trabajo';
SHOW TABLES LIKE 'vehiculos_ot';

-- Check stored procedure
SHOW PROCEDURE STATUS WHERE Name = 'prc_api_create_OT';

-- Check test technician exists
SELECT * FROM Tecnicos WHERE rut_tecnico = '98765432-1';

-- If not, create test technician:
INSERT INTO Tecnicos (rut_tecnico, nombre, telefono, email, creado_en)
VALUES ('98765432-1', 'Test Technician', '+56912345678', 'test@test.cl', NOW());
```

---

## Test Output

### Successful Test Run

```
========================================
  Cartec API Test Suite
========================================
Testing Health Check...
✓ Health check returns 200
✓ Health check returns ok status
✓ Health check includes timestamp

Testing OT Creation Validation...
✓ Missing cliente returns 400
✓ Invalid RUT returns 400
✓ Invalid email returns 400
✓ Invalid GPS provider returns 400
✓ No vehicles returns 400

Testing All GPS Providers...
✓ GPS provider 'gpsimple' accepted
✓ GPS provider 'entel' accepted
✓ GPS provider 'tattersall' accepted
✓ GPS provider 'cemin' accepted
✓ GPS provider 'carflex' accepted

========================================
  Test Results
========================================
Passed: 13
Failed: 0
Total: 13

All tests passed! ✓
```

---

## Troubleshooting

### API Not Responding

```bash
# Check service status
sudo systemctl status cartec-api

# Check logs
sudo journalctl -u cartec-api -n 50

# Restart service
sudo systemctl restart cartec-api
```

### Connection Refused

Ensure the API is running on the correct port:
```bash
curl http://localhost:3000/api/health
```

### Tests Timeout

Check if firewall is blocking the port:
```bash
sudo ufw status
```

### Database Errors in OT Creation Test

This is expected if database is not set up. The validation tests will still pass.

To see the actual error:
```bash
curl -X POST http://localhost:3000/api/ot/create \
  -H "Content-Type: application/json" \
  -d @test_data.json | python3 -m json.tool
```

---

## CI/CD Integration

### Exit Codes

Both test files return appropriate exit codes:
- `0` - All tests passed
- `1` - Some tests failed

### Example CI Script

```bash
#!/bin/bash
set -e

# Start API (if not running)
sudo systemctl start cartec-api

# Wait for API to be ready
sleep 2

# Run tests
node test/api.test.js

# Or use bash tests
# ./test/run_tests.sh

echo "Tests completed successfully"
```

---

## Adding New Tests

### Node.js Test

Add a new test function in `api.test.js`:

```javascript
async function testNewFeature() {
    console.log(`\n${colors.blue}Testing New Feature...${colors.reset}`);
    
    try {
        const response = await httpRequest('POST', '/api/new-endpoint', data);
        assertEqual(response.statusCode, 200, 'New feature returns 200');
        // Add more assertions
    } catch (error) {
        console.log(`${colors.red}✗${colors.reset} Test failed: ${error.message}`);
        failedTests++;
    }
}
```

Then call it in `runTests()`:
```javascript
await testNewFeature();
```

### Bash Test

Add a new test section in `run_tests.sh`:

```bash
echo -e "${BLUE}Test N: New Feature${NC}"
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$API_URL/api/new-endpoint" \
  -H "Content-Type: application/json" \
  -d '{"test": "data"}')
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)

if [ "$HTTP_CODE" = "200" ]; then
    echo -e "${GREEN}✓ New feature test passed${NC}"
    ((PASSED++))
else
    echo -e "${RED}✗ New feature test failed${NC}"
    ((FAILED++))
fi
echo ""
```

---

## Support

For issues or questions about tests:
- Check API logs: `sudo journalctl -u cartec-api -f`
- Verify database connection
- Ensure all dependencies are installed

