# Project Patterns and Rules Analysis

**Generated:** 2025-01-08  
**Project:** ShopFlow Playwright Test Suite  
**Base URL:** https://shopflow.php8

---

## 📋 Table of Contents

1. [Project Structure](#project-structure)
2. [Test Organization](#test-organization)
3. [Naming Conventions](#naming-conventions)
4. [Code Style & Patterns](#code-style--patterns)
5. [Configuration Patterns](#configuration-patterns)
6. [Authentication Patterns](#authentication-patterns)
7. [Test Data Management](#test-data-management)
8. [Helper & Utility Patterns](#helper--utility-patterns)
9. [Assertion Patterns](#assertion-patterns)
10. [Cleanup Patterns](#cleanup-patterns)
11. [Documentation Patterns](#documentation-patterns)
12. [Execution Patterns](#execution-patterns)

---

## 📁 Project Structure

### Directory Organization

```
playwright_tests/
├── tests/                          # All test files organized by phase
│   ├── 01-authentication/          # Phase 1: Authentication tests
│   ├── 02-core-commerce/           # Phase 2: Core commerce tests
│   ├── 03-user-management/         # Phase 3: User management tests
│   ├── 04-partner-management/      # Phase 4: Partner management tests
│   ├── 05-price-management/        # Phase 5: Price management tests
│   └── 06-seller-portal/           # Phase 6: Seller portal tests
│
├── fixtures/                       # Playwright fixtures
│   ├── authenticated.fixture.ts    # Pre-authenticated browser state
│   └── test-data.fixture.ts        # Test data loading/tracking
│
├── helpers/                        # Reusable helper functions
│   ├── test-helpers.ts             # Common utilities (waits, validation, cleanup)
│   └── assertions.ts               # Custom business rule assertions
│
├── utils/                          # Utility modules
│   ├── authentication.ts           # Authentication logic
│   ├── email-2fa-fetcher.ts        # 2FA code fetching from Gmail
│   └── test-config.ts              # Configuration management
│
├── test-data/                      # Test data files (JSON)
│   ├── products.json               # Product test data
│   ├── orders.json                 # Order test data
│   └── cleanup-tracker.json        # Test data cleanup tracking
│
├── playwright.config.ts            # Playwright configuration
├── package.json                    # NPM dependencies and scripts
├── config.env.example              # Environment configuration template
└── README.md                       # Project documentation
```

### Key Rules

1. **Phase-based organization**: Tests organized by numbered phases (01-06)
2. **Separation of concerns**: Tests, helpers, fixtures, and utils in separate directories
3. **Test data externalization**: Test data stored in JSON files, not hardcoded
4. **Configuration externalization**: All config in `.env` file (not committed)

---

## 🧪 Test Organization

### Test File Naming

**Pattern:** `[feature-name].spec.ts`

**Examples:**
- `login.spec.ts`
- `add-to-cart.spec.ts`
- `order-management.spec.ts`
- `seller-dashboard.spec.ts`

**Rules:**
- Use kebab-case for file names
- Always end with `.spec.ts`
- Descriptive names that indicate test scope

### Test Suite Structure

**Pattern:**
```typescript
test.describe('##_Module_Name - Feature Name @tag1 @tag2', () => {
  test.beforeEach(async ({ page }) => {
    // Setup code
  });
  
  test.afterEach(async ({ page }) => {
    // Cleanup code
  });
  
  test('Test Case N: Description', async ({ page }) => {
    // Test implementation
  });
});
```

**Rules:**
1. **Describe block format**: `##_Module_Name - Feature Name @tags`
   - Number prefix matches directory (e.g., `01_Authentication`)
   - Module name matches directory name
   - Tags for filtering (e.g., `@auth @p1 @smoke`)
   
2. **Test case naming**: `Test Case N: Description`
   - Numbered test cases (1, 2, 3...)
   - Clear, descriptive names
   - Mirrors Katalon test case structure

3. **Tags usage**:
   - `@auth` - Authentication tests
   - `@commerce` - Commerce tests
   - `@p1` - Priority 1 (critical)
   - `@p2` - Priority 2 (high)
   - `@p3` - Priority 3 (medium)
   - `@smoke` - Smoke tests
   - `@regression` - Regression tests
   - `@ui` - UI tests

### Test Execution Order

**Pattern:** Sequential execution via project dependencies

**Configuration:**
```typescript
projects: [
  { name: '01-authentication', testMatch: /01-authentication\/.*\.spec\.ts/ },
  { name: '02-core-commerce', dependencies: ['01-authentication'], ... },
  { name: '03-user-management', dependencies: ['02-core-commerce'], ... },
  // ... etc
]
```

**Rules:**
1. Tests run sequentially (not parallel) to prevent state conflicts
2. Phase dependencies enforce execution order
3. `workers: 1` ensures one test at a time
4. `fullyParallel: false` prevents cart state conflicts

---

## 🏷️ Naming Conventions

### Variables

**Pattern:** `camelCase`

**Examples:**
- `cartItemCount`
- `expectedTotal`
- `productName`
- `isAuthenticated`

**Rules:**
- Use descriptive names
- Boolean variables prefixed with `is`, `has`, `should`
- Count variables suffixed with `Count`

### Functions

**Pattern:** `camelCase` with verb prefix

**Examples:**
- `clearCart()`
- `waitForDataTable()`
- `handleIncreaseQuantityModal()`
- `ensureAuthenticated()`
- `parsePrice()`
- `calculateExpectedTotal()`

**Rules:**
- Use action verbs: `get`, `set`, `wait`, `handle`, `clear`, `calculate`
- Descriptive names indicating purpose
- Helper functions in `helpers/` directory
- Utility functions in `utils/` directory

### Constants

**Pattern:** `UPPER_SNAKE_CASE` for environment/config values

**Examples:**
- `SHOPFLOW_URL`
- `TEST_EMAIL`
- `GMAIL_APP_PASSWORD`
- `TWO_FA_MAX_WAIT_TIME`

**Rules:**
- Environment variables: `UPPER_SNAKE_CASE`
- Config object properties: `camelCase` (e.g., `testConfig.baseUrl`)

### Selectors

**Pattern:** Inline selectors (no centralized selector file)

**Examples:**
```typescript
page.locator('#cartTable tbody tr')
page.locator('input.quantity-input')
page.locator('.swal2-confirm')
page.locator('#selectAllCartItems')
```

**Rules:**
1. **Inline selectors preferred** - easier to understand and maintain
2. Use IDs when available: `#elementId`
3. Use classes for styling-based selection: `.className`
4. Use data attributes when appropriate: `[data-attribute="value"]`
5. Combine selectors for specificity: `#table tbody tr:visible`
6. Avoid overly complex selectors - prefer multiple simple locators

---

## 💻 Code Style & Patterns

### Import Organization

**Pattern:**
```typescript
// 1. Playwright imports
import { test, expect } from '@playwright/test';

// 2. Utility imports
import { authenticateUser } from '../../utils/authentication';
import { testConfig } from '../../utils/test-config';

// 3. Helper imports
import { printTestCase, printSuccess, clearCart } from '../../helpers/test-helpers';
import { expectAuthenticated } from '../../helpers/assertions';
```

**Rules:**
1. Group imports: Playwright → Utils → Helpers
2. Use relative paths: `../../utils/...`
3. Import only what's needed (no wildcard imports)

### Test Structure Pattern

**Pattern:**
```typescript
test('Test Case N: Description', async ({ page }) => {
  // 1. Print test case header
  printTestCase(N, 'Description');
  
  // 2. Setup/Arrange
  await page.goto('/shop');
  await page.waitForLoadState('load');
  
  // 3. Action
  await page.locator('button').click();
  
  // 4. Assertion
  await expect(page.locator('#element')).toBeVisible();
  
  // 5. Success message
  printSuccess('Action completed successfully');
});
```

**Rules:**
1. **AAA Pattern**: Arrange → Act → Assert
2. Print test case header at start
3. Use descriptive success messages
4. One logical assertion per test case (when possible)

### Console Output Pattern

**Pattern:**
```typescript
printTestCase(1, 'Initial Setup');
printSuccess('Page loaded successfully');
printWarning('Optional feature not found');
console.log('📊 Debug information');
```

**Rules:**
1. Use helper functions: `printTestCase()`, `printSuccess()`, `printWarning()`
2. Emoji prefixes for visual clarity: `📊`, `✅`, `❌`, `⚠️`, `🔐`, `🧹`
3. Success messages for verification steps
4. Warnings for non-critical issues

### Error Handling Pattern

**Pattern:**
```typescript
try {
  await page.locator('#element').click();
  printSuccess('Element clicked');
} catch (error) {
  printWarning('Element not found, continuing...');
  // Fallback logic
}
```

**Rules:**
1. Use try-catch for optional operations
2. Use `.catch(() => false)` for boolean checks
3. Log errors with context
4. Continue test execution when appropriate (non-critical failures)

### Wait Patterns

**Pattern:**
```typescript
// Wait for element
await page.locator('#element').waitFor({ state: 'visible', timeout: 10000 });

// Wait for DataTable
await waitForDataTable(page, '#productsTable', 20000);

// Wait for page load
await page.waitForLoadState('networkidle');

// Wait for timeout (use sparingly)
await page.waitForTimeout(2000);
```

**Rules:**
1. **Prefer explicit waits** over timeouts
2. Use `waitForDataTable()` for DataTables (handles AJAX)
3. Use `waitForLoadState()` for page navigation
4. Use `waitForTimeout()` only when necessary (e.g., animation completion)
5. Default timeout: 10000ms (10 seconds)
6. DataTable timeout: 15000-20000ms (15-20 seconds)

---

## ⚙️ Configuration Patterns

### Environment Variables

**File:** `.env` (not committed, use `config.env.example` as template)

**Pattern:**
```bash
# Application URL
SHOPFLOW_URL=https://shopflow.php8

# Test Credentials
TEST_EMAIL=siliconkatalontest@gmail.com
TEST_PASSWORD=your_password_here

# Gmail 2FA Configuration
GMAIL_APP_PASSWORD=your_app_password_here
GMAIL_IMAP_HOST=imap.gmail.com
GMAIL_IMAP_PORT=993
GMAIL_IMAP_USER=siliconkatalontest@gmail.com

# 2FA Timing
TWO_FA_MAX_WAIT_TIME=30000
TWO_FA_RETRY_INTERVAL=5000
```

**Rules:**
1. All sensitive data in `.env` file
2. Provide `config.env.example` as template
3. Use `dotenv` to load environment variables
4. Provide defaults in code for optional values

### Playwright Configuration

**File:** `playwright.config.ts`

**Key Settings:**
```typescript
{
  testDir: './tests',
  fullyParallel: false,        // Sequential execution
  workers: 1,                   // One worker at a time
  timeout: 60000,               // 60s per test
  retries: process.env.CI ? 2 : 0,
  
  use: {
    baseURL: process.env.SHOPFLOW_URL || 'https://shopflow.php8',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
    actionTimeout: 10000,
    navigationTimeout: 30000,
    ignoreHTTPSErrors: true,
  }
}
```

**Rules:**
1. Sequential execution (`fullyParallel: false`, `workers: 1`)
2. Retry only on CI (2 retries)
3. Trace/screenshot/video on failure only
4. Timeouts: 10s action, 30s navigation, 60s test
5. Ignore HTTPS errors (self-signed certificates)

### Test Configuration

**File:** `utils/test-config.ts`

**Pattern:**
```typescript
export interface TestConfig {
  baseUrl: string;
  testEmail: string;
  testPassword: string;
  gmailAppPassword?: string;
  twoFaMaxWaitTime: number;
  twoFaRetryInterval: number;
}

export function loadTestConfig(): TestConfig {
  return {
    baseUrl: process.env.SHOPFLOW_URL || 'https://shopflow.php8',
    testEmail: process.env.TEST_EMAIL || 'default@email.com',
    // ... with defaults
  };
}
```

**Rules:**
1. Type-safe configuration interface
2. Environment variable loading with defaults
3. Validation function for required values
4. Single source of truth for config

---

## 🔐 Authentication Patterns

### Authentication State Management

**Pattern:** Storage state persistence

**File:** `auth.json` (generated, not committed)

**Usage:**
```typescript
// In test file
test.use({ storageState: 'auth.json' });

// In beforeEach
await ensureAuthenticated(page);
```

**Rules:**
1. Use `storageState: 'auth.json'` for authenticated tests
2. Call `ensureAuthenticated()` in `beforeEach` to verify/refresh session
3. `auth.json` is auto-generated on first authentication
4. Session is reused across tests for speed
5. Auto re-authenticates if session expires

### Authentication Flow

**Pattern:**
```typescript
// 1. Navigate to base URL
await page.goto('/');

// 2. Check if already authenticated
const isLoginFormVisible = await page.locator('#inputEmail').isVisible();

// 3. If not authenticated, authenticate
if (isLoginFormVisible) {
  await authenticateUser(page);
}

// 4. Verify authentication
await expectAuthenticated(page);
```

**Rules:**
1. Check authentication state before proceeding
2. Use `authenticateUser()` utility for login
3. Handle 2FA automatically (if configured)
4. Verify authentication after login
5. Save state to `auth.json` for reuse

### 2FA Handling

**Pattern:**
```typescript
// Automated 2FA (if Gmail configured)
const gmailPassword = testConfig.gmailAppPassword;
if (gmailPassword) {
  const emailFetcher = createGmail2FAFetcher(gmailPassword);
  const result = await emailFetcher.fetch2FACode(loginTimestamp);
  if (result.success) {
    await codeInput.fill(result.code);
    await verifyButton.click();
  }
}

// Manual 2FA fallback
if (!automatedSuccess) {
  console.log('Waiting for manual 2FA code input...');
  await page.waitForTimeout(30000);
}
```

**Rules:**
1. Attempt automated 2FA first (if configured)
2. Fallback to manual input if automation fails
3. Capture login timestamp for email search
4. Wait for 2FA email with retry logic
5. Handle 2FA errors gracefully

---

## 📊 Test Data Management

### Test Data Files

**Location:** `test-data/`

**Files:**
- `products.json` - Product test data
- `orders.json` - Order test data
- `cleanup-tracker.json` - Cleanup tracking

**Pattern:**
```json
{
  "testProducts": [
    {
      "id": "test-product-1",
      "name": "Test Product",
      "expectedPrice": 100.00
    }
  ],
  "cartScenarios": [
    {
      "name": "single_item",
      "items": [{ "id": "test-product-1", "quantity": 1 }]
    }
  ]
}
```

**Rules:**
1. Store test data in JSON files (not hardcoded)
2. Use descriptive property names
3. Include expected values for validation
4. Track created data in `cleanup-tracker.json`

### Test Data Fixture

**Pattern:**
```typescript
import { test } from '../fixtures/test-data.fixture';

test('my test', async ({ testData }) => {
  const products = testData.products;
  const orders = testData.orders;
  // Use test data
});
```

**Rules:**
1. Load test data via fixture
2. Access via `testData` parameter
3. Auto-save cleanup tracker after test

### Cleanup Tracking

**Pattern:**
```typescript
// Track created data
await updateCleanupTracker({
  cartIds: ['cart-123'],
  orderIds: ['order-456'],
  testDataCreated: ['product-789']
});

// Cleanup tracked data
await clearCart(page);
await deleteTestOrders(page);
```

**Rules:**
1. Track all created test data
2. Use cleanup tracker JSON file
3. Clean up in `afterEach` hooks
4. Prevent test data accumulation

---

## 🛠️ Helper & Utility Patterns

### Helper Functions Location

**Files:**
- `helpers/test-helpers.ts` - Common utilities
- `helpers/assertions.ts` - Custom assertions
- `utils/authentication.ts` - Auth utilities
- `utils/test-config.ts` - Config utilities

### Helper Function Categories

**1. Wait Utilities**
```typescript
waitForElement(page, selector, timeout)
waitForText(page, selector, text, timeout)
waitForPageLoad(page)
waitForDataTable(page, tableSelector, timeout)
```

**2. Validation Helpers**
```typescript
isValidPrice(price: string | null): boolean
isValidDate(date: string | null): boolean
parsePrice(priceText: string | null): number
```

**3. Calculation Helpers**
```typescript
calculateExpectedTotal(price: number, quantity: number): number
calculateVAT(priceIncl: number, vatRate: number): number
approximatelyEqual(actual: number, expected: number, tolerance: number): boolean
```

**4. Cart Helpers**
```typescript
getCartItemCount(page: Page): Promise<number>
getCartTotal(page: Page): Promise<number>
clearCart(page: Page): Promise<void>
```

**5. Modal Helpers**
```typescript
handleIncreaseQuantityModal(page: Page, action: 'confirm' | 'cancel'): Promise<boolean>
```

**6. Store Helpers**
```typescript
switchToBranchStore(page: Page): Promise<boolean>
switchToHeadOfficeStore(page: Page): Promise<boolean>
```

**7. Authentication Helpers**
```typescript
ensureAuthenticated(page: Page): Promise<void>
authenticateUser(page: Page): Promise<AuthenticationResult>
```

**Rules:**
1. Group related functions together
2. Use descriptive function names
3. Document function purpose with JSDoc
4. Export functions for reuse
5. Handle errors gracefully

---

## ✅ Assertion Patterns

### Custom Assertions

**File:** `helpers/assertions.ts`

**Categories:**

**1. Business Rule Assertions**
```typescript
expectValidPrice(page, selector)
expectValidDate(page, selector)
expectPriceInRange(page, selector, min, max)
expectPricesEqual(actual, expected, tolerance)
```

**2. Session Assertions**
```typescript
expectAuthenticated(page)
expectSessionValid(page)
expectOnPage(page, urlPattern)
```

**3. Cart Assertions**
```typescript
expectCartItemCount(page, expectedCount)
expectCartEmpty(page)
expectCartNotEmpty(page)
expectCartTotalAccurate(page, expectedTotal, tolerance)
expectCartCalculationsValid(page)
```

**4. Data Integrity Assertions**
```typescript
expectElementText(page, selector, expectedText, exact)
expectElementAttribute(page, selector, attribute, expectedValue)
expectTableRowCount(page, tableSelector, expectedCount)
```

**5. Order Assertions**
```typescript
expectValidOrderStatus(status)
expectOrderDataComplete(orderData)
```

**Rules:**
1. Use custom assertions for business logic validation
2. Provide clear error messages
3. Use tolerance for floating-point comparisons
4. Group assertions by domain (cart, order, session, etc.)

### Standard Playwright Assertions

**Pattern:**
```typescript
await expect(page.locator('#element')).toBeVisible();
await expect(page.locator('#element')).toHaveText('Expected Text');
await expect(page.locator('#element')).toHaveValue('value');
await expect(page.locator('#element')).toBeEnabled();
```

**Rules:**
1. Use Playwright's `expect` for standard checks
2. Use custom assertions for business rules
3. Combine assertions for comprehensive validation

---

## 🧹 Cleanup Patterns

### Cleanup Strategy

**Pattern:**
```typescript
test.beforeEach(async ({ page }) => {
  await ensureAuthenticated(page);
  await page.goto('/shop');
  await clearCart(page);  // Clear before test
});

test.afterEach(async ({ page }) => {
  await clearCart(page);  // Clear after test
});
```

**Rules:**
1. **Clean before AND after** each test
2. Clear cart in `beforeEach` for clean state
3. Clear cart in `afterEach` to prevent accumulation
4. Use `clearCart()` helper function
5. Verify cleanup succeeded

### Cart Cleanup Implementation

**Pattern:**
```typescript
export async function clearCart(page: Page): Promise<void> {
  // 1. Navigate to shop if needed
  if (!page.url().includes('/shop')) {
    await page.goto('/shop');
  }
  
  // 2. Check if cart is empty
  const cartCount = await getCartItemCount(page);
  if (cartCount === 0) return;
  
  // 3. Select all items
  await page.locator('#selectAllCartItems').check();
  
  // 4. Click bulk delete
  await page.locator('#bulkDeleteBtn').click();
  
  // 5. Confirm deletion (SweetAlert)
  await page.locator('.swal2-confirm').click();
  
  // 6. Wait for completion
  await page.waitForTimeout(3000);
  
  // 7. Verify cart is empty
  const finalCount = await getCartItemCount(page);
  if (finalCount > 0) {
    throw new Error(`Cart cleanup failed: ${finalCount} items remaining`);
  }
}
```

**Rules:**
1. Check if cleanup is needed before proceeding
2. Use bulk operations when possible (faster)
3. Handle modals (SweetAlert) appropriately
4. Verify cleanup succeeded
5. Log cleanup actions for debugging

### Cleanup Tracker

**Pattern:**
```typescript
// Update tracker
await updateCleanupTracker({
  cartIds: ['cart-123'],
  orderIds: ['order-456'],
  lastUpdated: new Date().toISOString()
});

// Load tracker
const tracker = loadJsonFile('test-data/cleanup-tracker.json');
```

**Rules:**
1. Track all created test data
2. Update tracker after creating data
3. Use tracker for targeted cleanup
4. Save tracker to JSON file

---

## 📚 Documentation Patterns

### Test File Documentation

**Pattern:**
```typescript
/**
 * Add to Cart Test - Comprehensive
 * 
 * Tags: @commerce @p1 @smoke @ui
 * 
 * Mirrors Katalon's Add_To_Cart test with all verification:
 * - Initial setup and validation
 * - Product search and selection
 * - Quantity controls
 * - Add to cart functionality
 * - Cart state management
 * - Total calculations
 * - Duplicate item handling
 * - Data accuracy verification
 * - Business rules validation
 */
```

**Rules:**
1. Include test description at top of file
2. List all tags used
3. Document test scope and coverage
4. Reference related tests (e.g., "Mirrors Katalon's...")

### Function Documentation

**Pattern:**
```typescript
/**
 * Wait for DataTables to initialize and load data
 * @param page Playwright page object
 * @param tableSelector Table ID selector (e.g., '#productsTable')
 * @param timeout Maximum time to wait in milliseconds
 * @returns Promise<boolean> True if table initialized successfully
 */
export async function waitForDataTable(
  page: Page,
  tableSelector: string,
  timeout: number = 15000
): Promise<boolean> {
  // Implementation
}
```

**Rules:**
1. Use JSDoc comments for all exported functions
2. Document parameters with `@param`
3. Document return values with `@returns`
4. Include usage examples for complex functions
5. Document edge cases and error handling

### README Documentation

**Pattern:**
- Project overview
- Test organization structure
- Configuration setup
- Running tests
- Troubleshooting
- Contributing guidelines

**Rules:**
1. Keep README up-to-date
2. Include examples for common tasks
3. Document all configuration options
4. Provide troubleshooting section
5. Include links to related documentation

---

## 🚀 Execution Patterns

### Test Execution Commands

**Pattern:**
```bash
# Run all tests
npm test

# Run specific phase
npm test -- tests/01-authentication/ --project=chromium

# Run with tags
npm test -- --grep @smoke
npm test -- --grep @p1

# Run in headed mode
npm run test:headed

# Run in debug mode
npm run test:debug

# Run with UI mode
npm run test:ui

# View report
npm run report
```

**Rules:**
1. Use npm scripts for common commands
2. Support filtering by directory, tags, or project
3. Provide debug and UI modes for development
4. Generate HTML reports for results

### Sequential Execution

**Pattern:**
```typescript
// playwright.config.ts
{
  fullyParallel: false,  // Sequential execution
  workers: 1,             // One worker at a time
  projects: [
    { name: '01-authentication', ... },
    { name: '02-core-commerce', dependencies: ['01-authentication'], ... },
    // ... sequential dependencies
  ]
}
```

**Rules:**
1. Execute tests sequentially to prevent state conflicts
2. Use project dependencies to enforce order
3. One worker ensures no parallel execution
4. Prevents cart state conflicts between tests

### Retry Logic

**Pattern:**
```typescript
retries: process.env.CI ? 2 : 0,  // Retry only on CI
```

**Rules:**
1. Retry only in CI environment (2 retries)
2. No retries in local development (faster feedback)
3. Retry on first failure only (trace enabled)

---

## 🎯 Key Principles

### 1. Comprehensive Verification
- Test business logic, not just UI presence
- Verify calculations, state changes, data accuracy
- Test edge cases and error handling

### 2. Reusability
- Use fixtures for authentication
- Create helper functions for common operations
- Avoid code duplication

### 3. Maintainability
- Inline selectors (easier to understand)
- Clear test case descriptions
- Organized by business modules

### 4. Clean Test Data
- Clean before AND after tests
- Track created test data
- Prevent data accumulation

### 5. Sequential Execution
- Prevent state conflicts
- Ensure test isolation
- Reliable results

### 6. Self-Documenting
- Clear test case names
- Descriptive function names
- Comprehensive comments

---

## 📝 Summary

This project follows a **structured, phase-based testing approach** that:

1. **Organizes tests by business modules** (01-06 phases)
2. **Uses reusable authentication** via fixtures and storage state
3. **Implements comprehensive verification** of business logic
4. **Manages test data** through JSON files and cleanup tracking
5. **Follows consistent patterns** for code style, naming, and structure
6. **Executes sequentially** to prevent state conflicts
7. **Provides clear documentation** for maintainability

The patterns and rules documented here ensure:
- **Consistency** across all test files
- **Maintainability** through clear organization
- **Reliability** through proper cleanup and isolation
- **Reusability** through helper functions and fixtures
- **Clarity** through self-documenting code

---

**Last Updated:** 2025-01-08  
**Version:** 1.0

