Фабрики моделей, помощники HTTP-тестов, migrate:fresh и сидер

This commit is contained in:
rsgrinko committed 2026-09-15 22:14:50 +03:00
1 parent 9673ac46ba
commit 9508c29964
7 files changed
+649

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
/**
* Фабрики моделей: из чего делать записи в тестах и сидерах.
*
* Описание — функция, получающая порядковый номер вызова: им отличаются логины
* и адреса, иначе вторая запись упрётся в уникальный индекс.
*
* Factory::of(Note::class)->times(5)->create(['user_id' => $user->id()]);
*/
use App\Models\Note;
use Rsgrinko\Proton\Auth\Password;
use Rsgrinko\Proton\Database\Model\Factory;
use Rsgrinko\Proton\Models\Role;
use Rsgrinko\Proton\Models\User;
Factory::define(User::class, static fn (int $number): array => [
'login' => 'user_' . Factory::unique(),
'email' => Factory::unique('user') . '@example.com',
'name' => 'Пользователь ' . $number,
'role_id' => Role::query()->where('is_system', 0)->value('id') ?? 0,
'active' => 1,
// Пароль кладём хешем: фабрика не должна знать, как он считается,
// но и сырую строку в базу класть нельзя
'password_hash' => Password::hash(Factory::unique('pass')),
]);
Factory::define(Note::class, static fn (int $number): array => [
'title' => 'Заметка ' . $number . ': ' . Factory::sentence(3),
'body' => Factory::sentence(20),
'pinned' => 0,
]);
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
/**
* Стартовые данные для разработки: `php bin/proton seed` или
* `php bin/proton migrate:fresh --seed`.
*
* Роли и первый администратор заводятся установщиком, поэтому здесь только
* то, на чём удобно смотреть списки: несколько пользователей и заметки.
* На боевой базе это не запускают.
*/
use App\Models\Note;
use Rsgrinko\Proton\Database\Model\Factory;
use Rsgrinko\Proton\Models\User;
return static function (callable $say): void {
$users = User::query()->count();
if ($users === 0) {
$say('Пользователей нет — сначала php bin/proton install');
return;
}
/** @var array<int, User> $people */
$people = Factory::of(User::class)->times(5)->create();
$say('Заведено пользователей: ' . count($people));
$notes = 0;
foreach ($people as $person) {
// Заметки раскладываем по людям: так видно, что область видимости работает
Factory::of(Note::class)
->times(random_int(2, 6))
->state(['user_id' => $person->id()])
->create();
$notes += Note::query()->where('user_id', $person->id())->count();
}
$say('Заведено заметок: ' . $notes);
};
+1
View File
@@ -28,6 +28,7 @@ final class Application
Commands\MigrateCommand::class,
Commands\MigrateStatusCommand::class,
Commands\MigrateRollbackCommand::class,
Commands\MigrateFreshCommand::class,
Commands\SeedCommand::class,
Commands\AppKeyCommand::class,
Commands\StatusCommand::class,
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Database\Connection;
use Rsgrinko\Proton\Database\Migrator;
use Rsgrinko\Proton\Database\Schema\Builder;
use Rsgrinko\Proton\Support\Config;
/**
* пересобрать схему с нуля: снести все таблицы и накатить миграции заново.
*
* Это инструмент разработки. На боевой базе он уничтожает данные, поэтому
* при APP_ENV=production команда не работает вовсе, а в остальных случаях
* требует подтверждения или --force.
*/
final class MigrateFreshCommand extends Command
{
public function name(): string
{
return 'migrate:fresh';
}
public function description(): string
{
return 'снести таблицы и накатить миграции заново (разработка)';
}
public function usage(): string
{
return 'migrate:fresh [--seed] [--force]';
}
public function run(): int
{
$environment = (string) Config::get('app.env', 'production');
if ($environment === 'production') {
$this->fail('На боевом окружении команда не работает: она удаляет все данные');
return 1;
}
$db = Connection::instance();
$tables = $db->tables();
if ($tables !== [] && !$this->confirm('Будут удалены все таблицы (' . count($tables) . ') и данные в них. Продолжать?')) {
$this->line('Отменено');
return 0;
}
$builder = new Builder($db);
// Порядок не важен: внешних ключей ядро не заводит, а если их добавило
// приложение, снимаем проверку на время сноса
$this->withoutForeignKeys($db, static function () use ($builder, $tables): void {
foreach ($tables as $table) {
$builder->drop($table);
}
});
$this->ok('Удалено таблиц: ' . count($tables));
$applied = (new Migrator())->run();
$this->ok('Применено миграций: ' . count($applied));
if ($this->hasOption('seed')) {
$this->line('');
return (new SeedCommand())->withInput([], $this->options)->run();
}
return 0;
}
/**
* Снос таблиц без проверки внешних ключей.
*/
private function withoutForeignKeys(Connection $db, callable $body): void
{
$sqlite = $db->isSqlite();
$db->execute($sqlite ? 'PRAGMA foreign_keys = OFF' : 'SET FOREIGN_KEY_CHECKS = 0');
try {
$body();
} finally {
$db->execute($sqlite ? 'PRAGMA foreign_keys = ON' : 'SET FOREIGN_KEY_CHECKS = 1');
}
}
}
+257
View File
@@ -0,0 +1,257 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Database\Model;
use Rsgrinko\Proton\Support\ProtonException;
/**
* Фабрики моделей: заготовка записи с правдоподобными полями.
*
* Factory::define(Note::class, static fn (int $i): array => [
* 'title' => 'Заметка ' . $i,
* 'body' => Factory::sentence(),
* ]);
*
* $note = Factory::of(Note::class)->create(); // одна запись
* $notes = Factory::of(Note::class)->times(10)->create(); // десять
* $draft = Factory::of(Note::class)->make(['title' => 'Своё']); // без записи в базу
*
* Нужна и тестам, и сидерам: описание лежит в `database/factories.php`, поэтому
* одна и та же заготовка наполняет и тестовую базу, и базу разработчика.
*
* Случайные значения нарочно простые и без внешних библиотек: фабрике нужно,
* чтобы поля были разными и влезали в ограничения, а не чтобы выглядели
* как настоящие имена.
*/
final class Factory
{
/** @var array<class-string<Model>, callable(int): array<string, mixed>> */
private static array $definitions = [];
/** Счётчик вызовов на класс — им отличаются логины и адреса */
private static array $counters = [];
/** @var class-string<Model> */
private string $model;
private int $times = 1;
/** @var array<string, mixed> Что перебить поверх заготовки */
private array $overrides = [];
/** @var array<int, callable(Model): void> Что сделать с каждой записью после создания */
private array $after = [];
/**
* @param class-string<Model> $model
*/
private function __construct(string $model)
{
$this->model = $model;
}
/**
* Описание фабрики. Зовётся из database/factories.php.
*
* @param class-string<Model> $model
* @param callable(int): array<string, mixed> $definition
*/
public static function define(string $model, callable $definition): void
{
self::$definitions[$model] = $definition;
}
/**
* Фабрика модели.
*
* @param class-string<Model> $model
*/
public static function of(string $model): self
{
self::boot();
if (!isset(self::$definitions[$model])) {
throw new ProtonException(
'Для ' . $model . ' нет фабрики. Опишите её в database/factories.php через Factory::define()'
);
}
return new self($model);
}
/**
* Есть ли описание — сидеру полезно проверить, не падая.
*
* @param class-string<Model> $model
*/
public static function has(string $model): bool
{
self::boot();
return isset(self::$definitions[$model]);
}
/**
* Забыть описания и счётчики: нужно тестам, которые заводят свои фабрики.
*/
public static function reset(): void
{
self::$definitions = [];
self::$counters = [];
}
/**
* Сколько записей делать.
*/
public function times(int $times): self
{
$this->times = max(1, $times);
return $this;
}
/**
* Поля поверх заготовки — то, что в тесте важно, задаётся явно.
*
* @param array<string, mixed> $attributes
*/
public function state(array $attributes): self
{
$this->overrides = array_merge($this->overrides, $attributes);
return $this;
}
/**
* Что сделать с каждой созданной записью: связи, файлы, отметки.
*
* @param callable(Model): void $callback
*/
public function afterCreating(callable $callback): self
{
$this->after[] = $callback;
return $this;
}
/**
* Модель без записи в базу.
*
* @param array<string, mixed> $attributes
*
* @return Model|array<int, Model>
*/
public function make(array $attributes = []): Model|array
{
$made = [];
for ($number = 0; $number < $this->times; $number++) {
$model = new $this->model();
$model->forceFill($this->attributes($attributes));
$made[] = $model;
}
return $this->times === 1 ? $made[0] : $made;
}
/**
* Запись в базе. Одна модель или список — по times().
*
* @param array<string, mixed> $attributes
*
* @return Model|array<int, Model>
*/
public function create(array $attributes = []): Model|array
{
$created = [];
for ($number = 0; $number < $this->times; $number++) {
/** @var Model $model */
$model = new $this->model();
$model->forceFill($this->attributes($attributes));
$model->save();
foreach ($this->after as $callback) {
$callback($model);
}
$created[] = $model;
}
return $this->times === 1 ? $created[0] : $created;
}
/**
* Строка из нескольких слов — для названий и текстов.
*/
public static function sentence(int $words = 6): string
{
$dictionary = [
'заметка', 'отчёт', 'проверка', 'черновик', 'список', 'задача', 'письмо',
'счёт', 'договор', 'встреча', 'заявка', 'правка', 'вопрос', 'ответ',
];
$picked = [];
for ($number = 0; $number < max(1, $words); $number++) {
$picked[] = $dictionary[array_rand($dictionary)];
}
$text = implode(' ', $picked);
return mb_strtoupper(mb_substr($text, 0, 1)) . mb_substr($text, 1);
}
/**
* Уникальное слово: логины и адреса должны быть разными в пределах прогона.
*/
public static function unique(string $prefix = ''): string
{
return ($prefix !== '' ? $prefix . '_' : '') . bin2hex(random_bytes(4));
}
/**
* Дата в прошлом — для created_at и отметок активности.
*/
public static function pastDate(int $maxDaysAgo = 30): string
{
return date('Y-m-d H:i:s', time() - random_int(0, max(1, $maxDaysAgo)) * 86400);
}
/**
* Заготовка плюс то, что перебили.
*
* @param array<string, mixed> $attributes
*
* @return array<string, mixed>
*/
private function attributes(array $attributes): array
{
$counter = self::$counters[$this->model] = (self::$counters[$this->model] ?? 0) + 1;
$definition = (self::$definitions[$this->model])($counter);
return array_merge((array) $definition, $this->overrides, $attributes);
}
/**
* Описания приложения — читаются один раз.
*/
private static function boot(): void
{
if (self::$definitions !== []) {
return;
}
$file = APP_ROOT . '/database/factories.php';
if (is_file($file)) {
require $file;
}
}
}
+101
View File
@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
/**
* Фабрики моделей и помощники HTTP-тестов.
*/
use App\Models\Note;
use Rsgrinko\Proton\Database\Model\Factory;
use Rsgrinko\Proton\Models\User;
use Rsgrinko\Proton\Support\ProtonException;
test('фабрика: делает запись и разводит уникальные поля', function (): void {
withOwnDatabase(static function (): void {
/** @var User $first */
$first = Factory::of(User::class)->create();
/** @var User $second */
$second = Factory::of(User::class)->create();
assertTrue($first->id() > 0);
assertNotContains((string) $first->login, (string) $second->login, 'логины должны отличаться');
assertTrue((string) $first->email !== (string) $second->email);
assertSame(2, User::query()->count());
});
});
test('фабрика: times делает список, state и аргументы перебивают заготовку', function (): void {
withOwnDatabase(static function (): void {
/** @var User $owner */
$owner = Factory::of(User::class)->create();
$notes = Factory::of(Note::class)
->times(3)
->state(['user_id' => $owner->id()])
->create(['pinned' => 1]);
assertCount(3, $notes);
assertSame(3, Note::query()->where('user_id', $owner->id())->where('pinned', 1)->count());
// make() ничего не пишет в базу
$draft = Factory::of(Note::class)->make(['title' => 'Черновик']);
assertSame('Черновик', (string) $draft->title);
assertSame(3, Note::query()->count(), 'make не создаёт запись');
});
});
test('фабрика: без описания говорит, где его завести', function (): void {
$error = assertThrows(static fn () => Factory::of(Rsgrinko\Proton\Models\AuditEntry::class));
assertTrue($error instanceof ProtonException);
assertContains('database/factories.php', $error->getMessage());
});
test('помощники: actingAs и get работают вместе с фабрикой', function (): void {
$user = Factory::of(User::class)->create();
afterTests(static function () use ($user): void {
Note::query()->withTrashed()->where('user_id', $user->id())->forceDelete();
$user->forceDelete();
});
actingAs($user);
$response = get('/notes');
assertStatus(200, $response);
assertSee('Заметки', $response);
// Гостя уводит на вход
actingAs(null);
assertRedirect('/login', get('/'));
});
test('помощники: post подставляет токен формы, assertDontSee ловит лишнее', function (): void {
$user = Factory::of(User::class)->create();
afterTests(static function () use ($user): void {
Note::query()->withTrashed()->where('user_id', $user->id())->forceDelete();
$user->forceDelete();
});
actingAs($user);
$response = post('/notes/new', ['title' => 'Из помощника', 'body' => 'текст']);
assertRedirect('/notes', $response);
$note = assertNotNull(Note::query()->where('user_id', $user->id())->first());
assertSame('Из помощника', (string) $note->title);
$list = get('/notes');
assertSee('Из помощника', $list);
assertDontSee('Такой заметки нет', $list);
actingAs(null);
});
+114
View File
@@ -415,6 +415,120 @@ function assertMatches(string $pattern, string $subject, string $message = ''):
}
}
/**
* От чьего лица идут дальнейшие запросы. Без аргумента — от гостя.
*
* Возвращает того же пользователя, поэтому годится и как начало теста:
* $user = actingAs(Factory::of(User::class)->create());
*/
function actingAs(?Rsgrinko\Proton\Models\User $user = null): ?Rsgrinko\Proton\Models\User
{
Rsgrinko\Proton\Auth\Auth::forget();
Rsgrinko\Proton\Auth\Auth::actAs($user);
$GLOBALS['test_actor'] = $user;
return $user;
}
/**
* Запрос к ядру от лица actingAs(). Токен формы подставляется сам — иначе
* каждый POST в тесте начинался бы с его добычи.
*
* @param array<string, mixed> $body
* @param array<string, mixed> $query
* @param array<string, mixed> $headers
*/
function httpCall(
string $method,
string $path,
array $body = [],
array $query = [],
array $headers = []
): Rsgrinko\Proton\Http\Response {
$user = $GLOBALS['test_actor'] ?? null;
Rsgrinko\Proton\Auth\Auth::forget();
Rsgrinko\Proton\Auth\Auth::actAs($user instanceof Rsgrinko\Proton\Models\User ? $user : null);
$writing = in_array(strtoupper($method), ['POST', 'PUT', 'PATCH', 'DELETE'], true);
if ($writing && !isset($body[Rsgrinko\Proton\Auth\Csrf::FIELD])) {
$body[Rsgrinko\Proton\Auth\Csrf::FIELD] = Rsgrinko\Proton\Auth\Csrf::token();
}
$request = Rsgrinko\Proton\Http\Request::create($method, $path, $body, $query, $headers);
return (new Rsgrinko\Proton\Http\Kernel())->handle($request);
}
/**
* @param array<string, mixed> $query
* @param array<string, mixed> $headers
*/
function get(string $path, array $query = [], array $headers = []): Rsgrinko\Proton\Http\Response
{
return httpCall('GET', $path, [], $query, $headers);
}
/**
* @param array<string, mixed> $body
* @param array<string, mixed> $headers
*/
function post(string $path, array $body = [], array $headers = []): Rsgrinko\Proton\Http\Response
{
return httpCall('POST', $path, $body, [], $headers);
}
/**
* Текст есть на странице. Теги не считаются: тест не должен падать от того,
* что слово обернули в <b>.
*/
function assertSee(string $needle, Rsgrinko\Proton\Http\Response $response, string $message = ''): void
{
$text = preg_replace('/\s+/u', ' ', trim(strip_tags($response->body()))) ?? '';
if (!str_contains($text, $needle) && !str_contains($response->body(), $needle)) {
throw new TestFailure(
($message !== '' ? $message . ': ' : '') . 'на странице нет «' . $needle . '»'
);
}
}
/**
* Текста на странице быть не должно.
*/
function assertDontSee(string $needle, Rsgrinko\Proton\Http\Response $response, string $message = ''): void
{
$text = preg_replace('/\s+/u', ' ', trim(strip_tags($response->body()))) ?? '';
if (str_contains($text, $needle) || str_contains($response->body(), $needle)) {
throw new TestFailure(
($message !== '' ? $message . ': ' : '') . 'на странице не должно быть «' . $needle . '»'
);
}
}
/**
* Ответ уводит на другой адрес. Достаточно куска пути: домен в тестах разный.
*/
function assertRedirect(string $to, Rsgrinko\Proton\Http\Response $response, string $message = ''): void
{
if ($response->status() < 300 || $response->status() >= 400) {
throw new TestFailure(
($message !== '' ? $message . ': ' : '') . 'ожидался редирект, получен код ' . $response->status()
);
}
$location = $response->header('Location');
if (!str_contains($location, $to)) {
throw new TestFailure(
($message !== '' ? $message . ': ' : '') . 'ожидался переход на ' . $to . ', получен ' . $location
);
}
}
/**
* Код ответа. При расхождении показывает начало тела — сразу видно, что
* вернулось на самом деле: страница ошибки, редирект или JSON с описанием.