Skip to content

Commit

Permalink
fix rolling back transaction for errored tests
Browse files Browse the repository at this point in the history
  • Loading branch information
dmaicher committed Dec 5, 2023
1 parent e7ed492 commit f0d32de
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions src/DAMA/DoctrineTestBundle/PHPUnit/PHPUnitExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace DAMA\DoctrineTestBundle\PHPUnit;

use DAMA\DoctrineTestBundle\Doctrine\DBAL\StaticDriver;
use PHPUnit\Event\Test\Errored;
use PHPUnit\Event\Test\ErroredSubscriber;
use PHPUnit\Event\Test\Finished as TestFinishedEvent;
use PHPUnit\Event\Test\FinishedSubscriber as TestFinishedSubscriber;
use PHPUnit\Event\Test\PreparationStarted as TestStartedEvent;
Expand All @@ -28,7 +30,17 @@
*/
class PHPUnitExtension implements Extension
{
public static $rolledBack = false;
public static $transactionStarted = false;

public static function rollBack(): void
{
if (!self::$transactionStarted) {
return;
}

StaticDriver::rollBack();
self::$transactionStarted = false;
}

public function bootstrap(Configuration $configuration, Facade $facade, ParameterCollection $parameters): void
{
Expand All @@ -42,8 +54,8 @@ public function notify(TestRunnerStartedEvent $event): void
$facade->registerSubscriber(new class() implements TestStartedSubscriber {
public function notify(TestStartedEvent $event): void
{
PHPUnitExtension::$rolledBack = false;
StaticDriver::beginTransaction();
PHPUnitExtension::$transactionStarted = true;
}
});

Expand All @@ -52,18 +64,22 @@ public function notify(Skipped $event): void
{
// this is a workaround to allow skipping tests within the setUp() method
// as for those cases there is no Finished event
PHPUnitExtension::$rolledBack = true;
StaticDriver::rollBack();
PHPUnitExtension::rollBack();
}
});

$facade->registerSubscriber(new class() implements TestFinishedSubscriber {
public function notify(TestFinishedEvent $event): void
{
// we only roll back if we did not already do it in the SkippedSubscriber
if (!PHPUnitExtension::$rolledBack) {
StaticDriver::rollBack();
}
PHPUnitExtension::rollBack();
}
});

$facade->registerSubscriber(new class() implements ErroredSubscriber {
public function notify(Errored $event): void
{
// needed as for errored tests the "Finished" event is not triggered
PHPUnitExtension::rollBack();
}
});

Expand Down

0 comments on commit f0d32de

Please sign in to comment.