# 🧪 Aegilock Fraud Detection API - Test Suite

Umfassende Test-Suite für die Aegilock WooCommerce Fraud Detection API mit mehreren Testebenen und automatischer Berichtsgenerierung.

## 📋 Übersicht

Diese Test-Suite bietet:

- **Baseline Tests** - Normale Transaktionen und Standard-Szenarien
- **High-Risk Pattern Tests** - Typische Betrugsmuster (Packstation + COD, Velocity Attacks, etc.)
- **Edge Case Tests** - Grenzfälle und ungewöhnliche Szenarien
- **Validation Tests** - API Response-Struktur und Datenvalidierung
- **Security Tests** - SQL Injection, XSS, Rate Limiting
- **Performance Tests** - Latenz, Durchsatz, Concurrent Load
- **Business Logic Tests** - Komplexe Geschäftslogik-Szenarien

## 🚀 Schnellstart

### 1. API Key konfigurieren

```bash
export API_KEY="your_actual_api_key_here"
```

### 2. Alle Tests ausführen

```bash
cd /var/www/content-protector-release/wp-plugin/aegilock-transaction-guardian-for-woocommerce
chmod +x run-all-tests.sh
./run-all-tests.sh
```

### 3. Spezifische Tests ausführen

```bash
# Nur Bash-Tests
chmod +x comprehensive-api-tests.sh
./comprehensive-api-tests.sh

# Nur Python Business Logic Tests
python3 business-logic-tests.py --api-key YOUR_API_KEY

# Nur Validation Tests
node response-validator.js
```

## 📁 Test-Dateien

| Datei | Beschreibung | Sprache |
|-------|-------------|---------|
| `comprehensive-api-tests.sh` | Umfassende Bash-basierte API Tests | Bash |
| `business-logic-tests.py` | Erweiterte Business Logic Tests | Python |
| `response-validator.js` | Response-Struktur Validierung | JavaScript |
| `run-all-tests.sh` | Master Test Runner mit HTML Report | Bash |

## 🔧 Konfiguration

### Environment Variables

```bash
# API Konfiguration
export API_URL="https://api.aegilock.de/woocommerce/fraud-check"
export API_KEY="your_api_key"

# Test Optionen
export SKIP_PYTHON=1    # Python Tests überspringen
export SKIP_NODE=1      # Node.js Tests überspringen
```

### Command Line Optionen

```bash
./run-all-tests.sh --api-key YOUR_KEY --api-url https://custom-url.com
./run-all-tests.sh --skip-python --skip-node
```

## 📊 Test-Kategorien im Detail

### 1. Baseline Tests

**Normale, legitime Transaktionen:**

```bash
# Deutscher Stammkunde
curl -X POST $API_URL \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "order_id": "TEST-001",
    "order_amount": 89.99,
    "customer_email": "max.mueller@gmail.com",
    "billing_country": "DE",
    "is_guest": false,
    "previous_orders": 12
  }'
```

**Erwartung:** `risk_score < 0.3`, `decision: APPROVE`

### 2. High-Risk Pattern Tests

**Packstation + Nachnahme (DACH-spezifisch):**

```bash
curl -X POST $API_URL \
  -d '{
    "order_amount": 899.99,
    "shipping_address": "Packstation 123",
    "payment_method": "cod",
    "is_packstation": true,
    "is_guest": true
  }'
```

**Erwartung:** `risk_score > 0.8`, `decision: BLOCK`

### 3. Velocity Attack Tests

```bash
# 5 schnelle Requests von derselben IP
for i in {1..5}; do
  curl -X POST $API_URL \
    -d "{\"customer_ip\": \"185.220.101.45\", \"order_id\": \"VEL-$i\"}"
done
```

**Erwartung:** Ab 3. Request: `velocity_flag: true`, `risk_score > 0.9`

### 4. Geographic Risk Tests

```bash
# Billing/Shipping Mismatch
curl -X POST $API_URL \
  -d '{
    "billing_country": "DE",
    "shipping_country": "NG",
    "order_amount": 2000
  }'
```

**Erwartung:** `risk_score > 0.85`, `decision: BLOCK`

## 🛡️ Security Tests

### SQL Injection Protection

```bash
curl -X POST $API_URL \
  -d '{
    "customer_email": "test@test.com; DROP TABLE orders;--",
    "order_amount": 100
  }'
```

**Erwartung:** `HTTP 400` oder `403`

