# Testing & Troubleshooting

Source: https://appfig.com/docs/testing

Complete guide to testing your feature flags and debugging issues.

## Testing Your Rules

### 1. Enable Debug Logging

**Unity:**
```csharp
// SDK automatically logs to Console
// Look for lines starting with [AppFig]

// Check what's loaded
var debug = AppFig.GetDebugInfo();
Debug.Log($"Rules: {debug.rules.Count}");
Debug.Log($"Events: {debug.events.Count}");
```

**React:**
```typescript
await SmartConfig.init({
  userId: 'test-user',
  tenant: 'my-app',
  source: 'cdn',
  debugMode: true  // Enable verbose logging
});

// Console will show:
// [SmartConfig] 🔍 getConfig called for: welcome_message
// [SmartConfig] 🔍 Rule matches: true
// [SmartConfig] 🔍 Returning value: "Hello!"
```

### 2. Test Event Logging

Log events and verify they're tracked:

**Unity:**
```csharp
// Log event
AppFig.LogEvent("test_event");

// Check it was recorded
var events = AppFig.GetEventHistory();
Debug.Log($"Total events logged: {events.Count}");

// Verify specific event exists
var testEvents = events.FindAll(e => e.name == "test_event");
Debug.Log($"Found {testEvents.Count} test_event occurrences");
```

**React:**
```typescript
// Log event
SmartConfig.logEvent('test_event', { param: 'value' });

// Check it was recorded
const events = SmartConfig.getEventHistory();
console.log('Total events:', events.length);
console.log('Events:', events.map(e => e.name));
```

### 3. Test Properties

Set properties and verify they're stored:

**Unity:**
```csharp
// Set properties
AppFig.SetUserProperty("test_property", "test_value");
AppFig.SetDeviceProperty("test_device", "test_device_value");

// Check debug info
var debug = AppFig.GetDebugInfo();
Debug.Log($"User properties: {debug.userProperties.Count}");
Debug.Log($"Device properties: {debug.deviceProperties.Count}");
```

**React:**
```typescript
// Set properties
SmartConfig.setUserProperties({ test_property: 'test_value' });

// Check debug info
const debug = SmartConfig.getDebugInfo();
console.log('User properties:', debug.userProperties);
console.log('Device properties:', debug.deviceProperties);
```

### 4. Test Rule Evaluation

Create a simple test rule:

```json
{
  "test_feature": [
    {
      "conditions": {
        "events": {
          "mode": "simple",
          "operator": "AND",
          "items": [
            {
              "key": "test_event",
              "count": {
                "operator": ">=",
                "value": 1
              }
            }
          ]
        },
        "user_properties": [],
        "device": []
      },
      "value": "success"
    }
  ]
}
```

Test it step-by-step:

```csharp
// Unity
// 1. Before logging event
string value1 = AppFig.GetFeatureValue("test_feature");
Debug.Log($"Before event: {value1}"); // null

// 2. Log the event
AppFig.LogEvent("test_event");

// 3. After logging event
string value2 = AppFig.GetFeatureValue("test_feature");
Debug.Log($"After event: {value2}"); // "success"
```

### 5. Test Time Windows

```json
{
  "recent_activity": [
    {
      "conditions": {
        "events": {
          "mode": "simple",
          "operator": "AND",
          "items": [
            {
              "key": "app_open",
              "count": { "operator": ">=", "value": 1 },
              "within_last_days": 7
            }
          ]
        },
        "user_properties": [],
        "device": []
      },
      "value": "active"
    }
  ]
}
```

Test:
```csharp
AppFig.LogEvent("app_open");
string status = AppFig.GetFeatureValue("recent_activity");
Debug.Log($"Status: {status}"); // "active"

// To test old events, you can't easily fake timestamps
```

## Common Issues

### Issue: Features Always Return Null

**Symptoms:**
- `GetFeatureValue()` always returns `null`
- `IsFeatureEnabled()` always returns `false`

**Diagnosis:**
```csharp
// Check if rules are loaded
var debug = AppFig.GetDebugInfo();
Debug.Log($"Rules loaded: {debug.rules.Count}");

if (debug.rules.Count == 0) {
    Debug.LogError("No rules loaded!");
}
```

**Common causes:**

1. **Rules not loaded**
   - Check console for `[AppFig] ✅ Loaded X rule(s)` message
   - Verify internet connection
   - Check API key is correct
   - Verify company/tenant IDs

