repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/AlbumSongTest.php
tests/Feature/AlbumSongTest.php
<?php namespace Tests\Feature; use App\Http\Resources\SongResource; use App\Models\Album; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class AlbumSongTest extends TestCase { #[Test] public function index(): void { /** @var Album $album */ $album = Album::factory()->create(); Song::factory(5)->for($album)->create(); $this->getAs("api/albums/{$album->id}/songs") ->assertJsonStructure([0 => SongResource::JSON_STRUCTURE]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/SongSearchTest.php
tests/Feature/SongSearchTest.php
<?php namespace Tests\Feature; use App\Http\Resources\SongResource; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class SongSearchTest extends TestCase { public function setUp(): void { parent::setUp(); config()->set('scout.driver', 'collection'); } protected function tearDown(): void { config()->set('scout.driver', null); parent::tearDown(); // TODO: Change the autogenerated stub } #[Test] public function search(): void { $user = create_user(); Song::factory(2)->for($user, 'owner')->create(['title' => 'Foo Song']); $this->getAs('api/search/songs?q=foo', $user) ->assertJsonStructure([0 => SongResource::JSON_STRUCTURE]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/ArtistSongTest.php
tests/Feature/ArtistSongTest.php
<?php namespace Tests\Feature; use App\Http\Resources\SongResource; use App\Models\Artist; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class ArtistSongTest extends TestCase { #[Test] public function index(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); Song::factory(5)->for($artist)->create(); $this->getAs("api/artists/{$artist->id}/songs") ->assertJsonStructure([0 => SongResource::JSON_STRUCTURE]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/PlayCountTest.php
tests/Feature/PlayCountTest.php
<?php namespace Tests\Feature; use App\Events\PlaybackStarted; use App\Models\Interaction; use App\Models\Song; use Illuminate\Support\Facades\Event; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class PlayCountTest extends TestCase { #[Test] public function storeExistingEntry(): void { Event::fake(PlaybackStarted::class); /** @var Interaction $interaction */ $interaction = Interaction::factory()->create(['play_count' => 10]); $this->postAs('/api/interaction/play', ['song' => $interaction->song_id], $interaction->user) ->assertJsonStructure([ 'type', 'id', 'song_id', 'play_count', ]); self::assertSame(11, $interaction->refresh()->play_count); Event::assertDispatched(PlaybackStarted::class); } #[Test] public function storeNewEntry(): void { Event::fake(PlaybackStarted::class); /** @var Song $song */ $song = Song::factory()->create(); $user = create_user(); $this->postAs('/api/interaction/play', ['song' => $song->id], $user) ->assertJsonStructure([ 'type', 'id', 'song_id', 'play_count', ]); $interaction = Interaction::query() ->whereBelongsTo($song) ->whereBelongsTo($user) ->first(); self::assertSame(1, $interaction->play_count); Event::assertDispatched(PlaybackStarted::class); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/ArtistAlbumTest.php
tests/Feature/ArtistAlbumTest.php
<?php namespace Tests\Feature; use App\Http\Resources\AlbumResource; use App\Models\Album; use App\Models\Artist; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class ArtistAlbumTest extends TestCase { #[Test] public function index(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); Album::factory(5)->for($artist)->create(); $this->getAs("api/artists/{$artist->id}/albums") ->assertJsonStructure([0 => AlbumResource::JSON_STRUCTURE]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/InteractionTest.php
tests/Feature/InteractionTest.php
<?php namespace Tests\Feature; use App\Events\MultipleSongsLiked; use App\Events\PlaybackStarted; use App\Events\SongFavoriteToggled; use App\Models\Favorite; use App\Models\Interaction; use App\Models\Song; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\Event; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class InteractionTest extends TestCase { #[Test] public function increasePlayCount(): void { Event::fake(PlaybackStarted::class); $user = create_user(); /** @var Song $song */ $song = Song::factory()->create(); $this->postAs('api/interaction/play', ['song' => $song->id], $user); $this->assertDatabaseHas(Interaction::class, [ 'user_id' => $user->id, 'song_id' => $song->id, 'play_count' => 1, ]); // Try again $this->postAs('api/interaction/play', ['song' => $song->id], $user); $this->assertDatabaseHas(Interaction::class, [ 'user_id' => $user->id, 'song_id' => $song->id, 'play_count' => 2, ]); } #[Test] /** @deprecated Only for older client (e.g., mobile app) */ public function toggleLike(): void { Event::fake(SongFavoriteToggled::class); $user = create_user(); /** @var Song $song */ $song = Song::factory()->create(); // Toggle on $this->postAs('api/interaction/like', ['song' => $song->id], $user); $this->assertDatabaseHas(Favorite::class, [ 'user_id' => $user->id, 'favoriteable_id' => $song->id, 'favoriteable_type' => 'playable', ]); // Toggle off $this->postAs('api/interaction/like', ['song' => $song->id], $user) ->assertNoContent(); $this->assertDatabaseMissing(Favorite::class, [ 'user_id' => $user->id, 'favoriteable_id' => $song->id, 'favoriteable_type' => 'playable', ]); Event::assertDispatched(SongFavoriteToggled::class); } #[Test] /** @deprecated Only for older client (e.g., mobile app) */ public function toggleLikeBatch(): void { Event::fake(MultipleSongsLiked::class); $user = create_user(); /** @var Collection<Song> $songs */ $songs = Song::factory(2)->create(); $songIds = $songs->modelKeys(); $this->postAs('api/interaction/batch/like', ['songs' => $songIds], $user); foreach ($songs as $song) { $this->assertDatabaseHas(Favorite::class, [ 'user_id' => $user->id, 'favoriteable_id' => $song->id, 'favoriteable_type' => 'playable', ]); } Event::assertDispatched(MultipleSongsLiked::class); $this->postAs('api/interaction/batch/unlike', ['songs' => $songIds], $user); foreach ($songs as $song) { $this->assertDatabaseMissing(Favorite::class, [ 'user_id' => $user->id, 'favoriteable_id' => $song->id, 'favoriteable_type' => 'playable', ]); } Event::assertDispatched(MultipleSongsLiked::class); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/RadioStationTest.php
tests/Feature/RadioStationTest.php
<?php namespace Tests\Feature; use App\Helpers\Ulid; use App\Http\Resources\RadioStationResource; use App\Models\Organization; use App\Models\RadioStation; use App\Rules\ValidRadioStationUrl; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_admin; use function Tests\create_user; use function Tests\minimal_base64_encoded_image; class RadioStationTest extends TestCase { public function setUp(): void { parent::setUp(); $validator = app(ValidRadioStationUrl::class); $validator->bypass = true; } #[Test] public function create(): void { $user = create_user(); $ulid = Ulid::freeze(); $this->postAs('/api/radio/stations', [ 'url' => 'https://example.com/stream', 'name' => 'Test Radio Station', 'logo' => minimal_base64_encoded_image(), 'description' => 'A test radio station', 'is_public' => true, ], $user) ->assertCreated() ->assertJsonStructure(RadioStationResource::JSON_STRUCTURE); $this->assertDatabaseHas(RadioStation::class, [ 'url' => 'https://example.com/stream', 'name' => 'Test Radio Station', 'logo' => "$ulid.webp", 'description' => 'A test radio station', 'is_public' => true, 'user_id' => $user->id, ]); } #[Test] public function updateKeepingLogoIntact(): void { /** @var RadioStation $station */ $station = RadioStation::factory()->create([ 'logo' => 'neat-logo.webp', ]); $this->putAs("/api/radio/stations/{$station->id}", [ 'url' => 'https://example.com/updated-stream', 'name' => 'Updated Radio Station', 'description' => 'An updated test radio station', 'is_public' => false, ], $station->user) ->assertOk() ->assertJsonStructure(RadioStationResource::JSON_STRUCTURE); $station->refresh(); self::assertEquals('neat-logo.webp', $station->logo); self::assertEquals('https://example.com/updated-stream', $station->url); self::assertEquals('Updated Radio Station', $station->name); self::assertEquals('An updated test radio station', $station->description); self::assertFalse($station->is_public); } #[Test] public function updateWithNewLogo(): void { /** @var RadioStation $station */ $station = RadioStation::factory()->create(); $ulid = Ulid::freeze(); $this->putAs("/api/radio/stations/{$station->id}", [ 'url' => 'https://example.com/updated-stream', 'name' => 'Updated Radio Station', 'logo' => minimal_base64_encoded_image(), 'is_public' => true, ], $station->user) ->assertOk() ->assertJsonStructure(RadioStationResource::JSON_STRUCTURE); self::assertSame("$ulid.webp", $station->refresh()->logo); } #[Test] public function updateRemovingLogo(): void { /** @var RadioStation $station */ $station = RadioStation::factory()->create(); $this->putAs("/api/radio/stations/{$station->id}", [ 'url' => 'https://example.com/updated-stream', 'name' => 'Updated Radio Station', 'logo' => '', 'is_public' => true, ], $station->user) ->assertOk() ->assertJsonStructure(RadioStationResource::JSON_STRUCTURE); self::assertEmpty($station->refresh()->logo); } #[Test] public function normalNonAdminCannotUpdate(): void { /** @var RadioStation $station */ $station = RadioStation::factory()->create(); $data = [ 'url' => 'https://example.com/updated-stream', 'name' => 'Updated Radio Station', 'logo' => null, 'description' => 'An updated test radio station', 'is_public' => false, ]; $this->putAs("/api/radio/stations/{$station->id}", $data, create_user()) ->assertForbidden(); } #[Test] public function adminFromSameOrgCanUpdate(): void { /** @var RadioStation $station */ $station = RadioStation::factory()->create(); $data = [ 'url' => 'https://example.com/updated-stream', 'name' => 'Updated Radio Station', 'logo' => null, 'description' => 'An updated test radio station', 'is_public' => false, ]; $this->putAs("/api/radio/stations/{$station->id}", $data, create_admin()) ->assertOk(); } #[Test] public function adminFromOtherOrgCannotUpdate(): void { /** @var RadioStation $station */ $station = RadioStation::factory()->create(); $data = [ 'url' => 'https://example.com/updated-stream', 'name' => 'Updated Radio Station', 'logo' => null, 'description' => 'An updated test radio station', 'is_public' => false, ]; $this->putAs("/api/radio/stations/{$station->id}", $data, create_admin([ 'organization_id' => Organization::factory(), ])) ->assertForbidden(); } #[Test] public function listAll(): void { $user = create_user(); /** @var RadioStation $ownStation */ $ownStation = RadioStation::factory()->for($user)->create(); /** @var RadioStation $publicStation */ $publicStation = RadioStation::factory()->create(['is_public' => true]); // Non-public station should not be included RadioStation::factory()->count(2)->create(['is_public' => false]); // Public station but in another organization should not be included RadioStation::factory()->create([ 'is_public' => true, 'user_id' => create_user(['organization_id' => Organization::factory()])->id, ]); $this->getAs('/api/radio/stations', $user) ->assertOk() ->assertJsonStructure(['*' => RadioStationResource::JSON_STRUCTURE]) ->assertJsonCount(2, '*') ->assertJsonFragment(['id' => $ownStation->id]) ->assertJsonFragment(['id' => $publicStation->id]); } #[Test] public function destroy(): void { /** @var RadioStation $station */ $station = RadioStation::factory()->create(); $this->deleteAs("/api/radio/stations/{$station->id}", [], $station->user) ->assertNoContent(); $this->assertModelMissing($station); } #[Test] public function nonAdminCannotDelete(): void { /** @var RadioStation $station */ $station = RadioStation::factory()->create(); $this->deleteAs("/api/radio/stations/{$station->id}", [], create_user()) ->assertForbidden(); } #[Test] public function adminFromOtherOrgCannotDelete(): void { /** @var RadioStation $station */ $station = RadioStation::factory()->create(); $this->deleteAs("/api/radio/stations/{$station->id}", [], create_admin([ 'organization_id' => Organization::factory(), ])) ->assertForbidden(); } #[Test] public function adminFromSameOrgCanDelete(): void { /** @var RadioStation $station */ $station = RadioStation::factory()->create(); $this->deleteAs("/api/radio/stations/{$station->id}", [], create_admin()) ->assertNoContent(); $this->assertModelMissing($station); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/InitialDataTest.php
tests/Feature/InitialDataTest.php
<?php namespace Tests\Feature; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class InitialDataTest extends TestCase { #[Test] public function index(): void { $this->getAs('/api/data')->assertJsonStructure([ 'settings', 'playlists', 'playlist_folders', 'current_user', 'uses_last_fm', 'uses_you_tube', 'uses_i_tunes', 'uses_media_browser', 'uses_ticketmaster', 'allows_download', 'supports_transcoding', 'cdn_url', 'current_version', 'latest_version', 'song_count', 'song_length', 'queue_state' => [ 'songs', 'current_song', 'playback_position', ], 'koel_plus' => [ 'active', 'short_key', 'customer_name', 'customer_email', 'product_id', ], 'supports_batch_downloading', ]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/UserInvitationTest.php
tests/Feature/UserInvitationTest.php
<?php namespace Tests\Feature; use App\Http\Resources\UserProspectResource; use App\Mail\UserInvite; use App\Models\User; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Str; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_admin; use function Tests\create_manager; class UserInvitationTest extends TestCase { #[Test] public function invite(): void { Mail::fake(); $this->postAs('api/invitations', [ 'emails' => ['foo@bar.io', 'bar@baz.ai'], 'role' => 'admin', ], create_admin()) ->assertSuccessful() ->assertJsonStructure([0 => UserProspectResource::JSON_STRUCTURE]); Mail::assertQueued(UserInvite::class, 2); } #[Test] public function preventRoleEscalation(): void { $this->postAs('api/invitations', [ 'emails' => ['foo@bar.io', 'bar@baz.ai'], 'role' => 'admin', ], create_manager()) ->assertUnprocessable() ->assertJsonValidationErrors('role'); } #[Test] public function cannotInviteNonAvailableRole(): void { $this->postAs('api/invitations', [ 'emails' => ['foo@bar.io', 'bar@baz.ai'], 'role' => 'manager', ], create_admin()) ->assertUnprocessable() ->assertJsonValidationErrors('role'); } #[Test] public function nonAdminCannotInvite(): void { Mail::fake(); $this->postAs('api/invitations', [ 'emails' => ['foo@bar.io', 'bar@baz.ai'], 'role' => 'user', ]) ->assertForbidden(); Mail::assertNothingQueued(); } #[Test] public function getProspect(): void { $prospect = self::createProspect(); $this->get("api/invitations?token=$prospect->invitation_token") ->assertSuccessful() ->assertJsonStructure(UserProspectResource::JSON_STRUCTURE); } #[Test] public function revoke(): void { $prospect = self::createProspect(); $this->deleteAs('api/invitations', ['email' => $prospect->email], create_admin()) ->assertSuccessful(); $this->assertModelMissing($prospect); } #[Test] public function nonAdminCannotRevoke(): void { $prospect = self::createProspect(); $this->deleteAs('api/invitations', ['email' => $prospect->email]) ->assertForbidden(); $this->assertModelExists($prospect); } #[Test] public function accept(): void { $prospect = self::createProspect(); $this->post('api/invitations/accept', [ 'token' => $prospect->invitation_token, 'name' => 'Bruce Dickinson', 'password' => 'SuperSecretPassword', ]) ->assertSuccessful() ->assertJsonStructure(['token', 'audio-token']); $prospect->refresh(); self::assertFalse($prospect->is_prospect); } private static function createProspect(): User { return User::factory()->for(create_admin(), 'invitedBy')->create([ 'invitation_token' => Str::uuid()->toString(), 'invited_at' => now(), ]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/AlbumThumbnailTest.php
tests/Feature/AlbumThumbnailTest.php
<?php namespace Tests\Feature; use App\Models\Album; use App\Services\ImageStorage; use App\Values\ImageWritingConfig; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class AlbumThumbnailTest extends TestCase { private ImageStorage|MockInterface $imageStorage; public function setUp(): void { parent::setUp(); $this->imageStorage = $this->mock(ImageStorage::class); } #[Test] public function getAlbumThumbnail(): void { /** @var Album $createdAlbum */ $createdAlbum = Album::factory()->create(['cover' => 'foo.jpg']); $this->imageStorage ->expects('storeImage') ->with( image_storage_path('foo.jpg'), Mockery::on(static fn (ImageWritingConfig $config) => $config->maxWidth === 48), image_storage_path('foo_thumb.jpg'), ) ->andReturn('foo_thumb.jpg'); $response = $this->getAs("api/albums/{$createdAlbum->id}/thumbnail"); $response->assertJson(['thumbnailUrl' => image_storage_url('foo_thumb.jpg')]); } #[Test] public function getThumbnailForAlbumWithoutCover(): void { /** @var Album $createdAlbum */ $createdAlbum = Album::factory()->create(['cover' => '']); $this->imageStorage->expects('storeImage')->never(); $response = $this->getAs("api/albums/{$createdAlbum->id}/thumbnail"); $response->assertJson(['thumbnailUrl' => null]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/ForgotPasswordTest.php
tests/Feature/ForgotPasswordTest.php
<?php namespace Tests\Feature; use App\Services\AuthenticationService; use Illuminate\Auth\Events\PasswordReset; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Password; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class ForgotPasswordTest extends TestCase { #[Test] public function sendResetPasswordRequest(): void { $this->mock(AuthenticationService::class) ->expects('trySendResetPasswordLink') ->with('foo@bar.com') ->andReturnTrue(); $this->postJson('/api/forgot-password', ['email' => 'foo@bar.com']) ->assertNoContent(); } #[Test] public function sendResetPasswordRequestFailed(): void { $this->mock(AuthenticationService::class) ->expects('trySendResetPasswordLink') ->with('foo@bar.com') ->andReturnFalse(); $this->postJson('/api/forgot-password', ['email' => 'foo@bar.com']) ->assertNotFound(); } #[Test] public function resetPassword(): void { Event::fake(); $user = create_user(); $this->postJson('/api/reset-password', [ 'email' => $user->email, 'password' => 'new-password', 'token' => Password::createToken($user), ])->assertNoContent(); self::assertTrue(Hash::check('new-password', $user->refresh()->password)); Event::assertDispatched(PasswordReset::class); } #[Test] public function resetPasswordFailed(): void { Event::fake(); $user = create_user(['password' => Hash::make('old-password')]); $this->postJson('/api/reset-password', [ 'email' => $user->email, 'password' => 'new-password', 'token' => 'invalid-token', ])->assertJsonValidationErrors([ 'token' => 'Invalid or expired token.', ]); self::assertTrue(Hash::check('old-password', $user->refresh()->password)); Event::assertNotDispatched(PasswordReset::class); } #[Test] public function disabledInDemo(): void { config(['koel.misc.demo' => true]); $user = create_user(); $this->postJson('/api/reset-password', [ 'email' => $user->email, 'password' => 'new-password', 'token' => Password::createToken($user), ])->assertForbidden(); } public function tearDown(): void { config(['koel.misc.demo' => false]); parent::tearDown(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/PlaylistFolderTest.php
tests/Feature/PlaylistFolderTest.php
<?php namespace Tests\Feature; use App\Http\Resources\PlaylistFolderResource; use App\Models\PlaylistFolder; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_playlist; use function Tests\create_user; class PlaylistFolderTest extends TestCase { #[Test] public function listing(): void { $user = create_user(); PlaylistFolder::factory()->for($user)->count(2)->create(); $this->getAs('api/playlist-folders', $user) ->assertJsonStructure([0 => PlaylistFolderResource::JSON_STRUCTURE]) ->assertJsonCount(2); } #[Test] public function create(): void { $user = create_user(); $this->postAs('api/playlist-folders', ['name' => 'Classical'], $user) ->assertJsonStructure(PlaylistFolderResource::JSON_STRUCTURE); $this->assertDatabaseHas(PlaylistFolder::class, ['name' => 'Classical', 'user_id' => $user->id]); } #[Test] public function update(): void { $folder = PlaylistFolder::factory()->create(['name' => 'Metal']); $this->patchAs("api/playlist-folders/{$folder->id}", ['name' => 'Classical'], $folder->user) ->assertJsonStructure(PlaylistFolderResource::JSON_STRUCTURE); self::assertSame('Classical', $folder->fresh()->name); } #[Test] public function unauthorizedUpdate(): void { /** @var PlaylistFolder $folder */ $folder = PlaylistFolder::factory()->create(['name' => 'Metal']); $this->patchAs("api/playlist-folders/{$folder->id}", ['name' => 'Classical']) ->assertForbidden(); self::assertSame('Metal', $folder->fresh()->name); } #[Test] public function destroy(): void { /** @var PlaylistFolder $folder */ $folder = PlaylistFolder::factory()->create(); $this->deleteAs("api/playlist-folders/{$folder->id}", ['name' => 'Classical'], $folder->user) ->assertNoContent(); $this->assertModelMissing($folder); } #[Test] public function nonAuthorizedDelete(): void { /** @var PlaylistFolder $folder */ $folder = PlaylistFolder::factory()->create(); $this->deleteAs("api/playlist-folders/{$folder->id}", ['name' => 'Classical']) ->assertForbidden(); $this->assertModelExists($folder); } #[Test] public function movePlaylistToFolder(): void { $playlist = create_playlist(); /** @var PlaylistFolder $folder */ $folder = PlaylistFolder::factory()->for($playlist->owner)->create(); self::assertNull($playlist->getFolderId($folder->user)); $this->postAs( "api/playlist-folders/{$folder->id}/playlists", ['playlists' => [$playlist->id]], $folder->user ) ->assertSuccessful(); self::assertTrue($playlist->fresh()->getFolder($folder->user)->is($folder)); } #[Test] public function unauthorizedMovingPlaylistToFolderIsNotAllowed(): void { $playlist = create_playlist(); /** @var PlaylistFolder $folder */ $folder = PlaylistFolder::factory()->for($playlist->owner)->create(); self::assertNull($playlist->getFolderId($folder->user)); $this->postAs("api/playlist-folders/{$folder->id}/playlists", ['playlists' => [$playlist->id]]) ->assertUnprocessable(); self::assertNull($playlist->fresh()->getFolder($folder->user)); } #[Test] public function movePlaylistToRootLevel(): void { $playlist = create_playlist(); /** @var PlaylistFolder $folder */ $folder = PlaylistFolder::factory()->for($playlist->owner)->create(); $folder->playlists()->attach($playlist); self::assertTrue($playlist->refresh()->getFolder($folder->user)->is($folder)); $this->deleteAs( "api/playlist-folders/{$folder->id}/playlists", ['playlists' => [$playlist->id]], $folder->user ) ->assertSuccessful(); self::assertNull($playlist->fresh()->getFolder($folder->user)); } #[Test] public function unauthorizedMovingPlaylistToRootLevelIsNotAllowed(): void { $playlist = create_playlist(); /** @var PlaylistFolder $folder */ $folder = PlaylistFolder::factory()->for($playlist->owner)->create(); $folder->playlists()->attach($playlist); self::assertTrue($playlist->refresh()->getFolder($folder->user)->is($folder)); $this->deleteAs("api/playlist-folders/{$folder->id}/playlists", ['playlists' => [$playlist->id]]) ->assertUnprocessable(); self::assertTrue($playlist->refresh()->getFolder($folder->user)->is($folder)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/ExcerptSearchTest.php
tests/Feature/ExcerptSearchTest.php
<?php namespace Tests\Feature; use App\Http\Resources\AlbumResource; use App\Http\Resources\ArtistResource; use App\Http\Resources\PodcastResource; use App\Http\Resources\SongResource; use App\Models\Album; use App\Models\Artist; use App\Models\Podcast; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class ExcerptSearchTest extends TestCase { public function setUp(): void { parent::setUp(); config()->set('scout.driver', 'collection'); } protected function tearDown(): void { config()->set('scout.driver', null); parent::tearDown(); // TODO: Change the autogenerated stub } #[Test] public function search(): void { $user = create_user(); Song::factory()->for($user, 'owner')->create(['title' => 'Foo Song']); Song::factory()->create(); Artist::factory()->for($user)->create(['name' => 'Foo Fighters']); Artist::factory()->create(); Album::factory()->for($user)->create(['name' => 'Foo Number Five']); Album::factory()->create(); Podcast::factory()->hasAttached($user, relationship: 'subscribers')->create(['title' => 'Foo Podcast']); $this->getAs('api/search?q=foo', $user) ->assertJsonStructure([ 'songs' => [0 => SongResource::JSON_STRUCTURE], 'podcasts' => [0 => PodcastResource::JSON_STRUCTURE], 'artists' => [0 => ArtistResource::JSON_STRUCTURE], 'albums' => [0 => AlbumResource::JSON_STRUCTURE], ]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/FetchFavoriteSongsTest.php
tests/Feature/FetchFavoriteSongsTest.php
<?php namespace Tests\Feature; use App\Http\Resources\SongResource; use App\Models\Favorite; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class FetchFavoriteSongsTest extends TestCase { #[Test] public function index(): void { $user = create_user(); $songs = Song::factory(2)->for($user, 'owner')->create(); $songs->each(static function (Song $song) use ($user): void { Favorite::factory()->for($user)->create([ 'favoriteable_id' => $song->id, ]); }); $this->getAs('api/songs/favorite', $user) ->assertJsonStructure([0 => SongResource::JSON_STRUCTURE]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/HomeTest.php
tests/Feature/HomeTest.php
<?php namespace Tests\Feature; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class HomeTest extends TestCase { #[Test] public function renders(): void { $this->withoutVite() ->get('/') ->assertOk() ->assertSee('window.ACCEPTED_AUDIO_EXTENSIONS') ->assertSee('window.BRANDING') ->assertSee('window.MAILER_CONFIGURED') ->assertSee('window.SSO_PROVIDERS'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/SongPlayTest.php
tests/Feature/SongPlayTest.php
<?php namespace Tests\Feature; use App\Models\Song; use App\Services\Streamer\Adapters\LocalStreamerAdapter; use App\Services\Streamer\Adapters\TranscodingStreamerAdapter; use App\Services\TokenManager; use App\Values\CompositeToken; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; use function Tests\test_path; class SongPlayTest extends TestCase { public function setUp(): void { parent::setUp(); // Start output buffering to prevent binary data from being sent to the console during tests ob_start(); } protected function tearDown(): void { ob_end_clean(); parent::tearDown(); } #[Test] public function play(): void { $user = create_user(); /** @var CompositeToken $token */ $token = app(TokenManager::class)->createCompositeToken($user); /** @var Song $song */ $song = Song::factory()->create([ 'path' => test_path('songs/blank.mp3'), ]); $this->mock(LocalStreamerAdapter::class) ->expects('stream'); $this->get("play/{$song->id}?t=$token->audioToken") ->assertOk(); } #[Test] public function transcoding(): void { config(['koel.streaming.transcode_flac' => true]); $user = create_user(); /** @var CompositeToken $token */ $token = app(TokenManager::class)->createCompositeToken($user); /** @var Song $song */ $song = Song::factory()->create([ 'path' => '/tmp/blank.flac', 'mime_type' => 'audio/flac', ]); $this->mock(TranscodingStreamerAdapter::class) ->expects('stream'); $this->get("play/{$song->id}?t=$token->audioToken") ->assertOk(); config(['koel.streaming.transcode_flac' => false]); } #[Test] public function forceTranscoding(): void { $user = create_user(); /** @var CompositeToken $token */ $token = app(TokenManager::class)->createCompositeToken($user); /** @var Song $song */ $song = Song::factory()->create(['path' => '/var/songs/blank.mp3']); $this->mock(TranscodingStreamerAdapter::class) ->expects('stream'); $this->get("play/{$song->id}/1?t=$token->audioToken") ->assertOk(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/RecentlyPlayedSongTest.php
tests/Feature/RecentlyPlayedSongTest.php
<?php namespace Tests\Feature; use App\Http\Resources\SongResource; use App\Models\Interaction; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class RecentlyPlayedSongTest extends TestCase { #[Test] public function index(): void { $user = create_user(); Interaction::factory(5)->for($user)->create(); $this->getAs('api/songs/recently-played', $user) ->assertJsonStructure([0 => SongResource::JSON_STRUCTURE]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/PlaylistSongTest.php
tests/Feature/PlaylistSongTest.php
<?php namespace Tests\Feature; use App\Http\Resources\SongResource; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_playlist; class PlaylistSongTest extends TestCase { #[Test] public function getNormalPlaylist(): void { $playlist = create_playlist(); $playlist->addPlayables(Song::factory(5)->create()); $this->getAs("api/playlists/{$playlist->id}/songs", $playlist->owner) ->assertSuccessful() ->assertJsonStructure([0 => SongResource::JSON_STRUCTURE]); } #[Test] public function getSmartPlaylist(): void { Song::factory()->create(['title' => 'A foo song']); $playlist = create_playlist([ 'rules' => [ [ 'id' => '45368b8f-fec8-4b72-b826-6b295af0da65', 'rules' => [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'model' => 'title', 'operator' => 'contains', 'value' => ['foo'], ], ], ], ], ]); $this->getAs("api/playlists/{$playlist->id}/songs", $playlist->owner) ->assertJsonStructure([0 => SongResource::JSON_STRUCTURE]); } #[Test] public function nonOwnerCannotAccessPlaylist(): void { $playlist = create_playlist(); $playlist->addPlayables(Song::factory(5)->create()); $this->getAs("api/playlists/{$playlist->id}/songs") ->assertForbidden(); } #[Test] public function addSongsToPlaylist(): void { $playlist = create_playlist(); $songs = Song::factory(2)->create(); $this->postAs("api/playlists/{$playlist->id}/songs", ['songs' => $songs->modelKeys()], $playlist->owner) ->assertSuccessful(); self::assertEqualsCanonicalizing($songs->modelKeys(), $playlist->playables->modelKeys()); } #[Test] public function removeSongsFromPlaylist(): void { $playlist = create_playlist(); $toRemainSongs = Song::factory(5)->create(); $toBeRemovedSongs = Song::factory(2)->create(); $playlist->addPlayables($toRemainSongs->merge($toBeRemovedSongs)); self::assertCount(7, $playlist->playables); $this->deleteAs( "api/playlists/{$playlist->id}/songs", ['songs' => $toBeRemovedSongs->modelKeys()], $playlist->owner ) ->assertNoContent(); $playlist->refresh(); self::assertEqualsCanonicalizing($toRemainSongs->modelKeys(), $playlist->playables->modelKeys()); } #[Test] public function nonOwnerCannotModifyPlaylist(): void { $playlist = create_playlist(); /** @var Song $song */ $song = Song::factory()->create(); $this->postAs("api/playlists/{$playlist->id}/songs", ['songs' => [$song->id]]) ->assertForbidden(); $this->deleteAs("api/playlists/{$playlist->id}/songs", ['songs' => [$song->id]]) ->assertForbidden(); } #[Test] public function smartPlaylistContentCannotBeModified(): void { $playlist = create_playlist([ 'rules' => [ [ 'id' => '45368b8f-fec8-4b72-b826-6b295af0da65', 'rules' => [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'model' => 'title', 'operator' => 'contains', 'value' => ['foo'], ], ], ], ], ]); $songs = Song::factory(2)->create()->modelKeys(); $this->postAs("api/playlists/{$playlist->id}/songs", ['songs' => $songs], $playlist->owner) ->assertForbidden(); $this->deleteAs("api/playlists/{$playlist->id}/songs", ['songs' => $songs], $playlist->owner) ->assertForbidden(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/DownloadTest.php
tests/Feature/DownloadTest.php
<?php namespace Tests\Feature; use App\Models\Album; use App\Models\Artist; use App\Models\Favorite; use App\Models\Song; use App\Services\DownloadService; use App\Values\Downloadable; use Illuminate\Database\Eloquent\Collection; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_playlist; use function Tests\create_user; use function Tests\test_path; class DownloadTest extends TestCase { private MockInterface|DownloadService $downloadService; public function setUp(): void { parent::setUp(); $this->downloadService = $this->mock(DownloadService::class); } #[Test] public function nonLoggedInUserCannotDownload(): void { $this->downloadService->shouldNotReceive('getDownloadable'); $this->get('download/songs?songs[]=' . Song::factory()->create()->id) ->assertUnauthorized(); } #[Test] public function downloadOneSong(): void { $song = Song::factory()->create(); $user = create_user(); $this->downloadService ->expects('getDownloadable') ->with(Mockery::on(static function (Collection $retrievedSongs) use ($song) { return $retrievedSongs->count() === 1 && $retrievedSongs->first()->is($song); })) ->andReturn(Downloadable::make(test_path('songs/blank.mp3'))); $this->get("download/songs?songs[]={$song->id}&api_token=" . $user->createToken('Koel')->plainTextToken) ->assertOk(); } #[Test] public function downloadMultipleSongs(): void { $songs = Song::factory(2)->create(); $user = create_user(); $this->downloadService ->expects('getDownloadable') ->with(Mockery::on(static function (Collection $retrievedSongs) use ($songs): bool { self::assertEqualsCanonicalizing($retrievedSongs->modelKeys(), $songs->modelKeys()); return true; })) // should be a zip file, but we're testing here… ->andReturn(Downloadable::make(test_path('songs/blank.mp3'))); $this->get( "download/songs?songs[]={$songs[0]->id}&songs[]={$songs[1]->id}&api_token=" . $user->createToken('Koel')->plainTextToken ) ->assertOk(); } #[Test] public function downloadAlbum(): void { /** @var Album $album */ $album = Album::factory()->create(); $songs = Song::factory(2)->for($album)->create(); $user = create_user(); $this->downloadService ->expects('getDownloadable') ->with(Mockery::on(static function (Collection $retrievedSongs) use ($songs): bool { self::assertEqualsCanonicalizing($retrievedSongs->modelKeys(), $songs->modelKeys()); return true; })) ->andReturn(Downloadable::make(test_path('songs/blank.mp3'))); $this->get("download/album/{$album->id}?api_token=" . $user->createToken('Koel')->plainTextToken) ->assertOk(); } #[Test] public function downloadArtist(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); $songs = Song::factory(2)->for($artist)->create(); $user = create_user(); $this->downloadService ->expects('getDownloadable') ->with(Mockery::on(static function (Collection $retrievedSongs) use ($songs): bool { self::assertEqualsCanonicalizing($retrievedSongs->modelKeys(), $songs->modelKeys()); return true; })) ->andReturn(Downloadable::make(test_path('songs/blank.mp3'))); $this->get("download/artist/{$artist->id}?api_token=" . $user->createToken('Koel')->plainTextToken) ->assertOk(); } #[Test] public function downloadPlaylist(): void { $songs = Song::factory(2)->create(); $playlist = create_playlist(); $playlist->playables()->attach($songs, ['user_id' => $playlist->owner->id]); $this->downloadService ->expects('getDownloadable') ->with(Mockery::on(static function (Collection $retrievedSongs) use ($songs): bool { self::assertEqualsCanonicalizing($retrievedSongs->modelKeys(), $songs->modelKeys()); return true; })) ->andReturn(Downloadable::make(test_path('songs/blank.mp3'))); $this->get( "download/playlist/{$playlist->id}?api_token=" . $playlist->owner->createToken('Koel')->plainTextToken )->assertOk(); } #[Test] public function nonOwnerCannotDownloadPlaylist(): void { $playlist = create_playlist(); $this->get("download/playlist/{$playlist->id}?api_token=" . create_user()->createToken('Koel')->plainTextToken) ->assertForbidden(); } #[Test] public function downloadFavorites(): void { $user = create_user(); /** @var Collection<int, Song> $songs */ $songs = Song::factory(2)->for($user, 'owner')->create(); $songs->map(static function (Song $song) use ($user): Favorite { return Favorite::factory()->for($user)->create([ 'favoriteable_id' => $song->id, ]); }); $this->downloadService ->expects('getDownloadable') ->with(Mockery::on(static function (Collection $input) use ($songs): bool { self::assertEqualsCanonicalizing($input->modelKeys(), $songs->pluck('id')->all()); return true; })) ->andReturn(Downloadable::make(test_path('songs/blank.mp3'))); $this->get('download/favorites?api_token=' . $user->createToken('Koel')->plainTextToken) ->assertOk(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/BrandingSettingTest.php
tests/Feature/BrandingSettingTest.php
<?php namespace Tests\Feature; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_admin; use function Tests\minimal_base64_encoded_image; class BrandingSettingTest extends TestCase { #[Test] public function notAccessibleInCommunityLicense(): void { $this->putAs('api/settings/branding', [ 'name' => 'Little Bird', 'logo' => minimal_base64_encoded_image(), 'cover' => minimal_base64_encoded_image(), ], create_admin()) ->assertNotFound(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/UploadTest.php
tests/Feature/UploadTest.php
<?php namespace Tests\Feature; use App\Exceptions\MediaPathNotSetException; use App\Exceptions\SongUploadFailedException; use App\Models\Setting; use Illuminate\Http\Response; use Illuminate\Http\UploadedFile; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_admin; use function Tests\test_path; class UploadTest extends TestCase { private UploadedFile $file; public function setUp(): void { parent::setUp(); $this->file = UploadedFile::fromFile(test_path('songs/full.mp3'), 'song.mp3'); //@phpstan-ignore-line } #[Test] public function unauthorizedPost(): void { Setting::set('media_path', ''); $this->postAs('/api/upload', ['file' => $this->file])->assertForbidden(); } /** @return array<mixed> */ public function provideUploadExceptions(): array { return [ [MediaPathNotSetException::class, Response::HTTP_FORBIDDEN], [SongUploadFailedException::class, Response::HTTP_BAD_REQUEST], ]; } #[Test] public function uploadFailsIfMediaPathIsNotSet(): void { Setting::set('media_path', ''); $this->postAs('/api/upload', ['file' => $this->file], create_admin())->assertForbidden(); } #[Test] public function uploadSuccessful(): void { Setting::set('media_path', public_path('sandbox/media')); $this->postAs('/api/upload', ['file' => $this->file], create_admin())->assertJsonStructure(['song', 'album']); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/ArtistEventTest.php
tests/Feature/ArtistEventTest.php
<?php namespace Tests\Feature; use App\Models\Artist; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class ArtistEventTest extends TestCase { #[Test] public function disabledInCommunityEdition(): void { $artist = Artist::factory()->create(); $this->getAs("api/artists/{$artist->id}/events") ->assertNotFound(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/SongTest.php
tests/Feature/SongTest.php
<?php namespace Tests\Feature; use App\Facades\Dispatcher; use App\Http\Resources\SongResource; use App\Jobs\DeleteSongFilesJob; use App\Models\Album; use App\Models\Artist; use App\Models\Song; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Bus; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_admin; class SongTest extends TestCase { #[Test] public function index(): void { Song::factory(2)->create(); $this->getAs('api/songs')->assertJsonStructure(SongResource::PAGINATION_JSON_STRUCTURE); $this->getAs('api/songs?sort=title&order=desc')->assertJsonStructure(SongResource::PAGINATION_JSON_STRUCTURE); } #[Test] public function show(): void { /** @var Song $song */ $song = Song::factory()->create(); $this->getAs("api/songs/{$song->id}")->assertJsonStructure(SongResource::JSON_STRUCTURE); } #[Test] public function destroy(): void { Bus::fake(); Dispatcher::expects('dispatch')->with(DeleteSongFilesJob::class); $songs = Song::factory(2)->create(); $this->deleteAs('api/songs', ['songs' => $songs->modelKeys()], create_admin()) ->assertNoContent(); $songs->each(fn (Song $song) => $this->assertModelMissing($song)); } #[Test] public function unauthorizedDelete(): void { Bus::fake(); Dispatcher::expects('dispatch')->never(); $songs = Song::factory(2)->create(); $this->deleteAs('api/songs', ['songs' => $songs->modelKeys()]) ->assertForbidden(); $songs->each(fn (Song $song) => $this->assertModelExists($song)); } #[Test] public function singleUpdateAllInfoNoCompilation(): void { /** @var Song $song */ $song = Song::factory()->create(); $this->putAs('/api/songs', [ 'songs' => [$song->id], 'data' => [ 'title' => 'Foo Bar', 'artist_name' => 'John Cena', 'album_name' => 'One by One', 'lyrics' => 'Lorem ipsum dolor sic amet.', 'track' => 1, 'disc' => 2, ], ], create_admin()) ->assertOk(); /** @var Artist|null $artist */ $artist = Artist::query()->where('name', 'John Cena')->first(); self::assertNotNull($artist); /** @var Album|null $album */ $album = Album::query()->where('name', 'One by One')->first(); self::assertNotNull($album); $this->assertDatabaseHas(Song::class, [ 'id' => $song->id, 'album_id' => $album->id, 'lyrics' => 'Lorem ipsum dolor sic amet.', 'track' => 1, 'disc' => 2, ]); } #[Test] public function singleUpdateSomeInfoNoCompilation(): void { /** @var Song $song */ $song = Song::factory()->create(); $originalArtistId = $song->artist->id; $this->putAs('/api/songs', [ 'songs' => [$song->id], 'data' => [ 'title' => '', 'artist_name' => '', 'album_name' => 'One by One', 'lyrics' => 'Lorem ipsum dolor sic amet.', 'track' => 1, ], ], create_admin()) ->assertOk(); // We don't expect the song's artist to change self::assertSame($originalArtistId, $song->refresh()->artist->id); // But we expect a new album to be created for this artist and contain this song self::assertSame('One by One', $song->album->name); } #[Test] public function multipleUpdateNoCompilation(): void { $songIds = Song::factory(2)->create()->modelKeys(); $this->putAs('/api/songs', [ 'songs' => $songIds, 'data' => [ 'title' => null, 'artist_name' => 'John Cena', 'album_name' => 'One by One', 'lyrics' => null, 'track' => 9999, ], ], create_admin()) ->assertOk(); /** @var Collection<array-key, Song> $songs */ $songs = Song::query()->whereIn('id', $songIds)->get(); // All of these songs must now belong to a new album and artist set self::assertSame('One by One', $songs[0]->album->name); self::assertSame($songs[0]->album_id, $songs[1]->album_id); self::assertSame('John Cena', $songs[0]->artist->name); self::assertSame($songs[0]->artist_id, $songs[1]->artist_id); // Since the lyrics and title were not set, they should be left unchanged self::assertNotSame($songs[0]->title, $songs[1]->title); self::assertNotSame($songs[0]->lyrics, $songs[1]->lyrics); self::assertSame(9999, $songs[0]->track); self::assertSame(9999, $songs[1]->track); } #[Test] public function multipleUpdateCreatingNewAlbumsAndArtists(): void { $originalSongs = Song::factory(2)->create(); $originalSongIds = $originalSongs->modelKeys(); $originalAlbumNames = $originalSongs->pluck('album.name')->all(); $originalAlbumIds = $originalSongs->pluck('album_id')->all(); $this->putAs('/api/songs', [ 'songs' => $originalSongIds, 'data' => [ 'title' => 'Foo Bar', 'artist_name' => 'John Cena', 'album_name' => '', 'lyrics' => 'Lorem ipsum dolor sic amet.', 'track' => 1, ], ], create_admin()) ->assertOk(); $songs = Song::query()->whereIn('id', $originalSongIds)->get()->orderByArray($originalSongIds); // Even though the album name doesn't change, a new artist should have been created // and thus, a new album with the same name was created as well. collect([0, 1])->each(static function (int $i) use ($songs, $originalAlbumNames, $originalAlbumIds): void { self::assertSame($songs[$i]->album->name, $originalAlbumNames[$i]); self::assertNotSame($songs[$i]->album_id, $originalAlbumIds[$i]); }); // And of course, the new artist is... self::assertSame('John Cena', $songs[0]->artist->name); // JOHN CENA!!! self::assertSame('John Cena', $songs[1]->artist->name); // And... JOHN CENAAAAAAAAAAA!!! } #[Test] public function singleUpdateAllInfoWithCompilation(): void { /** @var Song $song */ $song = Song::factory()->create(); $this->putAs('/api/songs', [ 'songs' => [$song->id], 'data' => [ 'title' => 'Foo Bar', 'artist_name' => 'John Cena', 'album_name' => 'One by One', 'album_artist_name' => 'John Lennon', 'lyrics' => 'Lorem ipsum dolor sic amet.', 'track' => 1, 'disc' => 2, ], ], create_admin()) ->assertOk(); /** @var Album $album */ $album = Album::query()->where('name', 'One by One')->first(); /** @var Artist $albumArtist */ $albumArtist = Artist::query()->where('name', 'John Lennon')->first(); /** @var Artist $artist */ $artist = Artist::query()->where('name', 'John Cena')->first(); $this->assertDatabaseHas(Song::class, [ 'id' => $song->id, 'artist_id' => $artist->id, 'album_id' => $album->id, 'lyrics' => 'Lorem ipsum dolor sic amet.', 'track' => 1, 'disc' => 2, ]); self::assertTrue($album->artist->is($albumArtist)); } #[Test] public function updateSingleSongWithEmptyTrackAndDisc(): void { /** @var Song $song */ $song = Song::factory()->create([ 'track' => 12, 'disc' => 2, ]); $this->putAs('/api/songs', [ 'songs' => [$song->id], 'data' => [ 'track' => null, 'disc' => null, ], ], create_admin()) ->assertOk(); $song->refresh(); self::assertSame(0, $song->track); self::assertSame(1, $song->disc); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/EmbedOptionsTest.php
tests/Feature/EmbedOptionsTest.php
<?php namespace Tests\Feature; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class EmbedOptionsTest extends TestCase { #[Test] public function encrypt(): void { $this->post('api/embed-options', [ 'theme' => 'cat', 'layout' => 'compact', 'preview' => true, ])->assertSuccessful() ->assertJsonStructure(['encrypted']); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/AlbumInformationTest.php
tests/Feature/AlbumInformationTest.php
<?php namespace Tests\Feature; use App\Models\Album; use App\Services\EncyclopediaService; use App\Values\Album\AlbumInformation; use Mockery; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class AlbumInformationTest extends TestCase { #[Test] public function getInformation(): void { config(['koel.services.lastfm.key' => 'foo']); config(['koel.services.lastfm.secret' => 'geheim']); /** @var Album $album */ $album = Album::factory()->create(); $lastfm = $this->mock(EncyclopediaService::class); $lastfm->expects('getAlbumInformation') ->with(Mockery::on(static fn (Album $a) => $a->is($album))) ->andReturn(AlbumInformation::make( url: 'https://lastfm.com/album/foo', cover: 'https://lastfm.com/cover/foo', wiki: [ 'summary' => 'foo', 'full' => 'bar', ], tracks: [ [ 'title' => 'foo', 'length' => 123, 'url' => 'https://lastfm.com/track/foo', ], [ 'title' => 'bar', 'length' => 456, 'url' => 'https://lastfm.com/track/bar', ], ] )); $this->getAs("api/albums/{$album->id}/information") ->assertJsonStructure(AlbumInformation::JSON_STRUCTURE); } #[Test] public function getWithoutLastfmStillReturnsValidStructure(): void { config(['koel.services.lastfm.key' => null]); config(['koel.services.lastfm.secret' => null]); $this->getAs('api/albums/' . Album::factory()->create()->id . '/information') ->assertJsonStructure(AlbumInformation::JSON_STRUCTURE); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/FavoriteTest.php
tests/Feature/FavoriteTest.php
<?php namespace Tests\Feature; use App\Events\MultipleSongsLiked; use App\Events\MultipleSongsUnliked; use App\Events\SongFavoriteToggled; use App\Http\Resources\FavoriteResource; use App\Models\Favorite; use App\Models\Song; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\Event; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class FavoriteTest extends TestCase { #[Test] public function favorite(): void { Event::fake(SongFavoriteToggled::class); /** @var Song $song */ $song = Song::factory()->create(); $user = create_user(); $this->postAs('api/favorites/toggle', [ 'type' => 'playable', 'id' => $song->id, ], $user) ->assertJsonStructure(FavoriteResource::JSON_STRUCTURE); $this->assertDatabaseHas(Favorite::class, [ 'favoriteable_type' => 'playable', 'favoriteable_id' => $song->id, 'user_id' => $user->id, ]); Event::assertDispatched(SongFavoriteToggled::class); } #[Test] public function undoFavorite(): void { Event::fake(SongFavoriteToggled::class); /** @var Favorite $favorite */ $favorite = Favorite::factory()->create(); $this->postAs('api/favorites/toggle', [ 'type' => 'playable', 'id' => $favorite->favoriteable_id, ], $favorite->user) ->assertNoContent(); $this->assertDatabaseMissing(Favorite::class, [ 'id' => $favorite->id, ]); Event::assertDispatched(SongFavoriteToggled::class); } #[Test] public function batchFavorite(): void { Event::fake(MultipleSongsLiked::class); /** @var Collection<Song> $songs */ $songs = Song::factory()->count(2)->create(); $user = create_user(); $this->postAs('api/favorites', [ 'type' => 'playable', 'ids' => $songs->pluck('id')->toArray(), ], $user) ->assertNoContent(); foreach ($songs as $song) { $this->assertDatabaseHas(Favorite::class, [ 'favoriteable_type' => 'playable', 'favoriteable_id' => $song->id, 'user_id' => $user->id, ]); } Event::assertDispatched(MultipleSongsLiked::class); } #[Test] public function batchUndoFavorite(): void { Event::fake(MultipleSongsUnliked::class); $user = create_user(); /** @var Collection<Favorite> $favorites */ $favorites = Favorite::factory()->for($user)->count(2)->create(); $this->deleteAs('api/favorites', [ 'type' => 'playable', 'ids' => $favorites->pluck('favoriteable_id')->toArray(), ], $user) ->assertNoContent(); foreach ($favorites as $favorite) { $this->assertDatabaseMissing(Favorite::class, [ 'id' => $favorite->id, ]); } Event::assertDispatched(MultipleSongsUnliked::class); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/ScrobbleTest.php
tests/Feature/ScrobbleTest.php
<?php namespace Tests\Feature; use App\Facades\Dispatcher; use App\Jobs\ScrobbleJob; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class ScrobbleTest extends TestCase { #[Test] public function lastfmScrobble(): void { $user = create_user(); /** @var Song $song */ $song = Song::factory()->create(); Dispatcher::expects('dispatch') ->andReturnUsing(function (ScrobbleJob $job) use ($song, $user): void { $this->assertTrue($song->is($job->song)); $this->assertTrue($user->is($job->user)); self::assertEquals(100, $job->timestamp); }); $this->postAs("/api/songs/{$song->id}/scrobble", ['timestamp' => 100], $user) ->assertNoContent(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/UserTest.php
tests/Feature/UserTest.php
<?php namespace Tests\Feature; use App\Enums\Acl\Role; use App\Helpers\Ulid; use App\Models\Interaction; use App\Models\User; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Hash; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_admin; use function Tests\create_manager; use function Tests\create_user; class UserTest extends TestCase { #[Test] public function nonAdminCannotCreateUser(): void { $this->postAs('api/users', [ 'name' => 'Foo', 'email' => 'bar@baz.com', 'password' => 'secret', 'role' => 'user', ])->assertForbidden(); } #[Test] public function adminCreatesUser(): void { $this->postAs('api/users', [ 'name' => 'Foo', 'email' => 'bar@baz.com', 'password' => 'secret', 'role' => 'admin', ], create_admin()) ->assertSuccessful(); /** @var User $user */ $user = User::query()->firstWhere('email', 'bar@baz.com'); self::assertTrue(Hash::check('secret', $user->password)); self::assertSame('Foo', $user->name); self::assertSame('bar@baz.com', $user->email); self::assertSame(Role::ADMIN, $user->role); } #[Test] public function userWithNonAvailableRoleCannotBeCreated(): void { $this->postAs('api/users', [ 'name' => 'Foo', 'email' => 'bar@baz.com', 'password' => 'secret', 'role' => 'manager', ], create_admin()) ->assertUnprocessable() ->assertJsonValidationErrors(['role']); } #[Test] public function privilegeEscalationIsForbiddenWhenCreating(): void { $this->postAs('api/users', [ 'name' => 'Foo', 'email' => 'bar@baz.com', 'password' => 'secret', 'role' => 'admin', ], create_manager()) ->assertUnprocessable() ->assertJsonValidationErrors(['role']); } #[Test] public function creatingUsersWithHigherRoleIsNotAllowed(): void { $admin = create_admin(); $this->putAs("api/users/{$admin->public_id}", [ 'name' => 'Foo', 'email' => 'bar@baz.com', 'password' => 'new-secret', 'role' => 'user', ], create_manager()) ->assertForbidden(); } #[Test] public function adminUpdatesUser(): void { $admin = create_admin(); $user = create_admin(['password' => 'secret']); $this->putAs("api/users/{$user->public_id}", [ 'name' => 'Foo', 'email' => 'bar@baz.com', 'password' => 'new-secret', 'role' => 'user', ], $admin) ->assertSuccessful(); $user->refresh(); self::assertTrue(Hash::check('new-secret', $user->password)); self::assertSame('Foo', $user->name); self::assertSame('bar@baz.com', $user->email); self::assertSame(Role::USER, $user->role); } #[Test] public function privilegeEscalationIsForbiddenWhenUpdating(): void { $manager = create_manager(); $this->putAs("api/users/{$manager->public_id}", [ 'role' => 'admin', ], create_manager()) ->assertUnprocessable() ->assertJsonValidationErrors(['role']); } #[Test] public function updatingUserToANonAvailableRoleIsNotAllowed(): void { $manager = create_manager(); $this->putAs("api/users/{$manager->public_id}", [ 'role' => 'manager', ], create_manager()) ->assertUnprocessable() ->assertJsonValidationErrors(['role']); } #[Test] public function adminDeletesUser(): void { $user = create_user(); $this->deleteAs("api/users/{$user->public_id}", [], create_admin()); $this->assertModelMissing($user); } #[Test] public function selfDeletionNotAllowed(): void { $admin = create_admin(); $this->deleteAs("api/users/{$admin->public_id}", [], $admin)->assertForbidden(); $this->assertModelExists($admin); } #[Test] public function pruneOldDemoAccounts(): void { config(['koel.misc.demo' => true]); $oldUserWithNoActivity = create_user([ 'created_at' => now()->subDays(30), 'email' => Ulid::generate() . '@demo.koel.dev', ]); $oldUserWithOldActivity = create_user([ 'created_at' => now()->subDays(30), 'email' => Ulid::generate() . '@demo.koel.dev', ]); Interaction::factory()->for($oldUserWithOldActivity)->create([ 'last_played_at' => now()->subDays(14), ]); $oldUserWithNonDemoEmail = create_user([ 'created_at' => now()->subDays(30), 'email' => Ulid::generate() . '@example.com', ]); $oldUserWithNewActivity = create_user([ 'created_at' => now()->subDays(30), 'email' => Ulid::generate() . '@demo.koel.dev', ]); Interaction::factory()->for($oldUserWithNewActivity)->create([ 'last_played_at' => now()->subDays(6), ]); $newUser = create_user([ 'created_at' => now()->subDay(), 'email' => Ulid::generate() . '@demo.koel.dev', ]); Artisan::call('model:prune'); $this->assertModelMissing($oldUserWithNoActivity); $this->assertModelMissing($oldUserWithOldActivity); $this->assertModelExists($oldUserWithNonDemoEmail); $this->assertModelExists($oldUserWithNewActivity); $this->assertModelExists($newUser); config(['koel.misc.demo' => false]); } #[Test] public function noPruneIfNotInDemoMode(): void { $user = create_user([ 'created_at' => now()->subDays(30), 'email' => Ulid::generate() . '@demo.koel.dev', ]); Artisan::call('model:prune'); $this->assertModelExists($user); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/EmbedTest.php
tests/Feature/EmbedTest.php
<?php namespace Tests\Feature; use App\Http\Resources\EmbedOptionsResource; use App\Http\Resources\EmbedResource; use App\Models\Embed; use App\Models\Song; use App\Values\EmbedOptions; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_playlist; class EmbedTest extends TestCase { #[Test] public function resolveForEmbeddable(): void { /** @var Song $song */ $song = Song::factory()->create(); $this->postAs('api/embeds/resolve', [ 'embeddable_id' => $song->id, 'embeddable_type' => 'playable', ])->assertSuccessful() ->assertJsonStructure(EmbedResource::JSON_STRUCTURE); } #[Test] public function resolveFailsIfUserDoesntHaveAccessToEmbeddable(): void { $playlist = create_playlist(); $this->postAs('api/embeds/resolve', [ 'embeddable_id' => $playlist->id, 'embeddable_type' => 'playlist', ])->assertForbidden(); } #[Test] public function getPayload(): void { $jsonStructure = [ 'embed' => EmbedResource::JSON_PUBLIC_STRUCTURE, 'options' => EmbedOptionsResource::JSON_STRUCTURE, 'theme', ]; /** @var Embed $embed */ $embed = Embed::factory()->create(); $options = EmbedOptions::make(); $this->getAs("api/embeds/{$embed->id}/$options") ->assertSuccessful() ->assertJsonStructure($jsonStructure); // getJson() instead of getAs() to make sure it passes without authentication $this->getJson("api/embeds/{$embed->id}/$options") ->assertSuccessful() ->assertJsonStructure($jsonStructure); } #[Test] public function getPayloadThrowsNotFoundIfEmbeddableIsNotAvailableAnyMore(): void { /** @var Embed $embed */ $embed = Embed::factory()->create(); $embed->embeddable->delete(); $options = EmbedOptions::make(); $this->getJson("api/embeds/{$embed->id}/$options") ->assertNotFound(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/MediaPathSettingTest.php
tests/Feature/MediaPathSettingTest.php
<?php namespace Tests\Feature; use App\Models\Setting; use App\Services\Scanners\DirectoryScanner; use App\Values\Scanning\ScanResultCollection; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_admin; class MediaPathSettingTest extends TestCase { private DirectoryScanner|MockInterface $mediaScanner; public function setUp(): void { parent::setUp(); $this->mediaScanner = $this->mock(DirectoryScanner::class); } #[Test] public function saveSettings(): void { $this->mediaScanner->expects('scan') ->andReturn(ScanResultCollection::create()); $this->putAs('/api/settings/media-path', ['path' => __DIR__], create_admin()) ->assertSuccessful(); self::assertSame(__DIR__, Setting::get('media_path')); } #[Test] public function nonAdminCannotSaveSettings(): void { $this->putAs('/api/settings/media-path', ['path' => __DIR__]) ->assertForbidden(); } #[Test] public function mediaPathCannotBeSetForCloudStorage(): void { config(['koel.storage_driver' => 's3']); $this->putAs('/api/settings/media-path', ['path' => __DIR__], create_admin()) ->assertUnprocessable(); config(['koel.storage_driver' => 'local']); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/AuthTest.php
tests/Feature/AuthTest.php
<?php namespace Tests\Feature; use App\Services\AuthenticationService; use Illuminate\Support\Facades\Hash; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class AuthTest extends TestCase { #[Test] public function logIn(): void { create_user([ 'email' => 'koel@koel.dev', 'password' => Hash::make('secret'), ]); $this->post('api/me', [ 'email' => 'koel@koel.dev', 'password' => 'secret', ]) ->assertOk() ->assertJsonStructure([ 'token', 'audio-token', ]); $this->post('api/me', [ 'email' => 'koel@koel.dev', 'password' => 'wrong-secret', ]) ->assertUnauthorized(); } #[Test] public function loginViaOneTimeToken(): void { $user = create_user(); $authService = app(AuthenticationService::class); $token = $authService->generateOneTimeToken($user); $this->post('api/me/otp', ['token' => $token]) ->assertOk() ->assertJsonStructure([ 'token', 'audio-token', ]); } #[Test] public function logOut(): void { $user = create_user([ 'email' => 'koel@koel.dev', 'password' => Hash::make('secret'), ]); $response = $this->post('api/me', [ 'email' => 'koel@koel.dev', 'password' => 'secret', ]); self::assertSame(2, $user->tokens()->count()); // 1 for API, 1 for audio token $this->withToken($response->json('token')) ->delete('api/me') ->assertNoContent(); self::assertSame(0, $user->tokens()->count()); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/Demo/DemoSessionTest.php
tests/Feature/Demo/DemoSessionTest.php
<?php namespace Tests\Feature\Demo; use Jaybizzle\CrawlerDetect\CrawlerDetect; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class DemoSessionTest extends TestCase { public function setUp(): void { parent::setUp(); config(['koel.misc.demo' => true]); $this->followRedirects = true; $this->withoutVite(); } protected function tearDown(): void { config(['koel.misc.demo' => false]); $this->followRedirects = false; parent::tearDown(); } #[Test] public function dynamicallyCreateDemoAccount(): void { $this->mock(CrawlerDetect::class) ->expects('isCrawler') ->andReturnFalse(); $demoAccount = $this->get('/') ->assertSuccessful() ->assertSee('window.DEMO_ACCOUNT') ->viewData('demo_account'); self::assertStringEndsWith('@demo.koel.dev', $demoAccount['email']); self::assertEquals('demo', $demoAccount['password']); } #[Test] public function useFixedDemoAccountForBots(): void { $this->mock(CrawlerDetect::class) ->expects('isCrawler') ->andReturnTrue(); $this->get('/') ->assertSee('window.DEMO_ACCOUNT') ->assertViewHas('demo_account', [ 'email' => 'demo@koel.dev', 'password' => 'demo', ]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/ArtistTest.php
tests/Feature/KoelPlus/ArtistTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Http\Resources\ArtistResource; use App\Models\Artist; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_admin; use function Tests\create_user; class ArtistTest extends PlusTestCase { #[Test] public function updateAsOwner(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); $this->putAs( "api/artists/{$artist->id}", [ 'name' => 'Updated Artist Name', ], $artist->user )->assertJsonStructure(ArtistResource::JSON_STRUCTURE); $artist->refresh(); self::assertEquals('Updated Artist Name', $artist->name); } #[Test] public function adminCannotUpdateIfNonOwner(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); $scaryBossMan = create_admin(); self::assertFalse($artist->belongsToUser($scaryBossMan)); $this->putAs( "api/artists/{$artist->id}", [ 'name' => 'Updated Artist Name', ], $scaryBossMan )->assertForbidden(); } #[Test] public function updateForbiddenForNonOwners(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); $randomDude = create_user(); self::assertFalse($artist->belongsToUser($randomDude)); $this->putAs( "api/artists/{$artist->id}", [ 'name' => 'Updated Artist Name', ], $randomDude )->assertForbidden(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/ProfileTest.php
tests/Feature/KoelPlus/ProfileTest.php
<?php namespace Tests\Feature\KoelPlus; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; use function Tests\minimal_base64_encoded_image; class ProfileTest extends PlusTestCase { #[Test] public function updateSsoProfile(): void { $user = create_user([ 'sso_provider' => 'Google', 'sso_id' => '123', 'email' => 'user@koel.dev', 'name' => 'SSO User', 'avatar' => null, // no current password required for SSO users ]); self::assertTrue($user->is_sso); self::assertFalse($user->has_custom_avatar); $this->putAs('api/me', [ 'name' => 'Bruce Dickinson', 'email' => 'bruce@iron.com', 'avatar' => minimal_base64_encoded_image(), ], $user)->assertOk(); $user->refresh(); self::assertSame('Bruce Dickinson', $user->name); self::assertSame('user@koel.dev', $user->email); // email should not be updated self::assertTrue($user->has_custom_avatar); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/AlbumTest.php
tests/Feature/KoelPlus/AlbumTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Http\Resources\AlbumResource; use App\Models\Album; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_admin; use function Tests\create_user; class AlbumTest extends PlusTestCase { #[Test] public function updateAsOwner(): void { /** @var Album $album */ $album = Album::factory()->create(); $this->putAs( "api/albums/{$album->id}", [ 'name' => 'Updated Album Name', 'year' => 2023, ], $album->user )->assertJsonStructure(AlbumResource::JSON_STRUCTURE); $album->refresh(); self::assertEquals('Updated Album Name', $album->name); self::assertEquals(2023, $album->year); } #[Test] public function adminCannotUpdateIfNonOwner(): void { /** @var Album $album */ $album = Album::factory()->create(); $scaryBossMan = create_admin(); self::assertFalse($album->belongsToUser($scaryBossMan)); $this->putAs( "api/albums/{$album->id}", [ 'name' => 'Updated Album Name', 'year' => 2023, ], $scaryBossMan )->assertForbidden(); } #[Test] public function updateForbiddenForNonOwners(): void { /** @var Album $album */ $album = Album::factory()->create(); $randomDude = create_user(); self::assertFalse($album->belongsToUser($randomDude)); $this->putAs( "api/albums/{$album->id}", [ 'name' => 'Updated Album Name', 'year' => 2023, ], $randomDude )->assertForbidden(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/PlaylistTest.php
tests/Feature/KoelPlus/PlaylistTest.php
<?php namespace Tests\Feature\KoelPlus; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_playlist; use function Tests\create_user; class PlaylistTest extends PlusTestCase { #[Test] public function collaboratorCannotUpdatePlaylist(): void { $playlist = create_playlist(); $collaborator = create_user(); $playlist->addCollaborator($collaborator); $this->putAs("api/playlists/{$playlist->id}", [ 'name' => 'Nope', 'description' => 'Nopey Nope', ], $collaborator) ->assertForbidden(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/SongVisibilityTest.php
tests/Feature/KoelPlus/SongVisibilityTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; class SongVisibilityTest extends PlusTestCase { #[Test] public function makingSongPublic(): void { $currentUser = create_user(); $anotherUser = create_user(); $externalSongs = Song::factory(2)->for($anotherUser, 'owner')->private()->create(); // We can't make public songs that are not ours. $this->putAs('api/songs/publicize', ['songs' => $externalSongs->modelKeys()], $currentUser) ->assertForbidden(); // But we can our own songs. $ownSongs = Song::factory(2)->for($currentUser, 'owner')->create(); $this->putAs('api/songs/publicize', ['songs' => $ownSongs->modelKeys()], $currentUser) ->assertSuccessful(); $ownSongs->each(static fn (Song $song) => self::assertTrue($song->refresh()->is_public)); } #[Test] public function makingSongPrivate(): void { $currentUser = create_user(); $anotherUser = create_user(); $externalSongs = Song::factory(2)->for($anotherUser, 'owner')->public()->create(); // We can't Mark as Private songs that are not ours. $this->putAs('api/songs/privatize', ['songs' => $externalSongs->modelKeys()], $currentUser) ->assertForbidden(); // But we can our own songs. $ownSongs = Song::factory(2)->for($currentUser, 'owner')->create(); $this->putAs('api/songs/privatize', ['songs' => $ownSongs->modelKeys()], $currentUser) ->assertSuccessful(); $ownSongs->each(static fn (Song $song) => self::assertFalse($song->refresh()->is_public)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/InteractionTest.php
tests/Feature/KoelPlus/InteractionTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Events\MultipleSongsLiked; use App\Events\MultipleSongsUnliked; use App\Events\SongFavoriteToggled; use App\Models\Song; use Illuminate\Support\Facades\Event; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; class InteractionTest extends PlusTestCase { #[Test] public function policyForRegisterPlay(): void { Event::fake(SongFavoriteToggled::class); $owner = create_user(); // Can't increase play count of a private song that doesn't belong to the user /** @var Song $externalPrivateSong */ $externalPrivateSong = Song::factory()->private()->create(); $this->postAs('api/interaction/play', ['song' => $externalPrivateSong->id], $owner) ->assertForbidden(); // Can increase play count of a public song that doesn't belong to the user /** @var Song $externalPublicSong */ $externalPublicSong = Song::factory()->public()->create(); $this->postAs('api/interaction/play', ['song' => $externalPublicSong->id], $owner) ->assertSuccessful(); // Can increase play count of a private song that belongs to the user /** @var Song $ownPrivateSong */ $ownPrivateSong = Song::factory()->private()->for($owner, 'owner')->create(); $this->postAs('api/interaction/play', ['song' => $ownPrivateSong->id], $ownPrivateSong->owner) ->assertSuccessful(); } #[Test] public function policyForToggleLike(): void { Event::fake(SongFavoriteToggled::class); $owner = create_user(); // Can't like a private song that doesn't belong to the user /** @var Song $externalPrivateSong */ $externalPrivateSong = Song::factory()->private()->create(); $this->postAs('api/interaction/like', ['song' => $externalPrivateSong->id], $owner) ->assertForbidden(); // Can like a public song that doesn't belong to the user /** @var Song $externalPublicSong */ $externalPublicSong = Song::factory()->public()->create(); $this->postAs('api/interaction/like', ['song' => $externalPublicSong->id], $owner) ->assertSuccessful(); // Can like a private song that belongs to the user /** @var Song $ownPrivateSong */ $ownPrivateSong = Song::factory()->private()->for($owner, 'owner')->create(); $this->postAs('api/interaction/like', ['song' => $ownPrivateSong->id], $owner) ->assertSuccessful(); } #[Test] public function policyForBatchLike(): void { Event::fake(MultipleSongsLiked::class); $owner = create_user(); // Can't batch like private songs that don't belong to the user $externalPrivateSongs = Song::factory()->count(2)->private()->create(); $this->postAs('api/interaction/batch/like', ['songs' => $externalPrivateSongs->modelKeys()], $owner) ->assertForbidden(); // Can batch like public songs that don't belong to the user $externalPublicSongs = Song::factory()->count(1)->public()->create(); $this->postAs('api/interaction/batch/like', ['songs' => $externalPublicSongs->modelKeys()], $owner) ->assertSuccessful(); // Can batch like private songs that belong to the user $ownPrivateSongs = Song::factory()->count(2)->private()->for($owner, 'owner')->create(); $this->postAs('api/interaction/batch/like', ['songs' => $ownPrivateSongs->modelKeys()], $owner) ->assertSuccessful(); // Can't batch like a mix of inaccessible and accessible songs $mixedSongs = $externalPrivateSongs->merge($externalPublicSongs); $this->postAs('api/interaction/batch/like', ['songs' => $mixedSongs->modelKeys()], $owner) ->assertForbidden(); } #[Test] public function policyForBatchUnlike(): void { Event::fake(MultipleSongsUnliked::class); $owner = create_user(); // Can't batch unlike private songs that don't belong to the user $externalPrivateSongs = Song::factory()->count(2)->private()->create(); $this->postAs('api/interaction/batch/unlike', ['songs' => $externalPrivateSongs->modelKeys()], $owner) ->assertForbidden(); // Can batch unlike public songs that don't belong to the user $externalPublicSongs = Song::factory()->count(1)->public()->create(); $this->postAs('api/interaction/batch/unlike', ['songs' => $externalPublicSongs->modelKeys()], $owner) ->assertSuccessful(); // Can batch unlike private songs that belong to the user $ownPrivateSongs = Song::factory()->count(2)->private()->for($owner, 'owner')->create(); $this->postAs('api/interaction/batch/unlike', ['songs' => $ownPrivateSongs->modelKeys()], $owner) ->assertSuccessful(); // Can't batch unlike a mix of inaccessible and accessible songs $mixedSongs = $externalPrivateSongs->merge($externalPublicSongs); $this->postAs('api/interaction/batch/unlike', ['songs' => $mixedSongs->modelKeys()], $owner) ->assertForbidden(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/UserInvitationTest.php
tests/Feature/KoelPlus/UserInvitationTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Http\Resources\UserProspectResource; use App\Mail\UserInvite; use Illuminate\Support\Facades\Mail; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_admin; class UserInvitationTest extends PlusTestCase { #[Test] public function canInviteRolesAvailableInCommunityEdition(): void { Mail::fake(); $this->postAs('api/invitations', [ 'emails' => ['foo@bar.io', 'bar@baz.ai'], 'role' => 'manager', ], create_admin()) ->assertSuccessful() ->assertJsonStructure([0 => UserProspectResource::JSON_STRUCTURE]); Mail::assertQueued(UserInvite::class, 2); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/PlaylistFolderTest.php
tests/Feature/KoelPlus/PlaylistFolderTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Models\PlaylistFolder; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_playlist; use function Tests\create_user; class PlaylistFolderTest extends PlusTestCase { #[Test] public function collaboratorPuttingPlaylistIntoTheirFolder(): void { $collaborator = create_user(); $playlist = create_playlist(); $playlist->addCollaborator($collaborator); /** @var PlaylistFolder $ownerFolder */ $ownerFolder = PlaylistFolder::factory()->for($playlist->owner)->create(); $ownerFolder->playlists()->attach($playlist); self::assertTrue($playlist->refresh()->getFolder($playlist->owner)?->is($ownerFolder)); /** @var PlaylistFolder $collaboratorFolder */ $collaboratorFolder = PlaylistFolder::factory()->for($collaborator)->create(); self::assertNull($playlist->getFolder($collaborator)); $this->postAs( "api/playlist-folders/{$collaboratorFolder->id}/playlists", ['playlists' => [$playlist->id]], $collaborator ) ->assertSuccessful(); self::assertTrue($playlist->fresh()->getFolder($collaborator)?->is($collaboratorFolder)); // Verify the playlist is in the owner's folder too self::assertTrue($playlist->fresh()->getFolder($playlist->owner)?->is($ownerFolder)); } #[Test] public function collaboratorMovingPlaylistToRootLevel(): void { $collaborator = create_user(); $playlist = create_playlist(); $playlist->addCollaborator($collaborator); self::assertNull($playlist->getFolder($playlist->owner)); /** @var PlaylistFolder $ownerFolder */ $ownerFolder = PlaylistFolder::factory()->for($playlist->owner)->create(); $ownerFolder->playlists()->attach($playlist); self::assertTrue($playlist->refresh()->getFolder($playlist->owner)?->is($ownerFolder)); /** @var PlaylistFolder $collaboratorFolder */ $collaboratorFolder = PlaylistFolder::factory()->for($collaborator)->create(); $collaboratorFolder->playlists()->attach($playlist); self::assertTrue($playlist->refresh()->getFolder($collaborator)?->is($collaboratorFolder)); $this->deleteAs( "api/playlist-folders/{$collaboratorFolder->id}/playlists", ['playlists' => [$playlist->id]], $collaborator ) ->assertSuccessful(); self::assertNull($playlist->fresh()->getFolder($collaborator)); // Verify the playlist is still in the owner's folder self::assertTrue($playlist->getFolder($playlist->owner)?->is($ownerFolder)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/AuthorizeDropboxTest.php
tests/Feature/KoelPlus/AuthorizeDropboxTest.php
<?php namespace Tests\Feature\KoelPlus; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; class AuthorizeDropboxTest extends PlusTestCase { #[Test] public function authorize(): void { $this->get('/dropbox/authorize/foo') ->assertRedirect( "https://www.dropbox.com/oauth2/authorize?client_id=foo&response_type=code&token_access_type=offline", ); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/ProxyAuthTest.php
tests/Feature/KoelPlus/ProxyAuthTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Models\User; use Laravel\Sanctum\PersonalAccessToken; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; class ProxyAuthTest extends PlusTestCase { public function setUp(): void { parent::setUp(); config([ 'koel.proxy_auth.enabled' => true, 'koel.proxy_auth.allow_list' => ['192.168.1.0/24'], 'koel.proxy_auth.user_header' => 'remote-user', 'koel.proxy_auth.preferred_name_header' => 'remote-preferred-name', ]); // Disable Vite so that the test can run without a frontend build. $this->withoutVite(); } protected function tearDown(): void { config([ 'koel.proxy_auth.enabled' => false, 'koel.proxy_auth.allow_list' => [], 'koel.proxy_auth.user_header' => 'remote-user', 'koel.proxy_auth.preferred_name_header' => 'remote-preferred-name', ]); parent::tearDown(); } #[Test] public function proxyAuthenticateNewUser(): void { $response = $this->get('/', [ 'REMOTE_ADDR' => '192.168.1.127', 'remote-user' => '123456', 'remote-preferred-name' => 'Bruce Dickinson', ]); $response->assertOk(); $response->assertViewHas('token'); /** @var array $token */ $token = $response->viewData('token'); self::assertNotNull(PersonalAccessToken::findToken($token['token'])); $this->assertDatabaseHas(User::class, [ 'email' => '123456@reverse.proxy', 'name' => 'Bruce Dickinson', 'sso_id' => '123456', 'sso_provider' => 'Reverse Proxy', ]); } #[Test] public function proxyAuthenticateExistingUser(): void { $user = create_user([ 'sso_id' => '123456', 'sso_provider' => 'Reverse Proxy', ]); $response = $this->get('/', [ 'REMOTE_ADDR' => '192.168.1.127', 'remote-user' => '123456', 'remote-preferred-name' => 'Bruce Dickinson', ]); $response->assertOk(); $response->assertViewHas('token'); /** @var array $token */ $token = $response->viewData('token'); self::assertTrue($user->is(PersonalAccessToken::findToken($token['token'])->tokenable)); } #[Test] public function proxyAuthenticateWithDisallowedIp(): void { $response = $this->get('/', [ 'REMOTE_ADDR' => '255.168.1.127', 'remote-user' => '123456', 'remote-preferred-name' => 'Bruce Dickinson', ]); $response->assertOk(); self::assertNull($response->viewData('token')); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/SongPlayTest.php
tests/Feature/KoelPlus/SongPlayTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Models\Song; use App\Services\Streamer\Adapters\LocalStreamerAdapter; use App\Services\TokenManager; use App\Values\CompositeToken; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; use function Tests\test_path; class SongPlayTest extends PlusTestCase { #[Test] public function playPublicUnownedSong(): void { /** @var CompositeToken $token */ $token = app(TokenManager::class)->createCompositeToken(create_user()); /** @var Song $song */ $song = Song::factory()->public()->create([ 'path' => test_path('songs/blank.mp3'), ]); $this->mock(LocalStreamerAdapter::class) ->expects('stream'); $this->get("play/{$song->id}?t=$token->audioToken") ->assertOk(); } #[Test] public function playPrivateOwnedSong(): void { /** @var Song $song */ $song = Song::factory()->private()->create([ 'path' => test_path('songs/blank.mp3'), ]); /** @var CompositeToken $token */ $token = app(TokenManager::class)->createCompositeToken($song->owner); $this->mock(LocalStreamerAdapter::class) ->expects('stream'); $this->get("play/{$song->id}?t=$token->audioToken") ->assertOk(); } #[Test] public function cannotPlayPrivateUnownedSong(): void { /** @var Song $song */ $song = Song::factory()->private()->create([ 'path' => test_path('songs/blank.mp3'), ]); /** @var CompositeToken $token */ $token = app(TokenManager::class)->createCompositeToken(create_user()); $this->get("play/{$song->id}?t=$token->audioToken") ->assertForbidden(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/PlaylistSongTest.php
tests/Feature/KoelPlus/PlaylistSongTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Http\Resources\CollaborativeSongResource; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_playlist; use function Tests\create_user; class PlaylistSongTest extends PlusTestCase { #[Test] public function getSongsInCollaborativePlaylist(): void { $playlist = create_playlist(); $playlist->addPlayables(Song::factory()->public()->count(2)->create()); $collaborator = create_user(); $playlist->addCollaborator($collaborator); $this->getAs("api/playlists/{$playlist->id}/songs", $collaborator) ->assertSuccessful() ->assertJsonStructure([0 => CollaborativeSongResource::JSON_STRUCTURE]) ->assertJsonCount(2); } #[Test] public function privateSongsDoNotShowUpInCollaborativePlaylist(): void { $playlist = create_playlist(); $playlist->addPlayables(Song::factory()->public()->count(2)->create()); /** @var Song $privateSong */ $privateSong = Song::factory()->private()->create(); $playlist->addPlayables($privateSong); $collaborator = create_user(); $playlist->addCollaborator($collaborator); $this->getAs("api/playlists/{$playlist->id}/songs", $collaborator) ->assertSuccessful() ->assertJsonStructure([0 => CollaborativeSongResource::JSON_STRUCTURE]) ->assertJsonCount(2) ->assertJsonMissing(['id' => $privateSong->id]); } #[Test] public function collaboratorCanAddSongs(): void { $playlist = create_playlist(); $collaborator = create_user(); $playlist->addCollaborator($collaborator); $songs = Song::factory()->for($collaborator, 'owner')->count(2)->create(); $this->postAs("api/playlists/{$playlist->id}/songs", ['songs' => $songs->modelKeys()], $collaborator) ->assertSuccessful(); $playlist->refresh(); $songs->each(static fn (Song $song) => self::assertTrue($playlist->playables->contains($song))); } #[Test] public function collaboratorCanRemoveSongs(): void { $playlist = create_playlist(); $collaborator = create_user(); $playlist->addCollaborator($collaborator); $songs = Song::factory()->for($collaborator, 'owner')->count(2)->create(); $playlist->addPlayables($songs); $this->deleteAs("api/playlists/{$playlist->id}/songs", ['songs' => $songs->modelKeys()], $collaborator) ->assertSuccessful(); $playlist->refresh(); $songs->each(static fn (Song $song) => self::assertFalse($playlist->playables->contains($song))); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/DownloadTest.php
tests/Feature/KoelPlus/DownloadTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Models\Song; use App\Services\DownloadService; use App\Values\Downloadable; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; use function Tests\test_path; class DownloadTest extends PlusTestCase { #[Test] public function downloadPolicy(): void { $owner = create_user(); $apiToken = $owner->createToken('Koel')->plainTextToken; // Can't download a private song that doesn't belong to the user /** @var Song $externalPrivateSong */ $externalPrivateSong = Song::factory()->private()->create(); $this->get("download/songs?songs[]={$externalPrivateSong->id}&api_token=" . $apiToken) ->assertForbidden(); // Can download a public song that doesn't belong to the user /** @var Song $externalPublicSong */ $externalPublicSong = Song::factory()->public()->create(); $downloadService = $this->mock(DownloadService::class); $downloadService->expects('getDownloadable') ->andReturn(Downloadable::make(test_path('songs/blank.mp3'))); $this->get("download/songs?songs[]={$externalPublicSong->id}&api_token=" . $apiToken) ->assertOk(); // Can download a private song that belongs to the user /** @var Song $ownSong */ $ownSong = Song::factory()->for($owner, 'owner')->private()->create(); $downloadService->expects('getDownloadable') ->andReturn(Downloadable::make(test_path('songs/blank.mp3'))); $this->get("download/songs?songs[]={$ownSong->id}&api_token=" . $apiToken) ->assertOk(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/BrandingSettingTest.php
tests/Feature/KoelPlus/BrandingSettingTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Models\Setting; use Illuminate\Support\Str; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_admin; use function Tests\create_user; use function Tests\minimal_base64_encoded_image; class BrandingSettingTest extends PlusTestCase { #[Test] public function updateBrandingFromDefault(): void { $this->putAs('api/settings/branding', [ 'name' => 'Little Bird', 'logo' => minimal_base64_encoded_image(), 'cover' => minimal_base64_encoded_image(), ], create_admin()) ->assertNoContent(); $branding = Setting::get('branding'); self::assertSame('Little Bird', $branding['name']); self::assertTrue(Str::isUrl($branding['logo'])); self::assertTrue(Str::isUrl($branding['cover'])); } #[Test] public function updateBrandingWithNoLogoOrCoverChanges(): void { Setting::set('branding', [ 'name' => 'Koel', 'logo' => 'old-logo.png', 'cover' => 'old-cover.png', ]); $this->putAs('api/settings/branding', [ 'name' => 'Little Bird', 'logo' => image_storage_url('old-logo.png'), 'cover' => image_storage_url('old-cover.png'), ], create_admin()) ->assertNoContent(); $branding = Setting::get('branding'); self::assertSame('Little Bird', $branding['name']); self::assertSame(image_storage_url('old-logo.png'), $branding['logo']); self::assertSame(image_storage_url('old-cover.png'), $branding['cover']); } #[Test] public function updateBrandingReplacingLogoAndCover(): void { Setting::set('branding', [ 'name' => 'Koel', 'logo' => 'old-logo.png', 'cover' => 'old-cover.png', ]); $this->putAs('api/settings/branding', [ 'name' => 'Little Bird', 'logo' => minimal_base64_encoded_image(), 'cover' => minimal_base64_encoded_image(), ], create_admin()) ->assertNoContent(); $branding = Setting::get('branding'); self::assertSame('Little Bird', $branding['name']); self::assertTrue(Str::isUrl($branding['logo'])); self::assertTrue(Str::isUrl($branding['cover'])); self::assertNotSame(image_storage_url('old-logo.png'), $branding['logo']); self::assertNotSame(image_storage_url('old-cover.png'), $branding['cover']); } #[Test] public function nonAdminCannotSetBranding(): void { $this->putAs('api/settings/branding', [ 'name' => 'Little Bird', 'logo' => minimal_base64_encoded_image(), 'cover' => minimal_base64_encoded_image(), ], create_user()) ->assertForbidden(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/UploadTest.php
tests/Feature/KoelPlus/UploadTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Models\Setting; use App\Models\Song; use Illuminate\Http\UploadedFile; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; use function Tests\test_path; class UploadTest extends PlusTestCase { private UploadedFile $file; public function setUp(): void { parent::setUp(); Setting::set('media_path', public_path('sandbox/media')); $this->file = UploadedFile::fromFile(test_path('songs/full.mp3'), 'song.mp3'); //@phpstan-ignore-line } #[Test] public function upload(): void { $user = create_user(); $this->postAs('api/upload', ['file' => $this->file], $user)->assertSuccessful(); self::assertDirectoryExists(public_path("sandbox/media/__KOEL_UPLOADS_\${$user->id}__")); self::assertFileExists(public_path("sandbox/media/__KOEL_UPLOADS_\${$user->id}__/song.mp3")); /** @var Song $song */ $song = Song::query()->latest()->first(); self::assertSame($song->owner_id, $user->id); self::assertFalse($song->is_public); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/ArtistEventTest.php
tests/Feature/KoelPlus/ArtistEventTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Http\Integrations\IPinfo\Requests\GetLiteDataRequest; use App\Http\Integrations\Ticketmaster\Requests\AttractionSearchRequest; use App\Http\Integrations\Ticketmaster\Requests\EventSearchRequest; use App\Http\Resources\LiveEventResource; use App\Models\Artist; use App\Values\Ticketmaster\TicketmasterEvent; use App\Values\Ticketmaster\TicketmasterVenue; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\File; use PHPUnit\Framework\Attributes\Test; use Saloon\Http\Faking\MockResponse; use Saloon\Laravel\Facades\Saloon; use Tests\PlusTestCase; use function Tests\test_path; class ArtistEventTest extends PlusTestCase { public function setUp(): void { parent::setUp(); config(['koel.services.ticketmaster.key' => 'tm-key']); config(['koel.services.ipinfo.token' => 'ipinfo-token']); } #[Test] public function getEvents(): void { $attractionSearchJson = File::json(test_path('fixtures/ticketmaster/attraction-search.json')); $eventSearchJson = File::json(test_path('fixtures/ticketmaster/event-search.json')); $liteDataJson = File::json(test_path('fixtures/ipinfo/lite-data.json')); Saloon::fake([ AttractionSearchRequest::class => MockResponse::make(body: $attractionSearchJson), EventSearchRequest::class => MockResponse::make(body: $eventSearchJson), GetLiteDataRequest::class => MockResponse::make(body: $liteDataJson), ]); /** @var Artist $artist */ $artist = Artist::factory()->create([ 'name' => 'Slayer', ]); $this->getAs("api/artists/{$artist->id}/events") ->assertJsonStructure(['*' => LiveEventResource::JSON_STRUCTURE]) ->assertJsonCount(2) ->assertOk(); } #[Test] public function getEventsFromCache(): void { Saloon::fake([]); $event = TicketmasterEvent::make( id: '1234567890', name: 'Slayer', url: 'https://www.ticketmaster.com/event/1234567890', image: 'https://www.ticketmaster.com/image/1234567890', start: now()->addWeek(), end: now()->addWeek()->addDay(), venue: TicketmasterVenue::make( name: 'Sample Venue', url: 'https://www.ticketmaster.com/venue/1234567890', city: 'Sample City', ), ); Cache::put(cache_key('Ticketmaster events', 'Slayer', 'DE'), collect([$event]), now()->addDay()); Cache::forever(cache_key('IP to country code', '127.0.0.1'), 'DE'); /** @var Artist $artist */ $artist = Artist::factory()->create([ 'name' => 'Slayer', ]); $this->getAs("api/artists/{$artist->id}/events") ->assertJsonStructure(['*' => LiveEventResource::JSON_STRUCTURE]) ->assertJsonCount(1) ->assertOk(); Saloon::assertNothingSent(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/SongTest.php
tests/Feature/KoelPlus/SongTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; class SongTest extends PlusTestCase { #[Test] public function showSongPolicy(): void { $user = create_user(); /** @var Song $publicSong */ $publicSong = Song::factory()->public()->create(); // We can access public songs. $this->getAs("api/songs/{$publicSong->id}", $user)->assertSuccessful(); /** @var Song $ownPrivateSong */ $ownPrivateSong = Song::factory()->for($user, 'owner')->private()->create(); // We can access our own private songs. $this->getAs("api/songs/{$ownPrivateSong->id}", $user)->assertSuccessful(); /** @var Song $externalUnownedSong */ $externalUnownedSong = Song::factory()->private()->create(); // But we can't access private songs that are not ours. $this->getAs("api/songs/{$externalUnownedSong->id}", $user)->assertForbidden(); } #[Test] public function editSongsPolicy(): void { $currentUser = create_user(); $anotherUser = create_user(); $externalUnownedSongs = Song::factory(2)->for($anotherUser, 'owner')->private()->create(); // We can't edit songs that are not ours. $this->putAs('api/songs', [ 'songs' => $externalUnownedSongs->modelKeys(), 'data' => [ 'title' => 'New Title', ], ], $currentUser)->assertForbidden(); // Even if some of the songs are owned by us, we still can't edit them. $mixedSongs = $externalUnownedSongs->merge(Song::factory(2)->for($currentUser, 'owner')->create()); $this->putAs('api/songs', [ 'songs' => $mixedSongs->modelKeys(), 'data' => [ 'title' => 'New Title', ], ], $currentUser)->assertForbidden(); // But we can edit our own songs. $ownSongs = Song::factory(2)->for($currentUser, 'owner')->create(); $this->putAs('api/songs', [ 'songs' => $ownSongs->modelKeys(), 'data' => [ 'title' => 'New Title', ], ], $currentUser)->assertSuccessful(); } #[Test] public function deleteSongsPolicy(): void { $currentUser = create_user(); $anotherUser = create_user(); $externalUnownedSongs = Song::factory(2)->for($anotherUser, 'owner')->private()->create(); // We can't delete songs that are not ours. $this->deleteAs('api/songs', ['songs' => $externalUnownedSongs->modelKeys()], $currentUser) ->assertForbidden(); // Even if some of the songs are owned by us, we still can't delete them. $mixedSongs = $externalUnownedSongs->merge(Song::factory(2)->for($currentUser, 'owner')->create()); $this->deleteAs('api/songs', ['songs' => $mixedSongs->modelKeys()], $currentUser) ->assertForbidden(); // But we can delete our own songs. $ownSongs = Song::factory(2)->for($currentUser, 'owner')->create(); $this->deleteAs('api/songs', ['songs' => $ownSongs->modelKeys()], $currentUser) ->assertSuccessful(); } #[Test] public function markSongsAsPublic(): void { $user = create_user(); $songs = Song::factory(2)->for($user, 'owner')->private()->create(); $this->putAs('api/songs/publicize', ['songs' => $songs->modelKeys()], $user) ->assertSuccessful(); $songs->each(static function (Song $song): void { $song->refresh(); self::assertTrue($song->is_public); }); } #[Test] public function markSongsAsPrivate(): void { $user = create_user(); $songs = Song::factory(2)->for($user, 'owner')->public()->create(); $this->putAs('api/songs/privatize', ['songs' => $songs->modelKeys()], $user) ->assertSuccessful(); $songs->each(static function (Song $song): void { $song->refresh(); self::assertFalse($song->is_public); }); } #[Test] public function publicizingOrPrivatizingSongsRequiresOwnership(): void { $songs = Song::factory(2)->public()->create(); $this->putAs('api/songs/privatize', ['songs' => $songs->modelKeys()]) ->assertForbidden(); $otherSongs = Song::factory(2)->private()->create(); $this->putAs('api/songs/publicize', ['songs' => $otherSongs->modelKeys()]) ->assertForbidden(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/ThemeTest.php
tests/Feature/KoelPlus/ThemeTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Http\Resources\ThemeResource; use App\Models\Theme; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; use function Tests\minimal_base64_encoded_image; class ThemeTest extends PlusTestCase { #[Test] public function listTheme(): void { $user = create_user(); Theme::factory()->for($user)->create(); $this->getAs('api/themes', $user) ->assertSuccessful() ->assertJsonStructure(['*' => ThemeResource::JSON_STRUCTURE]); } #[Test] public function createTheme(): void { $user = create_user(); self::assertCount(0, $user->themes); $this->postAs('api/themes', [ 'name' => 'Test Theme', 'fg_color' => '#ffffff', 'bg_color' => '#000000', 'highlight_color' => '#ff0000', 'bg_image' => minimal_base64_encoded_image(), 'font_family' => 'system-ui', 'font_size' => '16.5', ], $user) ->assertCreated() ->assertJsonStructure(ThemeResource::JSON_STRUCTURE); self::assertCount(1, $user->refresh()->themes); /** @var Theme $theme */ $theme = $user->themes->first(); self::assertSame('Test Theme', $theme->name); self::assertSame('#ffffff', $theme->properties->fgColor); self::assertSame('#000000', $theme->properties->bgColor); self::assertSame('#ff0000', $theme->properties->highlightColor); self::assertSame('system-ui', $theme->properties->fontFamily); self::assertSame(16.5, $theme->properties->fontSize); } #[Test] public function deleteTheme(): void { /** @var Theme $theme */ $theme = Theme::factory()->create(); $this->deleteAs("api/themes/{$theme->id}", [], $theme->user) ->assertNoContent(); self::assertModelMissing($theme); } #[Test] public function deleteThemeUnauthorized(): void { /** @var Theme $theme */ $theme = Theme::factory()->create(); $this->deleteAs("api/themes/{$theme->id}", [], create_user()) ->assertForbidden(); self::assertModelExists($theme); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/FavoriteTest.php
tests/Feature/KoelPlus/FavoriteTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Models\Album; use App\Models\Artist; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; class FavoriteTest extends PlusTestCase { #[Test] public function toggleIsProhibitedIfSongIsNotAccessible(): void { /** @var Song $song */ $song = Song::factory()->private()->create(); $this->postAs('api/favorites/toggle', [ 'type' => 'playable', 'id' => $song->id, ]) ->assertForbidden(); } #[Test] public function toggleIsProhibitedIfAlbumIsNotAccessible(): void { /** @var Album $album */ $album = Album::factory()->create(); $this->postAs('api/favorites/toggle', [ 'type' => 'album', 'id' => $album->id, ]) ->assertForbidden(); } #[Test] public function toggleIsProhibitedIfArtistIsNotAccessible(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); $this->postAs('api/favorites/toggle', [ 'type' => 'artist', 'id' => $artist->id, ]) ->assertForbidden(); } #[Test] public function batchFavoriteIsProhibitedIfAnySongIsNotAccessible(): void { $songs = Song::factory()->count(2)->create(); $songs->first()->update(['is_public' => false]); $this->postAs('api/favorites', [ 'type' => 'playable', 'ids' => $songs->pluck('id')->toArray(), ]) ->assertForbidden(); } #[Test] public function batchUndoFavoriteIsProhibitedIfAnySongIsNotAccessible(): void { $songs = Song::factory()->count(2)->create(); $songs->first()->update(['is_public' => false]); $this->deleteAs('api/favorites', [ 'type' => 'playable', 'ids' => $songs->pluck('id')->toArray(), ]) ->assertForbidden(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/UserTest.php
tests/Feature/KoelPlus/UserTest.php
<?php namespace Tests\Feature\KoelPlus; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_admin; class UserTest extends PlusTestCase { #[Test] public function creatingManagersIsOk(): void { $this->postAs('api/users', [ 'name' => 'Manager', 'email' => 'foo@bar.com', 'password' => 'secret', 'role' => 'manager', ], create_admin()) ->assertSuccessful(); } #[Test] public function updatingUsersToManagersIsOk(): void { $user = create_admin(); $this->putAs("api/users/{$user->public_id}", [ 'name' => 'Manager', 'email' => 'foo@bar.com', 'role' => 'manager', ], create_admin()) ->assertSuccessful(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/EmbedTest.php
tests/Feature/KoelPlus/EmbedTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Http\Resources\EmbedOptionsResource; use App\Http\Resources\EmbedResource; use App\Http\Resources\ThemeResource; use App\Models\Embed; use App\Models\Theme; use App\Values\EmbedOptions; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; class EmbedTest extends PlusTestCase { #[Test] public function getPayloadWithCustomTheme(): void { /** @var Theme $theme */ $theme = Theme::factory()->create(); $jsonStructure = [ 'embed' => EmbedResource::JSON_PUBLIC_STRUCTURE, 'options' => EmbedOptionsResource::JSON_STRUCTURE, 'theme' => ThemeResource::JSON_STRUCTURE, ]; /** @var Embed $embed */ $embed = Embed::factory()->create(); $options = EmbedOptions::make(theme: $theme->id); $this->getAs("api/embeds/{$embed->id}/$options") ->assertSuccessful() ->assertJsonStructure($jsonStructure); // getJson() instead of getAs() to make sure it passes without authentication $this->getJson("api/embeds/{$embed->id}/$options") ->assertSuccessful() ->assertJsonStructure($jsonStructure); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/PlaylistCollaborationTest.php
tests/Feature/KoelPlus/PlaylistCollaborationTest.php
<?php namespace Tests\Feature\KoelPlus; use App\Http\Resources\PlaylistCollaborationTokenResource; use App\Http\Resources\PlaylistResource; use App\Models\PlaylistCollaborationToken; use App\Models\PlaylistFolder; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_playlist; use function Tests\create_user; class PlaylistCollaborationTest extends PlusTestCase { #[Test] public function createPlaylistCollaborationToken(): void { $playlist = create_playlist(); $this->postAs("api/playlists/{$playlist->id}/collaborators/invite", [], $playlist->owner) ->assertJsonStructure(PlaylistCollaborationTokenResource::JSON_STRUCTURE); } #[Test] public function acceptPlaylistCollaborationViaToken(): void { /** @var PlaylistCollaborationToken $token */ $token = PlaylistCollaborationToken::factory()->create(); $user = create_user(); $this->postAs('api/playlists/collaborators/accept', ['token' => $token->token], $user) ->assertJsonStructure(PlaylistResource::JSON_STRUCTURE); self::assertTrue($token->playlist->hasCollaborator($user)); } #[Test] public function removeCollaborator(): void { $playlist = create_playlist(); $user = create_user(); $playlist->addCollaborator($user); self::assertTrue($playlist->refresh()->hasCollaborator($user)); $this->deleteAs( "api/playlists/{$playlist->id}/collaborators", ['collaborator' => $user->public_id], $playlist->owner, ); self::assertFalse($playlist->refresh()->hasCollaborator($user)); } #[Test] public function collaboratorsCanAccessSharedPlaylistAtRootLevel(): void { $playlist = create_playlist(); $collaborator = create_user(); $playlist->addCollaborator($collaborator); $this->getAs('/api/data', $collaborator)->assertJsonPath('playlists.0.id', $playlist->id); } #[Test] public function collaboratorsCanAccessSharedPlaylistInFolder(): void { $playlist = create_playlist(); $playlist->folders()->attach(PlaylistFolder::factory()->create()); $collaborator = create_user(); $playlist->addCollaborator($collaborator); $this->getAs('/api/data', $collaborator)->assertJsonPath('playlists.0.id', $playlist->id); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/MediaBrowser/FetchRecursiveFolderSongsTest.php
tests/Feature/KoelPlus/MediaBrowser/FetchRecursiveFolderSongsTest.php
<?php namespace Tests\Feature\KoelPlus\MediaBrowser; use App\Models\Folder; use App\Models\Setting; use App\Models\Song; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; class FetchRecursiveFolderSongsTest extends PlusTestCase { public function setUp(): void { parent::setUp(); Setting::set('media_path', '/var/media'); } #[Test] public function includesSongsInNestedFolder(): void { /** @var Folder $folder */ $folder = Folder::factory()->create(['path' => 'foo']); /** @var Folder $subfolder */ $subfolder = Folder::factory()->for($folder, 'parent')->create(['path' => 'foo/bar']); $irrelevantFolder = Folder::factory()->create(['path' => 'foo/baz']); Song::factory()->for($irrelevantFolder)->create(); $songs = Song::factory()->for($subfolder)->count(2)->create() ->merge(Song::factory()->for($folder)->count(1)->create()); $response = $this->postAs('/api/songs/by-folders', [ 'paths' => ['foo', 'foo/bar'], ]); self::assertEqualsCanonicalizing($response->json('*.id'), $songs->pluck('id')->all()); } #[Test] public function resolveWhenOneOfThePathsIsRoot(): void { /** @var Folder $folder */ $folder = Folder::factory()->create(['path' => 'foo']); $songs = Song::factory()->for($folder)->count(2)->create() ->merge(Song::factory()->count(1)->create()); $response = $this->postAs('/api/songs/by-folders', [ 'paths' => ['', 'foo'], ]); self::assertEqualsCanonicalizing($response->json('*.id'), $songs->pluck('id')->all()); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/MediaBrowser/PaginateFolderSongsTest.php
tests/Feature/KoelPlus/MediaBrowser/PaginateFolderSongsTest.php
<?php namespace Tests\Feature\KoelPlus\MediaBrowser; use App\Http\Resources\SongFileResource; use App\Models\Folder; use App\Models\Song; use Illuminate\Database\Eloquent\Collection; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; class PaginateFolderSongsTest extends PlusTestCase { #[Test] public function paginate(): void { /** @var Folder $folder */ $folder = Folder::factory()->create(['path' => 'foo/bar']); /** @var Collection<Song> $songs */ $songs = Song::factory()->for($folder)->count(2)->create(); $response = $this->getAs('/api/browse/songs?path=foo/bar&page=1') ->assertJsonStructure(SongFileResource::PAGINATION_JSON_STRUCTURE); self::assertEqualsCanonicalizing($songs->pluck('id')->all(), $response->json('data.*.id')); } #[Test] public function paginateRootMediaFolder(): void { /** @var Collection<Song> $songs */ $songs = Song::factory()->count(2)->create(); $response = $this->getAs('/api/browse/songs') ->assertJsonStructure(SongFileResource::PAGINATION_JSON_STRUCTURE); self::assertEqualsCanonicalizing($songs->pluck('id')->all(), $response->json('data.*.id')); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/MediaBrowser/FetchFolderSongsTest.php
tests/Feature/KoelPlus/MediaBrowser/FetchFolderSongsTest.php
<?php namespace Tests\Feature\KoelPlus\MediaBrowser; use App\Http\Resources\SongFileResource; use App\Models\Folder; use App\Models\Setting; use App\Models\Song; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Arr; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; class FetchFolderSongsTest extends PlusTestCase { public function setUp(): void { parent::setUp(); Setting::set('media_path', '/var/media'); } #[Test] public function fetchSongsInFolderWithAValidPath(): void { $folder = Folder::factory()->create(['path' => 'foo']); $subfolder = Folder::factory()->for($folder, 'parent')->create(['path' => 'foo/bar']); /** @var Collection $songs */ $songs = Song::factory()->for($folder)->count(2)->create(); // create songs in the subfolder, which should not be returned Song::factory()->for($subfolder)->create(); $response = $this->getAs('api/songs/in-folder?path=foo'); $response->assertJsonStructure([0 => SongFileResource::JSON_STRUCTURE]); self::assertEqualsCanonicalizing($songs->pluck('id')->all(), $response->json('*.id')); } #[Test] public function fetchSongsInFolderWithEmptyPath(): void { /** @var Collection $songs */ $songs = Song::factory()->count(2)->create(); $folder = Folder::factory()->create(['path' => 'foo']); // create songs in the folder, which should not be returned Song::factory()->for($folder)->create(); $response = $this->getAs('api/songs/in-folder?path='); $response->assertJsonStructure([0 => SongFileResource::JSON_STRUCTURE]); self::assertEqualsCanonicalizing($songs->pluck('id')->all(), Arr::pluck($response->json(), 'id')); $response = $this->getAs('api/songs/in-folder'); $response->assertJsonStructure([0 => SongFileResource::JSON_STRUCTURE]); self::assertEqualsCanonicalizing($songs->pluck('id')->all(), $response->json('*.id')); } #[Test] public function doesNotFetchPrivateSongsFromOtherUsers(): void { /** @var Collection $songs */ $songs = Song::factory()->count(2)->create(); Song::factory()->create(['is_public' => false]); $response = $this->getAs('api/songs/in-folder?path='); $response->assertJsonStructure([0 => SongFileResource::JSON_STRUCTURE]); self::assertEqualsCanonicalizing($songs->pluck('id')->all(), $response->json('*.id')); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/MediaBrowser/FetchSubfoldersTest.php
tests/Feature/KoelPlus/MediaBrowser/FetchSubfoldersTest.php
<?php namespace Tests\Feature\KoelPlus\MediaBrowser; use App\Http\Resources\FolderResource; use App\Models\Folder; use App\Models\Setting; use Illuminate\Database\Eloquent\Collection; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; class FetchSubfoldersTest extends PlusTestCase { public function setUp(): void { parent::setUp(); Setting::set('media_path', '/var/media'); } #[Test] public function testFetch(): void { /** @var Folder $folder */ $folder = Folder::factory()->create(); /** @var Collection $subfolders */ $subfolders = Folder::factory()->for($folder, 'parent')->count(2)->create(); $response = $this->getAs('/api/browse/folders?path=' . $folder->path) ->assertJsonStructure([0 => FolderResource::JSON_STRUCTURE]); self::assertEqualsCanonicalizing($subfolders->pluck('id')->toArray(), $response->json('*.id')); } #[Test] public function tesFetchUnderMediaRoot(): void { $subfolders = Folder::factory()->count(2)->create(); $response = $this->getAs('/api/browse/folders') ->assertJsonStructure([0 => FolderResource::JSON_STRUCTURE]); self::assertEqualsCanonicalizing($subfolders->pluck('id')->toArray(), $response->json('*.id')); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/KoelPlus/SSO/GoogleTest.php
tests/Feature/KoelPlus/SSO/GoogleTest.php
<?php namespace Tests\Feature\KoelPlus\SSO; use Illuminate\Support\Str; use Laravel\Socialite\Facades\Socialite; use Laravel\Socialite\Two\User as GoogleUser; use Mockery; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; class GoogleTest extends PlusTestCase { #[Test] public function callbackWithNewUser(): void { $googleUser = Mockery::mock(GoogleUser::class, [ 'getEmail' => 'bruce@iron.com', 'getName' => 'Bruce Dickinson', 'getAvatar' => 'https://lh3.googleusercontent.com/a/vatar', 'getId' => Str::random(), ]); Socialite::expects('driver->user')->andReturn($googleUser); $response = $this->get('auth/google/callback'); $response->assertOk(); $response->assertViewIs('sso-callback'); $response->assertViewHas('token'); } #[Test] public function callbackWithExistingEmail(): void { create_user(['email' => 'bruce@iron.com']); $googleUser = Mockery::mock(GoogleUser::class, [ 'getEmail' => 'bruce@iron.com', 'getName' => 'Bruce Dickinson', 'getAvatar' => 'https://lh3.googleusercontent.com/a/vatar', 'getId' => Str::random(), ]); Socialite::expects('driver->user')->andReturn($googleUser); $response = $this->get('auth/google/callback'); $response->assertOk(); $response->assertViewIs('sso-callback'); $response->assertViewHas('token'); } #[Test] public function callbackWithExistingSSOUser(): void { create_user([ 'sso_provider' => 'Google', 'sso_id' => '123', 'email' => 'bruce@iron.com', ]); $googleUser = Mockery::mock(GoogleUser::class, [ 'getEmail' => 'bruce@iron.com', 'getName' => 'Bruce Dickinson', 'getAvatar' => 'https://lh3.googleusercontent.com/a/vatar', 'getId' => '123', ]); Socialite::expects('driver->user')->andReturn($googleUser); $response = $this->get('auth/google/callback'); $response->assertOk(); $response->assertViewIs('sso-callback'); $response->assertViewHas('token'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/ObjectStorage/S3Test.php
tests/Feature/ObjectStorage/S3Test.php
<?php namespace Tests\Feature\ObjectStorage; use App\Models\Song; use Illuminate\Foundation\Testing\WithoutMiddleware; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_admin; class S3Test extends TestCase { use WithoutMiddleware; public function setUp(): void { parent::setUp(); $this->disableMiddlewareForAllTests(); // ensure there's a default admin user create_admin(); } #[Test] public function storingASong(): void { $this->post('api/os/s3/song', [ 'bucket' => 'koel', 'key' => 'sample.mp3', 'tags' => [ 'title' => 'A Koel Song', 'album' => 'Koel Testing Vol. 1', 'artist' => 'Koel', 'lyrics' => "When you wake up, turn your radio on, and you'll hear this simple song", 'duration' => 10, 'track' => 5, ], ])->assertSuccessful(); /** @var Song $song */ $song = Song::query()->where('path', 's3://koel/sample.mp3')->firstOrFail(); self::assertSame('A Koel Song', $song->title); self::assertSame('Koel Testing Vol. 1', $song->album->name); self::assertSame('Koel', $song->artist->name); self::assertSame('When you wake up, turn your radio on, and you\'ll hear this simple song', $song->lyrics); self::assertSame(10, (int) $song->length); self::assertSame(5, $song->track); } #[Test] public function removingASong(): void { Song::factory()->create([ 'path' => 's3://koel/sample.mp3', ]); $this->delete('api/os/s3/song', [ 'bucket' => 'koel', 'key' => 'sample.mp3', ]); $this->assertDatabaseMissing(Song::class, ['path' => 's3://koel/sample.mp3']); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/ApplicationTest.php
tests/Unit/ApplicationTest.php
<?php namespace Tests\Unit; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class ApplicationTest extends TestCase { #[Test] public function staticUrlsWithoutCdnAreConstructedCorrectly(): void { config(['koel.cdn.url' => '']); self::assertSame('http://localhost/', static_url()); self::assertSame('http://localhost/foo.css', static_url('/foo.css ')); } #[Test] public function staticUrlsWithCdnAreConstructedCorrectly(): void { config(['koel.cdn.url' => 'http://cdn.tld']); self::assertSame('http://cdn.tld/', static_url()); self::assertSame('http://cdn.tld/foo.css', static_url('/foo.css ')); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Jobs/DeleteTranscodeFilesJobTest.php
tests/Unit/Jobs/DeleteTranscodeFilesJobTest.php
<?php namespace Tests\Unit\Jobs; use App\Enums\SongStorageType; use App\Jobs\DeleteTranscodeFilesJob; use App\Services\Transcoding\CloudTranscodingStrategy; use App\Services\Transcoding\LocalTranscodingStrategy; use App\Values\Transcoding\TranscodeFileInfo; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class DeleteTranscodeFilesJobTest extends TestCase { #[Test] public function handle(): void { $files = collect([ TranscodeFileInfo::make('path/to/transcode.m4a', SongStorageType::LOCAL), TranscodeFileInfo::make('key.m4a', SongStorageType::S3), ]); $this->mock(LocalTranscodingStrategy::class) ->expects('deleteTranscodeFile') ->with('path/to/transcode.m4a', SongStorageType::LOCAL); $this->mock(CloudTranscodingStrategy::class) ->expects('deleteTranscodeFile') ->with('key.m4a', SongStorageType::S3); $job = new DeleteTranscodeFilesJob($files); $job->handle(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Jobs/GenerateAlbumThumbnailJobTest.php
tests/Unit/Jobs/GenerateAlbumThumbnailJobTest.php
<?php namespace Tests\Unit\Jobs; use App\Jobs\GenerateAlbumThumbnailJob; use App\Models\Album; use App\Services\AlbumService; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class GenerateAlbumThumbnailJobTest extends TestCase { #[Test] public function handle(): void { /** @var Album $album */ $album = Album::factory()->create(); /** @var AlbumService|MockInterface $albumService */ $albumService = $this->mock(AlbumService::class); $albumService->expects('generateAlbumThumbnail')->with($album)->once(); (new GenerateAlbumThumbnailJob($album))->handle($albumService); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Jobs/ScrobbleJobTest.php
tests/Unit/Jobs/ScrobbleJobTest.php
<?php namespace Tests\Unit\Jobs; use App\Jobs\ScrobbleJob; use App\Models\Song; use App\Services\LastfmService; use Mockery; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class ScrobbleJobTest extends TestCase { #[Test] public function handle(): void { $user = create_user(); /** @var Song $song */ $song = Song::factory()->make(); $job = new ScrobbleJob($user, $song, 100); $lastfm = Mockery::mock(LastfmService::class); $lastfm->expects('scrobble') ->with($song, $user, 100); $job->handle($lastfm); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Jobs/DeleteSongFilesJobTest.php
tests/Unit/Jobs/DeleteSongFilesJobTest.php
<?php namespace Tests\Unit\Jobs; use App\Enums\SongStorageType; use App\Jobs\DeleteSongFilesJob; use App\Services\SongStorages\SongStorage; use App\Values\Song\SongFileInfo; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class DeleteSongFilesJobTest extends TestCase { #[Test] public function handle(): void { $files = collect([ SongFileInfo::make('path/to/song.mp3', SongStorageType::LOCAL), SongFileInfo::make('key.mp3', SongStorageType::S3), ]); /** @var SongStorage|MockInterface $storage */ $storage = Mockery::mock(SongStorage::class); $storage->expects('delete')->with('path/to/song.mp3', config('koel.backup_on_delete')); $storage->expects('delete')->with('key.mp3', config('koel.backup_on_delete')); $job = new DeleteSongFilesJob($files); $job->handle($storage); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Values/EmbedOptionsTest.php
tests/Unit/Values/EmbedOptionsTest.php
<?php namespace Tests\Unit\Values; use App\Values\EmbedOptions; use Illuminate\Http\Request; use Mockery; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class EmbedOptionsTest extends TestCase { #[Test] public function makeDefault(): void { $encrypted = (string) EmbedOptions::make(); $options = EmbedOptions::fromEncrypted($encrypted); self::assertSame('classic', $options->theme); self::assertSame('full', $options->layout); self::assertFalse($options->preview); } #[Test] public function make(): void { $encrypted = (string) EmbedOptions::make(layout: 'compact'); $options = EmbedOptions::fromEncrypted($encrypted); self::assertSame('classic', $options->theme); self::assertSame('compact', $options->layout); self::assertFalse($options->preview); } #[Test] public function themeAndPreviewCannotBeCustomizedForCommunityLicense(): void { $encrypted = (string) EmbedOptions::make('cat', 'compact', true); $options = EmbedOptions::fromEncrypted($encrypted); self::assertSame('classic', $options->theme); self::assertSame('compact', $options->layout); self::assertFalse($options->preview); } #[Test] public function invalidEncryptedResolvesIntoDefault(): void { $options = EmbedOptions::fromEncrypted('foo'); self::assertSame('classic', $options->theme); self::assertSame('full', $options->layout); self::assertFalse($options->preview); } #[Test] public function fromRequest(): void { $encrypted = (string) EmbedOptions::make(layout: 'compact'); $request = Mockery::mock(Request::class, ['route' => $encrypted]); $options = EmbedOptions::fromRequest($request); self::assertSame('classic', $options->theme); self::assertSame('compact', $options->layout); self::assertFalse($options->preview); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Http/Middleware/ForceHttpsTest.php
tests/Unit/Http/Middleware/ForceHttpsTest.php
<?php namespace Tests\Unit\Http\Middleware; use App\Http\Middleware\ForceHttps; use Illuminate\Http\Request; use Illuminate\Routing\UrlGenerator; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Symfony\Component\HttpFoundation\Response; use Tests\TestCase; class ForceHttpsTest extends TestCase { private UrlGenerator|MockInterface $url; private ForceHttps $middleware; public function setUp(): void { parent::setUp(); $this->url = Mockery::mock(UrlGenerator::class); $this->middleware = new ForceHttps($this->url); } #[Test] public function handle(): void { config(['koel.force_https' => true]); $this->url->expects('forceScheme')->with('https'); $request = Mockery::mock(Request::class); $request->expects('getClientIp')->andReturn('127.0.0.1'); $request->expects('setTrustedProxies') ->with( ['127.0.0.1'], Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO ); $response = Mockery::mock(Response::class); $next = static fn () => $response; self::assertSame($response, $this->middleware->handle($request, $next)); } #[Test] public function notHandle(): void { config(['koel.force_https' => false]); $this->url->expects('forceScheme')->with('https')->never(); $request = Mockery::mock(Request::class); $request->shouldNotReceive('setTrustedProxies'); $response = Mockery::mock(Response::class); $next = static fn () => $response; self::assertSame($response, $this->middleware->handle($request, $next)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Http/Integrations/Spotify/SpotifyClientTest.php
tests/Unit/Http/Integrations/Spotify/SpotifyClientTest.php
<?php namespace Tests\Unit\Http\Integrations\Spotify; use App\Exceptions\SpotifyIntegrationDisabledException; use App\Http\Integrations\Spotify\SpotifyClient; use Illuminate\Cache\Repository as Cache; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use SpotifyWebAPI\Session as SpotifySession; use SpotifyWebAPI\SpotifyWebAPI; use Tests\TestCase; class SpotifyClientTest extends TestCase { private SpotifySession|MockInterface $session; private SpotifyWebAPI|MockInterface $wrapped; private Cache|MockInterface $cache; private SpotifyClient $client; public function setUp(): void { parent::setUp(); config([ 'koel.services.spotify.client_id' => 'fake-client-id', 'koel.services.spotify.client_secret' => 'fake-client-secret', ]); $this->session = Mockery::mock(SpotifySession::class); $this->wrapped = Mockery::mock(SpotifyWebAPI::class); $this->cache = Mockery::mock(Cache::class); } #[Test] public function accessTokenIsSetUponInitialization(): void { $this->mockSetAccessToken(); $this->client = new SpotifyClient($this->wrapped, $this->session, $this->cache); self::addToAssertionCount(1); } #[Test] public function accessTokenIsRetrievedFromCacheWhenApplicable(): void { $this->wrapped->expects('setOptions')->with(['return_assoc' => true]); $this->cache->expects('get')->with('spotify.access_token')->andReturn('fake-access-token'); $this->session->shouldNotReceive('requestCredentialsToken'); $this->session->shouldNotReceive('getAccessToken'); $this->cache->shouldNotReceive('put'); $this->wrapped->expects('setAccessToken')->with('fake-access-token'); $this->client = new SpotifyClient($this->wrapped, $this->session, $this->cache); } #[Test] public function callForwarding(): void { $this->mockSetAccessToken(); $this->wrapped->expects('search')->with('foo', 'track')->andReturn('bar'); $this->client = new SpotifyClient($this->wrapped, $this->session, $this->cache); self::assertSame('bar', $this->client->search('foo', 'track')); } #[Test] public function callForwardingThrowsIfIntegrationIsDisabled(): void { config([ 'koel.services.spotify.client_id' => null, 'koel.services.spotify.client_secret' => null, ]); $this->expectException(SpotifyIntegrationDisabledException::class); (new SpotifyClient($this->wrapped, $this->session, $this->cache))->search('foo', 'track'); } private function mockSetAccessToken(): void { $this->wrapped->expects('setOptions')->with(['return_assoc' => true]); $this->cache->expects('get')->with('spotify.access_token')->andReturnNull(); $this->session->expects('requestCredentialsToken'); $this->session->expects('getAccessToken')->andReturn('fake-access-token'); $this->cache->expects('put')->with('spotify.access_token', 'fake-access-token', 3_540); $this->wrapped->expects('setAccessToken')->with('fake-access-token'); } protected function tearDown(): void { config([ 'koel.services.spotify.client_id' => null, 'koel.services.spotify.client_secret' => null, ]); parent::tearDown(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Listeners/DeletePodcastIfNoSubscribersTest.php
tests/Unit/Listeners/DeletePodcastIfNoSubscribersTest.php
<?php namespace Tests\Unit\Listeners; use App\Events\UserUnsubscribedFromPodcast; use App\Listeners\DeletePodcastIfNoSubscribers; use App\Models\Podcast; use App\Services\PodcastService; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class DeletePodcastIfNoSubscribersTest extends TestCase { private MockInterface|PodcastService $podcastService; private DeletePodcastIfNoSubscribers $listener; public function setUp(): void { parent::setUp(); $this->podcastService = Mockery::mock(PodcastService::class); $this->listener = new DeletePodcastIfNoSubscribers($this->podcastService); } #[Test] public function handlePodcastWithNoSubscribers(): void { /** @var Podcast $podcast */ $podcast = Podcast::factory()->create(); $this->podcastService->expects('deletePodcast')->once()->with($podcast); $this->listener->handle(new UserUnsubscribedFromPodcast(create_user(), $podcast)); } #[Test] public function handlePodcastWithSubscribers(): void { /** @var Podcast $podcast */ $podcast = Podcast::factory()->create(); $podcast->subscribers()->attach(create_user()); $this->podcastService->expects('deletePodcast')->never(); $this->listener->handle(new UserUnsubscribedFromPodcast(create_user(), $podcast)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Listeners/WriteSyncLogTest.php
tests/Unit/Listeners/WriteSyncLogTest.php
<?php namespace Tests\Unit\Listeners; use App\Events\MediaScanCompleted; use App\Listeners\WriteScanLog; use App\Values\Scanning\ScanResult; use App\Values\Scanning\ScanResultCollection; use Carbon\Carbon; use Illuminate\Support\Facades\File; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\test_path; class WriteSyncLogTest extends TestCase { private WriteScanLog $listener; private string $originalLogLevel; public function setUp(): void { parent::setUp(); $this->listener = new WriteScanLog(); $this->originalLogLevel = config('koel.sync_log_level'); Carbon::setTestNow(Carbon::create(2021, 1, 2, 12, 34, 56)); } protected function tearDown(): void { File::delete(storage_path('logs/sync-20210102-123456.log')); config(['koel.sync_log_level' => $this->originalLogLevel]); parent::tearDown(); } #[Test] public function handleWithLogLevelAll(): void { config(['koel.sync_log_level' => 'all']); $this->listener->handle(self::createSyncCompleteEvent()); self::assertStringEqualsFile( storage_path('logs/sync-20210102-123456.log'), File::get(test_path('fixtures/sync-log-all.log')) ); } #[Test] public function handleWithLogLevelError(): void { config(['koel.sync_log_level' => 'error']); $this->listener->handle(self::createSyncCompleteEvent()); self::assertStringEqualsFile( storage_path('logs/sync-20210102-123456.log'), File::get(test_path('fixtures/sync-log-error.log')) ); } private static function createSyncCompleteEvent(): MediaScanCompleted { $resultCollection = ScanResultCollection::create() ->add(ScanResult::success('/media/foo.mp3')) ->add(ScanResult::error('/media/baz.mp3', 'Something went wrong')) ->add(ScanResult::error('/media/qux.mp3', 'Something went horribly wrong')) ->add(ScanResult::skipped('/media/bar.mp3')); return new MediaScanCompleted($resultCollection); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Listeners/MakePlaylistSongsPublicTest.php
tests/Unit/Listeners/MakePlaylistSongsPublicTest.php
<?php namespace Tests\Unit\Listeners; use App\Events\NewPlaylistCollaboratorJoined; use App\Listeners\MakePlaylistSongsPublic; use App\Models\PlaylistCollaborationToken; use App\Services\PlaylistService; use Mockery; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class MakePlaylistSongsPublicTest extends TestCase { #[Test] public function handle(): void { /** @var PlaylistCollaborationToken $token */ $token = PlaylistCollaborationToken::factory()->create(); $service = Mockery::mock(PlaylistService::class); $service->expects('makePlaylistContentPublic')->with($token->playlist); (new MakePlaylistSongsPublic($service))->handle(new NewPlaylistCollaboratorJoined(create_user(), $token)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Listeners/UpdateLastfmNowPlayingTest.php
tests/Unit/Listeners/UpdateLastfmNowPlayingTest.php
<?php namespace Tests\Unit\Listeners; use App\Events\PlaybackStarted; use App\Listeners\UpdateLastfmNowPlaying; use App\Models\Song; use App\Services\LastfmService; use Mockery; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class UpdateLastfmNowPlayingTest extends TestCase { #[Test] public function updateNowPlayingStatus(): void { $user = create_user(); /** @var Song $song */ $song = Song::factory()->create(); $lastfm = Mockery::mock(LastfmService::class, ['enabled' => true]); $lastfm->expects('updateNowPlaying') ->with($song, $user); (new UpdateLastfmNowPlaying($lastfm))->handle(new PlaybackStarted($song, $user)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Listeners/LoveTrackOnLastFmTest.php
tests/Unit/Listeners/LoveTrackOnLastFmTest.php
<?php namespace Tests\Unit\Listeners; use App\Events\SongFavoriteToggled; use App\Listeners\LoveTrackOnLastfm; use App\Models\Song; use App\Services\LastfmService; use Mockery; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class LoveTrackOnLastFmTest extends TestCase { #[Test] public function handleFavoriteCase(): void { /** @var Song $song */ $song = Song::factory()->create(); $user = create_user(); $lastfm = Mockery::mock(LastfmService::class, ['enabled' => true]); $lastfm->expects('toggleLoveTrack')->with($song, $user, true); (new LoveTrackOnLastfm($lastfm))->handle(new SongFavoriteToggled($song, true, $user)); } #[Test] public function handleUndoFavoriteCase(): void { /** @var Song $song */ $song = Song::factory()->create(); $user = create_user(); $lastfm = Mockery::mock(LastfmService::class, ['enabled' => true]); $lastfm->expects('toggleLoveTrack')->with($song, $user, false); (new LoveTrackOnLastfm($lastfm))->handle(new SongFavoriteToggled($song, false, $user)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Rules/ValidSmartPlaylistRulePayloadTest.php
tests/Unit/Rules/ValidSmartPlaylistRulePayloadTest.php
<?php namespace Tests\Unit\Rules; use App\Rules\ValidSmartPlaylistRulePayload; use Exception; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class ValidSmartPlaylistRulePayloadTest extends TestCase { /** @return array<mixed> */ public static function provideInvalidPayloads(): array { return [ 'invalid format' => ['foo'], 'invalid model' => [ [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'rules' => [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'model' => 'foo', 'operator' => 'contains', 'value' => ['bar'], ], ], ], ], ], 'invalid operator' => [ [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'rules' => [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'model' => 'artist.name', 'operator' => '<script>', 'value' => ['bar'], ], ], ], ], ], 'values are not an array' => [ [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'rules' => [ [ 'id' => 'f5fcc10f-eb6a-40f6-baf9-db573de088f8', 'model' => 'artist.name', 'operator' => 'is', 'value' => 'bar', ], ], ], ], ], 'values are empty' => [ [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'rules' => [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'model' => 'artist.name', 'operator' => 'is', 'value' => [], ], ], ], ], ], 'values item account exceeds 2' => [ [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'rules' => [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'model' => 'artist.name', 'operator' => 'is', 'value' => ['bar', 'baz', 'qux'], ], ], ], ], ], ]; } #[DataProvider('provideInvalidPayloads')] #[Test] public function invalidCases($value): void { $this->expectExceptionMessage('Invalid smart playlist rules'); $fail = static fn (string $message) => throw new Exception($message); (new ValidSmartPlaylistRulePayload())->validate('rules', $value, $fail); } /** @return array<mixed> */ public static function provideValidPayloads(): array { return [ 'one rule' => [ [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'rules' => [ [ 'id' => '45368b8f-fec8-4b72-b826-6b295af0da65', 'model' => 'artist.name', 'operator' => 'is', 'value' => ['bar'], ], ], ], ], ], 'multiple rules' => [ [ [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'rules' => [ [ 'id' => '45368b8f-fec8-4b72-b826-6b295af0da65', 'model' => 'artist.name', 'operator' => 'is', 'value' => ['bar'], ], [ 'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026', 'model' => 'interactions.play_count', 'operator' => 'isGreaterThan', 'value' => [50], ], ], ], ], ], 'multiple groups' => [ [ [ 'id' => '54989bb8-9e4f-4f6e-a28f-320834f9435e', 'rules' => [ [ 'id' => '59e95d10-e297-4f33-b2d8-de55e64a02fa', 'model' => 'artist.name', 'operator' => 'is', 'value' => ['bar'], ], [ 'id' => 'fefa409c-5539-4612-949f-47f71d06c828', 'model' => 'interactions.play_count', 'operator' => 'isGreaterThan', 'value' => [50], ], ], ], [ 'id' => '45b23131-ece6-4461-8c1b-4d865f06a395', 'rules' => [ [ 'id' => 'e3e2f1cc-bde1-43fc-9fb2-96ea7d64412c', 'model' => 'album.name', 'operator' => 'contains', 'value' => ['bar'], ], [ 'id' => '39bba5c4-e9cb-4b72-a241-6b7c6cc14c3c', 'model' => 'interactions.play_count', 'operator' => 'isBetween', 'value' => [10, 100], ], ], ], ], ], ]; } #[DataProvider('provideValidPayloads')] #[Test] public function validCases($value): void { (new ValidSmartPlaylistRulePayload())->validate('rules', $value, static fn ($foo) => $foo); // @phpstan-ignore-line $this->addToAssertionCount(1); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Rules/ValidRadioStationUrlTest.php
tests/Unit/Rules/ValidRadioStationUrlTest.php
<?php namespace Tests\Unit\Rules; use App\Rules\ValidRadioStationUrl; use Illuminate\Support\Facades\Http; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class ValidRadioStationUrlTest extends TestCase { #[Test] public function valid(): void { Http::fake([ '*' => Http::response('', 200, ['Content-Type' => 'audio/mpeg']), ]); (new ValidRadioStationUrl())->validate( 'url', 'https://example.com/stream', fn (string $attribute, ?string $message) => $this->fail("Validation failed for $attribute: $message"), // @phpstan-ignore-line ); $this->addToAssertionCount(1); } /** @return array<mixed> */ public static function provideInvalidContentType(): array { return [ 'invalid content type' => ['text/html'], 'no content type' => [null], 'empty content type' => [''], ]; } #[Test, DataProvider('provideInvalidContentType')] public function invalidBecauseOfNullHeader(?string $contentType): void { Http::fake([ '*' => Http::response('', 200, ['Content-Type' => $contentType]), ]); (new ValidRadioStationUrl())->validate( 'url', 'https://example.com/stream', fn () => $this->addToAssertionCount(1), // @phpstan-ignore-line ); } #[Test] public function bypass(): void { Http::fake(); $rule = new ValidRadioStationUrl(); $rule->bypass = true; $rule->validate('url', 'https://example.com/stream', static fn () => null); // @phpstan-ignore-line $this->addToAssertionCount(1); Http::assertNothingSent(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/SvgSanitizerTest.php
tests/Unit/Services/SvgSanitizerTest.php
<?php namespace Tests\Unit\Services; use App\Services\SvgSanitizer; use enshrined\svgSanitize\Sanitizer; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class SvgSanitizerTest extends TestCase { private Sanitizer|MockInterface $sanitizer; private SvgSanitizer $service; public function setUp(): void { parent::setUp(); $this->sanitizer = Mockery::mock(Sanitizer::class); $this->service = new SvgSanitizer($this->sanitizer); } #[Test] public function sanitize(): void { $this->sanitizer ->expects('sanitize') ->with('<svg><raw /></svg>') ->andReturn('<svg><sanitized /></svg>'); self::assertSame('<svg><sanitized /></svg>', $this->service->sanitize('<svg><raw /></svg>')); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/ImageStorageTest.php
tests/Unit/Services/ImageStorageTest.php
<?php namespace Tests\Unit\Services; use App\Helpers\Ulid; use App\Services\ImageStorage; use App\Services\ImageWriter; use App\Services\SvgSanitizer; use Illuminate\Support\Facades\File; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class ImageStorageTest extends TestCase { private ImageWriter|MockInterface $imageWriter; private ImageStorage $service; private SvgSanitizer|MockInterface $svgSanitizer; public function setUp(): void { parent::setUp(); $this->imageWriter = Mockery::mock(ImageWriter::class); $this->svgSanitizer = Mockery::mock(SvgSanitizer::class); $this->service = new ImageStorage($this->imageWriter, $this->svgSanitizer); } #[Test] public function storeRasterImage(): void { $ulid = Ulid::freeze(); $logo = "$ulid.webp"; $this->imageWriter ->expects('write') ->with(image_storage_path($logo), 'dummy-logo-src', null); self::assertSame($logo, $this->service->storeImage('dummy-logo-src')); } #[Test] public function storeSvg(): void { $source = 'data:image/svg+xml;base64,Zm9v'; $ulid = Ulid::freeze(); $logo = "$ulid.svg"; $this->svgSanitizer ->expects('sanitize') ->with('foo') ->andReturn('foo'); File::expects('put') ->with(image_storage_path($logo), 'foo'); self::assertSame($logo, $this->service->storeImage($source)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/PlaylistFolderServiceTest.php
tests/Unit/Services/PlaylistFolderServiceTest.php
<?php namespace Tests\Unit\Services; use App\Models\Playlist; use App\Models\PlaylistFolder; use App\Services\PlaylistFolderService; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_playlist; use function Tests\create_playlists; use function Tests\create_user; class PlaylistFolderServiceTest extends TestCase { private PlaylistFolderService $service; public function setUp(): void { parent::setUp(); $this->service = new PlaylistFolderService(); } #[Test] public function create(): void { $user = create_user(); self::assertCount(0, $user->playlistFolders); $this->service->createFolder($user, 'Classical'); self::assertCount(1, $user->refresh()->playlistFolders); self::assertSame('Classical', $user->playlistFolders[0]->name); } #[Test] public function update(): void { /** @var PlaylistFolder $folder */ $folder = PlaylistFolder::factory()->create(['name' => 'Metal']); $this->service->renameFolder($folder, 'Classical'); self::assertSame('Classical', $folder->fresh()->name); } #[Test] public function addPlaylistsToFolder(): void { $user = create_user(); $playlists = create_playlists(count: 3, owner: $user); /** @var PlaylistFolder $folder */ $folder = PlaylistFolder::factory()->for($user)->create(); $this->service->addPlaylistsToFolder($folder, $playlists->modelKeys()); self::assertCount(3, $folder->playlists); } #[Test] public function aPlaylistCannotBelongToMultipleFoldersByOneUser(): void { $playlist = create_playlist(); /** @var PlaylistFolder $existingFolder */ $existingFolder = PlaylistFolder::factory()->for($playlist->owner)->create(); $existingFolder->playlists()->attach($playlist); /** @var PlaylistFolder $newFolder */ $newFolder = PlaylistFolder::factory()->for($playlist->owner)->create(); $this->service->addPlaylistsToFolder($newFolder, [$playlist->id]); self::assertSame(1, $playlist->refresh()->folders->count()); } #[Test] public function aPlaylistCanBelongToMultipleFoldersFromDifferentUsers(): void { /** @var PlaylistFolder $existingFolderFromAnotherUser */ $existingFolderFromAnotherUser = PlaylistFolder::factory()->create(); $playlist = create_playlist(); $existingFolderFromAnotherUser->playlists()->attach($playlist); /** @var PlaylistFolder $newFolder */ $newFolder = PlaylistFolder::factory()->for($playlist->owner)->create(); $this->service->addPlaylistsToFolder($newFolder, [$playlist->id]); self::assertSame(2, $playlist->refresh()->folders->count()); } #[Test] public function movePlaylistsToRootLevel(): void { /** @var PlaylistFolder $folder */ $folder = PlaylistFolder::factory()->create(); $playlists = create_playlists(count: 3); $folder->playlists()->attach($playlists); $this->service->movePlaylistsToRootLevel($folder, $playlists->modelKeys()); self::assertCount(0, $folder->playlists); $playlists->each(static fn (Playlist $playlist) => self::assertNull($playlist->refresh()->getFolder())); // @phpstan-ignore-line } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/AclTest.php
tests/Unit/Services/AclTest.php
<?php namespace Tests\Unit\Services; use App\Enums\Acl\Role; use App\Enums\PermissionableResourceType; use App\Models\Contracts\Permissionable; use App\Services\Acl; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Gate; use Mockery; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_admin; use function Tests\create_user; class AclTest extends TestCase { private Acl $acl; public function setUp(): void { parent::setUp(); $this->acl = new Acl(); } /** * @return array<array<PermissionableResourceType>> */ public static function providePermissionAbleResourceTypes(): array { return [PermissionableResourceType::cases()]; } #[Test] #[DataProvider('providePermissionAbleResourceTypes')] public function check(PermissionableResourceType $type): void { $user = create_user(); /** @var class-string<Model|Permissionable> $modelClass */ $modelClass = $type->modelClass(); $subject = $modelClass::factory()->create(); // @phpstan-ignore-line Gate::expects('forUser') ->with($user) ->andReturnSelf(); Gate::expects('allows') ->with('edit', Mockery::on(static fn (Model $s) => $s->is($subject))) ->andReturn(true); self::assertTrue($this->acl->checkPermission( $type, $subject->{$modelClass::getPermissionableIdentifier()}, // @phpstan-ignore-line 'edit', $user )); } #[Test] public function getAssignableRolesForUser(): void { $admin = create_admin(); $this->acl ->getAssignableRolesForUser($admin) ->each(static fn (Role $role) => self::assertTrue($admin->role->canManage($role))); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/UploadServiceTest.php
tests/Unit/Services/UploadServiceTest.php
<?php namespace Tests\Unit\Services; use App\Enums\SongStorageType; use App\Exceptions\SongUploadFailedException; use App\Models\Song; use App\Services\Scanners\FileScanner; use App\Services\SongService; use App\Services\SongStorages\Contracts\MustDeleteTemporaryLocalFileAfterUpload; use App\Services\SongStorages\SongStorage; use App\Services\UploadService; use App\Values\Scanning\ScanConfiguration; use App\Values\Scanning\ScanInformation; use App\Values\UploadReference; use Exception; use Illuminate\Support\Facades\File; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; class UploadServiceTest extends TestCase { private SongService|MockInterface $songService; private FileScanner|MockInterface $scanner; public function setUp(): void { parent::setUp(); $this->songService = Mockery::mock(SongService::class); $this->scanner = Mockery::mock(FileScanner::class); } #[Test] public function handleUpload(): void { $storage = Mockery::mock(SongStorage::class, ['getStorageType' => SongStorageType::LOCAL]); $scanInfo = ScanInformation::make(path: '/var/media/koel/some-file.mp3'); $file = '/var/media/koel/some-file.mp3'; $song = Song::factory()->create(); $uploader = create_user(); $reference = UploadReference::make( location: '/var/media/koel/some-file.mp3', localPath: '/var/media/koel/some-file.mp3', ); $storage->expects('storeUploadedFile') ->with($file, $uploader) ->andReturn($reference); $this->scanner->expects('scan') ->with('/var/media/koel/some-file.mp3') ->andReturn($scanInfo); $this->songService->expects('createOrUpdateSongFromScan') ->with($scanInfo, Mockery::on(static function (ScanConfiguration $config) use ($uploader): bool { return $config->owner->is($uploader) && $config->makePublic === $uploader->preferences->makeUploadsPublic && $config->extractFolderStructure; })) ->andReturn($song); $result = (new UploadService($this->songService, $storage, $this->scanner))->handleUpload($file, $uploader); self::assertSame($song, $result); } #[Test] public function uploadUpdatesSongPathAndStorage(): void { $storage = Mockery::mock(SongStorage::class, ['getStorageType' => SongStorageType::S3]); $file = '/tmp/some-tmp-file.mp3'; $scanInfo = ScanInformation::make(path: '/tmp/some-tmp-file.mp3'); $uploader = create_user(); /** @var Song $song */ $song = Song::factory()->create([ 'path' => '/tmp/some-tmp-file.mp3', // Initially set to the local path 'storage' => SongStorageType::LOCAL, // Initially set to local storage ]); $reference = UploadReference::make( location: 's3://koel/some-file.mp3', localPath: '/tmp/some-tmp-file.mp3', ); $storage->expects('storeUploadedFile') ->with($file, $uploader) ->andReturn($reference); $this->scanner->expects('scan') ->with('/tmp/some-tmp-file.mp3') ->andReturn($scanInfo); $this->songService->expects('createOrUpdateSongFromScan') ->with($scanInfo, Mockery::on(static function (ScanConfiguration $config) use ($uploader): bool { return $config->owner->is($uploader) && $config->makePublic === $uploader->preferences->makeUploadsPublic && !$config->extractFolderStructure; })) ->andReturn($song); $result = (new UploadService($this->songService, $storage, $this->scanner))->handleUpload($file, $uploader); self::assertSame($song, $result); self::assertSame('s3://koel/some-file.mp3', $song->path); self::assertSame(SongStorageType::S3, $song->storage); } #[Test] public function deletesTempLocalPathAfterUploading(): void { $scanInfo = ScanInformation::make(path: '/tmp/some-tmp-file.mp3'); /** @var SongStorage|MustDeleteTemporaryLocalFileAfterUpload|MockInterface $storage */ $storage = Mockery::mock( SongStorage::class . ',' . MustDeleteTemporaryLocalFileAfterUpload::class, ['getStorageType' => SongStorageType::S3] ); /** @var Song $song */ $song = Song::factory()->create(); $file = '/tmp/some-tmp-file.mp3'; $uploader = create_user(); $reference = UploadReference::make( location: 's3://koel/some-file.mp3', localPath: '/tmp/some-tmp-file.mp3', ); $storage->expects('storeUploadedFile')->andReturn($reference); $this->scanner->expects('scan')->andReturn($scanInfo); $this->songService->expects('createOrUpdateSongFromScan')->andReturn($song); File::expects('delete')->with('/tmp/some-tmp-file.mp3'); (new UploadService($this->songService, $storage, $this->scanner))->handleUpload($file, $uploader); } #[Test] public function undoUploadOnScanningProcessException(): void { $scanInfo = ScanInformation::make(path: '/var/media/koel/some-file.mp3'); $storage = Mockery::mock(SongStorage::class, ['getStorageType' => SongStorageType::LOCAL]); $file = '/tmp/some-file.mp3'; $uploader = create_user(); $reference = UploadReference::make( location: '/var/media/koel/some-file.mp3', localPath: '/var/media/koel/some-file.mp3', ); $storage->expects('storeUploadedFile')->with($file, $uploader)->andReturn($reference); $this->scanner->expects('scan')->andReturn($scanInfo); $storage->expects('undoUpload')->with($reference); $this->songService ->expects('createOrUpdateSongFromScan') ->andThrow(new Exception('File supports racism')); $this->expectException(SongUploadFailedException::class); $this->expectExceptionMessage('File supports racism'); (new UploadService($this->songService, $storage, $this->scanner))->handleUpload($file, $uploader); } #[Test] public function undoUploadOnScanningError(): void { $storage = Mockery::mock(SongStorage::class, ['getStorageType' => SongStorageType::LOCAL]); $file = '/tmp/some-file.mp3'; $uploader = create_user(); $reference = UploadReference::make( location: '/var/media/koel/some-file.mp3', localPath: '/var/media/koel/some-file.mp3', ); $storage->expects('storeUploadedFile')->with($file, $uploader)->andReturn($reference); $this->scanner->expects('scan')->andThrow(new Exception('File supports racism')); $storage->expects('undoUpload')->with($reference); $this->expectException(SongUploadFailedException::class); $this->expectExceptionMessage('File supports racism'); (new UploadService($this->songService, $storage, $this->scanner))->handleUpload($file, $uploader); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/SpotifyServiceTest.php
tests/Unit/Services/SpotifyServiceTest.php
<?php namespace Tests\Unit\Services; use App\Http\Integrations\Spotify\SpotifyClient; use App\Models\Album; use App\Models\Artist; use App\Services\SpotifyService; use Illuminate\Support\Facades\File; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\test_path; class SpotifyServiceTest extends TestCase { private SpotifyService $service; private SpotifyClient|MockInterface $client; public function setUp(): void { parent::setUp(); config([ 'koel.services.spotify.client_id' => 'fake-client-id', 'koel.services.spotify.client_secret' => 'fake-client-secret', ]); $this->client = Mockery::mock(SpotifyClient::class); $this->service = new SpotifyService($this->client); } #[Test] public function tryGetArtistImage(): void { /** @var Artist $artist */ $artist = Artist::factory(['name' => 'Foo'])->create(); $this->client ->expects('search') ->with('Foo', 'artist', ['limit' => 1]) ->andReturn(self::parseFixture('search-artist.json')); self::assertSame('https://foo/bar.jpg', $this->service->tryGetArtistImage($artist)); } #[Test] public function tryGetArtistImageWhenServiceIsNotEnabled(): void { config(['koel.services.spotify.client_id' => null]); $this->client->shouldNotReceive('search'); self::assertNull($this->service->tryGetArtistImage(Mockery::mock(Artist::class))); } #[Test] public function tryGetAlbumImage(): void { /** @var Album $album */ $album = Album::factory(['name' => 'Bar'])->for(Artist::factory(['name' => 'Foo']))->create(); $this->client ->expects('search') ->with('Bar artist:Foo', 'album', ['limit' => 1]) ->andReturn(self::parseFixture('search-album.json')); self::assertSame('https://foo/bar.jpg', $this->service->tryGetAlbumCover($album)); } #[Test] public function tryGetAlbumImageWhenServiceIsNotEnabled(): void { config(['koel.services.spotify.client_id' => null]); $this->client->shouldNotReceive('search'); self::assertNull($this->service->tryGetAlbumCover(Mockery::mock(Album::class))); } /** @return array<mixed> */ private static function parseFixture(string $name): array { return File::json(test_path("fixtures/spotify/$name")); } protected function tearDown(): void { config([ 'koel.services.spotify.client_id' => null, 'koel.services.spotify.client_secret' => null, ]); parent::tearDown(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/AuthenticationServiceTest.php
tests/Unit/Services/AuthenticationServiceTest.php
<?php namespace Tests\Unit\Services; use App\Repositories\UserRepository; use App\Services\AuthenticationService; use App\Services\TokenManager; use Illuminate\Auth\Passwords\PasswordBroker; use Illuminate\Support\Facades\Password; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class AuthenticationServiceTest extends TestCase { private UserRepository|MockInterface $userRepository; private TokenManager|MockInterface $tokenManager; private PasswordBroker|MockInterface $passwordBroker; private AuthenticationService $service; public function setUp(): void { parent::setUp(); $this->userRepository = $this->mock(UserRepository::class); $this->tokenManager = $this->mock(TokenManager::class); $this->passwordBroker = $this->mock(PasswordBroker::class); $this->service = new AuthenticationService( $this->userRepository, $this->tokenManager, $this->passwordBroker ); } #[Test] public function trySendResetPasswordLink(): void { $this->passwordBroker ->expects('sendResetLink') ->with(['email' => 'foo@bar.com']) ->andReturn(Password::RESET_LINK_SENT); $this->assertTrue($this->service->trySendResetPasswordLink('foo@bar.com')); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/SimpleLrcReaderTest.php
tests/Unit/Services/SimpleLrcReaderTest.php
<?php namespace Tests\Unit\Services; use App\Services\SimpleLrcReader; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\test_path; class SimpleLrcReaderTest extends TestCase { private SimpleLrcReader $reader; public function setUp(): void { parent::setUp(); $this->reader = new SimpleLrcReader(); } #[Test] public function tryReadForMediaFile(): void { $base = sys_get_temp_dir() . '/' . Str::uuid(); $lrcFile = $base . '.lrc'; File::copy(test_path('fixtures/simple.lrc'), $lrcFile); self::assertSame("Line 1\nLine 2\nLine 3", $this->reader->tryReadForMediaFile($base . '.mp3')); File::delete($lrcFile); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/EncyclopediaServiceTest.php
tests/Unit/Services/EncyclopediaServiceTest.php
<?php namespace Tests\Unit\Services; use App\Models\Album; use App\Models\Artist; use App\Services\Contracts\Encyclopedia; use App\Services\EncyclopediaService; use App\Services\ImageStorage; use App\Services\LastfmService; use App\Services\SpotifyService; use App\Values\Album\AlbumInformation; use App\Values\Artist\ArtistInformation; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class EncyclopediaServiceTest extends TestCase { private Encyclopedia|MockInterface $encyclopedia; private ImageStorage|MockInterface $imageStorage; private SpotifyService|MockInterface $spotifyService; private EncyclopediaService $encyclopediaService; private array $spotifyConfig; public function setUp(): void { parent::setUp(); $this->encyclopedia = Mockery::mock(LastfmService::class); $this->imageStorage = Mockery::mock(ImageStorage::class); $this->spotifyService = Mockery::mock(SpotifyService::class); $this->encyclopediaService = new EncyclopediaService( $this->encyclopedia, $this->imageStorage, $this->spotifyService, ); $this->spotifyConfig = config('koel.services.spotify'); } public function tearDown(): void { config()->set('koel.services.spotify', $this->spotifyConfig); parent::tearDown(); } #[Test] public function getAlbumInformation(): void { /** @var Album $album */ $album = Album::factory()->create(); $info = AlbumInformation::make(); $this->encyclopedia ->expects('getAlbumInformation') ->with($album) ->andReturn($info); self::assertSame($info, $this->encyclopediaService->getAlbumInformation($album)); self::assertNotNull(cache()->get(cache_key('album information', $album->name, $album->artist->name))); } #[Test] public function getAlbumInformationTriesDownloadingCover(): void { /** @var Album $album */ $album = Album::factory()->create(['cover' => '']); $info = AlbumInformation::make(cover: 'https://wiki.example.com/album-cover.jpg'); self::assertEmpty($album->cover); $this->encyclopedia ->expects('getAlbumInformation') ->with($album) ->andReturn($info); $this->imageStorage ->expects('storeImage') ->with('https://wiki.example.com/album-cover.jpg'); self::assertSame($info, $this->encyclopediaService->getAlbumInformation($album)); } #[Test] public function getAlbumInformationPrefersSpotifyForFetchingCoverImage(): void { config()->set('koel.services.spotify', [ 'client_id' => 'spotify-client-id', 'client_secret' => 'spotify-client-secret', ]); /** @var Album $album */ $album = Album::factory()->create(['cover' => '']); $info = AlbumInformation::make(cover: 'https://wiki.example.com/album-cover.jpg'); self::assertEmpty($album->cover); $this->encyclopedia ->expects('getAlbumInformation') ->with($album) ->andReturn($info); $this->spotifyService->expects('tryGetAlbumCover')->with($album)->andReturn('https://spotify.com/cover.jpg'); $this->imageStorage ->expects('storeImage') ->with('https://spotify.com/cover.jpg'); self::assertSame($info, $this->encyclopediaService->getAlbumInformation($album)); } #[Test] public function getArtistInformation(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); $info = ArtistInformation::make(); self::assertNotEmpty($artist->image); $this->encyclopedia ->expects('getArtistInformation') ->with($artist) ->andReturn($info); self::assertSame($info, $this->encyclopediaService->getArtistInformation($artist)); self::assertNotNull(cache()->get(cache_key('artist information', $artist->name))); } #[Test] public function getArtistInformationTriesDownloadingImage(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(['image' => '']); $info = ArtistInformation::make(image: 'https://wiki.example.com/artist-image.jpg'); self::assertEmpty($artist->image); $this->encyclopedia ->expects('getArtistInformation') ->with($artist) ->andReturn($info); $this->imageStorage ->expects('storeImage') ->with('https://wiki.example.com/artist-image.jpg'); self::assertSame($info, $this->encyclopediaService->getArtistInformation($artist)); } #[Test] public function getArtistInformationPrefersSpotifyForFetchingImage(): void { config()->set('koel.services.spotify', [ 'client_id' => 'spotify-client-id', 'client_secret' => 'spotify-client-secret', ]); /** @var Artist $artist */ $artist = Artist::factory()->create(['image' => '']); $info = ArtistInformation::make(image: 'https://wiki.example.com/artist-image.jpg'); self::assertEmpty($artist->image); $this->encyclopedia ->expects('getArtistInformation') ->with($artist) ->andReturn($info); $this->spotifyService->expects('tryGetArtistImage')->with($artist)->andReturn('https://spotify.com/image.jpg'); $this->imageStorage ->expects('storeImage') ->with('https://spotify.com/image.jpg'); self::assertSame($info, $this->encyclopediaService->getArtistInformation($artist)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/Transcoding/TranscoderTest.php
tests/Unit/Services/Transcoding/TranscoderTest.php
<?php namespace Tests\Unit\Services\Transcoding; use App\Services\Transcoding\Transcoder; use Illuminate\Process\PendingProcess; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Process; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class TranscoderTest extends TestCase { private Transcoder $transcoder; public function setUp(): void { parent::setUp(); config(['koel.streaming.ffmpeg_path' => '/usr/bin/ffmpeg']); $this->transcoder = new Transcoder(); } #[Test] public function transcode(): void { Process::fake(); File::expects('ensureDirectoryExists')->with('/path/to'); $this->transcoder->transcode('/path/to/song.flac', '/path/to/output.m4a', 128); $closure = static function (PendingProcess $process): bool { return $process->command === [ '/usr/bin/ffmpeg', '-i', '/path/to/song.flac', '-vn', '-c:a', 'aac', '-b:a', '128k', '-y', '/path/to/output.m4a', ]; }; Process::assertRanTimes($closure, 1); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/Transcoding/TranscodingStrategyFactoryTest.php
tests/Unit/Services/Transcoding/TranscodingStrategyFactoryTest.php
<?php namespace Tests\Unit\Services\Transcoding; use App\Enums\SongStorageType; use App\Services\Transcoding\CloudTranscodingStrategy; use App\Services\Transcoding\LocalTranscodingStrategy; use App\Services\Transcoding\SftpTranscodingStrategy; use App\Services\Transcoding\TranscodeStrategyFactory; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class TranscodingStrategyFactoryTest extends TestCase { /** @return array<mixed> */ public static function provideMakeData(): array { return [ 'Local' => [SongStorageType::LOCAL, LocalTranscodingStrategy::class], 'S3' => [SongStorageType::S3, CloudTranscodingStrategy::class], 'S3 Lambda' => [SongStorageType::S3_LAMBDA, CloudTranscodingStrategy::class], 'Dropbox' => [SongStorageType::DROPBOX, CloudTranscodingStrategy::class], 'SFTP' => [SongStorageType::SFTP, SftpTranscodingStrategy::class], ]; } #[Test] #[DataProvider('provideMakeData')] public function make(SongStorageType $storageType, string $concreteClass): void { self::assertInstanceOf($concreteClass, TranscodeStrategyFactory::make($storageType)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/SongStorages/S3LambdaStorageTest.php
tests/Unit/Services/SongStorages/S3LambdaStorageTest.php
<?php namespace Tests\Unit\Services\SongStorages; use App\Models\Song; use App\Repositories\SongRepository; use App\Repositories\UserRepository; use App\Services\AlbumService; use App\Services\SongStorages\S3LambdaStorage; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_admin; class S3LambdaStorageTest extends TestCase { private SongRepository|MockInterface $songRepository; private UserRepository|MockInterface $userRepository; private AlbumService|MockInterface $albumService; private S3LambdaStorage $storage; public function setUp(): void { parent::setUp(); $this->albumService = Mockery::mock(AlbumService::class); $this->songRepository = Mockery::mock(SongRepository::class); $this->userRepository = Mockery::mock(UserRepository::class); $this->storage = new S3LambdaStorage( $this->albumService, $this->songRepository, $this->userRepository ); } #[Test] public function createSongEntry(): void { $user = create_admin(); $this->userRepository->expects('getFirstAdminUser')->andReturn($user); $song = $this->storage->createSongEntry( bucket: 'foo', key: 'bar', artistName: 'Queen', albumName: 'A Night at the Opera', albumArtistName: 'Queen', cover: [], title: 'Bohemian Rhapsody', duration: 355.5, track: 1, lyrics: 'Is this the real life?' ); self::assertSame('Queen', $song->artist->name); self::assertSame('A Night at the Opera', $song->album->name); self::assertSame('Queen', $song->album_artist->name); self::assertSame('Bohemian Rhapsody', $song->title); self::assertSame(355.5, $song->length); self::assertSame('Is this the real life?', $song->lyrics); self::assertSame(1, $song->track); self::assertSame($user->id, $song->owner_id); } #[Test] public function updateSongEntry(): void { $user = create_admin(); $this->userRepository->expects('getFirstAdminUser')->andReturn($user); /** @var Song $song */ $song = Song::factory()->create([ 'path' => 's3://foo/bar', 'storage' => 's3-lambda', ]); $this->storage->createSongEntry( bucket: 'foo', key: 'bar', artistName: 'Queen', albumName: 'A Night at the Opera', albumArtistName: 'Queen', cover: [], title: 'Bohemian Rhapsody', duration: 355.5, track: 1, lyrics: 'Is this the real life?' ); self::assertSame(1, Song::query()->count()); $song->refresh(); self::assertSame('Queen', $song->artist->name); self::assertSame('A Night at the Opera', $song->album->name); self::assertSame('Queen', $song->album_artist->name); self::assertSame('Bohemian Rhapsody', $song->title); self::assertSame(355.5, $song->length); self::assertSame('Is this the real life?', $song->lyrics); self::assertSame(1, $song->track); self::assertSame($user->id, $song->owner_id); } #[Test] public function deleteSong(): void { /** @var Song $song */ $song = Song::factory()->create([ 'path' => 's3://foo/bar', 'storage' => 's3-lambda', ]); $this->songRepository->expects('findOneByPath')->with('s3://foo/bar')->andReturn($song); $this->storage->deleteSongEntry('foo', 'bar'); $this->assertModelMissing($song); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/SongStorages/CloudStorageFactoryTest.php
tests/Unit/Services/SongStorages/CloudStorageFactoryTest.php
<?php namespace Tests\Unit\Services\SongStorages; use App\Enums\SongStorageType; use App\Exceptions\NonCloudStorageException; use App\Services\SongStorages\CloudStorageFactory; use App\Services\SongStorages\DropboxStorage; use App\Services\SongStorages\S3CompatibleStorage; use App\Services\SongStorages\S3LambdaStorage; use Illuminate\Support\Facades\Cache; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class CloudStorageFactoryTest extends TestCase { /** @return array<mixed> */ public static function provideCloudStorageData(): array { return [ 'S3 Lambda' => [SongStorageType::S3_LAMBDA, S3LambdaStorage::class], 'S3 Compatible' => [SongStorageType::S3, S3CompatibleStorage::class], 'Dropbox' => [SongStorageType::DROPBOX, DropboxStorage::class], ]; } #[Test] #[DataProvider('provideCloudStorageData')] public function resolve(SongStorageType $storageType, string $concreteClassName): void { Cache::set('dropbox_access_token', 'foo'); $instance = CloudStorageFactory::make($storageType); self::assertInstanceOf($concreteClassName, $instance); Cache::delete('dropbox_access_token'); } /** @return array<mixed> */ public static function provideNonCloudStorageData(): array { return [ 'SFTP' => [SongStorageType::SFTP], 'Local' => [SongStorageType::LOCAL], ]; } #[Test] #[DataProvider('provideNonCloudStorageData')] public function resolveThrowsForNonCloudStorage(SongStorageType $storageType): void { $this->expectException(NonCloudStorageException::class); CloudStorageFactory::make($storageType); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Services/Scanners/ScannerCacheStrategyTest.php
tests/Unit/Services/Scanners/ScannerCacheStrategyTest.php
<?php namespace Tests\Unit\Services\Scanners; use App\Services\Scanners\ScannerCacheStrategy; use PHPUnit\Framework\Attributes\Test; use RuntimeException; use Tests\TestCase; class ScannerCacheStrategyTest extends TestCase { private ScannerCacheStrategy $cache; public function setUp(): void { parent::setUp(); $this->cache = new ScannerCacheStrategy(3); } #[Test] public function rememberCachesValueDoesNotRecomputeOnSubsequentCalls(): void { $counter = 0; $callback = static function () use (&$counter): int { $counter++; return 42; }; $first = $this->cache->remember('key', $callback); $second = $this->cache->remember('key', $callback); self::assertSame(42, $first); self::assertSame(42, $second); self::assertSame(1, $counter, 'Callback should be executed only once for the same key.'); } #[Test] public function differentKeysAreCachedIndependently(): void { $a = $this->cache->remember('a', static fn () => 'foo'); $b = $this->cache->remember('b', static fn () => 'bar'); self::assertSame('foo', $a); self::assertSame('bar', $b); $a2 = $this->cache->remember('a', static fn () => 'baz'); $b2 = $this->cache->remember('b', static fn () => 'qux'); self::assertSame('foo', $a2); self::assertSame('bar', $b2); } #[Test] public function evictsOldestEntryAfterCacheExceedsMaxSize(): void { for ($i = 1; $i <= 3; $i++) { $key = 'k' . $i; $val = $i; $this->cache->remember($key, static fn () => $val); } // Last entry before eviction $valueForK1 = $this->cache->remember('k1', static function (): void { throw new RuntimeException('Callback for k1 should not be executed before eviction.'); }); self::assertSame(1, $valueForK1); //Trigger eviction $this->cache->remember('k4', static fn () => 4); $new = $this->cache->remember('k1', static fn () => 9999); self::assertSame(9999, $new); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/KoelPlus/Values/EmbedOptionsTest.php
tests/Unit/KoelPlus/Values/EmbedOptionsTest.php
<?php namespace Tests\Unit\KoelPlus\Values; use App\Values\EmbedOptions; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; class EmbedOptionsTest extends PlusTestCase { #[Test] public function themeAndPreviewCanBeCustomizedForCommunityLicense(): void { $encrypted = (string) EmbedOptions::make('cat', 'compact', true); $options = EmbedOptions::fromEncrypted($encrypted); self::assertSame('cat', $options->theme); self::assertSame('compact', $options->layout); self::assertTrue($options->preview); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/KoelPlus/Models/ArtistTest.php
tests/Unit/KoelPlus/Models/ArtistTest.php
<?php namespace Tests\Unit\KoelPlus\Models; use App\Models\Artist; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; use function Tests\create_user; class ArtistTest extends PlusTestCase { #[Test] public function getOrCreate(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(['name' => 'Foo']); // The artist can be retrieved by its name and user self::assertTrue(Artist::getOrCreate($artist->user, 'Foo')->is($artist)); // Calling getOrCreate with a different user should return another artist self::assertFalse(Artist::getOrCreate(create_user(), 'Foo')->is($artist)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/KoelPlus/Models/AlbumTest.php
tests/Unit/KoelPlus/Models/AlbumTest.php
<?php namespace Tests\Unit\KoelPlus\Models; use App\Models\Album; use App\Models\Artist; use PHPUnit\Framework\Attributes\Test; use Tests\PlusTestCase; class AlbumTest extends PlusTestCase { #[Test] public function getOrCreate(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); /** @var Album $album */ $album = Album::factory()->for($artist)->for($artist->user)->create(['name' => 'Foo']); // The album can be retrieved by its artist and user self::assertTrue(Album::getOrCreate($album->artist, 'Foo')->is($album)); // Calling getOrCreate with a different artist should return another album self::assertFalse(Album::getOrCreate(Artist::factory()->create(), 'Foo')->is($album)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Models/ArtistTest.php
tests/Unit/Models/ArtistTest.php
<?php namespace Tests\Unit\Models; use App\Models\Artist; use Illuminate\Support\Facades\File; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; use function Tests\create_user; use function Tests\test_path; class ArtistTest extends TestCase { #[Test] public function existingArtistCanBeRetrievedUsingName(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(['name' => 'Foo']); self::assertTrue(Artist::getOrCreate($artist->user, 'Foo')->is($artist)); } #[Test] public function newArtistIsCreatedWithName(): void { self::assertNull(Artist::query()->where('name', 'Foo')->first()); self::assertSame('Foo', Artist::getOrCreate(create_user(), 'Foo')->name); } /** @return array<mixed> */ public static function provideEmptyNames(): array { return [ [''], [' '], [null], [false], ]; } #[DataProvider('provideEmptyNames')] #[Test] public function gettingArtistWithEmptyNameReturnsUnknownArtist($name): void { self::assertTrue(Artist::getOrCreate(create_user(), $name)->is_unknown); } #[Test] public function artistsWithNameInUtf16EncodingAreRetrievedCorrectly(): void { $name = File::get(test_path('fixtures/utf16')); $artist = Artist::getOrCreate(create_user(), $name); self::assertTrue(Artist::getOrCreate($artist->user, $name)->is($artist)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Models/AlbumTest.php
tests/Unit/Models/AlbumTest.php
<?php namespace Tests\Unit\Models; use App\Models\Album; use App\Models\Artist; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class AlbumTest extends TestCase { #[Test] public function existingAlbumCanBeRetrievedUsingArtistAndName(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); /** @var Album $album */ $album = Album::factory()->for($artist)->for($artist->user)->create(); self::assertTrue(Album::getOrCreate($artist, $album->name)->is($album)); } #[Test] public function newAlbumIsAutomaticallyCreatedWithUserAndArtistAndName(): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); $name = 'Foo'; self::assertNull(Album::query()->whereBelongsTo($artist)->where('name', $name)->first()); $album = Album::getOrCreate($artist, $name); self::assertSame('Foo', $album->name); self::assertTrue($album->artist->is($artist)); } /** @return array<mixed> */ public static function provideEmptyAlbumNames(): array { return [ [''], [' '], [null], [false], ]; } #[DataProvider('provideEmptyAlbumNames')] #[Test] public function newAlbumWithoutNameIsCreatedAsUnknownAlbum($name): void { /** @var Artist $artist */ $artist = Artist::factory()->create(); $album = Album::getOrCreate($artist, $name); self::assertSame('Unknown Album', $album->name); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Models/SettingTest.php
tests/Unit/Models/SettingTest.php
<?php namespace Tests\Unit\Models; use App\Models\Setting; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class SettingTest extends TestCase { #[Test] public function setKeyValuePair(): void { Setting::set('foo', 'bar'); $this->assertDatabaseHas(Setting::class, [ 'key' => 'foo', 'value' => json_encode('bar'), ]); } #[Test] public function supportAssociativeArray(): void { $settings = [ 'foo' => 'bar', 'baz' => 'qux', ]; Setting::set($settings); $this->assertDatabaseHas(Setting::class, [ 'key' => 'foo', 'value' => json_encode('bar'), ])->assertDatabaseHas(Setting::class, [ 'key' => 'baz', 'value' => json_encode('qux'), ]); } #[Test] public function updateSettings(): void { Setting::set('foo', 'bar'); Setting::set('foo', 'baz'); self::assertSame('baz', Setting::get('foo')); } #[Test] public function getSettings(): void { Setting::factory()->create([ 'key' => 'foo', 'value' => 'bar', ]); self::assertSame('bar', Setting::get('foo')); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Models/SongTest.php
tests/Unit/Models/SongTest.php
<?php namespace Tests\Unit\Models; use App\Models\Genre; use App\Models\Song; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use Tests\TestCase; class SongTest extends TestCase { #[Test] public function retrievedLyricsPreserveTimestamps(): void { /** @var Song $song */ $song = Song::factory()->create(['lyrics' => "[00:00.00]Line 1\n[00:01.00]Line 2\n[00:02.00]Line 3"]); self::assertSame("[00:00.00]Line 1\n[00:01.00]Line 2\n[00:02.00]Line 3", $song->lyrics); self::assertSame("[00:00.00]Line 1\n[00:01.00]Line 2\n[00:02.00]Line 3", $song->getAttributes()['lyrics']); } #[Test] public function syncGenres(): void { /** @var Song $song */ $song = Song::factory()->create(); $song->syncGenres('Pop, Rock'); self::assertCount(2, $song->genres); self::assertEqualsCanonicalizing(['Pop', 'Rock'], $song->genres->pluck('name')->all()); } /** @return array<mixed> */ public static function provideGenreData(): array { return [ ['Rock, Pop', true], ['Pop, Rock', true], ['Rock, Pop ', true], ['Rock', false], ['Jazz, Pop', false], ]; } #[Test] #[DataProvider('provideGenreData')] public function genreEqualsTo(string $target, bool $isEqual): void { /** @var Song $song */ $song = Song::factory() ->hasAttached(Genre::factory()->create(['name' => 'Pop'])) ->hasAttached(Genre::factory()->create(['name' => 'Rock'])) ->create(); self::assertSame($isEqual, $song->genreEqualsTo($target)); } #[Test] public function deletingByChunk(): void { Song::factory(5)->create(); Song::deleteByChunk(Song::query()->get()->modelKeys(), 1); self::assertSame(0, Song::query()->count()); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Pipelines/Encyclopedia/GetArtistWikidataIdUsingMbidTest.php
tests/Unit/Pipelines/Encyclopedia/GetArtistWikidataIdUsingMbidTest.php
<?php namespace Tests\Unit\Pipelines\Encyclopedia; use App\Http\Integrations\MusicBrainz\MusicBrainzConnector; use App\Http\Integrations\MusicBrainz\Requests\GetArtistUrlRelationshipsRequest; use App\Pipelines\Encyclopedia\GetArtistWikidataIdUsingMbid; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\File; use PHPUnit\Framework\Attributes\Test; use Saloon\Http\Faking\MockResponse; use Saloon\Laravel\Facades\Saloon; use Tests\Concerns\TestsPipelines; use Tests\TestCase; use function Tests\test_path; class GetArtistWikidataIdUsingMbidTest extends TestCase { use TestsPipelines; #[Test] public function getWikidataId(): void { $json = File::json(test_path('fixtures/musicbrainz/artist-rel-urls.json')); Saloon::fake([ GetArtistUrlRelationshipsRequest::class => MockResponse::make(body: $json), ]); $mock = self::createNextClosureMock('Q461269'); (new GetArtistWikidataIdUsingMbid(new MusicBrainzConnector()))( 'sample-mbid', static fn ($args) => $mock->next($args) // @phpstan-ignore-line ); Saloon::assertSent(static function (GetArtistUrlRelationshipsRequest $request): bool { self::assertSame(['inc' => 'url-rels'], $request->query()->all()); return true; }); self::assertSame( 'Q461269', Cache::get(cache_key('artist wikidata id from mbid', 'sample-mbid')), ); } #[Test] public function getFromCache(): void { Saloon::fake([]); Cache::put(cache_key('artist wikidata id from mbid', 'sample-mbid'), 'Q461269'); $mock = self::createNextClosureMock('Q461269'); (new GetArtistWikidataIdUsingMbid(new MusicBrainzConnector()))( 'sample-mbid', static fn ($args) => $mock->next($args) // @phpstan-ignore-line ); Saloon::assertNothingSent(); } #[Test] public function justPassOnIfMbidIsNull(): void { Saloon::fake([]); $mock = self::createNextClosureMock(null); (new GetArtistWikidataIdUsingMbid(new MusicBrainzConnector()))( null, static fn ($args) => $mock->next($args) // @phpstan-ignore-line ); Saloon::assertNothingSent(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Pipelines/Encyclopedia/GetAlbumWikidataIdUsingReleaseGroupMbidTest.php
tests/Unit/Pipelines/Encyclopedia/GetAlbumWikidataIdUsingReleaseGroupMbidTest.php
<?php namespace Tests\Unit\Pipelines\Encyclopedia; use App\Http\Integrations\MusicBrainz\MusicBrainzConnector; use App\Http\Integrations\MusicBrainz\Requests\GetReleaseGroupUrlRelationshipsRequest; use App\Pipelines\Encyclopedia\GetAlbumWikidataIdUsingReleaseGroupMbid; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\File; use PHPUnit\Framework\Attributes\Test; use Saloon\Http\Faking\MockResponse; use Saloon\Laravel\Facades\Saloon; use Tests\Concerns\TestsPipelines; use Tests\TestCase; use function Tests\test_path; class GetAlbumWikidataIdUsingReleaseGroupMbidTest extends TestCase { use TestsPipelines; #[Test] public function getWikidataId(): void { $json = File::json(test_path('fixtures/musicbrainz/release-group-rel-urls.json')); Saloon::fake([ GetReleaseGroupUrlRelationshipsRequest::class => MockResponse::make(body: $json), ]); $mock = self::createNextClosureMock('Q1929918'); (new GetAlbumWikidataIdUsingReleaseGroupMbid(new MusicBrainzConnector()))( 'sample-mbid', static fn ($args) => $mock->next($args) // @phpstan-ignore-line ); Saloon::assertSent(static function (GetReleaseGroupUrlRelationshipsRequest $request): bool { self::assertSame(['inc' => 'url-rels'], $request->query()->all()); return true; }); self::assertSame( 'Q1929918', Cache::get(cache_key('album wikidata id from release group mbid', 'sample-mbid')), ); } #[Test] public function getFromCache(): void { Saloon::fake([]); Cache::put(cache_key('album wikidata id from release group mbid', 'sample-mbid'), 'Q1929918'); $mock = self::createNextClosureMock('Q1929918'); (new GetAlbumWikidataIdUsingReleaseGroupMbid(new MusicBrainzConnector()))( 'sample-mbid', static fn ($args) => $mock->next($args) // @phpstan-ignore-line ); Saloon::assertNothingSent(); } #[Test] public function justPassOnIfMbidIsNull(): void { Saloon::fake([]); $mock = self::createNextClosureMock(null); (new GetAlbumWikidataIdUsingReleaseGroupMbid(new MusicBrainzConnector()))( null, static fn ($args) => $mock->next($args) // @phpstan-ignore-line ); Saloon::assertNothingSent(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Pipelines/Encyclopedia/GetWikipediaPageSummaryUsingPageTitleTest.php
tests/Unit/Pipelines/Encyclopedia/GetWikipediaPageSummaryUsingPageTitleTest.php
<?php namespace Tests\Unit\Pipelines\Encyclopedia; use App\Http\Integrations\Wikipedia\Requests\GetPageSummaryRequest; use App\Http\Integrations\Wikipedia\WikipediaConnector; use App\Pipelines\Encyclopedia\GetWikipediaPageSummaryUsingPageTitle; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\File; use PHPUnit\Framework\Attributes\Test; use Saloon\Http\Faking\MockResponse; use Saloon\Laravel\Facades\Saloon; use Tests\Concerns\TestsPipelines; use Tests\TestCase; use function Tests\test_path; class GetWikipediaPageSummaryUsingPageTitleTest extends TestCase { use TestsPipelines; #[Test] public function getPageSummary(): void { $json = File::json(test_path('fixtures/wikipedia/artist-page-summary.json')); Saloon::fake([ GetPageSummaryRequest::class => MockResponse::make(body: $json), ]); $mock = self::createNextClosureMock($json); // we're passing the whole JSON response through the pipeline (new GetWikipediaPageSummaryUsingPageTitle(new WikipediaConnector()))( 'Skid Row (American band)', static fn ($args) => $mock->next($args), // @phpstan-ignore-line ); Saloon::assertSent(static function (GetPageSummaryRequest $request): bool { return $request->resolveEndpoint() === 'page/summary/Skid Row (American band)'; }); self::assertSame( $json, Cache::get(cache_key('wikipedia page summary from page title', 'Skid Row (American band)')), ); } #[Test] public function getFromCache(): void { Saloon::fake([]); Cache::put( cache_key('wikipedia page summary from page title', 'Skid Row (American band)'), ['Spider Man' => 'How’d that get in there?'], ); $mock = self::createNextClosureMock(['Spider Man' => 'How’d that get in there?']); (new GetWikipediaPageSummaryUsingPageTitle(new WikipediaConnector()))( 'Skid Row (American band)', static fn ($args) => $mock->next($args), // @phpstan-ignore-line ); Saloon::assertNothingSent(); } #[Test] public function justPassOnIfPageTitleIsNull(): void { Saloon::fake([]); $mock = self::createNextClosureMock(null); (new GetWikipediaPageSummaryUsingPageTitle(new WikipediaConnector()))( null, static fn ($args) => $mock->next($args), // @phpstan-ignore-line ); Saloon::assertNothingSent(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Unit/Pipelines/Encyclopedia/GetWikipediaPageTitleUsingWikidataIdTest.php
tests/Unit/Pipelines/Encyclopedia/GetWikipediaPageTitleUsingWikidataIdTest.php
<?php namespace Tests\Unit\Pipelines\Encyclopedia; use App\Http\Integrations\Wikidata\Requests\GetEntityDataRequest; use App\Http\Integrations\Wikidata\WikidataConnector; use App\Pipelines\Encyclopedia\GetWikipediaPageTitleUsingWikidataId; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\File; use PHPUnit\Framework\Attributes\Test; use Saloon\Http\Faking\MockResponse; use Saloon\Laravel\Facades\Saloon; use Tests\Concerns\TestsPipelines; use Tests\TestCase; use function Tests\test_path; class GetWikipediaPageTitleUsingWikidataIdTest extends TestCase { use TestsPipelines; #[Test] public function getName(): void { $json = File::json(test_path('fixtures/wikidata/entity.json')); Saloon::fake([ GetEntityDataRequest::class => MockResponse::make(body: $json), ]); $mock = self::createNextClosureMock('Skid Row (American band)'); (new GetWikipediaPageTitleUsingWikidataId(new WikidataConnector()))( 'Q461269', static fn ($args) => $mock->next($args), // @phpstan-ignore-line ); Saloon::assertSent(static function (GetEntityDataRequest $request): bool { return $request->resolveEndpoint() === 'Special:EntityData/Q461269'; }); self::assertSame( 'Skid Row (American band)', Cache::get(cache_key('wikipedia page title from wikidata id', 'Q461269')), ); } #[Test] public function getFromCache(): void { Saloon::fake([]); Cache::put( cache_key('wikipedia page title from wikidata id', 'Q461269'), 'How’d that get in there?' ); $mock = self::createNextClosureMock('How’d that get in there?'); (new GetWikipediaPageTitleUsingWikidataId(new WikidataConnector()))( 'Q461269', static fn ($args) => $mock->next($args), // @phpstan-ignore-line ); Saloon::assertNothingSent(); } #[Test] public function justPassOnIfIdIsNull(): void { Saloon::fake([]); $mock = self::createNextClosureMock(null); (new GetWikipediaPageTitleUsingWikidataId(new WikidataConnector()))( null, static fn ($args) => $mock->next($args), // @phpstan-ignore-line ); Saloon::assertNothingSent(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false