From 9508c2996402d722be32569753a8c6f071e59314 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Tue, 15 Sep 2026 22:14:50 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A4=D0=B0=D0=B1=D1=80=D0=B8=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=BC=D0=BE=D0=B4=D0=B5=D0=BB=D0=B5=D0=B9,=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=BC=D0=BE=D1=89=D0=BD=D0=B8=D0=BA=D0=B8=20HTTP-=D1=82=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D0=BE=D0=B2,=20migrate:fresh=20=D0=B8=20=D1=81?= =?UTF-8?q?=D0=B8=D0=B4=D0=B5=D1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- database/factories.php | 35 +++ database/seed.php | 45 +++ framework/Console/Application.php | 1 + .../Console/Commands/MigrateFreshCommand.php | 96 +++++++ framework/Database/Model/Factory.php | 257 ++++++++++++++++++ tests/FactoryTest.php | 101 +++++++ tests/run.php | 114 ++++++++ 7 files changed, 649 insertions(+) create mode 100644 database/factories.php create mode 100644 database/seed.php create mode 100644 framework/Console/Commands/MigrateFreshCommand.php create mode 100644 framework/Database/Model/Factory.php create mode 100644 tests/FactoryTest.php diff --git a/database/factories.php b/database/factories.php new file mode 100644 index 0000000..2a207bd --- /dev/null +++ b/database/factories.php @@ -0,0 +1,35 @@ +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, +]); diff --git a/database/seed.php b/database/seed.php new file mode 100644 index 0000000..c14cff4 --- /dev/null +++ b/database/seed.php @@ -0,0 +1,45 @@ +count(); + + if ($users === 0) { + $say('Пользователей нет — сначала php bin/proton install'); + + return; + } + + /** @var array $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); +}; diff --git a/framework/Console/Application.php b/framework/Console/Application.php index bb5ed9b..28ceb8c 100644 --- a/framework/Console/Application.php +++ b/framework/Console/Application.php @@ -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, diff --git a/framework/Console/Commands/MigrateFreshCommand.php b/framework/Console/Commands/MigrateFreshCommand.php new file mode 100644 index 0000000..7c3ccb6 --- /dev/null +++ b/framework/Console/Commands/MigrateFreshCommand.php @@ -0,0 +1,96 @@ +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'); + } + } +} diff --git a/framework/Database/Model/Factory.php b/framework/Database/Model/Factory.php new file mode 100644 index 0000000..8214e77 --- /dev/null +++ b/framework/Database/Model/Factory.php @@ -0,0 +1,257 @@ + [ + * '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, callable(int): array> */ + private static array $definitions = []; + + /** Счётчик вызовов на класс — им отличаются логины и адреса */ + private static array $counters = []; + + /** @var class-string */ + private string $model; + + private int $times = 1; + + /** @var array Что перебить поверх заготовки */ + private array $overrides = []; + + /** @var array Что сделать с каждой записью после создания */ + private array $after = []; + + /** + * @param class-string $model + */ + private function __construct(string $model) + { + $this->model = $model; + } + + /** + * Описание фабрики. Зовётся из database/factories.php. + * + * @param class-string $model + * @param callable(int): array $definition + */ + public static function define(string $model, callable $definition): void + { + self::$definitions[$model] = $definition; + } + + /** + * Фабрика модели. + * + * @param class-string $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 + */ + 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 $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 $attributes + * + * @return Model|array + */ + 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 $attributes + * + * @return Model|array + */ + 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 $attributes + * + * @return array + */ + 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; + } + } +} diff --git a/tests/FactoryTest.php b/tests/FactoryTest.php new file mode 100644 index 0000000..5819ce2 --- /dev/null +++ b/tests/FactoryTest.php @@ -0,0 +1,101 @@ +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); +}); diff --git a/tests/run.php b/tests/run.php index 4a108bf..31be9e5 100644 --- a/tests/run.php +++ b/tests/run.php @@ -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 $body + * @param array $query + * @param array $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 $query + * @param array $headers + */ +function get(string $path, array $query = [], array $headers = []): Rsgrinko\Proton\Http\Response +{ + return httpCall('GET', $path, [], $query, $headers); +} + +/** + * @param array $body + * @param array $headers + */ +function post(string $path, array $body = [], array $headers = []): Rsgrinko\Proton\Http\Response +{ + return httpCall('POST', $path, $body, [], $headers); +} + +/** + * Текст есть на странице. Теги не считаются: тест не должен падать от того, + * что слово обернули в . + */ +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 с описанием.