koel/tests/Feature/UploadTest.php

83 lines
2.3 KiB
PHP
Raw Normal View History

2020-06-07 20:43:04 +00:00
<?php
namespace Tests\Feature;
use App\Exceptions\MediaPathNotSetException;
use App\Exceptions\SongUploadFailedException;
use App\Models\Setting;
use App\Models\Song;
use App\Models\User;
use App\Services\UploadService;
2022-08-08 16:00:59 +00:00
use Illuminate\Http\Response;
2020-06-07 20:43:04 +00:00
use Illuminate\Http\UploadedFile;
2022-06-10 10:47:46 +00:00
use Mockery\MockInterface;
2020-06-07 20:43:04 +00:00
class UploadTest extends TestCase
{
2022-07-27 15:32:36 +00:00
private UploadService|MockInterface $uploadService;
2022-08-08 16:00:59 +00:00
private UploadedFile $file;
2020-06-07 20:43:04 +00:00
public function setUp(): void
{
parent::setUp();
2020-12-22 23:01:49 +00:00
$this->uploadService = self::mock(UploadService::class);
2022-08-08 16:00:59 +00:00
$this->file = UploadedFile::fake()
->createWithContent('song.mp3', file_get_contents(__DIR__ . '/../songs/full.mp3'));
2020-06-07 20:43:04 +00:00
}
public function testUnauthorizedPost(): void
{
Setting::set('media_path', '/media/koel');
$this->uploadService
->shouldReceive('handleUploadedFile')
->never();
2022-08-08 16:00:59 +00:00
$this->postAs('/api/upload', ['file' => $this->file])->assertForbidden();
2020-06-07 20:43:04 +00:00
}
2020-12-22 20:11:22 +00:00
/** @return array<mixed> */
2020-06-07 20:43:04 +00:00
public function provideUploadExceptions(): array
{
return [
2022-08-08 16:00:59 +00:00
[MediaPathNotSetException::class, Response::HTTP_FORBIDDEN],
[SongUploadFailedException::class, Response::HTTP_BAD_REQUEST],
2020-06-07 20:43:04 +00:00
];
}
/** @dataProvider provideUploadExceptions */
2020-06-07 20:43:04 +00:00
public function testPostShouldFail(string $exceptionClass, int $statusCode): void
{
2022-07-27 15:32:36 +00:00
/** @var User $admin */
$admin = User::factory()->admin()->create();
2020-06-07 20:43:04 +00:00
$this->uploadService
->shouldReceive('handleUploadedFile')
->once()
2022-08-08 16:00:59 +00:00
->with($this->file)
2020-06-07 20:43:04 +00:00
->andThrow($exceptionClass);
2022-08-08 16:00:59 +00:00
$this->postAs('/api/upload', ['file' => $this->file], $admin)->assertStatus($statusCode);
2020-06-07 20:43:04 +00:00
}
public function testPost(): void
{
Setting::set('media_path', '/media/koel');
2022-07-27 15:32:36 +00:00
2020-06-07 20:43:04 +00:00
/** @var Song $song */
$song = Song::factory()->create();
2022-07-27 15:32:36 +00:00
/** @var User $admin */
$admin = User::factory()->admin()->create();
2020-06-07 20:43:04 +00:00
$this->uploadService
->shouldReceive('handleUploadedFile')
->once()
2022-08-08 16:00:59 +00:00
->with($this->file)
2020-06-07 20:43:04 +00:00
->andReturn($song);
2022-08-08 16:00:59 +00:00
$this->postAs('/api/upload', ['file' => $this->file], $admin)->assertJsonStructure(['song', 'album']);
2020-06-07 20:43:04 +00:00
}
}