Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,96 @@ jobs:
files: runtime/clover.xml
disable_search: true
token: ${{ secrets.CODECOV_TOKEN }}

code-coverage-turbocov:
runs-on: ubuntu-latest
name: Code Coverage (turbocov)
concurrency:
group: code-coverage-turbocov-${{ github.ref }}
cancel-in-progress: true

steps:

- name: Checkout
uses: actions/checkout@v7

- name: Resolve root package version
run: echo "COMPOSER_ROOT_VERSION=$(jq -r '.["."]' resources/version.json)" >> "$GITHUB_ENV"

- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.5
coverage: none
tools: pie
ini-values: opcache.enable_cli=0

- name: Resolve turbocov build key
id: turbocov
run: |
echo "version=$(curl -fsSL https://repo.packagist.org/p2/shipmonk/turbocov.json | jq -r '.packages["shipmonk/turbocov"][0].version')" >> "$GITHUB_OUTPUT"
echo "php=$(php -r 'echo PHP_VERSION;')" >> "$GITHUB_OUTPUT"

- name: Cache turbocov build
id: turbocov-cache
uses: actions/cache@v4
with:
path: ~/.turbocov
key: turbocov-${{ runner.os }}-php${{ steps.turbocov.outputs.php }}-${{ steps.turbocov.outputs.version }}

- name: Build turbocov
if: steps.turbocov-cache.outputs.cache-hit != 'true'
run: |
sudo pie install "shipmonk/turbocov:${{ steps.turbocov.outputs.version }}"
mkdir -p ~/.turbocov
cp "$(php-config --extension-dir)/turbocov.so" ~/.turbocov/

# One ini for both a fresh build and a cache hit; whatever PIE enabled is replaced by it.
- name: Enable turbocov
run: |
scan="$(php -r 'echo PHP_CONFIG_FILE_SCAN_DIR;')"
sudo rm -f "$scan"/*turbocov*.ini
echo "extension=$HOME/.turbocov/turbocov.so" | sudo tee "$scan/99-turbocov.ini"
php --ri turbocov

- name: Install Composer dependencies
uses: ramsey/composer-install@v3
with:
dependency-versions: highest

- name: Install bin tools
run: composer bin all install --ignore-platform-req=php

# A loaded turbocov that cannot collect the sources must abort a mandatory coverage run with
# its reason instead of writing an empty report.
- name: Reject a turbocov that cannot collect
env:
TESTO_CI: 1
run: |
expect_failure() {
local message=$1; shift
if php "$@" vendor/bin/testo --coverage --suite=Codecov/Unit > /tmp/run.log 2>&1; then
cat /tmp/run.log; echo "Expected the run to fail with: $message"; exit 1
fi
# Console output wraps long messages, so whitespace is collapsed before the search.
tr -s "[:space:]" " " < /tmp/run.log | grep -qF "$message" || { cat /tmp/run.log; exit 1; }
}
expect_failure 'turbocov.collect_paths is not set'
expect_failure 'contains none of the configured source paths' -d turbocov.collect_paths="$GITHUB_WORKSPACE/tests"

# turbocov instruments only `turbocov.collect_paths`, read at compile time; the source filter
# of testo.php narrows it further.
- name: Run Tests with Coverage
env:
TESTO_CI: 1
run: >-
php
-d turbocov.collect_paths="$GITHUB_WORKSPACE/core:$GITHUB_WORKSPACE/plugin:$GITHUB_WORKSPACE/bridge"
vendor/bin/testo --coverage --coverage-clover=runtime/clover.xml --type=!bench

- name: Upload coverage to Codecov
uses: codecov/codecov-action@v5
with:
files: runtime/clover.xml
disable_search: true
token: ${{ secrets.CODECOV_TOKEN }}
30 changes: 15 additions & 15 deletions bridge/rector/src/TestoToPhpunit/ThrowSkipTestToPhpUnitRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Throw_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
Expand All @@ -32,7 +35,8 @@
* untouched.
*
* Only rewrites a throw that lives inside a class: `$this->markTestSkipped()` needs a method scope,
* so a `throw new SkipTest(...)` in a free function or at namespace level is left as-is.
* so a `throw new SkipTest(...)` in a free function or at namespace level is left as-is. Inside a
* static method, which has no `$this`, it becomes `self::markTestSkipped()`.
*/
#[TestRectorFixtures('ThrowSkipTestToPhpUnitRector')]
final class ThrowSkipTestToPhpUnitRector extends AbstractRector
Expand Down Expand Up @@ -76,27 +80,23 @@ public function refactor(Node $node): ?Node
return null;
}

