Фабрики моделей, помощники HTTP-тестов, migrate:fresh и сидер
This commit is contained in:
1 parent
9673ac46ba
commit
9508c29964
7 files changed
+649
No files matched your search
@@ -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
@@ -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 с описанием.
|
||||
|
||||
Reference in new issue
Block a user