Version note: references describe SonarQube Server 2025.2 behaviour. Check your server, scanner and edition requirements. These examples were not run against a live SonarQube server.
What this guide covers
Coverage.py can record Python test execution and write an XML report for SonarQube. Both tools must refer to the same source files for the imported coverage to appear.
Before you start
Use a Python environment with your project dependencies, pytest and Coverage.py installed. This example assumes an importable package at src/my_service and tests under tests.
Step 1: Configure Coverage.py
Save this in .coveragerc, changing the source path to your package:
[run]
branch = True
relative_files = True
source = src/my_service
branch = True also measures decisions such as both sides of an if. Relative paths help when reports move between build steps.
Step 2: Run the tests and create XML
From the project root:
python -m coverage erase
python -m coverage run -m pytest
python -m coverage xml -o coverage.xml
test -s coverage.xml
Run python -m coverage report --show-missing to inspect the local result. Stop if tests fail or the report is empty.
Step 3: Configure the scanner
Add these settings to sonar-project.properties, alongside your project key:
sonar.sources=src/my_service
sonar.tests=tests
sonar.python.coverage.reportPaths=coverage.xml
Set the server URL and token securely, then run sonar-scanner in the same checkout.
Step 4: Resolve path differences
If coverage is missing, inspect source paths inside coverage.xml and scanner warnings. They must match the files the scanner sees. For parallel tests, combine Coverage.py data files first, then generate one final XML report.
Check the result
Check a tested and an untested source file in SonarQube. The values should match the XML report for this run, including source files the tests did not import.
Conversation
0 commentsNo comments yet. Start the conversation below.