Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: throw an error if Factories trait is not used in a KernelTestCase #766

Merged
Merged
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
/.phpunit.cache
/vendor/
/bin/tools/*/vendor/
/bin/tools/php-cs-fixer/composer.lock
/bin/tools/csfixer
/build/
/.php-cs-fixer.cache
/.phpunit.result.cache
Expand Down
7 changes: 7 additions & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@
\file_get_contents('https://raw.githubusercontent.com/zenstruck/.github/main/.php-cs-fixer.dist.php')
);

$finder = PhpCsFixer\Finder::create()
->in([__DIR__.'/src', __DIR__.'/tests'])

// we want to keep the traits in "wrong order"
->notName('KernelTestCaseWithBothTraitsInWrongOrderTest.php')
;

try {
return require $file;
} finally {
Expand Down
1 change: 1 addition & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<testsuite name="main">
<directory>tests</directory>
<exclude>tests/Integration/ResetDatabase</exclude>
<exclude>tests/Integration/ForceFactoriesTraitUsage</exclude>
</testsuite>
<testsuite name="reset-database">
<directory>tests/Integration/ResetDatabase</directory>
Expand Down
3 changes: 3 additions & 0 deletions src/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Zenstruck\Foundry;

use Faker;
use Zenstruck\Foundry\Exception\FactoriesTraitNotUsed;
use Zenstruck\Foundry\Exception\FoundryNotBooted;
use Zenstruck\Foundry\Exception\PersistenceDisabled;
use Zenstruck\Foundry\Exception\PersistenceNotAvailable;
Expand Down Expand Up @@ -90,6 +91,8 @@ public static function instance(): self
throw new FoundryNotBooted();
}

FactoriesTraitNotUsed::throwIfComingFromKernelTestCaseWithoutFactoriesTrait();

return \is_callable(self::$instance) ? (self::$instance)() : self::$instance;
}

Expand Down
67 changes: 67 additions & 0 deletions src/Exception/FactoriesTraitNotUsed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

declare(strict_types=1);

/*
* This file is part of the zenstruck/foundry package.
*
* (c) Kevin Bond <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Zenstruck\Foundry\Exception;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Zenstruck\Foundry\Test\Factories;

/**
* @author Nicolas PHILIPPE <[email protected]>
*/
final class FactoriesTraitNotUsed extends \LogicException
{
/**
* @param class-string<KernelTestCase> $class
*/
private function __construct(string $class)
{
parent::__construct(
\sprintf('You must use the trait "%s" in "%s" in order to use Foundry.', Factories::class, $class)
);
}

public static function throwIfComingFromKernelTestCaseWithoutFactoriesTrait(): void
{
$backTrace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); // @phpstan-ignore ekinoBannedCode.function

foreach ($backTrace as $trace) {
if (
'->' === ($trace['type'] ?? null)
&& isset($trace['class'])
&& KernelTestCase::class !== $trace['class']
&& \is_a($trace['class'], KernelTestCase::class, allow_string: true)
&& !(new \ReflectionClass($trace['class']))->hasMethod('_bootFoundry')
) {
self::throwIfClassDoesNotHaveFactoriesTrait($trace['class']);
}
}
}

/**
* @param class-string<KernelTestCase> $class
*/
public static function throwIfClassDoesNotHaveFactoriesTrait(string $class): void
{
if (!(new \ReflectionClass($class))->hasMethod('_bootFoundry')) {
// throw new self($class);
trigger_deprecation(
'zenstruck/foundry',
'2.4',
'In order to use Foundry, you must use the trait "%s" in your "%s" tests. This will throw an exception in 3.0.',
KernelTestCase::class,
$class
);
Comment on lines +58 to +64
Copy link
Member Author

@nikophil nikophil Jan 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

at first I built everything to throw an error, but now I think we should not throw, it's a little bit too much violent I think 😆 🥊

But since everything is ready to throw, I propose to keep it like this in the exception

}
}
}
3 changes: 3 additions & 0 deletions src/PHPUnit/BuildStoryOnTestPrepared.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use PHPUnit\Event;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Zenstruck\Foundry\Attribute\WithStory;
use Zenstruck\Foundry\Exception\FactoriesTraitNotUsed;

