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
13 changes: 8 additions & 5 deletions bridge/rector/FEATURE_PARITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,14 @@ Done since the first cut: **structural class/method conversion** (Testo ↔ PHPU
`#[\PHPUnit\Framework\Attributes\Test]` attribute is renamed to `#[\Testo\Test]`, a `@test` docblock
annotation is dropped and replaced by the attribute, and a bare `test`-prefixed method simply gains
the attribute (idempotent — a method already carrying `#[\Testo\Test]` is left alone); a trait's
non-abstract test methods gain it the same way. `parent::method();` statements that resolve into
PHPUnit are dropped, while calls reaching a method of a converted local base stay; a `parent::` call
to a static assertion of PHPUnit's `Assert` becomes `\PHPUnit\Framework\Assert::assertX()`, which the
assertion rules convert when Testo maps it and which stays a valid PHPUnit call otherwise (a
`TestCase` hook such as `assertPostConditions()` is dropped with the rest). The mirror
non-abstract test methods gain it the same way. Calls reaching a method of a converted local base
stay, while `parent::method();` statements that resolve into PHPUnit, which would no longer compile,
are rewritten: a call to a `TestCase` hook (`setUp()`, `tearDown()`, `assertPostConditions()` and the
like), or to the PHPUnit method its enclosing method overrides, is dropped; a call to a static
assertion of PHPUnit's `Assert` becomes `\PHPUnit\Framework\Assert::assertX()`, which the assertion
rules convert when Testo maps it and which stays a valid PHPUnit call otherwise; any other call, such
as `parent::markTestSkipped()` or `parent::expectException()`, becomes `self::`/`$this->` and converts
like that spelling. An anonymous class extending `TestCase` directly is handled the same way. The mirror
`TestClassToTestCaseRector` (Testo → PHPUnit) adds `extends \PHPUnit\Framework\TestCase` and, for a
class-level `#[\Testo\Test]`, removes it and adds a per-method `#[\PHPUnit\Framework\Attributes\Test]`
to every public, non-static, `void`/`never` method (mirroring Testo's locator, so static/`iterable`
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

final class ParentBehaviourSetTest extends \PHPUnit\Framework\TestCase
{
public function testSkipped(): void
{
parent::markTestSkipped('not ready');
}

public function testThrows(): void
{
parent::expectException(\RuntimeException::class);
throw new \RuntimeException();
}

public function testGuarded(): void
{
if (\PHP_INT_SIZE === 4) {
parent::markTestIncomplete('32-bit');
}
}
}
-----
<?php

final class ParentBehaviourSetTest
{
#[\Testo\Test]
#[\Testo\Skip('not ready')]
public function testSkipped(): void
{
}

#[\Testo\Test]
public function testThrows(): void
{
\Testo\Expect::exception(\RuntimeException::class);
throw new \RuntimeException();
}

#[\Testo\Test]
public function testGuarded(): void
{
if (\PHP_INT_SIZE === 4) {
throw new \Testo\Core\Exception\SkipTest('Incomplete: 32-bit');
}
}
}
113 changes: 85 additions & 28 deletions bridge/rector/src/PhpunitToTesto/ExtendsTestCaseToTestoRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
use PhpParser\Node\Arg;
use PhpParser\Node\Attribute;
use PhpParser\Node\AttributeGroup;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Name\FullyQualified;
Expand All @@ -18,6 +20,7 @@
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Trait_;
use PhpParser\NodeVisitor;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
Expand All @@ -44,8 +47,12 @@
* `TestCase` hooks), since PHP rejects the attribute on a method without a parent declaration.
* A method declared by one of the class's interfaces keeps it, as does every method when an
* interface cannot be resolved;
* - drops the `parent::setUp()`-style call statements that resolve into PHPUnit, since PHP rejects
* `parent` in a class without one. A call whose result is used is left for the manual pass.
* - rewrites the `parent::` call statements that resolve into PHPUnit, since PHP rejects `parent`
* in a class without one: a `parent::setUp()`-style hook call, or a call to the PHPUnit method
* its own enclosing method overrides, is dropped, and any other call, such as
* `parent::markTestSkipped()`, becomes `self::`/`$this->` for the skip and expectation rules to
* convert. A call whose result is used is left for the manual pass. An anonymous class that
* extends `TestCase` directly is handled the same way; one on a project base is left untouched.
*
* "Test method" mirrors PHPUnit's own discovery: a method carrying the PHPUnit
* `#[\PHPUnit\Framework\Attributes\Test]` attribute, a method with a `@test` docblock
Expand All @@ -58,8 +65,8 @@
* `extends` and its `#[\Override]` attributes — the base is still there, converted on its own —
* and only gains `#[\Testo\Test]` on its test methods. Without them Testo would not discover the
* subclass's tests at all. Its `parent::` calls to a PHPUnit method the base does not override are
* dropped as well. A base that cannot be resolved, or does not lead to `TestCase`, leaves the class
* untouched.
* rewritten the same way. A base that cannot be resolved, or does not lead to `TestCase`, leaves the
* class untouched.
*
* A base from outside the processed paths, such as a framework's test case in vendor, stays a
* PHPUnit class. Its subclasses are converted all the same, keep their `parent::` calls, and the
Expand All @@ -82,6 +89,21 @@ final class ExtendsTestCaseToTestoRector extends AbstractRector
{
use OriginalTokens;

/**
* `TestCase` methods whose `parent::` call only reaches PHPUnit's own plumbing; Testo runs the
* overriding method on its own, so the call has nothing left to do.
*/
private const DROPPED_HOOKS = [
'__construct',
'setup',
'teardown',
'setupbeforeclass',
'teardownafterclass',
'assertpreconditions',
'assertpostconditions',
'onnotsuccessfultest',
];

public function __construct(
private readonly PhpDocInfoFactory $phpDocInfoFactory,
private readonly PhpDocTagRemover $phpDocTagRemover,
Expand Down Expand Up @@ -153,10 +175,11 @@ public function refactor(Node $node): ?Node

# Indirect subclass: the base stays, only discovery needs the attribute.
$vendorBase = $this->testCaseClass->phpunitBaseFromVendor($node);
$base = $vendorBase === null ? $this->base($node) : null;
$changed = false;
foreach ($node->getMethods() as $method) {
$method->isPublic() && $this->markTestMethod($method) and $changed = true;
$vendorBase === null && $this->removePhpunitParentCalls($node, $method) and $changed = true;
$base !== null && $this->rewritePhpunitParentCalls($base, $method) and $changed = true;
}

$vendorBase !== null && $vendorBase['direct'] && $this->skipOnVendorBase($node, $vendorBase['name'])
Expand All @@ -165,13 +188,14 @@ public function refactor(Node $node): ?Node
return $changed ? $node : null;
}

$base = $this->base($node);
$node->extends = null;

$interfaces = $this->nodeNameResolver->getNames($node->implements);
foreach ($node->getMethods() as $method) {
$method->isPublic() and $this->markTestMethod($method);
$this->isDeclaredByInterface($method, $interfaces) or $this->removeOverrideAttribute($method);
$this->removePhpunitParentCalls($node, $method);
$this->rewritePhpunitParentCalls($base, $method);
}

return $node;
Expand Down Expand Up @@ -209,27 +233,46 @@ private function skipOnVendorBase(Class_ $class, string $vendorBase): bool
}

/**
* Drops the `parent::method()` statements that resolve into PHPUnit, which the converted chain no
* longer extends: without a parent PHP rejects `parent` at compile time, and on a converted base
* The class's direct base as loaded from source, read from the name it extends before its
* `extends` is removed: an anonymous class has no name of its own to reflect.
*
* @return ClassReflection|null Null when the base cannot be resolved.
*/
private function base(Class_ $class): ?ClassReflection
{
$base = $class->extends === null ? null : $this->getName($class->extends);

return $base !== null && $this->reflectionProvider->hasClass($base)
? $this->reflectionProvider->getClass($base)
: null;
}

/**
* Rewrites the `parent::method()` statements that resolve into PHPUnit, which the converted chain
* no longer extends: without a parent PHP rejects `parent` at compile time, and on a converted base
* the method is gone. A call reaching a method a local base declares stays, as does a call whose
* result is used. An anonymous class inside the method has a parent of its own and is not entered.
*
* A PHPUnit assertion is kept as an explicit `\PHPUnit\Framework\Assert::` call instead: the
* assertion rules convert the ones Testo maps, and the rest stay valid PHPUnit calls rather than
* a `parent::` that would stop the whole file from compiling.
* Only a call to a `TestCase` hook, or to the PHPUnit method the enclosing one overrides, is
* dropped. A PHPUnit assertion becomes an explicit `\PHPUnit\Framework\Assert::` call: the
* assertion rules convert the ones Testo maps, and the rest stay valid PHPUnit calls. Any other
* call, such as `markTestSkipped()` or `expectException()`, becomes `self::` or `$this->`, the
* spelling the skip and expectation rules convert by name; dropping it would silently change what
* the test checks.
*
* Without the base's reflection, as for a class extending `TestCase` directly while PHPUnit cannot
* be resolved, every call is taken to reach PHPUnit.
*
* @return bool Whether a call was changed.
*/
private function removePhpunitParentCalls(Class_ $class, ClassMethod $method): bool
private function rewritePhpunitParentCalls(?ClassReflection $base, ClassMethod $method): bool
{
$name = $class->namespacedName?->toString();
if ($name === null || !$this->reflectionProvider->hasClass($name)) {
return false;
}

$parents = $this->reflectionProvider->getClass($name)->getParents();
$native = $base?->getNativeReflection();
$changed = false;
$this->traverseNodesWithCallable($method, function (Node $node) use ($parents, &$changed): ?int {
# Within its own override a rewritten call would reach the override again.
$dropped = [...self::DROPPED_HOOKS, $method->name->toLowerString()];
$inStatic = $method->isStatic();
$this->traverseNodesWithCallable($method, function (Node $node) use ($native, $dropped, $inStatic, &$changed): ?int {
if ($node instanceof Class_) {
return NodeVisitor::DONT_TRAVERSE_CHILDREN;
}
Expand All @@ -244,14 +287,17 @@ private function removePhpunitParentCalls(Class_ $class, ClassMethod $method): b
}

$called = $node->expr->name->toString();
foreach ($parents as $parent) {
$native = $parent->getNativeReflection();
if (!\str_starts_with($parent->getName(), 'PHPUnit\\')
&& $native->hasMethod($called)
&& !\str_starts_with($native->getMethod($called)->getDeclaringClass()->getName(), 'PHPUnit\\')
) {
# The base's reflection covers every inherited method. A method no ancestor declares
# becomes `$this->` too: a visible call to a missing method rather than a statement that
# silently disappears.
$static = false;
if ($native?->hasMethod($called)) {
$declared = $native->getMethod($called);
if (!\str_starts_with($declared->getDeclaringClass()->getName(), 'PHPUnit\\')) {
return null;
}

$static = $declared->isStatic();
}

$changed = true;
Expand All @@ -261,15 +307,26 @@ private function removePhpunitParentCalls(Class_ $class, ClassMethod $method): b
return null;
}

return NodeVisitor::REMOVE_NODE;
if (\in_array(\strtolower($called), $dropped, true)) {
return NodeVisitor::REMOVE_NODE;
}

# A static method has no `$this` to call on.
if ($static || $inStatic) {
$node->expr->class = new Name('self');
} else {
$node->expr = new MethodCall(new Variable('this'), $node->expr->name, $node->expr->args);
}

return null;
});

return $changed;
}

/**
* Only a static assertion declared on `Assert` survives the rewrite; `TestCase` hooks such as
* `assertPostConditions()` exist on the instance alone and are dropped with the other calls.
* Only a static assertion declared on `Assert` counts; `TestCase` hooks such as
* `assertPostConditions()` exist on the instance alone and are dropped as hooks.
*/
private function isPhpunitAssertion(StaticCall $call): bool
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

final class AnonymousFactory
{
public function make(): object
{
return new class extends \PHPUnit\Framework\TestCase {
protected function setUp(): void
{
parent::setUp();
parent::markTestIncomplete('later');
}
};
}
}
-----
<?php

final class AnonymousFactory
{
public function make(): object
{
return new class {
protected function setUp(): void
{
self::markTestIncomplete('later');
}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

final class ParentBehaviourTest extends \PHPUnit\Framework\TestCase
{
public function testSkipped(): void
{
parent::markTestSkipped('not ready');
}

public function testThrows(): void
{
parent::expectException(\RuntimeException::class);
parent::expectExceptionMessage('boom');
throw new \RuntimeException('boom');
}

public function testCounted(): void
{
parent::addToAssertionCount(1);
}
}
-----
<?php

final class ParentBehaviourTest
{
#[\Testo\Test]
public function testSkipped(): void
{
self::markTestSkipped('not ready');
}

#[\Testo\Test]
public function testThrows(): void
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('boom');
throw new \RuntimeException('boom');
}

#[\Testo\Test]
public function testCounted(): void
{
$this->addToAssertionCount(1);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

final class OwnOverrideTest extends \PHPUnit\Framework\TestCase
{
public function expectException($exception): void
{
parent::expectException($exception);
}
}
-----
<?php

final class OwnOverrideTest
{
public function expectException($exception): void
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

final class StaticParentCallTest extends \PHPUnit\Framework\TestCase
{
public static function bootOnce(): void
{
parent::bootKernel();
}
}
-----
<?php

final class StaticParentCallTest
{
public static function bootOnce(): void
{
self::bootKernel();
}
}
Loading
Loading