# SensFRX Plugin Testing Guide

## Phase 4: Comprehensive Testing

This guide covers all testing aspects for the database security improvements implemented in Phase 2 and Phase 3.

---

## 1. Automated Unit Testing

### Running Unit Tests

**Option A: Using PHPUnit (if installed)**
```bash
cd sensfrx-fraud-prevention-for-woocommerce
phpunit
```

**Option B: Using Simple Test Runner (no PHPUnit required)**
```bash
cd sensfrx-fraud-prevention-for-woocommerce
php tests/run-tests.php
```

### Expected Results
- ✅ All 18 unit tests should pass
- ✅ 100% success rate
- ✅ No errors or exceptions

### What the Unit Tests Cover
1. Table name validation (whitelisting)
2. Safe SELECT queries with various parameters
3. Safe INSERT operations
4. Safe UPDATE operations
5. Safe DELETE operations
6. SQL injection prevention
7. Column sanitization
8. ORDER BY sanitization
9. Edge cases (empty values, null values)
10. GDPR user data deletion
11. Error logging (debug mode)
12. Invalid table handling
13. Malicious input rejection

---

## 2. Manual Integration Testing

### Pre-Testing Checklist
- [ ] Backup your WordPress database
- [ ] Enable WordPress debug mode (`WP_DEBUG = true` in `wp-config.php`)
- [ ] Enable debug logging (`WP_DEBUG_LOG = true`)
- [ ] Clear all caches (WordPress, browser, plugin)
- [ ] Verify plugin is active

### Test Suite A: Transaction Processing (Critical)

#### Test 1: Standard Order Payment
1. Add products to cart
2. Proceed to checkout
3. Fill in billing details
4. Complete payment
5. **Verify:**
   - ✅ Order processes successfully
   - ✅ Fraud check executes
   - ✅ Custom fields are retrieved
   - ✅ Activity logged in database
   - ✅ No PHP errors in debug log

#### Test 2: Order Status Update
1. Go to WooCommerce → Orders
2. Change order status (e.g., Pending → Processing)
3. **Verify:**
   - ✅ Status updates successfully
   - ✅ Fraud check triggered
   - ✅ Data logged correctly
   - ✅ No errors

#### Test 3: Pre-Payment Validation
1. Attempt checkout with suspicious data (if configured)
2. **Verify:**
   - ✅ Pre-payment fraud check executes
   - ✅ Appropriate action taken (allow/challenge/deny)
   - ✅ Data saved correctly

### Test Suite B: User Registration & Login (Critical)

#### Test 4: WooCommerce Registration
1. Go to My Account page
2. Register a new user account
3. **Verify:**
   - ✅ Registration completes
   - ✅ Fraud check executes
   - ✅ Shadow activity retrieved
   - ✅ User data logged
   - ✅ No PHP errors

#### Test 5: WordPress Native Registration
1. Go to wp-login.php?action=register
2. Register a new user
3. **Verify:**
   - ✅ Registration successful
   - ✅ Fraud detection runs
   - ✅ Data saved correctly

#### Test 6: User Login
1. Log out of WordPress
2. Log in with existing credentials
3. **Verify:**
   - ✅ Login successful
   - ✅ Login tracking works
   - ✅ Sleep data retrieved correctly
   - ✅ No errors in logs

#### Test 7: Failed Login Attempt
1. Try logging in with wrong password
2. **Verify:**
   - ✅ Login fails appropriately
   - ✅ Failed attempt logged
   - ✅ No database errors

### Test Suite C: User Profile & Updates (Medium Priority)

#### Test 8: Profile Update
1. Log in as a user
2. Update profile information (email, name, etc.)
3. **Verify:**
   - ✅ Profile updates successfully
   - ✅ Fraud check runs
   - ✅ Custom field data retrieved
   - ✅ No errors

#### Test 9: Password Change
1. Go to profile page
2. Change password
3. **Verify:**
   - ✅ Password updates successfully
   - ✅ Fraud detection triggered
   - ✅ Activity logged

### Test Suite D: Webhooks & API Callbacks (Critical)

#### Test 10: Webhook Processing
1. Trigger a webhook event (if configured)
2. **Verify:**
   - ✅ Webhook received
   - ✅ Logout data retrieved correctly
   - ✅ API active status checked
   - ✅ Email templates loaded
   - ✅ No database errors

#### Test 11: API Callback
1. Trigger API callback from SensFRX service
2. **Verify:**
   - ✅ Callback processed
   - ✅ Tab data retrieved
   - ✅ Real activity data fetched
   - ✅ Response sent correctly

### Test Suite E: Admin Dashboard (Medium Priority)

#### Test 12: Dashboard Notifications
1. Go to WordPress admin dashboard
2. Check SensFRX notifications widget
3. **Verify:**
   - ✅ Notifications display correctly
   - ✅ Real activity data shown
   - ✅ Shadow activity data shown
   - ✅ No SQL errors

#### Test 13: Comments Fraud Check
1. Post a comment (if comment checking is enabled)
2. **Verify:**
   - ✅ Comment fraud check runs
   - ✅ Custom fields retrieved
   - ✅ Decision applied correctly

### Test Suite F: Edge Cases & Error Handling

#### Test 14: Empty Database Tables
1. Ensure some tables are empty
2. Perform operations that query those tables
3. **Verify:**
   - ✅ No PHP warnings about empty results
   - ✅ Code handles empty arrays gracefully
   - ✅ No fatal errors

#### Test 15: Large Data Sets
1. If possible, test with many records (100+)
2. **Verify:**
   - ✅ Queries execute in reasonable time
   - ✅ No memory issues
   - ✅ Pagination works (if implemented)