/**
* @internal
Expand Down Expand Up @@ -46,6 +47,8 @@ public function notify(Event\Test\Prepared $event): void
throw new \InvalidArgumentException(\sprintf('The test class "%s" must extend "%s" to use the "%s" attribute.', $test->className(), KernelTestCase::class, WithStory::class));
}

FactoriesTraitNotUsed::throwIfClassDoesNotHaveFactoriesTrait($test->className());

foreach ($withStoryAttributes as $withStoryAttribute) {
$withStoryAttribute->newInstance()->story::load();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

/*
* This file is part of the zenstruck/foundry package.
*
* (c) Kevin Bond <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Zenstruck\Foundry\Tests\Integration\ForceFactoriesTraitUsage;

use PHPUnit\Framework\Attributes\RequiresPhpunit;
use PHPUnit\Framework\Attributes\Test;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Zenstruck\Foundry\Test\Factories;
use Zenstruck\Foundry\Test\ResetDatabase;
use Zenstruck\Foundry\Tests\Fixture\Factories\Object1Factory;

#[RequiresPhpunit('>=11.0')]
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only PhpUnit 11 handles correctly deprecation, so all tests in this namespace will only be ran with phpunit 11

final class KernelTestCaseWithBothTraitsInWrongOrderTest extends KernelTestCase
{
use ResetDatabase, Factories;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in my different tests, I noticed that sometimes, the order of these traits could have an impact, so I wanted to test with both cases


#[Test]
public function should_not_throw(): void
{
Object1Factory::createOne();

$this->expectNotToPerformAssertions();
}

#[Test]
public function should_not_throw_even_when_kernel_is_booted(): void
{
self::getContainer()->get('.zenstruck_foundry.configuration');

Object1Factory::createOne();

$this->expectNotToPerformAssertions();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

/*
* This file is part of the zenstruck/foundry package.
*
* (c) Kevin Bond <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Zenstruck\Foundry\Tests\Integration\ForceFactoriesTraitUsage;

use PHPUnit\Framework\Attributes\RequiresPhpunit;
use PHPUnit\Framework\Attributes\Test;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Zenstruck\Foundry\Test\Factories;
use Zenstruck\Foundry\Test\ResetDatabase;
use Zenstruck\Foundry\Tests\Fixture\Factories\Object1Factory;

#[RequiresPhpunit('>=11.0')]
final class KernelTestCaseWithBothTraitsTest extends KernelTestCase
{
use Factories, ResetDatabase;

#[Test]
public function should_not_throw(): void
{
Object1Factory::createOne();

$this->expectNotToPerformAssertions();
}

#[Test]
public function should_not_throw_even_when_kernel_is_booted(): void
{
self::getContainer()->get('.zenstruck_foundry.configuration');

Object1Factory::createOne();

$this->expectNotToPerformAssertions();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

/*
* This file is part of the zenstruck/foundry package.
*
* (c) Kevin Bond <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Zenstruck\Foundry\Tests\Integration\ForceFactoriesTraitUsage;

use PHPUnit\Framework\Attributes\RequiresPhpunit;
use PHPUnit\Framework\Attributes\Test;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Zenstruck\Foundry\Test\Factories;
use Zenstruck\Foundry\Tests\Fixture\Factories\Object1Factory;

#[RequiresPhpunit('>=11.0')]
final class KernelTestCaseWithFactoriesTraitTest extends KernelTestCase
{
use Factories;

#[Test]
public function should_not_throw(): void
{
Object1Factory::createOne();

$this->expectNotToPerformAssertions();
}

#[Test]
public function should_not_throw_even_when_kernel_is_booted(): void
{
self::getContainer()->get('.zenstruck_foundry.configuration');

Object1Factory::createOne();

$this->expectNotToPerformAssertions();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

/*
* This file is part of the zenstruck/foundry package.
*
* (c) Kevin Bond <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Zenstruck\Foundry\Tests\Integration\ForceFactoriesTraitUsage;

use PHPUnit\Framework\Attributes\RequiresPhpunit;
use Zenstruck\Foundry\Test\ResetDatabase;

#[RequiresPhpunit('>=11.0')]
final class KernelTestCaseWithOnlyResetDatabaseTraitTest extends KernelTestCaseWithoutFactoriesTraitTestCase
{
use ResetDatabase;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

/*
* This file is part of the zenstruck/foundry package.
*
* (c) Kevin Bond <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Zenstruck\Foundry\Tests\Integration\ForceFactoriesTraitUsage;

use PHPUnit\Framework\Attributes\RequiresPhpunit;

#[RequiresPhpunit('>=11.0')]
final class KernelTestCaseWithoutFactoriesTraitTest extends KernelTestCaseWithoutFactoriesTraitTestCase
{
}
Loading
Loading