fix(tests): isolate databases in memory and reject persistent connections

This commit is contained in:
2026-09-14 12:35:34 -03:00
parent 28ab6c9ae4
commit 289ceba3af
8 changed files with 177 additions and 14 deletions

View File

@@ -3,8 +3,11 @@
namespace Tests;
use Illuminate\Foundation\Application;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Bootstrap\LoadConfiguration;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use RuntimeException;
use Tests\Support\InMemoryConnectionFactory;
abstract class TestCase extends BaseTestCase
{
@@ -13,19 +16,28 @@ abstract class TestCase extends BaseTestCase
*/
public function createApplication(): Application
{
$app = parent::createApplication();
$app = require dirname(__DIR__).'/bootstrap/app.php';
$this->traitsUsedByTest = class_uses_recursive(static::class);
$database = (string) $app['config']->get(
'database.connections.'.$app['config']->get('database.default').'.database'
);
if (! preg_match('/^shopit_(?:test|testing)(?:_\d+)?$/', $database)) {
throw new RuntimeException(sprintf(
'Refusing to run tests against database [%s]. Use [shopit_test] or [shopit_testing].',
$database !== '' ? $database : '(empty)'
));
if ($app->configurationIsCached()) {
throw new RuntimeException('Tests refuse cached configuration. Remove the test config cache before retrying.');
}
// Validate before providers boot or RefreshDatabase can run migrations.
$app->afterBootstrapping(LoadConfiguration::class, function (Application $app): void {
if (! $app->environment('testing')) {
throw new RuntimeException('Tests require APP_ENV=testing.');
}
InMemoryConnectionFactory::assertSafe((array) $app['config']->get(
'database.connections.'.$app['config']->get('database.default')
));
});
// Also guard named/dynamic connections and changes made by individual tests.
$app->extend('db.factory', fn () => new InMemoryConnectionFactory($app));
$app->make(Kernel::class)->bootstrap();
return $app;
}
}