#### Test 16: Special Characters
1. Use special characters in forms (quotes, apostrophes, etc.)
2. **Verify:**
   - ✅ Data saved correctly (escaped properly)
   - ✅ No SQL syntax errors
   - ✅ Data retrieved accurately

---

## 3. Security Testing

### SQL Injection Tests (Should All Fail Safely)

#### Test 17: Attempt SQL Injection in Custom Fields
Try entering these values in custom field inputs:
- `'; DROP TABLE wp_users; --`
- `' OR '1'='1`
- `" OR 1=1 --`

**Expected:** 
- ✅ Values treated as strings, not SQL
- ✅ No database changes
- ✅ Data sanitized properly

#### Test 18: Malicious ORDER BY Injection
(Requires code modification for testing)
Try passing malicious values to ORDER BY clauses:
- `id; DELETE FROM table`
- `id UNION SELECT password FROM users`

**Expected:**
- ✅ Sanitization rejects malicious input
- ✅ Query fails safely or uses default ordering
- ✅ No data leakage

---

## 4. Performance Testing

### Test 19: Query Performance
1. Enable Query Monitor plugin (optional)
2. Perform typical operations
3. **Verify:**
   - ✅ Queries execute in < 100ms (typical)
   - ✅ No N+1 query problems
   - ✅ Proper use of caching

### Test 20: Concurrent Users
1. Simulate multiple users (if possible)
2. **Verify:**
   - ✅ No race conditions
   - ✅ Data integrity maintained
   - ✅ No deadlocks

---

## 5. GDPR Compliance Testing

### Test 21: User Data Deletion
1. Use plugin's GDPR deletion feature (if exposed)
2. Or call `SensFRX_DB_Helper::gdpr_delete_user_data($user_id)`
3. **Verify:**
   - ✅ User data removed from all plugin tables
   - ✅ Referential integrity maintained
   - ✅ No orphaned records

---

## 6. Error Log Analysis

### After All Tests
1. Check WordPress debug log: `wp-content/debug.log`
2. **Look for:**
   - ❌ Any PHP warnings or notices
   - ❌ Any SQL errors
   - ❌ Any "Undefined variable" errors
   - ❌ Any fatal errors
   
3. **Expected:**
   - ✅ Clean log (or only expected debug messages)
   - ✅ No deprecation notices
   - ✅ No security warnings

---

## 7. Cross-Browser Testing (Frontend)

If your plugin has frontend components:
1. Test on Chrome, Firefox, Safari, Edge
2. **Verify:**
   - ✅ Device fingerprinting works
   - ✅ AJAX calls complete
   - ✅ No console errors

---

## 8. Compatibility Testing

### WordPress Version
- Test on WordPress 5.9+ (minimum supported)
- Test on latest WordPress version

### WooCommerce Version
- Test on WooCommerce 6.0+ (minimum supported)
- Test on latest WooCommerce version

### PHP Version
- Verify works on PHP 7.4+
- Optimal on PHP 8.0+

---

## 9. Regression Testing Checklist

Ensure nothing broke from Phase 2 & 3 changes:

- [ ] All existing functionality still works
- [ ] No new PHP errors introduced
- [ ] Database queries return correct data
- [ ] Fraud detection still triggers
- [ ] Email notifications still send
- [ ] Webhook callbacks still process
- [ ] Admin pages load correctly
- [ ] No JavaScript console errors
- [ ] Plugin settings save correctly
- [ ] Uninstall process works

---

## 10. Test Results Documentation

### Record Results
For each test, document:
- Test name
- Date/time tested
- Result (Pass/Fail)
- Notes (any observations)
- Error messages (if any)

### Test Summary Template
```
Phase 4 Testing Summary
=======================
Date: ___________
Tester: ___________

Unit Tests:       [  ] Passed  [  ] Failed  (___/18 passed)
Integration Tests:[  ] Passed  [  ] Failed  (___/21 passed)
Security Tests:   [  ] Passed  [  ] Failed
Performance:      [  ] Acceptable  [  ] Needs improvement

Critical Issues Found: ___
Medium Issues Found:   ___
Minor Issues Found:    ___

Ready for Phase 5: [  ] Yes  [  ] No

Notes:
_________________________________
_________________________________
```

---

## 11. Troubleshooting

### Common Issues

**Issue: "Class not found" errors**
- Solution: Ensure DB Helper is loaded in `class-sensfrx.php`
- Check: Line 148 has correct `require_once` statement

**Issue: Empty results when data should exist**
- Solution: Verify table suffix in whitelist
- Check: `$valid_tables` array in DB Helper

**Issue: Tests fail on "Invalid table"**
- Solution: Table not in whitelist
- Check: Add table to `$valid_tables` array

**Issue: SQL syntax errors**
- Solution: Check column names and WHERE clauses
- Debug: Enable `WP_DEBUG` and check logs

---

## Success Criteria

Phase 4 is complete when:
- ✅ All 18 unit tests pass
- ✅ All critical integration tests pass (Suites A, B, D)
- ✅ No PHP errors in debug log
- ✅ No SQL injection vulnerabilities
- ✅ Performance is acceptable
- ✅ All existing functionality preserved
- ✅ GDPR compliance verified

---

## Next Steps

After Phase 4 completion:
- Move to **Phase 5: Standards Compliance** (WPCS, code quality)
- Move to **Phase 6: Documentation** (inline docs, user guide)

---

**Testing Status: [ ] In Progress  [ ] Complete**

**Approved by: ________________  Date: __________**

