HasPermissionsTest.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Tests\Unit;
  3. use App\Models\AdminPermission;
  4. use App\Models\AdminRole;
  5. use App\Models\AdminUser;
  6. use Illuminate\Foundation\Testing\WithFaker;
  7. use Illuminate\Foundation\Testing\RefreshDatabase;
  8. use Tests\TestCase;
  9. class HasPermissionsTest extends TestCase
  10. {
  11. use RefreshDatabase;
  12. public function testMethods()
  13. {
  14. /** @var AdminUser $user */
  15. $user = factory(AdminUser::class)->create();
  16. $role1 = factory(AdminRole::class)->create(['slug' => 'role_1']);
  17. $perm1 = factory(AdminPermission::class)->create(['slug' => 'perm_1']);
  18. $role1->permissions()->attach($perm1->id);
  19. $user->roles()->attach($role1->id);
  20. $role2 = factory(AdminRole::class)->create(['slug' => 'role_2']);
  21. $perm2 = factory(AdminPermission::class)->create(['slug' => 'perm_2']);
  22. $user->permissions()->attach($perm2->id);
  23. $perm3 = factory(AdminPermission::class)->create(['slug' => 'perm_3']);
  24. // allPermissions
  25. $allPerms = $user->allPermissions()->pluck('slug')->all();
  26. $this->assertTrue(count(array_intersect($allPerms, ['perm_1', 'perm_2'])) == 2);
  27. // can
  28. $this->assertTrue($user->can('perm_1'));
  29. $this->assertTrue($user->can('perm_2'));
  30. $this->assertFalse($user->can('perm_3'));
  31. // isRole
  32. $this->assertTrue($user->isRole('role_1'));
  33. $this->assertFalse($user->isRole('role_2'));
  34. // inRoles
  35. $this->assertTrue($user->inRoles(['role_1', 'role_2']));
  36. $this->assertFalse($user->inRoles(['role_2']));
  37. // visible
  38. $this->assertTrue($user->visible([$role1, $role2]));
  39. $this->assertFalse($user->visible([$role2]));
  40. // administrator
  41. $admin = factory(AdminRole::class)->create(['slug' => 'administrator']);
  42. $user->roles()->attach($admin->id);
  43. $user->setRelation('roles', $user->roles()->get());
  44. $this->assertTrue($user->can('perm_3'));
  45. $this->assertTrue($user->visible(['role_2']));
  46. }
  47. }