AdminTestCase.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Tests;
  3. use App\Contracts\PermissionMiddleware;
  4. use App\Http\Middleware\AdminPermission;
  5. use App\Models\AdminUser;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Facades\Storage;
  8. class AdminTestCase extends TestCase
  9. {
  10. protected $routePrefix = 'admin';
  11. /**
  12. * @var AdminUser
  13. */
  14. protected $user;
  15. /**
  16. * @var \Illuminate\Contracts\Filesystem\Filesystem|\Illuminate\Contracts\Filesystem\Cloud
  17. */
  18. protected $storage;
  19. protected $filesystem = 'uploads';
  20. protected function login(AdminUser $user = null)
  21. {
  22. $user = $user ?: factory(AdminUser::class)->create(['username' => 'admin']);
  23. $this->actingAs($user, 'admin');
  24. $auth = auth('admin');
  25. $this->user = $user;
  26. $this->token = $auth->tokenById($user->id);
  27. $auth->setToken($this->token);
  28. }
  29. protected function setUp(): void
  30. {
  31. parent::setUp();
  32. $this->checkPermission(false);
  33. $this->storage = Storage::disk($this->filesystem);
  34. }
  35. /**
  36. * 设置是否需要检测权限
  37. *
  38. * @param bool $check
  39. */
  40. protected function checkPermission($check)
  41. {
  42. if ($check) {
  43. $ins = new class extends AdminPermission
  44. {
  45. protected $urlWhitelist = [
  46. '/test-resources/pass-through',
  47. ];
  48. };
  49. } else {
  50. $ins = new class extends AdminPermission
  51. {
  52. public function handle(Request $request, \Closure $next, ...$args)
  53. {
  54. return $next($request);
  55. }
  56. };
  57. }
  58. $this->app->singleton(PermissionMiddleware::class, function () use ($ins) {
  59. return $ins;
  60. });
  61. }
  62. }