408 lines
16 KiB
PHP
408 lines
16 KiB
PHP
<?php
|
||
|
||
namespace goodboyalex\php_db_components_pack\tests\classes;
|
||
|
||
use Exception;
|
||
use goodboyalex\php_components_pack\classes\ObjectArray;
|
||
use goodboyalex\php_components_pack\types\GUID;
|
||
use goodboyalex\php_db_components_pack\classes\ConditionBuilder;
|
||
use goodboyalex\php_db_components_pack\classes\Database;
|
||
use goodboyalex\php_db_components_pack\models\DBConfig;
|
||
use goodboyalex\php_db_components_pack\tests\data\UserModel;
|
||
use PHPUnit\Framework\TestCase;
|
||
|
||
class DatabaseTest extends TestCase
|
||
{
|
||
public function testDatabase ()
|
||
{
|
||
/**
|
||
* ВНИМАТЕЛЬНО ПРОЧТИТЕ, ПЕРЕД ВЫПОЛНЕНИЕМ ТЕСТА.
|
||
*
|
||
* Подготовка к тесту:
|
||
*
|
||
* - создайте тестовую базу данных;
|
||
* - создайте пользователя и его пароль;
|
||
* - сделайте его создателем с правами управления созданной в п. 1 БД;
|
||
* - в корне папки "tests" создайте файл "database_config.php";
|
||
* - убедитесь, что он добавлен в .gitignore и НИКАКИМ ОБРАЗОМ НЕ ПОПАДЁТ В РЕПОЗИТАРИЙ (это
|
||
* скомпрометирует вшу БД!);
|
||
* - в этом файле задайте переменной $testConfig класс настроек с необходимыми настройками или можете
|
||
* воспользоваться файлом "database_config_sample.php", переименовав его в "database_config.php".
|
||
*/
|
||
|
||
/**
|
||
* Подключаем настройки базы данных.
|
||
*
|
||
* @var DBConfig $testConfig Конфигурация СУБД.
|
||
*/
|
||
require_once "../database_config.php";
|
||
|
||
// Подключаем данные
|
||
require_once '../data/Converters.php';
|
||
require_once '../data/UserModel.php';
|
||
|
||
// Задаём действие при ошибке
|
||
$onException = fn (Exception $exception, bool $terminate)
|
||
=> $terminate
|
||
? die($exception->getMessage())
|
||
: print $exception->getMessage();
|
||
|
||
// Подключаем базу данных
|
||
$db = new Database($testConfig, $onException);
|
||
|
||
/* ТЕСТ 1: Создание таблицы */
|
||
|
||
// Задаём имя таблицы
|
||
$tableName = 'users';
|
||
|
||
// Создаю таблицу
|
||
$db->CreateTable(
|
||
tableName: $tableName,
|
||
dbItemClass: '\goodboyalex\php_db_components_pack\tests\data\UserModel'
|
||
);
|
||
|
||
// Проверяю создание
|
||
$this->assertTrue($db->IsTableExist($tableName));
|
||
|
||
/* 2. Добавление данных */
|
||
|
||
/* 2.1. Модели */
|
||
|
||
// Модель 1
|
||
$model1 = new UserModel(
|
||
id: GUID::Parse('8b5dab25-4445-436c-8f25-0f5352cb8500', true),
|
||
login: "account1",
|
||
password: "password1",
|
||
salt: GUID_EMPTY,
|
||
firstName: "firstName1",
|
||
middleName: "middleName1",
|
||
lastName: "lastName1",
|
||
email: "email1@ya.ru",
|
||
isEmailVerified: false,
|
||
groupName: "default",
|
||
createdAt: time(),
|
||
updatedAt: 0,
|
||
userData: ['key1' => 'value1', 'key2' => 'value2']
|
||
);
|
||
|
||
// Модель 2
|
||
$model2 = new UserModel(
|
||
id: GUID::Parse('3552914c-9ffc-4c73-8946-97c40b0d81b5'),
|
||
login: "account2",
|
||
password: "password2",
|
||
salt: GUID_EMPTY,
|
||
firstName: "firstName2",
|
||
middleName: "middleName2",
|
||
lastName: "lastName2",
|
||
email: "email2@ya.ru",
|
||
isEmailVerified: false,
|
||
groupName: "default",
|
||
createdAt: time(),
|
||
updatedAt: 0,
|
||
userData: ['key1' => 'value3', 'key2' => 4]
|
||
);
|
||
|
||
// Модель 3
|
||
$model3 = new UserModel(
|
||
id: GUID::Parse('73828df6-89a3-4feb-ae9a-ef79d0e67cb0'),
|
||
login: "account3",
|
||
password: "password3",
|
||
salt: GUID_EMPTY,
|
||
firstName: "firstName3",
|
||
middleName: "middleName3",
|
||
lastName: "lastName3",
|
||
email: "email3@ya.ru",
|
||
isEmailVerified: true,
|
||
groupName: "default1",
|
||
createdAt: time(),
|
||
updatedAt: time(),
|
||
userData: ['key1' => 1, 'key2' => 2]
|
||
);
|
||
|
||
// Модель 4
|
||
$model4 = new UserModel(
|
||
id: GUID::Parse('df39f53f-faff-42cf-bf00-f5855c3e11ec'),
|
||
login: "account4",
|
||
password: "password4",
|
||
salt: GUID_EMPTY,
|
||
firstName: "firstName4",
|
||
middleName: "middleName4",
|
||
lastName: "lastName4",
|
||
email: "email4@ya.ru",
|
||
isEmailVerified: true,
|
||
groupName: "default1",
|
||
createdAt: time(),
|
||
updatedAt: time(),
|
||
userData: ['key1' => 3, 'key2' => '2']
|
||
);
|
||
|
||
/* 2.2. Добавление 1 элемента */
|
||
// Вставляю $model1
|
||
$result = $db->Insert($tableName, $model1);
|
||
|
||
// Проверяю, успешно ли прошло
|
||
$this->assertTrue($result !== false);
|
||
|
||
// - и совпадает ли идентификатор
|
||
$this->assertTrue($model1->Id->IsEqualsTo($result));
|
||
|
||
/* 2.3. Добавление более 1 элемента */
|
||
// Массив ожидаемых результатов
|
||
$expectedResult = [
|
||
GUID::Parse('3552914c-9ffc-4c73-8946-97c40b0d81b5'),
|
||
GUID::Parse('73828df6-89a3-4feb-ae9a-ef79d0e67cb0'),
|
||
GUID::Parse('df39f53f-faff-42cf-bf00-f5855c3e11ec')
|
||
];
|
||
|
||
// Вставляю несколько
|
||
$result = $db->InsertMany('users', $model2, $model3, $model4);
|
||
|
||
// Убеждаюсь, что вставка успешна
|
||
$this->assertTrue($result !== false);
|
||
|
||
// - и все идентификаторы совпадают
|
||
$this->assertEqualsCanonicalizing($expectedResult, $result);
|
||
}
|
||
|
||
public function testGetRow ()
|
||
{
|
||
$this->IncludeReq();
|
||
|
||
$db = $this->GetDatabase();
|
||
|
||
if (!$db->IsTableExist('users'))
|
||
die('Таблица не существует. Сперва запустите тест testCreateTable / Table does not exist. Run testCreateTable first');
|
||
|
||
if (!$db->IsExist(
|
||
table: 'users',
|
||
where: new ConditionBuilder()->WhereEquals('login', 'account1')
|
||
))
|
||
die('Записи с логином account1 не существует в таблице users / Record with login account1 is not exists in table users');
|
||
|
||
/**
|
||
* @var false|UserModel $model
|
||
*/
|
||
$model = $db->GetRow(
|
||
table: 'users',
|
||
where: new ConditionBuilder()->WhereEquals('login', 'account1'),
|
||
className: '\goodboyalex\php_db_components_pack\tests\data\UserModel'
|
||
);
|
||
|
||
$this->assertTrue($model !== false);
|
||
$this->assertEquals('account1', $model->Login);
|
||
$this->assertEquals(
|
||
'account1', $model->Id->IsEqualsTo(GUID::Parse('8b5dab25-4445-436c-8f25-0f5352cb8500'))
|
||
);
|
||
}
|
||
|
||
public function testGetCol ()
|
||
{
|
||
$this->IncludeReq();
|
||
|
||
$db = $this->GetDatabase();
|
||
|
||
if (!$db->IsTableExist('users'))
|
||
die('Таблица не существует. Сперва запустите тест testCreateTable / Table does not exist. Run testCreateTable first');
|
||
|
||
if (!$db->IsExist(
|
||
table: 'users',
|
||
where: new ConditionBuilder()
|
||
->WhereEquals('login', 'account2')
|
||
->Or()
|
||
->WhereEquals('login', 'account3')
|
||
->Or()
|
||
->WhereEquals('login', 'account4')
|
||
))
|
||
die('Записи с логином account1 не существует в таблице users / Record with login account1 is not exists in table users');
|
||
|
||
$models = $db->GetCol(
|
||
table: 'users',
|
||
column: 'id',
|
||
where: new ConditionBuilder()->WhereNotEquals('login', 'account1')
|
||
);
|
||
|
||
$this->assertTrue($models !== false);
|
||
|
||
$expected = [
|
||
"3552914c-9ffc-4c73-8946-97c40b0d81b5",
|
||
"73828df6-89a3-4feb-ae9a-ef79d0e67cb0",
|
||
"df39f53f-faff-42cf-bf00-f5855c3e11ec"
|
||
];
|
||
|
||
$this->assertEqualsCanonicalizing($expected, $models);
|
||
}
|
||
|
||
public function testGetRows ()
|
||
{
|
||
$this->IncludeReq();
|
||
|
||
$db = $this->GetDatabase();
|
||
|
||
if (!$db->IsTableExist('users'))
|
||
die('Таблица не существует. Сперва запустите тест testCreateTable / Table does not exist. Run testCreateTable first');
|
||
|
||
if (!$db->IsExist(
|
||
table: 'users',
|
||
where: new ConditionBuilder()
|
||
->WhereEquals('login', 'account2')
|
||
->Or()
|
||
->WhereEquals('login', 'account3')
|
||
->Or()
|
||
->WhereEquals('login', 'account4')
|
||
))
|
||
die('Записи с логином account1 не существует в таблице users / Record with login account1 is not exists in table users');
|
||
|
||
/**
|
||
* @var false|ObjectArray $model
|
||
*/
|
||
$models = $db->GetRows(
|
||
table: 'users',
|
||
where: new ConditionBuilder()->WhereNotEquals('login', 'account1'),
|
||
className: '\goodboyalex\php_db_components_pack\tests\data\UserModel'
|
||
);
|
||
|
||
$this->assertTrue($models !== false);
|
||
$this->assertTrue($models->IsExist(fn (UserModel $model) => $model->Login == 'account2'));
|
||
}
|
||
|
||
public function testDropTable ()
|
||
{
|
||
$this->IncludeReq();
|
||
|
||
$db = $this->GetDatabase();
|
||
|
||
$result = $db->DropTable('users');
|
||
|
||
$this->assertTrue($result);
|
||
}
|
||
|
||
public function testGetValue ()
|
||
{
|
||
$this->IncludeReq();
|
||
|
||
$db = $this->GetDatabase();
|
||
|
||
if (!$db->IsTableExist('users'))
|
||
die('Таблица не существует. Сперва запустите тест testCreateTable / Table does not exist. Run testCreateTable first');
|
||
|
||
if (!$db->IsExist(
|
||
table: 'users',
|
||
where: new ConditionBuilder()
|
||
->WhereEquals('login', 'account2')
|
||
->Or()
|
||
->WhereEquals('login', 'account3')
|
||
->Or()
|
||
->WhereEquals('login', 'account4')
|
||
))
|
||
die('Записи с логином account1 не существует в таблице users / Record with login account1 is not exists in table users');
|
||
|
||
$id = $db->GetValue(
|
||
table: 'users',
|
||
column: 'id',
|
||
where: new ConditionBuilder()->WhereEquals('login', 'account2')
|
||
);
|
||
|
||
$this->assertEquals("3552914c-9ffc-4c73-8946-97c40b0d81b5", $id);
|
||
}
|
||
|
||
public function testUpdate ()
|
||
{
|
||
$this->IncludeReq();
|
||
|
||
$db = $this->GetDatabase();
|
||
|
||
if (!$db->IsTableExist('users'))
|
||
die('Таблица не существует. Сперва запустите тест testCreateTable / Table does not exist. Run testCreateTable first');
|
||
|
||
if (!$db->IsExist(
|
||
table: 'users',
|
||
where: new ConditionBuilder()->WhereEquals('login', 'account1')
|
||
))
|
||
die('Запись с логином account1 не существует в таблице users. Сперва удалите запись с логином account1 (можно использовать метод testDelete) / Record with login account1 already exists in table users. Delete record with login account1 first');
|
||
|
||
$model = $db->GetRow(
|
||
'users',
|
||
where: new ConditionBuilder()->WhereEquals('login', 'account1'),
|
||
className: '\goodboyalex\php_db_components_pack\tests\data\UserModel'
|
||
);
|
||
|
||
$this->assertTrue($model !== false);
|
||
|
||
$model->Email = 'account1@yandex.ru';
|
||
|
||
$result = $db->Update('users', $model);
|
||
|
||
$this->assertTrue($result);
|
||
}
|
||
|
||
public function testUpdateMany ()
|
||
{
|
||
$this->IncludeReq();
|
||
|
||
$db = $this->GetDatabase();
|
||
|
||
$model1 = $db->GetRow(
|
||
'users',
|
||
where: new ConditionBuilder()->WhereEquals('login', 'account2'),
|
||
className: '\goodboyalex\php_db_components_pack\tests\data\UserModel'
|
||
);
|
||
|
||
$this->assertTrue($model1 !== false);
|
||
|
||
$model1->Email = 'account2@yandex.ru';
|
||
$model1->IsEmailVerified = true;
|
||
|
||
$model2 = $db->GetRow(
|
||
'users',
|
||
where: new ConditionBuilder()->WhereEquals('login', 'account3'),
|
||
className: '\goodboyalex\php_db_components_pack\tests\data\UserModel'
|
||
);
|
||
|
||
$this->assertTrue($model2 !== false);
|
||
|
||
|
||
$model2->Email = 'account3@yandex.ru';
|
||
$model2->IsEmailVerified = true;
|
||
|
||
$model3 = $db->GetRow(
|
||
'users',
|
||
where: new ConditionBuilder()->WhereEquals('login', 'account4'),
|
||
className: '\goodboyalex\php_db_components_pack\tests\data\UserModel'
|
||
);
|
||
|
||
$this->assertTrue($model3 !== false);
|
||
|
||
$model3->Email = 'account4@yandex.ru';
|
||
$model3->IsEmailVerified = true;
|
||
|
||
|
||
$result = $db->UpdateMany('users', $model1, $model2, $model3);
|
||
|
||
$this->assertTrue($result);
|
||
}
|
||
|
||
public function testDelete ()
|
||
{
|
||
$this->IncludeReq();
|
||
|
||
$db = $this->GetDatabase();
|
||
|
||
$result = $db->Delete('users', new ConditionBuilder()->WhereEquals('email_verified', 0));
|
||
|
||
$this->assertTrue($result);
|
||
|
||
$count = $db->Count('users');
|
||
$this->assertEquals(3, $count);
|
||
|
||
$result = $db->Delete('users');
|
||
|
||
$this->assertTrue($result);
|
||
|
||
$count = $db->Count('users');
|
||
$this->assertEquals(0, $count);
|
||
}
|
||
|
||
private function IncludeReq (): void {}
|
||
|
||
private function GetDatabase (): Database {}
|
||
} |