TestCase.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests;
  4. use PDO;
  5. use PHPUnit\Framework\TestCase as PhpUnitTestCase;
  6. /**
  7. * Base TestCase with helpers for building an in-memory SQLite DB loaded with
  8. * the same migrations the app runs. Every test gets a fresh isolated database.
  9. */
  10. abstract class TestCase extends PhpUnitTestCase
  11. {
  12. protected function makeDb(): PDO
  13. {
  14. $pdo = new PDO('sqlite::memory:', null, null, [
  15. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  16. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  17. PDO::ATTR_EMULATE_PREPARES => false,
  18. ]);
  19. $pdo->exec('PRAGMA foreign_keys = ON');
  20. // Apply every NNN_*.sql in order — matches the production Migrator.
  21. $dir = __DIR__ . '/../migrations';
  22. $files = glob($dir . '/*.sql') ?: [];
  23. sort($files);
  24. foreach ($files as $file) {
  25. if (!preg_match('#/\d{3,}_[A-Za-z0-9_\-]+\.sql$#', $file)) {
  26. continue;
  27. }
  28. $sql = file_get_contents($file);
  29. if ($sql === false) {
  30. $this->fail("Could not read migration: {$file}");
  31. }
  32. $pdo->exec($sql);
  33. }
  34. return $pdo;
  35. }
  36. }