coverage-enable-subprocess

1.0 · active · verified Thu Apr 16

This package installs a .pth file that enables the coverage.py process_startup feature in the Python prefix/virtualenv in subsequent runs, facilitating automatic coverage measurement for subprocesses. It is currently stable and actively maintained, with version 1.0 being the latest. The release cadence is as-needed for stability and compatibility with coverage.py.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to enable coverage for a Python subprocess. It involves installing `coverage-enable-subprocess`, creating a `.coveragerc` file, setting the `COVERAGE_PROCESS_START` environment variable, and then running a Python script as a subprocess. The installed `.pth` file ensures that `coverage.py`'s `process_startup()` function is called, initiating coverage collection in the subprocess.

import os
import subprocess
import sys

# 1. Create a dummy .coveragerc for demonstration
with open('.coveragerc', 'w') as f:
    f.write('[run]\n')
    f.write('parallel = True\n')
    f.write('data_file = .coverage.subprocess\n')

# 2. Set the environment variable to point coverage.py to the config file
os.environ['COVERAGE_PROCESS_START'] = os.path.abspath('.coveragerc')

# 3. Create a simple script to run as a subprocess
script_content = """
import os
import sys

# This line should be covered by the subprocess
def my_subprocess_func():
    print("Hello from subprocess!")

if __name__ == '__main__':
    my_subprocess_func()
"""
with open('subprocess_target.py', 'w') as f:
    f.write(script_content)

print("Running subprocess...")

# 4. Run the script as a subprocess
# Ensure environment variables are passed correctly
subprocess_env = os.environ.copy()
process = subprocess.Popen([sys.executable, 'subprocess_target.py'], env=subprocess_env)
process.wait()

print("Subprocess finished. Check for .coverage.subprocess file.")

# Clean up (optional for quickstart, but good practice)
os.remove('.coveragerc')
os.remove('subprocess_target.py')

# To see the actual coverage report, you would then run:
# coverage combine --data-file=.coverage.subprocess
# coverage report --data-file=.coverage.subprocess

view raw JSON →