### Rate Limiting

```bash
# 30 schnelle Requests
for i in {1..30}; do
  curl -X POST $API_URL -d "{\"order_id\": \"RATE-$i\"}" &
done
```

**Erwartung:** `HTTP 429` nach X Requests

## ⚡ Performance Tests

### Latenz Tests

- **Einzelne Requests:** < 50ms Antwortzeit
- **95th Percentile:** < 100ms
- **Concurrent Load:** 20 parallele Requests

### Load Testing

```python
# Python concurrent test
with ThreadPoolExecutor(max_workers=10) as executor:
    futures = [executor.submit(make_request, test_data) for _ in range(50)]
```

## 📈 Business Logic Tests

### Risiko-Kategorisierung

| Risk Score | Kategorie | Erwartete Decision |
|------------|-----------|-------------------|
| 0.0 - 0.3  | Low       | APPROVE          |
| 0.3 - 0.6  | Medium    | APPROVE/REVIEW   |
| 0.6 - 0.8  | High      | REVIEW           |
| 0.8 - 1.0  | Very High | BLOCK            |

### Payment Method Risks

```python
payment_risks = {
    "sepa": "low",
    "paypal": "low", 
    "credit_card": "medium",
    "cod": "high",
    "cod + packstation": "very_high"
}
```

## 📋 Response Validation

### Required Fields

```javascript
const required = ['decision', 'risk_score', 'confidence'];
const validDecisions = ['APPROVE', 'REVIEW', 'BLOCK'];
```

### Optional Fields

- `fraud_indicators[]`
- `velocity_detected`
- `blacklist_match`
- `whitelist_match`
- `ip_reputation`
- `processing_time_ms`

## 📊 Reporting

### HTML Report

Nach dem Test-Lauf wird automatisch ein HTML-Report generiert:

```
test-results/master_test_report_TIMESTAMP.html
```

Der Report enthält:
- ✅ Test Overview mit Status aller Kategorien
- 🛡️ Security Test Results mit Details
- ⚡ Performance Metrics und Benchmarks
- 📋 Detailed Logs aller Test-Läufe

### Log Files

```
test-results/
├── bash_tests_TIMESTAMP.log
├── python_tests_TIMESTAMP.log
├── validation_tests_TIMESTAMP.log
├── security_tests_TIMESTAMP.log
├── performance_tests_TIMESTAMP.log
└── master_test_report_TIMESTAMP.html
```

## 🔍 Troubleshooting

### Häufige Probleme

**API Key Fehler:**
```bash
export API_KEY="correct_key_here"
./run-all-tests.sh --api-key $API_KEY
```

**Python Dependencies:**
```bash
pip3 install requests
```

**Node.js nicht verfügbar:**
```bash
./run-all-tests.sh --skip-node
```

**Rate Limiting:**
```bash
# Warten zwischen Test-Läufen
sleep 60
./run-all-tests.sh
```

### Debug Mode

```bash
# Verbose Output
set -x
./comprehensive-api-tests.sh

# Einzelne Tests debuggen
curl -v -X POST $API_URL -d '{"order_id":"DEBUG"}'
```

## 📋 Test Checklist

Vor dem Produktions-Deployment:

- [ ] Alle Baseline Tests bestanden
- [ ] High-Risk Patterns korrekt erkannt  
- [ ] Security Tests erfolgreich
- [ ] Performance unter 100ms
- [ ] Rate Limiting funktioniert
- [ ] Business Logic konsistent
- [ ] Response Validation fehlerfrei

## 🤝 Erweitere die Tests

### Neue Test Cases hinzufügen

1. **Bash Tests** - Edit `comprehensive-api-tests.sh`
2. **Python Tests** - Edit `business-logic-tests.py`
3. **Validation** - Edit `response-validator.js`

### Custom Test Patterns

```python
# In business-logic-tests.py
custom_tests = [
    {
        "name": "Custom fraud pattern",
        "data": {"special_field": "test_value"},
        "expected_risk": "high"
    }
]
```

## 📚 Weitere Ressourcen

- **API Dokumentation:** [Internal API Docs]
- **WooCommerce Integration:** `aegilock-transaction-guardian.php`
- **Monitoring:** `/wp-admin/admin.php?page=aegilock-fraud-logs`

---

**💡 Tipp:** Führe die Tests regelmäßig aus, besonders nach API-Änderungen oder neuen Fraud-Regeln!