Files
duckbrain/tests/TestCase.php

62 lines
1.7 KiB
PHP

<?php
namespace Tests;
use Libs\Database;
use PDO;
use PHPUnit\Framework\TestCase as FrameworkTestCase;
/**
* TestCase - DuckBrain test harness
*
* Base class for the framework's own tests. Deliberately lightweight: this
* repo has no migrations/ nor duckbrain-commands, so each test defines its
* schema with raw DDL through createTable(), and tables registered there are
* dropped automatically after the class finishes.
*/
abstract class TestCase extends FrameworkTestCase
{
/**
* @var list<string> Tables created through createTable() for this class.
*/
private static array $tables = [];
/**
* Returns the PDO connection to the in-memory test database.
*
* @return PDO
*/
protected static function db(): PDO
{
return Database::getInstance(DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS);
}
/**
* Creates a table in the test database and registers it for cleanup.
*
* @param string $name
* Table name.
*
* @param string $columns
* Raw column definition, as accepted by the test
* engine (sqlite): "id INTEGER PRIMARY KEY, x TEXT".
*/
protected static function createTable(string $name, string $columns): void
{
static::db()->exec("CREATE TABLE IF NOT EXISTS {$name} ({$columns})");
static::$tables[] = $name;
}
/**
* Drops every table registered through createTable() during this class.
*/
public static function tearDownAfterClass(): void
{
foreach (array_unique(static::$tables) as $table) {
static::db()->exec("DROP TABLE IF EXISTS {$table}");
}
static::$tables = [];
}
}