# Only convert inside a class: `$this->markTestSkipped()` has no valid target in a free
# function or at namespace level, so such a throw is left unchanged.
if (!$this->isInClassScope($node)) {
# Only convert inside a class: `markTestSkipped()` has no valid target in a free function or
# at namespace level, so such a throw is left unchanged.
$scope = $node->getAttribute(AttributeKey::SCOPE);
if (!$scope instanceof Scope || !$scope->isInClass()) {
return null;
}

# `markTestSkipped()` is static in PHPUnit; a static helper has no `$this` to call it on.
$function = $scope->getFunction();
if ($function instanceof MethodReflection && $function->isStatic()) {
return new StaticCall(new Name('self'), new Identifier('markTestSkipped'), $thrown->args);
}

return new MethodCall(
new Variable('this'),
new Identifier('markTestSkipped'),
$thrown->args,
);
}

/**
* Whether $node sits inside a class. Outside one — a free function or namespace-level code — the
* emitted `$this->markTestSkipped()` call would have no valid target, so the throw is left as-is.
*/
private function isInClassScope(Node $node): bool
{
$scope = $node->getAttribute(AttributeKey::SCOPE);

return $scope instanceof Scope && $scope->isInClass();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

class SomeTest
{
public function test()
{
self::requireDriver();
}

private static function requireDriver(): void
{
\extension_loaded('turbocov') or throw new \Testo\Core\Exception\SkipTest('turbocov is not loaded');
}
}
-----
<?php

class SomeTest
{
public function test()
{
self::requireDriver();
}

private static function requireDriver(): void
{
\extension_loaded('turbocov') or self::markTestSkipped('turbocov is not loaded');
}
}
7 changes: 5 additions & 2 deletions plugin/codecov/src/Exception/CoverageDriverNotAvailable.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@
*/
final class CoverageDriverNotAvailable extends \RuntimeException
{
public function __construct()
/**
* @param non-empty-string|null $reason Why a loaded extension cannot collect, replacing the default message.
*/
public function __construct(?string $reason = null)
{
parent::__construct(
'No code coverage driver available. Install the PCOV or XDebug extension.',
$reason ?? 'No code coverage driver available. Install the turbocov, PCOV or XDebug extension.',

Check warning on line 20 in plugin/codecov/src/Exception/CoverageDriverNotAvailable.php

View check run for this annotation

Codecov / codecov/patch

plugin/codecov/src/Exception/CoverageDriverNotAvailable.php#L20

Added line #L20 was not covered by tests
);
}
}
58 changes: 39 additions & 19 deletions plugin/codecov/src/Internal/CoverageActivation.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Testo\Codecov\Config\CoverageMode;
use Testo\Codecov\Exception\CoverageDriverNotAvailable;
use Testo\Codecov\Internal\Driver\PcovDriver;
use Testo\Codecov\Internal\Driver\TurbocovDriver;
use Testo\Codecov\Internal\Driver\XdebugDriver;
use Testo\Codecov\Internal\Middleware\CoverageTestInterceptor;
use Testo\Codecov\Report\CoverageReport;
Expand Down Expand Up @@ -59,6 +60,13 @@ final class CoverageActivation
*/
private ?CoverageDriver $driver = null;

/**
* Why a loaded driver extension cannot collect, reported when coverage is mandatory.
*
* @var non-empty-string|null
*/
private ?string $driverUnavailableReason = null;

private bool $driverResolved = false;
private CoverageLevel $level = CoverageLevel::Line;
private CoverageMode $mode = CoverageMode::IfAvailable;
Expand Down Expand Up @@ -146,7 +154,7 @@ public function contribute(CoverageLevel $level, array $testTypes, array $report
// from `ApplicationConfig::$src`), hence created once.
if (!$this->driverResolved) {
$this->driverResolved = true;
$this->driver = self::detectAvailableDriver($this->container->get(ApplicationConfig::class)->src);
$this->driver = $this->detectAvailableDriver($this->container->get(ApplicationConfig::class)->src);
}
}

Expand All @@ -162,7 +170,8 @@ public function contribute(CoverageLevel $level, array $testTypes, array $report
*/
public function verifyDriverRequirement(): void
{
$this->mode === CoverageMode::Always && $this->driver === null and throw new CoverageDriverNotAvailable();
$this->mode === CoverageMode::Always && $this->driver === null
and throw new CoverageDriverNotAvailable($this->driverUnavailableReason);
}

/**
Expand Down Expand Up @@ -216,23 +225,6 @@ private static function rank(CoverageLevel $level): int
};
}

/**
* Returns a usable driver if a coverage extension is present, otherwise null. Never throws — the
* {@see CoverageMode::Always} "no driver" failure is decided in {@see onSessionStarting()} once
* the merged mode is known. `Never` plugins return before contributing, so mode is not consulted
* here.
*
* For XDebug this also installs the engine-level coverage filter (see {@see XdebugDriver::create()}).
*/
private static function detectAvailableDriver(FinderConfig $src): ?CoverageDriver
{
return match (true) {
\extension_loaded('pcov') => PcovDriver::create($src),
self::isXdebugCoverageEnabled() => XdebugDriver::create($src),
default => null,
};
}

/**
* True when Xdebug is loaded and `coverage` is among its active modes; otherwise
* `xdebug_start_code_coverage()` is a no-op and reports come back empty.
Expand Down Expand Up @@ -290,4 +282,32 @@ private static function resolveSourceRoot(FinderConfig $src): ?string

return $commonLen === 0 ? null : \implode('/', \array_slice($first, 0, $commonLen));
}

/**
* Returns a usable driver if a coverage extension is present, otherwise null. Never throws — the
* {@see CoverageMode::Always} "no driver" failure is decided in {@see onSessionStarting()} once
* the merged mode is known. `Never` plugins return before contributing, so mode is not consulted
* here.
*
* For XDebug this also installs the engine-level coverage filter (see {@see XdebugDriver::create()}).
*
* A turbocov that cannot collect the sources (next to Xdebug, without `turbocov.collect_paths`, or with
* one that shares no path with `src`) yields to the other drivers; its reason is kept for the error
* when none is left.
*/
private function detectAvailableDriver(FinderConfig $src): ?CoverageDriver
{
if (\extension_loaded('turbocov')) {
$this->driverUnavailableReason = TurbocovDriver::unavailableReason($src);
if ($this->driverUnavailableReason === null) {
return TurbocovDriver::create($src);
}
}

return match (true) {
\extension_loaded('pcov') => PcovDriver::create($src),
self::isXdebugCoverageEnabled() => XdebugDriver::create($src),
default => null,
};
}
}
39 changes: 39 additions & 0 deletions plugin/codecov/src/Internal/Driver/PathFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace Testo\Codecov\Internal\Driver;

/**
* File-level filtering for drivers that report every file they instrument and leave the source
* filter to the caller.
*
* Expects `list<non-empty-string> $includes` and `$excludes` built with {@see NormalizePath}.
*
* @internal
*/
trait PathFilter
{
private function matchesFilter(string $file): bool
{
$included = false;
foreach ($this->includes as $path) {
if (\str_starts_with($file, $path)) {
$included = true;
break;

Check warning on line 23 in plugin/codecov/src/Internal/Driver/PathFilter.php

View check run for this annotation

Codecov / codecov/patch

plugin/codecov/src/Internal/Driver/PathFilter.php#L19-L23

Added lines #L19 - L23 were not covered by tests
}
}

if (!$included) {
return false;

Check warning on line 28 in plugin/codecov/src/Internal/Driver/PathFilter.php

View check run for this annotation

Codecov / codecov/patch

plugin/codecov/src/Internal/Driver/PathFilter.php#L27-L28

Added lines #L27 - L28 were not covered by tests
}

foreach ($this->excludes as $path) {
if (\str_starts_with($file, $path)) {
return false;

Check warning on line 33 in plugin/codecov/src/Internal/Driver/PathFilter.php

View check run for this annotation

Codecov / codecov/patch

plugin/codecov/src/Internal/Driver/PathFilter.php#L31-L33

Added lines #L31 - L33 were not covered by tests
}
}

return true;

Check warning on line 37 in plugin/codecov/src/Internal/Driver/PathFilter.php

View check run for this annotation

Codecov / codecov/patch

plugin/codecov/src/Internal/Driver/PathFilter.php#L37

Added line #L37 was not covered by tests
}
}
24 changes: 1 addition & 23 deletions plugin/codecov/src/Internal/Driver/PcovDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
final readonly class PcovDriver implements CoverageDriver
{
use NormalizePath;
use PathFilter;

/**
* @param list<non-empty-string> $includes
Expand Down Expand Up @@ -87,27 +88,4 @@ public function clear(): void
{
\pcov\clear();
}

private function matchesFilter(string $file): bool
{
$included = false;
foreach ($this->includes as $path) {
if (\str_starts_with($file, $path)) {
$included = true;
break;
}
}

if (!$included) {
return false;
}

foreach ($this->excludes as $path) {
if (\str_starts_with($file, $path)) {
return false;
}
}

return true;
}
}
Loading
Loading