# CodeCov Integration Demo

**File:** `.github/workflows/codecov-demo.yml`  
**Purpose:** Reference implementation for CodeCov integration testing  
**Duration:** ~1 minute  

## Overview
This pipeline serves as a reference implementation for setting up CodeCov integration in new repositories. It uses a simple calculator example to demonstrate coverage reporting without project-specific dependencies.

## Use Cases

### Primary Uses
1. **Template for new repos:** Copy-paste CodeCov setup
2. **Integration testing:** Verify CodeCov configuration
3. **Onboarding reference:** Show developers how coverage works
4. **Troubleshooting:** Isolated environment for debugging CodeCov issues

## Technical Implementation

### Trigger Conditions
```yaml
on:
  push:
    branches: [ "codecov-demo" ]
  pull_request:
    branches: [ "codecov-demo" ]
```

**Strategy:** Runs only on dedicated `codecov-demo` branch to avoid noise in main development workflow. Completely isolated from production pipelines.

### Simple Test Environment
```yaml
# Creates isolated test environment
- Python 3.10 setup
- Minimal dependencies (pytest, pytest-cov, fastapi)
- Self-contained calculator module
- Basic test suite
```

### Demo Code Structure
```
calculator.py              ← Simple functions for testing
tests/test_calculator.py    ← Basic test cases
```

#### Calculator Module
```python
def add(a, b):
    """Add two numbers."""
    return a + b

def subtract(a, b):
    """Subtract two numbers."""
    return a - b
```

#### Test Suite
```python
def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

def test_subtract():
    assert subtract(5, 3) == 2
    assert subtract(0, 1) == -1
```

## CodeCov Configuration

### Coverage Generation
```bash
pytest --cov=. --cov-report=xml --cov-report=term-missing
```

### Upload Configuration
```yaml
- name: Upload coverage to Codecov
  uses: codecov/codecov-action@v3
  with:
    token: ${{ secrets.CODECOV_TOKEN }}
    file: ./coverage.xml
    fail_ci_if_error: false
```

### Key Features
- **XML format:** Standard coverage reporting
- **Terminal output:** Human-readable results
- **Non-blocking:** `fail_ci_if_error: false`
- **Token authentication:** Secure upload

## Expected Results

### Coverage Output
```
Name                Stmts   Miss  Cover   Missing
-----------------------------------------------
calculator.py           4      0   100%
-----------------------------------------------
TOTAL                   4      0   100%
```

### CodeCov Dashboard
- **Repository setup:** Verified
- **Coverage trends:** Tracked
- **Report uploads:** Successful
- **Integration status:** Active

## Replication Guide

### For New Repositories

#### 1. Create Demo Branch
```bash
git checkout -b codecov-demo
```

#### 2. Copy Workflow File
```bash
cp .github/workflows/codecov-demo.yml /path/to/new/repo/.github/workflows/
```

#### 3. Set Up CodeCov Token
1. Visit [codecov.io](https://codecov.io)
2. Add your repository
3. Copy the repository token
4. Add to GitHub Secrets as `CODECOV_TOKEN`

#### 3. Customize for Your Project
```yaml
# Replace calculator.py with your module
# Update test paths
# Modify coverage paths
```

### Verification Steps
1. Push to `codecov-demo` branch to trigger pipeline
2. Check pipeline success in GitHub Actions
3. Verify CodeCov dashboard shows results
4. Confirm coverage reports are generated
5. Clean up: Delete `codecov-demo` branch when done

## Integration Testing

### Test CodeCov Setup
```bash
# Verify token access
curl -X POST --data-binary @coverage.xml \
  -H "Content-Type: text/plain" \
  "https://codecov.io/upload/v4?token=YOUR_TOKEN"

# Check repository status
curl -H "Authorization: token YOUR_TOKEN" \
  "https://api.codecov.io/gh/username/repository"
```

### Common Validation Points
- ✅ Token authentication works
- ✅ Coverage files generated correctly
- ✅ Upload process succeeds
- ✅ Dashboard displays results

## Configuration Options

### CodeCov Action Parameters
```yaml
token: ${{ secrets.CODECOV_TOKEN }}    # Required
file: ./coverage.xml                   # Coverage file path
flags: demo                           # Optional flags
name: demo-coverage                   # Upload name
fail_ci_if_error: false              # Non-blocking mode
verbose: true                        # Detailed logging
```

### pytest-cov Options
```bash
--cov=.                              # Coverage scope
--cov-report=xml                     # XML output format
--cov-report=term-missing           # Terminal display
--cov-report=html                   # HTML report
--cov-fail-under=80                 # Minimum threshold
```

## Troubleshooting

### Common Issues

#### Token Authentication Failure
**Symptoms:**
- Upload fails with 401 error
- "Invalid token" messages

**Solutions:**
1. Verify token in GitHub Secrets
2. Check token scope and permissions
3. Regenerate token in CodeCov dashboard
4. Ensure repository is added to CodeCov

#### Coverage File Not Found
**Symptoms:**
- "coverage.xml not found" errors
- Upload step skipped

**Solutions:**
1. Check pytest execution logs
2. Verify coverage generation command
3. List files after test execution
4. Confirm working directory

#### Upload Timeout
**Symptoms:**
- Slow upload process
- Network timeout errors

**Solutions:**
1. Check network connectivity
2. Retry with verbose logging
3. Use curl for direct upload testing
4. Contact CodeCov support

### Debug Commands
```bash
# List coverage files
ls -la *.xml

# Test coverage generation
pytest --cov=. --cov-report=xml -v

# Manual upload test
curl -Os https://cli.codecov.io/latest/linux/codecov
chmod +x codecov
./codecov --verbose upload-process --file coverage.xml
```

## Best Practices

### ✅ Template Design
- **Self-contained:** No external dependencies
- **Minimal complexity:** Easy to understand
- **Well-documented:** Clear instructions
- **Version controlled:** Track changes

### ✅ Integration Testing
- **Isolated environment:** No interference with main project
- **Quick execution:** Fast feedback
- **Reliable results:** Consistent behavior
- **Easy debugging:** Clear error messages

### ✅ Maintenance
- **Regular updates:** Keep dependencies current
- **Documentation sync:** Match implementation
- **Security review:** Token management
- **Compatibility testing:** New CodeCov features

---
**Last Updated:** September 2024  
**Template Version:** v1.0  
**Contact:** SRE/DevOps Team  
**CodeCov Version:** v3 action
