coverage-tool 1.0.6
Multi-language unit test coverage analysis tool
License: MIT
Requires Python: >=3.8

# Multi-Language Unit Test Coverage Tool

A powerful multi-language unit test coverage analysis tool supporting Python, Java, Go, C, and C++. It automatically executes tests, analyzes coverage, removes failed test cases, and generates detailed reports.

## Features

- **Multi-language Support**: Python, Java, Go, C, C++
- **Smart Compilation Fix**: Progressive deletion strategy based on file priority and dependencies
- **AST Parsing**: Python tests use AST for accurate test function identification
- **Auto Coverage Injection**: Automatically installs and configures coverage tools for all languages
- **Unified Coverage Calculation**: Consistent coverage extractor across all languages
- **Complete Logging**: Detailed execution logs for troubleshooting
- **File Backup**: Automatic backup before deletion with recovery support

## Installation

### Direct Use

```bash
# Clone the repository
git clone <repository-url>
cd coverage_tool

# Ensure Python >= 3.8
python3 --version
```

### Install Dependencies

```bash
pip install -r requirements.txt
```

### Language Requirements

| Language | Required Tools |
|----------|---------------|
| Python | Python 3.8+, pytest, coverage.py |
| Java | JDK 8+, Maven |
| Go | Go SDK 1.16+ |
| C/C++ | GCC/G++, Make |

## Usage

### Basic Syntax

```bash
coverage-tool -l <language> -t <target_dir> [options]
```

### Parameters

| Parameter | Short | Description | Default |
|-----------|-------|-------------|---------|
| --language | -l | Programming language (python/java/go/c/cpp) | Required |
| --target | -t | Target directory path | Required |
| --output | -o | Output report filename | coverage_report |
| --format | -f | Report format (text/json/csv/html) | text |
| --no-delete | - | Don't delete files on compile failure | False |
| --compile-timeout | - | Compile timeout (seconds) | 60 |
| --test-timeout | - | Test timeout (seconds) | 300 |
| --max-compile-iterations | - | Max compile fix iterations | 10 |
| --max-cleanup-iterations | - | Max test cleanup iterations | 10 |

### Examples

#### Python Project

```bash
coverage-tool --language python --target ./src --output report
coverage-tool -l python -t ./project -f json
```

#### Java Project

```bash
coverage-tool --language java --target ./myproject
coverage-tool -l java -t ./project -f html
```

#### Go Project

```bash
coverage-tool --language go --target ./module
coverage-tool -l go -t ./src -o go_coverage -f html
```

#### C/C++ Project

```bash
coverage-tool --language c --target ./c_project
coverage-tool --language cpp --target ./cpp_project -f json
```

## Project Structure

```
coverage_tool/
├── src/coverage_tool/
│   ├── main.py                    # Main entry point
│   ├── __init__.py                # Package init
│   ├── analyzers/                 # Dependency analyzers
│   │   ├── dependency.py
│   │   └── __init__.py
│   ├── converters/                # Test output converters
│   │   ├── base.py                # Base converter
│   │   ├── factory.py             # Converter factory
│   │   ├── gtest_converter.py     # Google Test converter
│   │   ├── go_converter.py        # Go test converter
│   │   ├── cunit_converter.py     # CUnit converter
│   │   ├── generic_converter.py   # Generic converter
│   │   └── __init__.py
│   ├── core/                      # Core functionality
│   │   ├── config.py               # Language configurations
│   │   ├── reporter.py            # Report generator
│   │   └── __init__.py
│   ├── handlers/                  # Event handlers
│   │   ├── compilation.py         # Compilation handler
│   │   ├── coverage_injector.py   # Auto coverage tool injection
│   │   ├── env_checker.py         # Environment checker
│   │   └── __init__.py
│   ├── parsers/                    # Report parsers
│   │   ├── junit.py               # JUnit XML parser
│   │   └── __init__.py
│   ├── runners/                    # Language runners
│   │   ├── base.py                # Base runner
│   │   ├── factory.py             # Runner factory
│   │   ├── python_runner.py       # Python runner
│   │   ├── java_runner.py         # Java runner
│   │   ├── go_runner.py           # Go runner
│   │   ├── c_runner.py            # C runner
│   │   ├── cpp_runner.py          # C++ runner
│   │   └── __init__.py
│   ├── test_removers/              # Test removal modules
│   │   ├── base.py                # Base remover class
│   │   ├── factory.py             # Remover factory
│   │   ├── python_remover.py      # Python AST remover
│   │   ├── java_remover.py        # Java remover
│   │   ├── go_remover.py          # Go remover
│   │   ├── c_remover.py           # C remover
│   │   ├── cpp_remover.py         # C++ remover
│   │   └── __init__.py
│   └── utils/                      # Utility functions
│       ├── dependency_graph.py     # Dependency analysis
│       ├── file_backup.py          # File backup manager
│       ├── helpers.py              # Helper functions
│       ├── logger.py               # Logging
│       ├── progress.py             # Progress tracking
│       └── __init__.py
├── tests/                           # Test files
├── pyproject.toml                   # Project config
├── requirements.txt                 # Python dependencies
└── README.md                        # This file
```

## Architecture

