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

93 lines
2.5 KiB
PHP
Raw Normal View History

2022-11-27 13:54:13 +01:00
<?php
namespace com\fwdekker\deathnotifier;
2022-11-27 13:54:13 +01:00
use com\fwdekker\deathnotifier\mailer\EmailQueue;
use com\fwdekker\deathnotifier\tracking\TrackingList;
use com\fwdekker\deathnotifier\user\UserList;
2022-11-27 13:54:13 +01:00
use Exception;
use PHPUnit\Framework\TestCase;
2022-11-27 13:54:13 +01:00
/**
* 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
2022-11-27 13:54:13 +01:00
*/
function get_email_queue(): EmailQueue
2022-11-27 13:54:13 +01:00
{
return $this->createStub(EmailQueue::class);
2022-11-27 13:54:13 +01:00
}
/**
* @return TrackingList the `TrackingList` to install the database schema of
2022-11-27 13:54:13 +01:00
*/
function get_tracking_list(): TrackingList
2022-11-27 13:54:13 +01:00
{
return $this->createStub(TrackingList::class);
2022-11-27 13:54:13 +01:00
}
/**
* @return UserList the `UserList` to install the database schema of
2022-11-27 13:54:13 +01:00
*/
function get_user_list(): UserList
2022-11-27 13:54:13 +01:00
{
return $this->createStub(UserList::class);
2022-11-27 13:54:13 +01:00
}
/**
* 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.");
2022-12-01 23:05:12 +01:00
$this->database = new Database($db_tmp_file);
$this->database->auto_install($this->get_email_queue(), $this->get_user_list(), $this->get_tracking_list());
2022-11-27 13:54:13 +01:00
}
}