Commit awal: prototipe UI SIAKAD Untan

This commit is contained in:
Ariyutta
2026-10-24 11:45:32 +07:00
commit d9b9cb5c0f
477 changed files with 51958 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace Tests\Feature\Admin;
use App\Enums\Role;
use Tests\Feature\RoleDashboardTestCase;
class DashboardTest extends RoleDashboardTestCase
{
protected function role(): Role
{
return Role::Admin;
}
protected function userName(): string
{
return 'Siti Nurhaliza, S.Kom.';
}
protected function profileData(): array
{
return [
'nip' => '198203152008012002',
'jabatan' => 'Administrator Akademik',
'unit_kerja' => 'Biro Akademik dan Kemahasiswaan',
];
}
protected function expectedDetails(): array
{
return [
'NIP' => '198203152008012002',
'Jabatan' => 'Administrator Akademik',
'Unit kerja' => 'Biro Akademik dan Kemahasiswaan',
];
}
}
+306
View File
@@ -0,0 +1,306 @@
<?php
namespace Tests\Feature\Auth;
use App\Enums\Role;
use App\Models\User;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\RateLimiter;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\Concerns\InspectsHtml;
use Tests\TestCase;
class LoginTest extends TestCase
{
use InspectsHtml;
use RefreshDatabase;
/** @return array<string, array{Role}> */
public static function roles(): array
{
return array_combine(Role::values(), array_map(fn (Role $role): array => [$role], Role::cases()));
}
public function test_login_page_renders_for_guests(): void
{
$this->get(route('login'))
->assertOk()
->assertSee('Masuk ke SIAKAD');
}
public function test_login_page_uses_indonesian_html_language(): void
{
$this->get(route('login'))->assertSee('<html lang="id"', false);
}
public function test_login_form_has_the_required_fields(): void
{
$xpath = $this->dom($this->get(route('login')));
$form = $xpath->query("//form[@action='".route('login.store')."']");
$this->assertSame(1, $form->length);
$this->assertSame('post', strtolower($this->attr($form, 'method')));
$formText = $this->textOf($form->item(0));
$username = $xpath->query("//form//input[@name='username']");
$this->assertSame(1, $username->length);
$this->assertSame('username', $this->attr($username, 'autocomplete'));
$password = $xpath->query("//form//input[@name='password']");
$this->assertSame(1, $password->length);
$this->assertSame('password', $this->attr($password, 'type'));
$this->assertSame('current-password', $this->attr($password, 'autocomplete'));
$this->assertSame(1, $xpath->query("//form//input[@name='remember'][@type='checkbox']")->length);
$this->assertSame(1, $xpath->query("//form//input[@name='_token']")->length);
$this->assertStringContainsString('Username / NIM / NIP', $formText);
$this->assertStringContainsString('Kata sandi', $formText);
$this->assertStringContainsString('Ingat saya', $formText);
$submit = $xpath->query("//form//button[@type='submit']");
$this->assertSame(1, $submit->length);
$this->assertSame('Masuk', $this->textOf($submit->item(0)));
}
public function test_login_page_has_no_dead_links(): void
{
$response = $this->get(route('login'));
$response->assertDontSee('Lupa', false);
$response->assertDontSee('Daftar', false);
$response->assertDontSee('href="#"', false);
$this->assertSame(0, $this->dom($response)->query('//a[not(@href)]')->length);
}
#[DataProvider('roles')]
public function test_each_role_logs_in_and_lands_on_its_own_dashboard(Role $role): void
{
$user = $this->userWithRole($role, ['username' => 'akun-'.$role->value]);
$response = $this->post(route('login.store'), [
'username' => 'akun-'.$role->value,
'password' => 'password',
]);
$response->assertRedirect(route($role->dashboardRoute()));
$this->assertAuthenticatedAs($user);
$this->assertNotNull($user->fresh()->last_login_at);
}
public function test_login_redirects_back_to_the_intended_page(): void
{
$this->userWithRole(Role::Dosen, ['username' => 'dosen']);
$this->get(route('dosen.dashboard'))->assertRedirect(route('login'));
$this->post(route('login.store'), ['username' => 'dosen', 'password' => 'password'])
->assertRedirect(route('dosen.dashboard'));
}
public function test_wrong_password_is_rejected_with_a_generic_message(): void
{
$this->userWithRole(Role::Admin, ['username' => 'admin']);
$this->from(route('login'))
->post(route('login.store'), ['username' => 'admin', 'password' => 'salah'])
->assertRedirect(route('login'))
->assertSessionHasErrors(['username' => trans('auth.failed')]);
$this->assertGuest();
}
public function test_unknown_username_gets_the_same_message_as_a_wrong_password(): void
{
$this->post(route('login.store'), ['username' => 'tidak-ada', 'password' => 'password'])
->assertSessionHasErrors(['username' => trans('auth.failed')]);
$this->assertGuest();
}
public function test_failed_login_shows_the_error_on_the_page_accessibly(): void
{
$this->userWithRole(Role::Admin, ['username' => 'admin']);
$response = $this->followingRedirects()
->from(route('login'))
->post(route('login.store'), ['username' => 'admin', 'password' => 'salah']);
$response->assertOk();
$response->assertSee(trans('auth.failed'));
$alerts = $this->dom($response)
->query("//*[@role='alert' or @aria-live][contains(., '".trans('auth.failed')."')]");
$this->assertGreaterThanOrEqual(1, $alerts->length, 'Pesan galat harus berada dalam wilayah role=alert atau aria-live.');
}
public function test_inactive_account_cannot_log_in_and_gets_the_same_generic_message(): void
{
$this->userWithRole(Role::Mahasiswa, ['username' => 'nonaktif', 'is_active' => false]);
$this->post(route('login.store'), ['username' => 'nonaktif', 'password' => 'password'])
->assertSessionHasErrors(['username' => trans('auth.failed')]);
$this->assertGuest();
// Pesan sama persis dengan kata sandi salah pada akun aktif; status akun tidak bocor.
$this->assertSame(trans('auth.failed'), session('errors')->first('username'));
$this->assertStringNotContainsStringIgnoringCase('aktif', session('errors')->first('username'));
}
public function test_required_fields_are_validated_in_indonesian(): void
{
$this->post(route('login.store'), [])
->assertSessionHasErrors(['username', 'password']);
$this->assertStringContainsString('wajib diisi', session('errors')->first('username'));
$this->assertStringContainsStringIgnoringCase('kata sandi', session('errors')->first('password'));
}
public function test_login_is_throttled_after_five_failed_attempts(): void
{
Event::fake([Lockout::class]);
$this->userWithRole(Role::Admin, ['username' => 'admin']);
for ($attempt = 1; $attempt <= 5; $attempt++) {
$this->post(route('login.store'), ['username' => 'admin', 'password' => 'salah'])
->assertSessionHasErrors(['username' => trans('auth.failed')]);
}
// Percobaan ke-6 terkunci, bahkan dengan kata sandi yang benar.
$this->post(route('login.store'), ['username' => 'admin', 'password' => 'password'])
->assertSessionHasErrors('username');
$this->assertStringContainsString('Terlalu banyak percobaan', session('errors')->first('username'));
$this->assertStringContainsString('detik', session('errors')->first('username'));
$this->assertGuest();
Event::assertDispatched(Lockout::class);
}
public function test_throttle_is_per_username_and_case_insensitive(): void
{
$this->userWithRole(Role::Admin, ['username' => 'admin']);
$this->userWithRole(Role::Dosen, ['username' => 'dosen']);
foreach (['admin', 'ADMIN', 'Admin', 'admin', 'AdMiN'] as $username) {
$this->post(route('login.store'), ['username' => $username, 'password' => 'salah']);
}
$this->post(route('login.store'), ['username' => 'admin', 'password' => 'password'])
->assertSessionHasErrors('username');
$this->assertGuest();
// Username lain tidak ikut terkunci.
$this->post(route('login.store'), ['username' => 'dosen', 'password' => 'password'])
->assertRedirect(route('dosen.dashboard'));
}
public function test_four_failures_do_not_lock_and_success_clears_the_counter(): void
{
$this->userWithRole(Role::Admin, ['username' => 'admin']);
$key = 'admin|127.0.0.1';
for ($attempt = 1; $attempt <= 4; $attempt++) {
$this->post(route('login.store'), ['username' => 'admin', 'password' => 'salah']);
}
$this->assertSame(4, RateLimiter::attempts($key));
$this->post(route('login.store'), ['username' => 'admin', 'password' => 'password'])
->assertRedirect(route('admin.dashboard'));
$this->assertSame(0, RateLimiter::attempts($key));
}
#[DataProvider('roles')]
public function test_authenticated_users_are_redirected_away_from_the_login_page(Role $role): void
{
$this->actingAs($this->userWithRole($role))
->get(route('login'))
->assertRedirect(route('dashboard'));
}
public function test_authenticated_users_cannot_post_to_login_again(): void
{
$this->actingAs($this->userWithRole(Role::Admin))
->post(route('login.store'), ['username' => 'x', 'password' => 'y'])
->assertRedirect(route('dashboard'));
}
public function test_an_account_deactivated_mid_session_is_logged_out_on_the_next_request(): void
{
$user = $this->userWithRole(Role::Dosen, ['username' => 'dosen']);
$this->post(route('login.store'), ['username' => 'dosen', 'password' => 'password']);
$this->assertAuthenticatedAs($user);
$this->get(route('dosen.dashboard'))->assertOk();
User::whereKey($user->id)->update(['is_active' => false]);
// Permintaan berikutnya berjalan di proses PHP baru; di tes guard harus dilepas agar akun dibaca ulang dari DB.
Auth::forgetGuards();
$this->get(route('dosen.dashboard'))
->assertRedirect(route('login'))
->assertSessionHasErrors(['username' => trans('auth.inactive')]);
$this->assertGuest();
$this->get(route('dosen.dashboard'))->assertRedirect(route('login'));
}
#[DataProvider('roles')]
public function test_deactivated_account_of_every_role_is_logged_out_on_a_protected_route(Role $role): void
{
$user = $this->userWithRole($role, ['is_active' => false]);
$this->actingAs($user)->get(route('dashboard'))
->assertRedirect(route('login'));
$this->assertGuest();
}
public function test_root_redirects_guests_to_the_login_page(): void
{
$this->get('/')->assertRedirect(route('login'));
}
#[DataProvider('roles')]
public function test_root_sends_every_signed_in_role_to_its_dashboard(Role $role): void
{
$this->actingAs($this->userWithRole($role));
$this->get('/')->assertRedirect(route('dashboard'));
$this->get(route('dashboard'))->assertRedirect(route($role->dashboardRoute()));
$this->followingRedirects()->get('/')->assertOk()->assertSee('Selamat Datang,');
}
public function test_demo_accounts_panel_is_absent_outside_local(): void
{
foreach (['testing', 'production', 'staging'] as $environment) {
$this->app->detectEnvironment(fn (): string => $environment);
$this->get(route('login'))
->assertOk()
->assertDontSee('Akun demo');
}
}
public function test_demo_accounts_panel_lists_the_five_roles_in_local(): void
{
$this->app->detectEnvironment(fn (): string => 'local');
$response = $this->get(route('login'))->assertOk()->assertSee('Akun demo');
$xpath = $this->dom($response);
$details = $xpath->query('//details');
$this->assertSame(1, $details->length);
$panel = $this->textOf($details->item(0));
foreach (Role::cases() as $role) {
$this->assertStringContainsString($role->label(), $panel);
$this->assertStringContainsString($role->value, $panel);
}
$this->assertSame(5, $xpath->query('//details//button')->length);
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace Tests\Feature\Auth;
use App\Enums\Role;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\Concerns\InspectsHtml;
use Tests\TestCase;
class LogoutTest extends TestCase
{
use InspectsHtml;
use RefreshDatabase;
/** @return array<string, array{Role}> */
public static function roles(): array
{
return array_combine(Role::values(), array_map(fn (Role $role): array => [$role], Role::cases()));
}
#[DataProvider('roles')]
public function test_post_logout_ends_the_session_and_redirects_to_login(Role $role): void
{
$user = $this->userWithRole($role, ['username' => 'akun']);
$this->post(route('login.store'), ['username' => 'akun', 'password' => 'password']);
$this->assertAuthenticatedAs($user);
$oldSessionId = session()->getId();
$this->post(route('logout'))->assertRedirect(route('login'));
$this->assertGuest();
$this->assertNotSame($oldSessionId, session()->getId(), 'Id sesi harus diganti saat keluar.');
$this->get(route($role->dashboardRoute()))->assertRedirect(route('login'));
}
public function test_logout_invalidates_session_data(): void
{
$this->actingAs($this->userWithRole(Role::Admin))
->withSession(['rahasia' => 'nilai'])
->post(route('logout'));
$this->assertNull(session('rahasia'));
}
public function test_logout_is_post_only(): void
{
$this->actingAs($this->userWithRole(Role::Admin));
$this->get('/logout')->assertStatus(405);
$this->assertAuthenticated();
}
public function test_guests_posting_to_logout_are_sent_to_login(): void
{
$this->post(route('logout'))->assertRedirect(route('login'));
}
#[DataProvider('roles')]
public function test_sidebar_has_a_logout_form_posting_to_the_logout_route(Role $role): void
{
$response = $this->actingAs($this->userWithRole($role))->get(route($role->dashboardRoute()));
$xpath = $this->dom($response);
$formPath = "//aside//form[@action='".route('logout')."']";
$form = $xpath->query($formPath);
$this->assertSame(1, $form->length);
$this->assertSame('post', strtolower($this->attr($form, 'method')));
$this->assertSame(1, $xpath->query($formPath."//input[@name='_token']")->length);
$this->assertSame('Keluar', $this->textOf($xpath->query($formPath.'//button')->item(0)));
}
}
+134
View File
@@ -0,0 +1,134 @@
<?php
namespace Tests\Feature\Auth;
use App\Enums\Role;
use App\Http\Middleware\EnsureUserHasRole;
use Illuminate\Foundation\Http\Kernel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
class RoleAccessTest extends TestCase
{
use RefreshDatabase;
/** @return array<string, array{Role, Role}> semua pasangan (akun, dashboard yang dibuka) */
public static function matrix(): array
{
$cases = [];
foreach (Role::cases() as $actor) {
foreach (Role::cases() as $target) {
$cases["{$actor->value} membuka {$target->value}"] = [$actor, $target];
}
}
return $cases;
}
/** @return array<string, array{string, string}> */
public static function protectedRoutes(): array
{
return [
'dashboard' => ['get', '/dashboard'],
'logout' => ['post', '/logout'],
'superuser dashboard' => ['get', '/superuser/dashboard'],
'admin dashboard' => ['get', '/admin/dashboard'],
'operator dashboard' => ['get', '/operator/dashboard'],
'dosen dashboard' => ['get', '/dosen/dashboard'],
'mahasiswa dashboard' => ['get', '/mahasiswa/dashboard'],
];
}
#[DataProvider('matrix')]
public function test_a_user_can_only_open_the_dashboard_of_their_own_role(Role $actor, Role $target): void
{
$this->actingAs($this->userWithRole($actor));
$response = $this->get(route($target->dashboardRoute()));
if ($actor === $target) {
$response->assertOk();
} else {
$response->assertForbidden();
}
}
#[DataProvider('protectedRoutes')]
public function test_guests_are_redirected_to_login_from_every_protected_route(string $method, string $uri): void
{
$this->{$method}($uri)->assertRedirect(route('login'));
$this->assertGuest();
}
public function test_route_names_and_paths_match_the_contract(): void
{
$this->assertSame('/login', route('login', [], false));
$this->assertSame('/logout', route('logout', [], false));
$this->assertSame('/dashboard', route('dashboard', [], false));
foreach (Role::cases() as $role) {
$this->assertSame("/{$role->value}/dashboard", route($role->dashboardRoute(), [], false));
}
}
public function test_every_role_group_is_protected_by_auth_active_and_its_own_role_middleware(): void
{
foreach (Role::cases() as $role) {
$middleware = Route::getRoutes()->getByName($role->dashboardRoute())->gatherMiddleware();
$this->assertContains('auth', $middleware);
$this->assertContains('active', $middleware);
$this->assertContains("role:{$role->value}", $middleware);
}
}
public function test_dashboard_redirect_sends_each_role_to_its_own_dashboard(): void
{
foreach (Role::cases() as $role) {
$this->actingAs($this->userWithRole($role, ['username' => 'akun-'.$role->value]))
->get(route('dashboard'))
->assertRedirect(route($role->dashboardRoute()));
}
}
public function test_forbidden_page_is_the_indonesian_error_view(): void
{
$this->actingAs($this->userWithRole(Role::Mahasiswa))
->get(route('admin.dashboard'))
->assertForbidden()
->assertSee('Akses ditolak')
->assertSee('Kode galat');
}
public function test_role_middleware_accepts_several_roles_and_has_no_implicit_superuser_bypass(): void
{
Route::middleware(['web', 'auth', EnsureUserHasRole::class.':admin,operator'])
->get('/_uji/multi-role', fn (): string => 'ok');
$this->actingAs($this->userWithRole(Role::Admin))->get('/_uji/multi-role')->assertOk();
$this->actingAs($this->userWithRole(Role::Operator))->get('/_uji/multi-role')->assertOk();
$this->actingAs($this->userWithRole(Role::Superuser))->get('/_uji/multi-role')->assertForbidden();
$this->actingAs($this->userWithRole(Role::Dosen))->get('/_uji/multi-role')->assertForbidden();
}
public function test_role_middleware_alias_and_active_alias_are_registered(): void
{
$aliases = app(Kernel::class)->getMiddlewareAliases();
$this->assertSame(EnsureUserHasRole::class, $aliases['role']);
$this->assertArrayHasKey('active', $aliases);
}
public function test_unknown_pages_return_the_404_view_for_guests_and_users(): void
{
$this->get('/halaman-tidak-ada')->assertNotFound()->assertSee('Kode galat');
$this->actingAs($this->userWithRole(Role::Admin))
->get('/halaman-tidak-ada')
->assertNotFound()
->assertSee('Kode galat');
}
}
+156
View File
@@ -0,0 +1,156 @@
<?php
namespace Tests\Feature;
use App\Enums\Role;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\Concerns\InspectsHtml;
use Tests\TestCase;
class BrandingTest extends TestCase
{
use InspectsHtml;
use RefreshDatabase;
/** @return array<string, array{Role}> */
public static function roles(): array
{
return array_combine(Role::values(), array_map(fn (Role $role): array => [$role], Role::cases()));
}
/** @return array<string, array{int}> */
public static function errorCodes(): array
{
return array_combine([403, 404, 419, 429, 500, 503], array_map(fn (int $code): array => [$code], [403, 404, 419, 429, 500, 503]));
}
public function test_login_page_shows_the_untan_logo_once(): void
{
$xpath = $this->dom($this->get(route('login')));
$this->assertHasUntanLogo($xpath, 'halaman masuk');
$this->assertSame(1, $this->logos($xpath)->length, 'Halaman masuk tidak boleh memuat dua lambang.');
}
#[DataProvider('roles')]
public function test_every_role_dashboard_shows_the_untan_logo(Role $role): void
{
$response = $this->actingAs($this->userWithRole($role))->get(route($role->dashboardRoute()));
$this->assertHasUntanLogo($this->dom($response), "dashboard {$role->value}");
}
public function test_the_403_error_page_shows_the_untan_logo_once(): void
{
$response = $this->actingAs($this->userWithRole(Role::Mahasiswa))->get(route('admin.dashboard'));
$response->assertForbidden();
$xpath = $this->dom($response);
$this->assertHasUntanLogo($xpath, 'halaman 403');
$this->assertSame(1, $this->logos($xpath)->length);
}
public function test_the_404_error_page_shows_the_untan_logo_once_for_guests_and_users(): void
{
$guest = $this->get('/tidak-ada');
$guest->assertNotFound();
$this->assertHasUntanLogo($this->dom($guest), 'halaman 404 (tamu)');
$this->assertSame(1, $this->logos($this->dom($guest))->length);
$user = $this->actingAs($this->userWithRole(Role::Dosen))->get('/tidak-ada');
$user->assertNotFound();
$this->assertHasUntanLogo($this->dom($user), 'halaman 404 (masuk)');
$this->assertSame(1, $this->logos($this->dom($user))->length);
}
#[DataProvider('errorCodes')]
public function test_every_error_view_renders_with_the_logo_and_its_code(int $code): void
{
$html = view("errors.{$code}")->render();
$xpath = $this->domFromHtml($html);
$this->assertHasUntanLogo($xpath, "halaman {$code}");
$this->assertSame(1, $this->logos($xpath)->length);
$this->assertStringContainsString("Kode galat {$code}", $this->textOf($xpath->query('//main')->item(0)));
$this->assertStringContainsString('<html lang="id"', $html);
$this->assertSame(1, $xpath->query('//h1')->length);
$this->assertSame(1, $xpath->query('//main//a')->length, 'Satu tindakan kembali.');
}
public function test_error_page_action_goes_to_login_for_guests_and_dashboard_for_users(): void
{
$guestLink = $this->attr($this->dom($this->get('/tidak-ada'))->query('//main//a'), 'href');
$this->assertSame(route('login'), $guestLink);
$this->actingAs($this->userWithRole(Role::Operator));
$userLink = $this->attr($this->dom($this->get('/tidak-ada'))->query('//main//a'), 'href');
$this->assertSame(route('dashboard'), $userLink);
}
public function test_pages_carry_the_logo_as_favicon_and_never_hotlink_wikipedia(): void
{
$pages = [
$this->get(route('login')),
$this->get('/tidak-ada'),
$this->actingAs($this->userWithRole(Role::Admin))->get(route('admin.dashboard')),
];
foreach ($pages as $response) {
$xpath = $this->dom($response);
$icon = $xpath->query("//link[@rel='icon']");
$this->assertSame(1, $icon->length);
$this->assertStringContainsString('logo-untan', $this->attr($icon, 'href'));
$this->assertStringNotContainsStringIgnoringCase('wikipedia', $response->getContent());
$this->assertStringNotContainsStringIgnoringCase('wikimedia', $response->getContent());
}
}
public function test_logo_files_exist_in_all_sizes(): void
{
foreach (['logo-untan.png', 'logo-untan-64.png', 'logo-untan-128.png', 'logo-untan-256.png', 'logo-untan-512.png'] as $file) {
$this->assertFileExists(public_path("images/{$file}"));
$this->assertSame(IMAGETYPE_PNG, exif_imagetype(public_path("images/{$file}")), "{$file} harus PNG.");
}
}
public function test_the_logo_component_is_the_only_place_that_emits_an_img(): void
{
$offenders = [];
foreach (File::allFiles(resource_path('views')) as $file) {
if ($file->getRelativePathname() === 'components'.DIRECTORY_SEPARATOR.'brand'.DIRECTORY_SEPARATOR.'logo.blade.php') {
continue;
}
if (preg_match('/<img\b/i', File::get($file->getPathname()))) {
$offenders[] = $file->getRelativePathname();
}
}
$this->assertSame([], $offenders, 'Hanya <x-brand.logo> yang boleh memancarkan <img>.');
}
public function test_no_view_or_script_hotlinks_the_wikipedia_logo(): void
{
foreach ([resource_path('views'), resource_path('js'), resource_path('css')] as $directory) {
foreach (File::allFiles($directory) as $file) {
$this->assertDoesNotMatchRegularExpression(
'/wikipedia|wikimedia/i',
File::get($file->getPathname()),
"{$file->getRelativePathname()} merujuk langsung ke Wikipedia.",
);
}
}
}
public function test_skeleton_leftovers_are_gone(): void
{
$this->assertFileDoesNotExist(resource_path('views/welcome.blade.php'));
$this->assertFileDoesNotExist(base_path('tests/Feature/ExampleTest.php'));
$this->assertFileDoesNotExist(base_path('tests/Unit/ExampleTest.php'));
$this->assertFileDoesNotExist(public_path('favicon.ico'));
}
}
+122
View File
@@ -0,0 +1,122 @@
<?php
namespace Tests\Feature;
use App\Enums\Role;
use App\Models\User;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
class DatabaseSeederTest extends TestCase
{
use RefreshDatabase;
/** @return array<string, array{Role}> */
public static function roles(): array
{
return array_combine(Role::values(), array_map(fn (Role $role): array => [$role], Role::cases()));
}
private function seedDemo(): void
{
$this->app->make(DatabaseSeeder::class)->run();
}
public function test_it_creates_exactly_the_five_demo_accounts_with_their_profiles(): void
{
$this->seedDemo();
$this->assertSame(5, User::count());
$this->assertEqualsCanonicalizing(Role::values(), User::pluck('username')->all());
foreach (Role::cases() as $role) {
$this->assertSame(1, $role->profileModel()::count(), "profil {$role->value}");
}
}
#[DataProvider('roles')]
public function test_each_demo_account_has_the_documented_shape(Role $role): void
{
$this->seedDemo();
$user = User::where('username', $role->value)->firstOrFail();
$this->assertSame($role, $user->role);
$this->assertSame("{$role->value}@siakad-untan.test", $user->email);
$this->assertTrue($user->is_active);
$this->assertNotNull($user->email_verified_at);
$this->assertTrue(Hash::check('password', $user->password));
$this->assertNotSame('password', $user->getRawOriginal('password'));
$this->assertInstanceOf($role->profileModel(), $user->profile);
$this->assertNotEmpty($user->profile->nomor_induk);
$this->assertNotSame('', trim($user->name));
}
public function test_demo_identifiers_and_names(): void
{
$this->seedDemo();
$this->assertSame('D1041211001', User::where('username', 'mahasiswa')->first()->profile->nim);
$this->assertSame(2021, (int) User::where('username', 'mahasiswa')->first()->profile->angkatan);
$this->assertSame('0012058701', User::where('username', 'dosen')->first()->profile->nidn);
$this->assertStringContainsString('Dr.', User::where('username', 'dosen')->first()->name);
}
public function test_it_is_idempotent(): void
{
$this->seedDemo();
$ids = User::orderBy('id')->pluck('id', 'username')->all();
$this->seedDemo();
$this->seedDemo();
$this->assertSame(5, User::count());
$this->assertSame($ids, User::orderBy('id')->pluck('id', 'username')->all());
foreach (Role::cases() as $role) {
$this->assertSame(1, $role->profileModel()::count(), "profil {$role->value} tidak boleh ganda");
}
}
public function test_rerun_restores_a_changed_demo_account_without_duplicates(): void
{
$this->seedDemo();
User::where('username', 'admin')->update(['is_active' => false, 'name' => 'Diubah']);
$this->seedDemo();
$admin = User::where('username', 'admin')->firstOrFail();
$this->assertTrue($admin->is_active);
$this->assertNotSame('Diubah', $admin->name);
$this->assertSame(5, User::count());
}
public function test_demo_accounts_can_log_in_through_the_form(): void
{
$this->seedDemo();
foreach (Role::cases() as $role) {
$this->post(route('login.store'), ['username' => $role->value, 'password' => 'password'])
->assertRedirect(route($role->dashboardRoute()));
$this->post(route('logout'));
}
}
public function test_it_is_skipped_in_production(): void
{
$this->app->detectEnvironment(fn (): string => 'production');
$this->assertTrue(app()->isProduction());
$this->seedDemo();
$this->assertSame(0, User::count());
foreach (Role::cases() as $role) {
$this->assertSame(0, $role->profileModel()::count());
}
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace Tests\Feature\Dosen;
use App\Enums\Role;
use Tests\Feature\RoleDashboardTestCase;
class DashboardTest extends RoleDashboardTestCase
{
protected function role(): Role
{
return Role::Dosen;
}
protected function userName(): string
{
return 'Dr. Rina Kartika Sari, M.Si.';
}
protected function profileData(): array
{
return [
'nidn' => '0012058701',
'nip' => '198705122014042001',
'jabatan_fungsional' => 'Lektor Kepala',
];
}
protected function expectedDetails(): array
{
return [
'NIDN' => '0012058701',
'NIP' => '198705122014042001',
'Jabatan fungsional' => 'Lektor Kepala',
];
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace Tests\Feature\Mahasiswa;
use App\Enums\Role;
use Tests\Feature\RoleDashboardTestCase;
class DashboardTest extends RoleDashboardTestCase
{
protected function role(): Role
{
return Role::Mahasiswa;
}
protected function userName(): string
{
return 'Muhammad Rizky Ramadhan';
}
protected function profileData(): array
{
return [
'nim' => 'D1041211001',
'angkatan' => 2021,
'status' => 'aktif',
];
}
protected function expectedDetails(): array
{
return [
'NIM' => 'D1041211001',
'Angkatan' => '2021',
'Status' => 'aktif',
];
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace Tests\Feature\Operator;
use App\Enums\Role;
use Tests\Feature\RoleDashboardTestCase;
class DashboardTest extends RoleDashboardTestCase
{
protected function role(): Role
{
return Role::Operator;
}
protected function userName(): string
{
return 'Andi Pratama, S.Kom.';
}
protected function profileData(): array
{
return [
'nip' => '199001202019031003',
'jabatan' => 'Operator Akademik',
'unit_kerja' => 'Fakultas Teknik',
];
}
protected function expectedDetails(): array
{
return [
'NIP' => '199001202019031003',
'Jabatan' => 'Operator Akademik',
'Unit kerja' => 'Fakultas Teknik',
];
}
}
+131
View File
@@ -0,0 +1,131 @@
<?php
namespace Tests\Feature;
use App\Enums\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\Concerns\InspectsHtml;
use Tests\TestCase;
/** Kontrak dashboard yang sama untuk kelima role; tiap role mengisi data profilnya sendiri. */
abstract class RoleDashboardTestCase extends TestCase
{
use InspectsHtml;
use RefreshDatabase;
abstract protected function role(): Role;
abstract protected function userName(): string;
/** @return array<string, mixed> kolom profil yang dibuat untuk akun uji */
abstract protected function profileData(): array;
/** @return array<string, string> label tampil => nilai yang harus muncul */
abstract protected function expectedDetails(): array;
protected function makeUser(): User
{
return $this->userWithRole(
$this->role(),
['name' => $this->userName(), 'username' => 'akun-'.$this->role()->value],
$this->profileData(),
);
}
public function test_dashboard_requires_authentication(): void
{
$this->get(route($this->role()->dashboardRoute()))->assertRedirect(route('login'));
}
public function test_dashboard_renders_the_welcome_heading_exactly(): void
{
$response = $this->actingAs($this->makeUser())->get(route($this->role()->dashboardRoute()));
$response->assertOk();
$headings = $this->dom($response)->query('//h1');
$this->assertSame(1, $headings->length, 'Tepat satu h1 per halaman.');
$this->assertSame("Selamat Datang, {$this->userName()}!", $this->textOf($headings->item(0)));
}
public function test_dashboard_shows_the_identifier_and_details_from_the_profile(): void
{
$response = $this->actingAs($this->makeUser())->get(route($this->role()->dashboardRoute()));
$xpath = $this->dom($response);
$main = $this->textOf($xpath->query('//main')->item(0));
$this->assertStringContainsString('Identitas akademik', $main);
$this->assertStringContainsString($this->role()->label(), $main);
$this->assertStringContainsString('akun-'.$this->role()->value, $main);
foreach ($this->expectedDetails() as $label => $value) {
$this->assertStringContainsString($label, $main, "Label {$label} tidak tampil.");
$this->assertStringContainsString($value, $main, "Nilai {$label} tidak tampil.");
}
$identifierLabel = $this->role()->identifierLabel();
$this->assertArrayHasKey($identifierLabel, $this->expectedDetails());
$this->assertStringContainsString($this->expectedDetails()[$identifierLabel], $this->textOf($xpath->query("//p[contains(@class, 'num')]")->item(0)));
}
public function test_dashboard_without_a_profile_row_still_renders_without_the_identifier(): void
{
$user = User::factory()->state(['role' => $this->role(), 'name' => $this->userName()])->create();
$response = $this->actingAs($user)->get(route($this->role()->dashboardRoute()));
$response->assertOk();
$this->assertSame("Selamat Datang, {$this->userName()}!", $this->textOf($this->dom($response)->query('//h1')->item(0)));
$this->assertSame(0, $this->dom($response)->query("//p[contains(@class, 'num')]")->length, 'Tanpa profil tidak ada nomor induk.');
}
public function test_sidebar_lists_the_dashboard_as_the_only_active_item(): void
{
$response = $this->actingAs($this->makeUser())->get(route($this->role()->dashboardRoute()));
$xpath = $this->dom($response);
$items = $xpath->query("//aside//nav//a[contains(concat(' ', normalize-space(@class), ' '), ' nav-item ')]");
$this->assertGreaterThanOrEqual(1, $items->length);
$this->assertSame('Dashboard', $this->textOf($items->item(0)), 'Dashboard adalah butir pertama.');
$this->assertSame(route($this->role()->dashboardRoute()), $items->item(0)->getAttribute('href'));
$active = $xpath->query("//aside//nav//a[@aria-current='page']");
$this->assertSame(1, $active->length, 'Tepat satu butir menu aktif.');
$this->assertSame(route($this->role()->dashboardRoute()), $active->item(0)->getAttribute('href'));
$this->assertStringContainsString('Menu '.$this->role()->label(), $this->textOf($xpath->query('//aside//nav')->item(0)));
}
public function test_shell_landmarks_and_language(): void
{
$response = $this->actingAs($this->makeUser())->get(route($this->role()->dashboardRoute()));
$xpath = $this->dom($response);
$response->assertSee('<html lang="id"', false);
$this->assertSame(1, $xpath->query('//main[@id="isi"]')->length);
$this->assertSame(1, $xpath->query('//a[@class="skip-link"][@href="#isi"]')->length);
$this->assertSame(1, $xpath->query('//aside//nav')->length);
$this->assertSame(1, $xpath->query('//header')->length);
$this->assertStringContainsString('Dashboard', $this->textOf($xpath->query('//title')->item(0)));
$this->assertStringContainsString($this->userName(), $this->textOf($xpath->query('//header')->item(0)));
}
public function test_dashboard_shows_the_untan_logo(): void
{
$response = $this->actingAs($this->makeUser())->get(route($this->role()->dashboardRoute()));
$this->assertHasUntanLogo($this->dom($response), "dashboard {$this->role()->value}");
}
public function test_dashboard_does_not_show_data_of_other_accounts(): void
{
$this->userWithRole(Role::Admin, ['name' => 'Orang Lain Sekali', 'username' => 'orang-lain']);
$response = $this->actingAs($this->makeUser())->get(route($this->role()->dashboardRoute()));
$response->assertDontSee('Orang Lain Sekali');
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace Tests\Feature\Superuser;
use App\Enums\Role;
use Tests\Feature\RoleDashboardTestCase;
class DashboardTest extends RoleDashboardTestCase
{
protected function role(): Role
{
return Role::Superuser;
}
protected function userName(): string
{
return 'Ir. Budi Santoso, M.T.';
}
protected function profileData(): array
{
return [
'nip' => '197501012000121001',
'jabatan' => 'Administrator Sistem',
'unit_kerja' => 'Pusat Data dan Teknologi Informasi',
];
}
protected function expectedDetails(): array
{
return [
'NIP' => '197501012000121001',
'Jabatan' => 'Administrator Sistem',
'Unit kerja' => 'Pusat Data dan Teknologi Informasi',
];
}
}