Files
vkv/tests/Feature/Admin/UserControllerTest.php
Zdeněk Burda 41e3ce6f25 Initial commit
2026-01-09 21:26:40 +01:00

97 lines
2.6 KiB
PHP

<?php
namespace Tests\Feature\Admin;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class UserControllerTest extends TestCase
{
use RefreshDatabase;
public function test_admin_can_list_users(): void
{
$admin = $this->actingAsAdmin();
$user = $this->createUser();
$response = $this->getJson('/api/users');
$response->assertStatus(200)
->assertJsonFragment(['id' => $admin->id])
->assertJsonFragment(['id' => $user->id]);
}
public function test_non_admin_cannot_list_users(): void
{
$this->actingAsUser();
$this->getJson('/api/users')->assertStatus(403);
}
public function test_admin_can_create_user(): void
{
$this->actingAsAdmin();
$response = $this->postJson('/api/users', [
'name' => 'Test User',
'email' => 'test-user@example.com',
'password' => 'secretpass',
'is_admin' => true,
'is_active' => true,
]);
$response->assertStatus(201)
->assertJsonFragment(['email' => 'test-user@example.com']);
$this->assertDatabaseHas('users', [
'email' => 'test-user@example.com',
'is_admin' => 1,
'is_active' => 1,
]);
}
public function test_admin_can_update_user_and_password(): void
{
$this->actingAsAdmin();
$user = $this->createUser(['password' => 'oldpass']);
$response = $this->putJson("/api/users/{$user->id}", [
'name' => 'Updated Name',
'email' => 'updated@example.com',
'password' => 'newpass123',
'is_admin' => false,
'is_active' => true,
]);
$response->assertStatus(200)
->assertJsonFragment(['email' => 'updated@example.com']);
$user->refresh();
$this->assertSame('Updated Name', $user->name);
$this->assertTrue(Hash::check('newpass123', $user->password));
}
public function test_admin_can_deactivate_user(): void
{
$this->actingAsAdmin();
$user = $this->createUser(['is_active' => true]);
$response = $this->deleteJson("/api/users/{$user->id}");
$response->assertStatus(200);
$this->assertDatabaseHas('users', [
'id' => $user->id,
'is_active' => 0,
]);
}
public function test_admin_cannot_deactivate_self(): void
{
$admin = $this->actingAsAdmin();
$this->deleteJson("/api/users/{$admin->id}")
->assertStatus(422);
}
}