2. **Feature name mismatch**
   ```csharp
   // Feature in JSON: "doubleXP"
   // Your code: "double_xp"  ← Case mismatch!

   // Solution: Match exactly
   AppFig.GetFeatureValue("doubleXP");
   ```

4. **Conditions don't match**
   ```csharp
   // Rule requires 10 level_complete events
   // But you only logged 5

   // Check event count
   var events = AppFig.GetEventHistory();
   var levelEvents = events.FindAll(e => e.name == "level_complete");
   Debug.Log($"Level events: {levelEvents.Count}");
   ```

### Issue: Rules Not Updating

**Symptoms:**
- Changed rules in dashboard
- App still uses old rules

**Solutions:**

1. **Wait for auto-refresh**
   - Default: 10 seconds
   - Check console for `[AppFig] 🔄 Auto-refresh` message

2. **Manual refresh**
   ```csharp
   AppFig.RefreshRules();
   ```

3. **Check auto-refresh is enabled**
   ```csharp
   // Enable if disabled
   AppFig.SetAutoRefresh(true);
   ```

4. **Clear cache**
   ```csharp
   // Restart app to clear cached rules
   // Or call RefreshRules()
   ```

### Issue: Initialization Failed

**Symptoms:**
- `[AppFig] Failed to load rules` in console
- SDK methods throw errors

**Solutions:**

1. **Check credentials**
   ```csharp
   // Verify all parameters are correct - use Firestore document IDs
   AppFig.Init(
       "acmegames",      // Company ID from Firestore (not display name)
       "spaceshooter",   // Tenant ID from Firestore (not display name)
       "prod",           // or "dev"
       "your-api-key"    // API key from dashboard
   );
   ```

2. **Check network**
   - Verify internet connection
   - Check firewall isn't blocking requests
   - Try from different network

3. **Check endpoint**
   - Console will show URL being fetched
   - Verify URL is accessible in browser


### Issue: Events Not Counted

**Symptoms:**
- Logged 10 events
- Rule says count >= 10
- Feature still returns null

**Diagnosis:**
```csharp
// Check event history
var events = AppFig.GetEventHistory();
Debug.Log($"Total events: {events.Count}");

// Check specific event
var targetEvents = events.FindAll(e => e.name == "level_complete");
Debug.Log($"level_complete events: {targetEvents.Count}");

// Check if time window is restricting
// Rules with within_last_days will filter out old events
```

**Solutions:**

1. **Event name mismatch**
   ```csharp
   // Rule: "level_complete"
   // Code: "levelComplete"  ← Mismatch!

   // Fix: Match exactly
   AppFig.LogEvent("level_complete");
   ```

2. **Time window restriction**
   ```json
   {
     "key": "level_complete",
     "count": { "operator": ">=", "value": 10 },
     "within_last_days": 7  // ← Only counts last 7 days!
   }
   ```

3. **Parameter mismatch**
   ```json
   // Rule requires:
   {
     "key": "purchase",
     "param": {
       "amount": {
         "operator": ">",
         "value": 10
       }
     }
   }
   ```

   ```csharp
   // Your code doesn't include param
   AppFig.LogEvent("purchase");  // Won't match!

   // Fix: Include required parameter
   AppFig.LogEvent("purchase", new Dictionary<string, string> {
       { "amount", "15" }
   });
   ```

### Issue: Properties Not Working

**Symptoms:**
- Set user/device property
- Rule checks property
- Feature still returns null

**Diagnosis:**
```csharp
// Check properties are set
var debug = AppFig.GetDebugInfo();
Debug.Log($"User props: {string.Join(", ", debug.userProperties.Keys)}");
Debug.Log($"Device props: {string.Join(", ", debug.deviceProperties.Keys)}");

// Check specific property value
if (debug.userProperties.TryGetValue("subscription_tier", out string value)) {
    Debug.Log($"subscription_tier = {value}");
} else {
    Debug.Log("subscription_tier not set!");
}
```

**Solutions:**

1. **Property not set**
   ```csharp
   // Make sure you set it before checking feature
   AppFig.SetUserProperty("subscription_tier", "premium");

   // Then check feature
   if (AppFig.IsFeatureEnabled("premium_features")) {
       // ...
   }
   ```

