death-notifier/src/test/php/com/fwdekker/deathnotifier/DatabaseTestCase.php

93 lines
2.5 KiB
PHP

<?php
namespace com\fwdekker\deathnotifier;
use com\fwdekker\deathnotifier\mailer\EmailQueue;
use com\fwdekker\deathnotifier\tracking\TrackingList;
use com\fwdekker\deathnotifier\user\UserList;
use Exception;
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 Database the database
*/
public Database $database;
/**
* @return EmailQueue the `EmailQueue` to install the database schema of
*/
function get_email_queue(): EmailQueue
{
return $this->createStub(EmailQueue::class);
}
/**
* @return TrackingList the `TrackingList` to install the database schema of
*/
function get_tracking_list(): TrackingList
{
return $this->createStub(TrackingList::class);
}
/**
* @return UserList the `UserList` to install the database schema of
*/
function get_user_list(): UserList
{
return $this->createStub(UserList::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->database = new Database($db_tmp_file);
$this->database->auto_install($this->get_email_queue(), $this->get_user_list(), $this->get_tracking_list());
}
}