97 lines
2.5 KiB
PHP
97 lines
2.5 KiB
PHP
|
<?php
|
||
|
|
||
|
namespace php;
|
||
|
|
||
|
use Exception;
|
||
|
use Monolog\Logger;
|
||
|
use Monolog\Test\TestCase;
|
||
|
|
||
|
|
||
|
/**
|
||
|
* For tests that use a fully-installed database.
|
||
|
*
|
||
|
* By default, only the main schema of the database is installed. Override the getters to additionally install the
|
||
|
* corresponding parts of the schema.
|
||
|
*/
|
||
|
abstract class DatabaseTestCase extends TestCase
|
||
|
{
|
||
|
/**
|
||
|
* @var string the temporary directory to store database files in
|
||
|
*/
|
||
|
private static string $db_tmp_dir;
|
||
|
|
||
|
/**
|
||
|
* @var Logger the logger
|
||
|
*/
|
||
|
public Logger $logger;
|
||
|
/**
|
||
|
* @var Database the database
|
||
|
*/
|
||
|
public Database $database;
|
||
|
|
||
|
|
||
|
/**
|
||
|
* @return Mailer the `Mailer` to install the database schema of
|
||
|
*/
|
||
|
function getMailer(): Mailer
|
||
|
{
|
||
|
return $this->createStub(Mailer::class);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @return TrackingManager the `TrackingManager` to install the database schema of
|
||
|
*/
|
||
|
function getTrackingManager(): TrackingManager
|
||
|
{
|
||
|
return $this->createStub(TrackingManager::class);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @return UserManager the `UserManager` to install the database schema of
|
||
|
*/
|
||
|
function getUserManager(): UserManager
|
||
|
{
|
||
|
return $this->createStub(UserManager::class);
|
||
|
}
|
||
|
|
||
|
|
||
|
/**
|
||
|
* Sets up a directory for temporary files.
|
||
|
*
|
||
|
* @throws Exception if the directory could not be created
|
||
|
*/
|
||
|
public static function setUpBeforeClass(): void
|
||
|
{
|
||
|
parent::setUpBeforeClass();
|
||
|
|
||
|
self::$db_tmp_dir = sys_get_temp_dir() . "/DatabaseTestCase-" . rand();
|
||
|
if (!mkdir(self::$db_tmp_dir))
|
||
|
throw new Exception("Failed to create temporary directory '" . self::$db_tmp_dir . "'.");
|
||
|
|
||
|
register_shutdown_function(function () {
|
||
|
$files = glob(self::$db_tmp_dir . "/*");
|
||
|
if ($files === false) return;
|
||
|
|
||
|
array_map("unlink", $files);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Sets up and installs a database.
|
||
|
*
|
||
|
* @throws Exception if the database file could not be created
|
||
|
*/
|
||
|
public function setUp(): void
|
||
|
{
|
||
|
parent::setUp();
|
||
|
|
||
|
$db_tmp_file = tempnam(self::$db_tmp_dir, "database-");
|
||
|
if ($db_tmp_file === false) throw new Exception("Failed to create temporary database file.");
|
||
|
|
||
|
$this->logger = new Logger("DatabaseTestCase");
|
||
|
$this->database = new Database($this->logger, $db_tmp_file);
|
||
|
|
||
|
$this->database->auto_install($this->getMailer(), $this->getUserManager(), $this->getTrackingManager());
|
||
|
}
|
||
|
}
|