2. **Property name/value mismatch**
   ```json
   // Rule checks:
   {
     "key": "subscription_tier",
     "value": { "operator": "==", "value": "premium" }
   }
   ```

   ```csharp
   // Your code:
   AppFig.SetUserProperty("subscriptionTier", "Premium");
   // Wrong! Case matters for both key and value

   // Fix:
   AppFig.SetUserProperty("subscription_tier", "premium");
   ```

3. **Type mismatch**
   ```json
   // Rule expects string "true"
   {
     "key": "is_verified",
     "value": { "operator": "==", "value": "true" }
   }
   ```

   ```csharp
   // Your code:
   AppFig.SetUserProperty("is_verified", "True");  // Capital T!

   // Fix: Match exactly
   AppFig.SetUserProperty("is_verified", "true");
   ```

## Testing Workflows

### Test Sequence: New User Flow

```csharp
// 1. Reset session (simulate new user)
AppFig.ResetSession();

// 2. Initialize
AppFig.Init(...);

// 3. Check welcome bonus (should be available)
string bonus1 = AppFig.GetFeatureValue("welcome_bonus");
Debug.Log($"New user bonus: {bonus1}"); // "on"

// 4. Make a purchase
AppFig.LogEvent("purchase_made");

// 5. Check bonus again (should be gone if rule excludes purchasers)
string bonus2 = AppFig.GetFeatureValue("welcome_bonus");
Debug.Log($"After purchase bonus: {bonus2}"); // null
```

### Test Sequence: Engagement Flow

```csharp
// 1. User opens app
AppFig.LogEvent("app_open");

// 2. Completes levels
for (int i = 0; i < 10; i++) {
    AppFig.LogEvent("level_complete");
}

// 3. Check veteran bonus (should be available at 10 completions)
string bonus = AppFig.GetFeatureValue("veteran_bonus");
Debug.Log($"Veteran bonus: {bonus}"); // "2x"
```

### Test Sequence: Platform Check

```csharp
// 1. Check auto-detected platform
var debug = AppFig.GetDebugInfo();
string platform = debug.deviceProperties["platform"];
Debug.Log($"Platform: {platform}");

// 2. Check platform-specific feature
string controls = AppFig.GetFeatureValue("mobile_controls");
Debug.Log($"Mobile controls: {controls}");

// Should be "on" for iOS/Android, null for desktop
```

## Performance Testing

### Measure Feature Check Speed

```csharp
var stopwatch = System.Diagnostics.Stopwatch.StartNew();

// First call (evaluates rules)
string value1 = AppFig.GetFeatureValue("test_feature");

stopwatch.Stop();
Debug.Log($"First call: {stopwatch.ElapsedTicks} ticks");

stopwatch.Restart();

// Second call (cached)
string value2 = AppFig.GetFeatureValue("test_feature");

stopwatch.Stop();
Debug.Log($"Second call: {stopwatch.ElapsedTicks} ticks");

// Expected results:
// First call: ~1000-10000 ticks (~100 microseconds)
// Second call: ~10-100 ticks (~0.5 microseconds)
```

### Memory Usage

```csharp
// Get memory before
long memBefore = System.GC.GetTotalMemory(false);

// Initialize SDK
AppFig.Init(...);

// Get memory after
long memAfter = System.GC.GetTotalMemory(false);
long memUsed = memAfter - memBefore;

Debug.Log($"SDK memory usage: {memUsed / 1024} KB");

// Typical: 100-500 KB depending on rule complexity
```

## Troubleshooting Checklist

When features don't work as expected:

- [ ] Rules loaded? Check console for load confirmation
- [ ] Feature name matches exactly? (case-sensitive)
- [ ] Events logged? Check event history
- [ ] Properties set? Check debug info
- [ ] Time windows correct? Recent enough events?
- [ ] Parameters match? Check event params
- [ ] Operators correct? `>=` not `>`, `==` not `=`
- [ ] AND/OR logic correct? Check operators
- [ ] NOT logic intended? Check `not` field
- [ ] Multiple rules? First match wins
- [ ] Cache cleared? Call RefreshRules() or restart

## Next Steps

- **[Rule Schema](https://appfig.com/docs/rule-schema)** - Complete rule reference
- **[Unity SDK](https://appfig.com/docs/unity-integration)** - Unity integration
- **[React SDK](https://appfig.com/docs/react-web-guide)** - React integration
