# Quick Start Guide - ColaFlow Integration Tests

## TL;DR - Run Tests Now

```bash
# 1. Navigate to project root
cd c:\Users\yaoji\git\ColaCoder\product-master\colaflow-api

# 2. Build solution (stop API server first if running)
dotnet build

# 3. Run all integration tests
dotnet test tests/Modules/Identity/ColaFlow.Modules.Identity.IntegrationTests

# Done! ✓
```

## What These Tests Cover

### Day 5 - Phase 1: Refresh Token (9 tests)
- ✓ Register/Login returns access + refresh tokens
- ✓ Refresh token generates new token pair
- ✓ Old refresh tokens cannot be reused (rotation)
- ✓ Invalid refresh tokens fail
- ✓ Logout revokes refresh tokens
- ✓ User identity is maintained across refresh
- ✓ Multiple refresh operations work

### Day 5 - Phase 2: RBAC (11 tests)
- ✓ TenantOwner role assigned on registration
- ✓ JWT contains role claims
- ✓ Role persists across login/refresh
- ✓ /api/auth/me returns role information
- ✓ Protected endpoints enforce role requirements

### Day 4 - Regression (10 tests)
- ✓ Registration and login work
- ✓ Password hashing (BCrypt) verification
- ✓ JWT authentication and authorization
- ✓ Protected endpoint access control

**Total: 30 Integration Tests**

## Running Specific Test Categories

### Only Refresh Token Tests
```bash
dotnet test --filter "FullyQualifiedName~RefreshTokenTests"
```

### Only RBAC Tests
```bash
dotnet test --filter "FullyQualifiedName~RbacTests"
```

### Only Authentication Tests (Regression)
```bash
dotnet test --filter "FullyQualifiedName~AuthenticationTests"
```

## Expected Output

### Successful Run
```
Test run for ColaFlow.Modules.Identity.IntegrationTests.dll (.NETCoreApp,Version=v9.0)
Microsoft (R) Test Execution Command Line Tool Version 17.14.1 (x64)

Starting test execution, please wait...
A total of 1 test files matched the specified pattern.

Passed!  - Failed:     0, Passed:    30, Skipped:     0, Total:    30, Duration: 15s
```

### Failed Test Example
```
Failed RefreshTokenTests.RefreshToken_ShouldReturnNewTokenPair [125 ms]
  Error Message:
   Expected response.StatusCode to be OK, but found Unauthorized.
  Stack Trace:
     at RefreshTokenTests.RefreshToken_ShouldReturnNewTokenPair()
```

## Test Database

### In-Memory Database (Default)
- No setup required
- Fast execution
- Perfect for CI/CD

### Real PostgreSQL (Optional)
To run tests against real PostgreSQL:

1. Ensure PostgreSQL is running:
   ```bash
   # Check if PostgreSQL is running
   pg_isready
   ```

2. Edit test fixture in test files:
   ```csharp
   // Change from
   public class RefreshTokenTests : IClassFixture<DatabaseFixture>

   // To
   public class RefreshTokenTests : IClassFixture<RealDatabaseFixture>
   ```

3. Run tests normally

## Troubleshooting

### Issue: Build fails with "file locked by another process"
**Solution**: Stop the API server
```bash
taskkill /F /IM ColaFlow.API.exe
```

### Issue: Tests fail with "Connection refused"
**Solution**: Tests use In-Memory database by default, no connection needed. If you modified tests to use PostgreSQL, ensure it's running.

### Issue: Tests are slow
**Solution**:
1. Verify you're using In-Memory database (default)
2. Run specific test category instead of all tests
3. Disable parallel execution for debugging:
   ```csharp
   [assembly: CollectionBehavior(DisableTestParallelization = true)]
   ```

### Issue: "Could not find test file"
**Solution**: Rebuild the project
```bash
dotnet clean
dotnet build
dotnet test
```

## Viewing Test Details

### Visual Studio
1. Open Test Explorer: `Test` → `Test Explorer`
2. Run all tests or specific test
3. View detailed output in Test Explorer window

### JetBrains Rider
1. Open Unit Tests window: `View` → `Tool Windows` → `Unit Tests`
2. Run tests with `Ctrl+U, Ctrl+R`
3. View test results in Unit Tests window

### Command Line (Detailed Output)
```bash
dotnet test --logger "console;verbosity=detailed"
```

## Integration with Day 5 Implementation

These tests verify:

### 1. Refresh Token Flow
```
User Registration → Access Token + Refresh Token
              ↓
        Use Access Token (expires in 15 min)
              ↓
  Call /api/auth/refresh with Refresh Token
              ↓
     New Access Token + New Refresh Token
              ↓
    Old Refresh Token is invalidated (rotation)
```

### 2. RBAC Flow
```
Tenant Registration → User assigned "TenantOwner" role
              ↓
         JWT includes role claims
              ↓
        Login/Refresh preserves role
              ↓
    Protected endpoints check role claims
```

## Test Assertions

Tests use **FluentAssertions** for readable assertions:

```csharp
// HTTP Status
response.StatusCode.Should().Be(HttpStatusCode.OK);

// Token validation
result.AccessToken.Should().NotBeNullOrEmpty();
result.RefreshToken.Should().NotBe(oldRefreshToken);

// Role verification
TestAuthHelper.HasRole(accessToken, "TenantOwner").Should().BeTrue();
```

## Next Steps

After tests pass:
1. ✓ Day 5 Phase 1 (Refresh Token) verified
2. ✓ Day 5 Phase 2 (RBAC) verified
3. ✓ Day 4 regression tests pass
4. Ready to proceed to Day 6: Email Verification or MCP integration

## CI/CD Ready

This test project is CI/CD ready:
- No manual setup required (uses In-Memory database)
- Isolated tests (no external dependencies)
- Fast execution (~15-30 seconds for 30 tests)
- Deterministic results
- Easy to integrate with GitHub Actions, Azure DevOps, Jenkins, etc.

## Questions?

- See `README.md` for detailed documentation
- Check test files for implementation examples
- Review `TestAuthHelper.cs` for helper methods

---

**Run tests now and verify your Day 5 implementation!**

```bash
cd c:\Users\yaoji\git\ColaCoder\product-master\colaflow-api
dotnet test tests/Modules/Identity/ColaFlow.Modules.Identity.IntegrationTests
```