```
main.py (CoverageTool)
├── Environment Checking (env_checker.py)
├── Coverage Injection (coverage_injector.py)
│   └── Auto-install and configure coverage tools
├── Compilation Handling (handlers/compilation.py)
│   └── SmartCompilationHandler
├── Test Execution (runners/)
│   └── RunnerFactory
├── Test Cleanup (test_removers/)
│   └── SmartTestRemoverFactory
└── Report Generation (core/reporter.py)

parsers/
└── JUnit XML Parser

converters/
├── Go Test Converter
├── Google Test Converter
└── Generic Converter

utils/
├── FileBackupManager
├── DependencyGraph
└── Logger
```

## Automatic Coverage Injection

The tool automatically installs and configures coverage tools for all languages - no manual setup required!

| Language | Coverage Tool | Auto-Injection Method |
|----------|---------------|----------------------|
| Python | coverage.py | `coverage run --source=` prefix |
| Java | JaCoCo | Auto-add plugin to pom.xml |
| Go | go test | `-coverprofile=` flag |
| C/C++ | gcov/gcc | `-fprofile-arcs -ftest-coverage` flags |

### How It Works

```
coverage-tool -l java -t ./myproject

# Tool automatically:
# 1. Check if JaCoCo is configured in pom.xml
# 2. If not, inject JaCoCo plugin configuration
# 3. Run mvn test (with JaCoCo agent)
# 4. Extract coverage from target/site/jacoco/index.html
```

### Java JaCoCo Injection

```xml
<!-- Automatically added to pom.xml if missing -->
<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.11</version>
    <executions>
        <execution>
            <goals>
                <goal>prepare-agent</goal>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>
```

### C/C++ Makefile Injection

```makefile
# Automatically added flags
CFLAGS += -fprofile-arcs -ftest-coverage
CXXFLAGS += -fprofile-arcs -ftest-coverage
LDFLAGS += -lgcov
```

### Coverage Injector Module

**`handlers/coverage_injector.py`** - Unified coverage tool injector:

- `check_coverage_tool_available(language)` - Check if coverage tool is available
- `inject_coverage_flags(language, commands)` - Inject coverage flags
- `ensure_java_coverage(project_dir)` - Configure JaCoCo for Java projects
- `_find_jacoco_agent()` - Find or download JaCoCo agent
- `get_coverage_report_paths(language, project_dir)` - Get report paths

## Key Components

### Smart Compilation Handler

Handles compilation failures with intelligent strategies:
- **File Priority System**: Files categorized by type (test, source, core)
- **Dependency Analysis**: Uses `DependencyGraph` to avoid over-deletion
- **Progressive Deletion**: Max 3 files per iteration, up to 10 retries
- **Error Parsing**: Supports multiple language error formats

### Automatic Coverage Injector

Automatically configures coverage tools for all languages:
- **Python**: Injects `coverage run --source=` before pytest
- **Java**: Parses pom.xml and adds JaCoCo plugin if missing
- **Go**: Adds `-coverprofile=` flag to test command
- **C/C++**: Injects `-fprofile-arcs -ftest-coverage` into Makefile
- **Non-destructive**: Only modifies configuration when needed

### Smart Test Removers

Modular test removal for each language:
- **Python**: AST-based parsing for accurate function identification
- **Java**: Regex-based method extraction
- **Go**: Test function removal
- **C/C++**: Support for Google Test and CUnit formats

### Unified Coverage Extraction

- Single `CoverageExtractor` for all languages
- Supports multiple formats: coverage.out, gcov, JaCoCo
- Fallback parsing strategies for reliability

### Utility Modules

| Module | Purpose |
|--------|---------|
| `FileBackupManager` | Backup/restore deleted files |
| `DependencyGraph` | Analyze file dependencies |
| `Logger` | Structured logging with levels |

## Performance & Reliability

- **File Backup**: All deletions are reversible
- **Dependency Analysis**: Prevents cascading failures
- **Context Managers**: Proper resource cleanup
- **Enhanced Logging**: Detailed execution tracking

## Workflow

```
1. Environment Check
   └── Analyze project config files
   └── Check required tools

2. Auto Coverage Injection
   └── Detect if coverage tool is configured
   └── If not, automatically install/configure

3. Compile with Retry
   └── First compilation attempt
   └── On failure → Smart deletion → Retry (up to 10 iterations)

4. Run Tests
   └── Generate JUnit XML report

5. Parse Test Results
   └── Extract failure/error information

6. Cleanup Failed Tests
   └── Delete failed test functions
   └── Re-run tests for verification

7. Generate Report
   └── Text / JSON / CSV / HTML formats
```

## Configuration

### Language-Specific Settings

```python
from coverage_tool.core import Language, LANGUAGE_CONFIGS

# Configure language settings
config = LANGUAGE_CONFIGS[Language.PYTHON]
```

## Version History

- **v1.0.3**: Automatic coverage injection for all languages
  - Added `coverage_injector.py` for auto coverage tool configuration
  - Java JaCoCo: Auto-detect and inject plugin into pom.xml
  - C/C++: Auto-inject coverage flags into Makefile
  - All languages now generate coverage reports without manual setup
- **v1.0.2**: Current version with modular architecture
- **v1.0.1**: Refactored test removers into modular structure
- **v1.0.0**: Initial release

## License

MIT License

## Contributing

Issues and Pull Requests are welcome!