# AI Standard: Tests vs Production Code Philosophy

## Fundamental Principle

> **Tests MUST ALWAYS reflect production code logic, not the other way around.**

Tests are executable specifications that document and validate the system's actual behavior. When a test fails, the first instinct should be to ask: **"Is the code wrong or is the test wrong?"**

---

## When to Modify Code for Tests

### ✅ Valid Cases

1. **Real Bug Identified**
   - Test exposes a legitimate production error
   - Examples: TypeError, inconsistent format, incorrect logic, memory leaks
   - **Action:** Fix code + document the bug

2. **Confusing or Ambiguous Logic**
   - Code has undefined or unclear behavior
   - Multiple possible interpretations
   - **Action:** Discuss with user → Decide → Document

3. **Agreed Architectural Refactoring**
   - Change previously approved in backlog
   - Documented design improvement
   - **Action:** Implement according to plan + update tests

---

## When to Fix Tests (NOT Code)

### ✅ Common Cases

1. **Outdated Test**
   - Code evolved, test became obsolete
   - Test reflects old version of behavior
   
2. **Test with Incorrect Expectations**
   - Assumes behavior that never existed
   - Wrong schema, validations, or constraints

3. **Test Testing Implementation vs Behavior**
   - Mocking private methods that changed
   - Dependencies on implementation details

---

## Validation Process

```
┌─────────────────┐
│  Test Fails     │
└────────┬────────┘
         │
         ▼
┌─────────────────────────────┐
│ Is it a real bug?           │
│ (TypeError, incorrect       │
│ logic, inconsistent         │
│ format)                     │
└─┬───────────────────────┬───┘
  │ YES                   │ NO
  ▼                       ▼
┌──────────────────┐   ┌──────────────────────┐
│ Fix code         │   │ Hard to test?        │
│ + Document bug   │   │ (overload: errors,   │
└──────────────────┘   │ test contamination,  │
                       │ complex workarounds) │
                       └─┬────────────────┬───┘
                         │ YES           │ NO
                         ▼               ▼
                  ┌──────────────┐  ┌──────────────────┐
                  │ Consider     │  │ Confusing logic? │
                  │ Architectural│  └─┬────────────┬───┘
                  │ Refactor     │    │ YES       │ NO
                  │ (Service     │    ▼           ▼
                  │ Pattern)     │  ┌─────────┐ ┌────────────┐
                  └──────────────┘  │ Consult │ │ Fix test   │
                                    │ user    │ │ to reflect │
                                    └─────────┘ │ reality    │
                                                └────────────┘
```

---

## Concrete Examples

### Example 1: Real Bug - Inconsistent Format ✅

**Situation:** Test fails with `Undefined array key 'success'`

**Analysis:**
```php
// Código devuelve (en algunos casos)
['chunk_individual_success' => 2]

// Pero TODOS los consumidores esperan
['success' => 2]
```

**Decision:** ✅ MODIFY CODE (real bug)

**Reason:** 18 production services depend on `['success']`. Code has a path that returns inconsistent format.

**Action:**
1. Normalize response format

---

### Example 2: Incorrect Test - Divergent Schema ❌

**Situation:** Test fails with `NOT NULL constraint violation`

**Analysis:**
```php
// Test crea tabla con
$table->string('name')->nullable();

// Pero producción tiene
$table->string('name'); // NOT NULL
```

**Decision:** ❌ DO NOT MODIFY CODE - FIX TEST

**Reason:** Test uses a schema that doesn't reflect production reality. Changing production would break existing validations.

**Action:**
1. Update test to use correct schema (`name` NOT NULL)
2. Adjust expectations: record without `name` should fail

---

## Warning Signs (STOP and Consult)

🚨 Stop and consult if you're about to:

- ✋ Change database schema to make test pass
- ✋ Relax production validations
- ✋ Change data types (nullable, defaults) without impact analysis
- ✋ Modify behavior affecting multiple services
- ✋ Change business logic without clear bug

🎯 **Consider Architectural Refactor if:**

- ✋ Tests require complex workarounds (mocking internals, bypassing encapsulation)
- ✋ `overload:`/`alias:` mocks causing "Cannot redeclare" errors → Use Service Pattern
- ✋ Test contamination across suite → Check cleanup order
- ✋ Production code hard to test without hacks → Question the architecture first

---

## Anti-Patterns

### ❌ Anti-Pattern 1: "Test-Driven Code Modification"
```php
// ❌ MALO
// "El test espera X, cambio el código para que haga X"
if ($testMode) {
    return ['success' => $count]; // Para que pase el test
}
```

### ✅ Correct Pattern: "Reality-Driven Test Modification"
```php
// ✅ BUENO
// "Producción hace Y, actualizo test para validar Y"
expect($result)->toHaveKey('success'); // Valida comportamiento real
```

---

### ❌ Anti-Patrón 2: "Relaxing Constraints for Tests"
```php
// ❌ MALO
$table->string('email')->nullable(); // Para que test pase
```

### ✅ Patrón Correcto: "Enforcing Real Constraints"
```php
// ✅ BUENO
$table->string('email'); // NOT NULL como en producción
// Test debe validar que falla sin email
expect($result['errors'])->toHaveCount(1);
expect($result['errors'][0]['error'])->toContain('NOT NULL');
```
