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/app/Pipelines/Encyclopedia/GetMbidForArtist.php | app/Pipelines/Encyclopedia/GetMbidForArtist.php | <?php
namespace App\Pipelines\Encyclopedia;
use App\Http\Integrations\MusicBrainz\MusicBrainzConnector;
use App\Http\Integrations\MusicBrainz\Requests\SearchForArtistRequest;
use Closure;
class GetMbidForArtist
{
use TriesRemember;
public function __construct(private readonly MusicBrainzConnector $connector)
{
}
public function __invoke(?string $name, Closure $next): mixed
{
if (!$name) {
return $next(null);
}
$mbid = $this->tryRememberForever(
key: cache_key('artist mbid', $name),
callback: fn () => $this->connector->send(new SearchForArtistRequest($name))->json('artists.0.id'),
);
return $next($mbid);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Pipelines/Encyclopedia/GetWikipediaPageSummaryUsingPageTitle.php | app/Pipelines/Encyclopedia/GetWikipediaPageSummaryUsingPageTitle.php | <?php
namespace App\Pipelines\Encyclopedia;
use App\Http\Integrations\Wikipedia\Requests\GetPageSummaryRequest;
use App\Http\Integrations\Wikipedia\WikipediaConnector;
use Closure;
class GetWikipediaPageSummaryUsingPageTitle
{
use TriesRemember;
public function __construct(private readonly WikipediaConnector $connector)
{
}
public function __invoke(?string $pageTitle, Closure $next): mixed
{
if (!$pageTitle) {
return $next(null);
}
$summary = $this->tryRemember(
key: cache_key('wikipedia page summary from page title', $pageTitle),
ttl: now()->addMonth(),
callback: fn () => $this->connector
->send(new GetPageSummaryRequest($pageTitle))
->json(),
);
return $next($summary);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Pipelines/Encyclopedia/GetAlbumTracksUsingMbid.php | app/Pipelines/Encyclopedia/GetAlbumTracksUsingMbid.php | <?php
namespace App\Pipelines\Encyclopedia;
use App\Http\Integrations\MusicBrainz\MusicBrainzConnector;
use App\Http\Integrations\MusicBrainz\Requests\GetRecordingsRequest;
use Closure;
use Illuminate\Support\Arr;
class GetAlbumTracksUsingMbid
{
use TriesRemember;
public function __construct(private readonly MusicBrainzConnector $connector)
{
}
public function __invoke(?string $mbid, Closure $next): mixed
{
if (!$mbid) {
return $next(null);
}
$tracks = $this->tryRememberForever(
key: cache_key('album tracks', $mbid),
callback: function () use ($mbid): array {
$tracks = [];
// There can be multiple media entries (e.g. CDs) in a release, each with its own set of tracks.
// To simplify things, we will collect all tracks from all media entries.
foreach ($this->connector->send(new GetRecordingsRequest($mbid))->json('media', []) as $media) {
array_push($tracks, ...Arr::get($media, 'tracks', []));
}
return $tracks;
},
);
return $next($tracks);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Pipelines/Encyclopedia/GetWikipediaPageTitleUsingWikidataId.php | app/Pipelines/Encyclopedia/GetWikipediaPageTitleUsingWikidataId.php | <?php
namespace App\Pipelines\Encyclopedia;
use App\Http\Integrations\Wikidata\Requests\GetEntityDataRequest;
use App\Http\Integrations\Wikidata\WikidataConnector;
use Closure;
class GetWikipediaPageTitleUsingWikidataId
{
use TriesRemember;
public function __construct(private readonly WikidataConnector $connector)
{
}
public function __invoke(?string $wikidataId, Closure $next): mixed
{
if (!$wikidataId) {
return $next(null);
}
$pageTitle = $this->tryRememberForever(
key: cache_key('wikipedia page title from wikidata id', $wikidataId),
callback: fn () => $this->connector
->send(new GetEntityDataRequest($wikidataId))
->json("entities.$wikidataId.sitelinks.enwiki.title"),
);
return $next($pageTitle);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Pipelines/Encyclopedia/GetReleaseAndReleaseGroupMbidsForAlbum.php | app/Pipelines/Encyclopedia/GetReleaseAndReleaseGroupMbidsForAlbum.php | <?php
namespace App\Pipelines\Encyclopedia;
use App\Http\Integrations\MusicBrainz\MusicBrainzConnector;
use App\Http\Integrations\MusicBrainz\Requests\SearchForReleaseRequest;
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
class GetReleaseAndReleaseGroupMbidsForAlbum
{
use TriesRemember;
public function __construct(private readonly MusicBrainzConnector $connector)
{
}
public function __invoke(?array $params, Closure $next): mixed
{
if (!$params) {
return $next(null);
}
$mbids = $this->tryRememberForever(
key: cache_key('release and release group mbids', $params['album'], $params['artist']),
callback: function () use ($params): array {
$response = $this->connector->send(new SearchForReleaseRequest($params['album'], $params['artist']));
// Opportunistically, cache the artist mbids as well.
// Our future requests for artist mbids will be faster this way.
foreach ($response->json('releases.0.artist-credit', []) as $credit) {
Cache::forever(
cache_key('artist mbid', Arr::get($credit, 'artist.name')),
Arr::get($credit, 'artist.id'),
);
}
return [
$response->json('releases.0.id'),
$response->json('releases.0.release-group.id'),
];
},
);
return $next($mbids);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Pipelines/Encyclopedia/TriesRemember.php | app/Pipelines/Encyclopedia/TriesRemember.php | <?php
namespace App\Pipelines\Encyclopedia;
use Closure;
use DateTimeInterface;
use Illuminate\Support\Facades\Cache;
trait TriesRemember
{
private function tryRemember(string $key, DateTimeInterface|int $ttl, Closure $callback): mixed
{
return Cache::has($key)
? Cache::get($key)
: rescue(static fn () => Cache::remember($key, $ttl, $callback));
}
private function tryRememberForever(string $key, Closure $callback): mixed
{
return Cache::has($key)
? Cache::get($key)
: rescue(static fn () => Cache::rememberForever($key, $callback));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Responses/BroadcastableResponse.php | app/Responses/BroadcastableResponse.php | <?php
namespace App\Responses;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\JsonResponse;
/**
* A broadcastable response is a class that can be used to return a JSON response in a standard HTTP lifecycle
* (i.e., from a controller) and can also be broadcasted to a channel in an asynchronous manner.
* Since Koel supports both HTTP and WebSocket communication (via Pusher), this design ensures consistency
* and simplifies the process of sending data to clients as well as for the client to handle the data.
*/
abstract class BroadcastableResponse implements Arrayable, ShouldBroadcast, ShouldDispatchAfterCommit
{
/**
* Transform the object into a JSON response, ready for returning from a controller.
*/
public function toResponse(int $status = 200, array $headers = [], int $options = 0): JsonResponse
{
return response()->json(
data: $this->toArray(),
status: $status,
headers: $headers,
options: $options
);
}
/**
* @return array<mixed>
*/
public function broadcastWith(): array
{
return $this->toArray();
}
abstract public function broadcastAs(): string;
public static function make(...$args): static
{
return new static(...$args);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Responses/SongUploadResponse.php | app/Responses/SongUploadResponse.php | <?php
namespace App\Responses;
use App\Http\Resources\AlbumResource;
use App\Http\Resources\SongResource;
use App\Models\Album;
use App\Models\Song;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
class SongUploadResponse extends BroadcastableResponse
{
protected function __construct(private readonly Song $song, private readonly Album $album)
{
}
public function broadcastOn(): Channel|string
{
return new PrivateChannel("user.{$this->song->owner->public_id}");
}
public function broadcastAs(): string
{
return 'song.uploaded';
}
/** @inheritdoc */
public function toArray(): array
{
return [
'song' => SongResource::make($this->song)->for($this->song->owner),
'album' => AlbumResource::make($this->album)->for($this->album->user),
];
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Events/NewPlaylistCollaboratorJoined.php | app/Events/NewPlaylistCollaboratorJoined.php | <?php
namespace App\Events;
use App\Models\PlaylistCollaborationToken;
use App\Models\User;
class NewPlaylistCollaboratorJoined extends Event
{
public function __construct(public User $collaborator, public PlaylistCollaborationToken $token)
{
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Events/LibraryChanged.php | app/Events/LibraryChanged.php | <?php
namespace App\Events;
class LibraryChanged extends Event
{
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Events/MultipleSongsLiked.php | app/Events/MultipleSongsLiked.php | <?php
namespace App\Events;
use App\Models\Song;
use App\Models\User;
use Illuminate\Support\Collection;
class MultipleSongsLiked extends Event
{
/**
* @param Collection<Song> $songs
*/
public function __construct(public readonly Collection $songs, public readonly User $user)
{
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Events/MediaScanCompleted.php | app/Events/MediaScanCompleted.php | <?php
namespace App\Events;
use App\Values\Scanning\ScanResultCollection;
class MediaScanCompleted extends Event
{
public function __construct(public ScanResultCollection $results)
{
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Events/MultipleSongsUnliked.php | app/Events/MultipleSongsUnliked.php | <?php
namespace App\Events;
use App\Models\Song;
use App\Models\User;
use Illuminate\Support\Collection;
class MultipleSongsUnliked extends Event
{
/**
* @param Collection<Song> $songs
*/
public function __construct(public readonly Collection $songs, public readonly User $user)
{
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Events/Event.php | app/Events/Event.php | <?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Queue\SerializesModels;
abstract class Event implements ShouldBroadcast, ShouldDispatchAfterCommit
{
use SerializesModels;
public function broadcastOn(): array|Channel|null
{
return [];
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Events/PlaybackStarted.php | app/Events/PlaybackStarted.php | <?php
namespace App\Events;
use App\Models\Song;
use App\Models\User;
class PlaybackStarted extends Event
{
public function __construct(public Song $song, public User $user)
{
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Events/SongFavoriteToggled.php | app/Events/SongFavoriteToggled.php | <?php
namespace App\Events;
use App\Models\Song;
use App\Models\User;
class SongFavoriteToggled extends Event
{
public function __construct(public readonly Song $song, public bool $favorite, public readonly User $user)
{
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Events/UserUnsubscribedFromPodcast.php | app/Events/UserUnsubscribedFromPodcast.php | <?php
namespace App\Events;
use App\Models\Podcast;
use App\Models\User;
class UserUnsubscribedFromPodcast extends Event
{
public function __construct(public readonly User $user, public readonly Podcast $podcast)
{
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/PlaylistFolderPolicy.php | app/Policies/PlaylistFolderPolicy.php | <?php
namespace App\Policies;
use App\Models\PlaylistFolder;
use App\Models\User;
class PlaylistFolderPolicy
{
public function own(User $user, PlaylistFolder $folder): bool
{
return $folder->ownedBy($user);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/LicensePolicy.php | app/Policies/LicensePolicy.php | <?php
namespace App\Policies;
use App\Enums\Acl\Permission;
use App\Facades\License;
use App\Models\User;
class LicensePolicy
{
public function activate(User $user): bool
{
return $user->hasPermissionTo(Permission::MANAGE_SETTINGS) && License::isCommunity();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/FolderPolicy.php | app/Policies/FolderPolicy.php | <?php
namespace App\Policies;
use App\Models\Folder;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class FolderPolicy
{
public function browse(User $user, Folder $folder): Response
{
// We simply deny access if the folder is an upload folder and the user is not the uploader.
return $folder->browsableBy($user)
? Response::allow()
: Response::deny('You do not have permission to browse this folder.');
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/UserPolicy.php | app/Policies/UserPolicy.php | <?php
namespace App\Policies;
use App\Enums\Acl\Permission;
use App\Facades\License;
use App\Models\User;
class UserPolicy
{
public function manage(User $currentUser): bool
{
return $currentUser->hasPermissionTo(Permission::MANAGE_USERS);
}
public function update(User $currentUser, User $userToUpdate): bool
{
return $currentUser->hasPermissionTo(Permission::MANAGE_USERS)
&& $currentUser->canManage($userToUpdate);
}
public function destroy(User $currentUser, User $userToDestroy): bool
{
return $currentUser->hasPermissionTo(Permission::MANAGE_USERS)
&& $userToDestroy->isNot($currentUser)
&& $currentUser->canManage($userToDestroy);
}
public function upload(User $currentUser): bool
{
return License::isCommunity()
? $currentUser->hasPermissionTo(Permission::MANAGE_SONGS)
: true; // For Plus Edition, any user can upload songs (to their own library).
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/SongPolicy.php | app/Policies/SongPolicy.php | <?php
namespace App\Policies;
use App\Enums\Acl\Permission;
use App\Facades\License;
use App\Models\Song;
use App\Models\User;
class SongPolicy
{
public function access(User $user, Song $song): bool
{
return License::isCommunity() || $song->accessibleBy($user);
}
public function own(User $user, Song $song): bool
{
return $song->ownedBy($user);
}
public function delete(User $user, Song $song): bool
{
return License::isCommunity()
? $user->hasPermissionTo(Permission::MANAGE_SONGS)
: $song->ownedBy($user);
}
public function edit(User $user, Song $song): bool
{
return License::isCommunity()
? $user->hasPermissionTo(Permission::MANAGE_SONGS)
: $song->accessibleBy($user);
}
public function download(User $user, Song $song): bool
{
return $this->access($user, $song);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/AlbumPolicy.php | app/Policies/AlbumPolicy.php | <?php
namespace App\Policies;
use App\Enums\Acl\Permission;
use App\Facades\License;
use App\Models\Album;
use App\Models\User;
class AlbumPolicy
{
public function access(User $user, Album $album): bool
{
return License::isCommunity() || $album->belongsToUser($user);
}
/**
* If the user can update the album (e.g., edit name, year, or upload the cover image).
*/
public function update(User $user, Album $album): bool
{
// Unknown albums are not editable.
if ($album->is_unknown) {
return false;
}
// For CE, if the user can manage songs, they can update any album.
if ($user->hasPermissionTo(Permission::MANAGE_SONGS) && License::isCommunity()) {
return true;
}
// For Plus, only the owner of the album can update it.
return $album->belongsToUser($user) && License::isPlus();
}
public function edit(User $user, Album $album): bool
{
return $this->update($user, $album);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/PlaylistPolicy.php | app/Policies/PlaylistPolicy.php | <?php
namespace App\Policies;
use App\Facades\License;
use App\Models\Playlist;
use App\Models\User;
class PlaylistPolicy
{
public function access(User $user, Playlist $playlist): bool
{
return $this->own($user, $playlist) || $playlist->hasCollaborator($user);
}
public function own(User $user, Playlist $playlist): bool
{
return $playlist->ownedBy($user);
}
public function download(User $user, Playlist $playlist): bool
{
return $this->access($user, $playlist);
}
public function inviteCollaborators(User $user, Playlist $playlist): bool
{
return License::isPlus() && $this->own($user, $playlist) && !$playlist->is_smart;
}
public function collaborate(User $user, Playlist $playlist): bool
{
return $this->own($user, $playlist) || $playlist->hasCollaborator($user);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/PodcastPolicy.php | app/Policies/PodcastPolicy.php | <?php
namespace App\Policies;
use App\Models\Podcast;
use App\Models\User;
class PodcastPolicy
{
public function access(User $user, Podcast $podcast): bool
{
return $user->subscribedToPodcast($podcast);
}
public function view(User $user, Podcast $podcast): bool
{
return $user->subscribedToPodcast($podcast);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/ArtistPolicy.php | app/Policies/ArtistPolicy.php | <?php
namespace App\Policies;
use App\Enums\Acl\Permission;
use App\Facades\License;
use App\Models\Artist;
use App\Models\User;
class ArtistPolicy
{
public function access(User $user, Artist $artist): bool
{
return License::isCommunity() || $artist->belongsToUser($user);
}
public function update(User $user, Artist $artist): bool
{
if ($artist->is_unknown || $artist->is_various) {
return false;
}
// For CE, if the user can manage songs, they can update any artist.
if ($user->hasPermissionTo(Permission::MANAGE_SONGS) && License::isCommunity()) {
return true;
}
// For Plus, only the owner of the artist can update it.
return $artist->belongsToUser($user) && License::isPlus();
}
public function edit(User $user, Artist $artist): bool
{
return $this->update($user, $artist);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/ThemePolicy.php | app/Policies/ThemePolicy.php | <?php
namespace App\Policies;
use App\Models\Theme;
use App\Models\User;
class ThemePolicy
{
public function own(User $user, Theme $theme): bool
{
return $user->id === $theme->user_id;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Policies/RadioStationPolicy.php | app/Policies/RadioStationPolicy.php | <?php
namespace App\Policies;
use App\Enums\Acl\Permission;
use App\Models\RadioStation;
use App\Models\User;
class RadioStationPolicy
{
public function access(User $user, RadioStation $station): bool
{
return $station->user_id === $user->id || $station->is_public;
}
public function edit(User $user, RadioStation $station): bool
{
// For radio stations, if the user has the permission, they can update any station.
// This is regardless of the license type (unlike artists or albums).
if (
$user->hasPermissionTo(Permission::MANAGE_RADIO_STATIONS)
&& $user->organization_id === $station->user->organization_id
) {
return true;
}
return $station->user_id === $user->id;
}
public function update(User $user, RadioStation $station): bool
{
// The update policy is the same as edit for radio stations.
return $this->edit($user, $station);
}
public function delete(User $user, RadioStation $station): bool
{
// The delete policy is the same as edit for radio stations.
return $this->update($user, $station);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/bootstrap/app.php | bootstrap/app.php | <?php
use App\Http\Middleware\AudioAuthenticate;
use App\Http\Middleware\ForceHttps;
use App\Http\Middleware\HandleDemoMode;
use App\Http\Middleware\ObjectStorageAuthenticate;
use App\Http\Middleware\RestrictPlusFeatures;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
using: static function (): void {
RouteServiceProvider::loadVersionAwareRoutes('web');
RouteServiceProvider::loadVersionAwareRoutes('api');
},
commands: __DIR__ . '/../routes/console.php',
channels: __DIR__ . '/../routes/channels.php',
health: '/up',
)
->withMiddleware(static function (Middleware $middleware): void {
$middleware->api(append: [
RestrictPlusFeatures::class,
HandleDemoMode::class,
ForceHttps::class,
]);
$middleware->web(append: [
RestrictPlusFeatures::class,
HandleDemoMode::class,
ForceHttps::class,
]);
$middleware->alias([
'audio.auth' => AudioAuthenticate::class,
'os.auth' => ObjectStorageAuthenticate::class,
]);
})
->withExceptions(static function (Exceptions $exceptions): void {
$exceptions->render(
static function (AuthenticationException $e, Request $request): JsonResponse|RedirectResponse {
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('/');
}
);
})->create();
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/bootstrap/autoload.php | bootstrap/autoload.php | <?php
/*
|--------------------------------------------------------------------------
| Register The Composer Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__ . '/../vendor/autoload.php';
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/bootstrap/providers.php | bootstrap/providers.php | <?php
use App\Providers\AppServiceProvider;
use App\Providers\AuthServiceProvider;
use App\Providers\BroadcastServiceProvider;
use App\Providers\DownloadServiceProvider;
use App\Providers\EventServiceProvider;
use App\Providers\ITunesServiceProvider;
use App\Providers\LicenseServiceProvider;
use App\Providers\MacroProvider;
use App\Providers\ObjectStorageServiceProvider;
use App\Providers\SongStorageServiceProvider;
use App\Providers\StreamerServiceProvider;
use App\Providers\UtilServiceProvider;
use App\Providers\YouTubeServiceProvider;
use Intervention\Image\ImageServiceProvider;
use Jackiedo\DotenvEditor\DotenvEditorServiceProvider;
use Laravel\Scout\ScoutServiceProvider;
use OwenIt\Auditing\AuditingServiceProvider;
use TeamTNT\Scout\TNTSearchScoutServiceProvider;
return [
DotenvEditorServiceProvider::class,
ImageServiceProvider::class,
ScoutServiceProvider::class,
AuditingServiceProvider::class,
TNTSearchScoutServiceProvider::class,
AppServiceProvider::class,
AuthServiceProvider::class,
EventServiceProvider::class,
UtilServiceProvider::class,
YouTubeServiceProvider::class,
DownloadServiceProvider::class,
BroadcastServiceProvider::class,
ITunesServiceProvider::class,
StreamerServiceProvider::class,
SongStorageServiceProvider::class,
ObjectStorageServiceProvider::class,
MacroProvider::class,
LicenseServiceProvider::class,
];
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/TestCase.php | tests/TestCase.php | <?php
namespace Tests;
use App\Facades\License;
use App\Helpers\Ulid;
use App\Helpers\Uuid;
use App\Models\Album;
use App\Services\License\CommunityLicenseService;
use App\Services\MediaBrowser;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\Testing\LazilyRefreshDatabase;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\File;
use Tests\Concerns\AssertsArraySubset;
use Tests\Concerns\CreatesApplication;
use Tests\Concerns\MakesHttpRequests;
abstract class TestCase extends BaseTestCase
{
use AssertsArraySubset;
use CreatesApplication;
use LazilyRefreshDatabase;
use MakesHttpRequests;
/**
* @var Filesystem The backup of the real filesystem instance, to restore after tests.
* This is necessary because we might be mocking the File facade in tests, and at the same time
* we delete test resources during suite's teardown.
*/
private Filesystem $fileSystem;
public function setUp(): void
{
parent::setUp();
License::swap($this->app->make(CommunityLicenseService::class));
$this->fileSystem = File::getFacadeRoot();
// During the Album's `saved` event, we attempt to generate a thumbnail by dispatching a job.
// Disable this to avoid noise and side effects.
Album::getEventDispatcher()?->forget('eloquent.saved: ' . Album::class);
self::createSandbox();
}
protected function tearDown(): void
{
File::swap($this->fileSystem);
self::destroySandbox();
MediaBrowser::clearCache();
Ulid::unfreeze();
Uuid::unfreeze();
parent::tearDown();
}
private static function createSandbox(): void
{
config([
'koel.image_storage_dir' => 'sandbox/img/storage/',
'koel.artifacts_path' => public_path('sandbox/artifacts/'),
]);
File::ensureDirectoryExists(public_path(config('koel.image_storage_dir')));
File::ensureDirectoryExists(public_path('sandbox/media/'));
}
private static function destroySandbox(): void
{
File::deleteDirectory(public_path('sandbox'));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Helpers.php | tests/Helpers.php | <?php
namespace Tests;
use App\Models\Playlist;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\File;
function create_user(array $attributes = []): User
{
return User::factory()->create($attributes);
}
function create_admin(array $attributes = []): User
{
return User::factory()->admin()->create($attributes);
}
function create_manager(array $attributes = []): User
{
return User::factory()->manager()->create($attributes);
}
function create_user_prospect(array $attributes = []): User
{
return User::factory()->prospect()->create($attributes);
}
function test_path(string $path = ''): string
{
return base_path('tests' . DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR));
}
function read_as_data_url(string $path): string
{
return 'data:' . mime_content_type($path) . ';base64,' . base64_encode(File::get($path));
}
function create_playlist(array $attributes = [], bool $smart = false): Playlist
{
return $smart
? Playlist::factory()->smart()->create($attributes)
: Playlist::factory()->create($attributes);
}
/**
* @return Collection<Playlist>|array<array-key, Playlist>
*/
function create_playlists(int $count, array $attributes = [], ?User $owner = null): Collection
{
return Playlist::factory()
->count($count)
->create($attributes)
->when($owner, static function (Collection $playlists) use ($owner): void {
$playlists->each(static function (Playlist $p) use ($owner): void {
$p->users()->detach();
$p->users()->attach($owner, ['role' => 'owner']);
});
});
}
/**
* A minimal base64 encoded image that's still valid binary data and can be used
* in tests that involve reading/writing image files.
*/
function minimal_base64_encoded_image(): string
{
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII'; // @phpcs:ignore
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/PlusTestCase.php | tests/PlusTestCase.php | <?php
namespace Tests;
use App\Facades\License;
use Tests\Fakes\FakePlusLicenseService;
use Tests\TestCase as BaseTestCase;
class PlusTestCase extends BaseTestCase
{
public static function enablePlusLicense(): void
{
License::swap(app(FakePlusLicenseService::class));
}
public function setUp(): void
{
parent::setUp();
self::enablePlusLicense();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/TicketmasterServiceTest.php | tests/Integration/TicketmasterServiceTest.php | <?php
namespace Tests\Integration;
use App\Http\Integrations\IPinfo\Requests\GetLiteDataRequest;
use App\Http\Integrations\Ticketmaster\Requests\AttractionSearchRequest;
use App\Http\Integrations\Ticketmaster\Requests\EventSearchRequest;
use App\Models\Artist;
use App\Services\TicketmasterService;
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\Http\PendingRequest;
use Saloon\Laravel\Facades\Saloon;
use Tests\TestCase;
use function Tests\test_path;
class TicketmasterServiceTest extends TestCase
{
private TicketmasterService $service;
public function setUp(): void
{
parent::setUp();
config(['koel.services.ticketmaster.key' => 'tm-key']);
config(['koel.services.ipinfo.token' => 'ipinfo-token']);
$this->service = app(TicketmasterService::class);
}
#[Test]
public function searchEventForArtist(): void
{
Saloon::fake([
AttractionSearchRequest::class => static function (PendingRequest $request) {
self::assertEqualsCanonicalizing([
'keyword' => 'Slayer',
'size' => 5,
'classificationName' => ['Music'],
'apikey' => 'tm-key',
], $request->query()->all());
$attractionSearchJson = File::json(test_path('fixtures/ticketmaster/attraction-search.json'));
return MockResponse::make(body: $attractionSearchJson);
},
EventSearchRequest::class => static function (PendingRequest $request) {
self::assertEqualsCanonicalizing([
'attractionId' => 'slayer-id-1234567890',
'countryCode' => 'DE',
'classificationName' => ['Music'],
'apikey' => 'tm-key',
], $request->query()->all());
$eventSearchJson = File::json(test_path('fixtures/ticketmaster/event-search.json'));
return MockResponse::make(body: $eventSearchJson);
},
GetLiteDataRequest::class => static function (PendingRequest $request) {
self::assertSame('https://api.ipinfo.io/lite/84.124.22.13', $request->getUrl());
self::assertSame('ipinfo-token', $request->query()->get('token'));
$liteDataJson = File::json(test_path('fixtures/ipinfo/lite-data.json'));
return MockResponse::make(body: $liteDataJson);
},
]);
/** @var Artist $artist */
$artist = Artist::factory()->create([
'name' => 'Slayer',
]);
$events = $this->service->searchEventForArtist($artist->name, '84.124.22.13');
self::assertCount(2, $events);
}
#[Test]
public function searchEventsCached(): 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',
),
);
$events = collect([$event]);
Cache::put(cache_key('Ticketmaster events', 'Coolio', 'BR'), $events, now()->addDay());
Cache::put(cache_key('IP to country code', '84.124.22.13'), 'BR', now()->addDay());
self::assertSame($events, $this->service->searchEventForArtist('Coolio', '84.124.22.13'));
Saloon::assertNothingSent();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Values/EpisodePlayableTest.php | tests/Integration/Values/EpisodePlayableTest.php | <?php
namespace Tests\Integration\Values;
use App\Models\Song;
use App\Values\Podcast\EpisodePlayable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class EpisodePlayableTest extends TestCase
{
#[Test]
public function createAndRetrieved(): void
{
Http::fake([
'https://example.com/episode.mp3' => Http::response('foo'),
]);
/** @var Song $episode */
$episode = Song::factory()->asEpisode()->create([
'path' => 'https://example.com/episode.mp3',
]);
$playable = EpisodePlayable::getForEpisode($episode);
Http::assertSentCount(1);
self::assertSame('acbd18db4cc2f85cedef654fccc4a4d8', $playable->checksum);
self::assertTrue(Cache::has("episode-playable.{$episode->id}"));
$retrieved = EpisodePlayable::getForEpisode($episode);
// No extra HTTP request should be made.
Http::assertSentCount(1);
self::assertSame($playable, $retrieved);
self::assertTrue($retrieved->valid());
file_put_contents($playable->path, 'bar');
self::assertFalse($retrieved->valid());
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Casts/UserPreferencesCastTest.php | tests/Integration/Casts/UserPreferencesCastTest.php | <?php
namespace Tests\Integration\Casts;
use App\Values\User\UserPreferences;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
class UserPreferencesCastTest extends TestCase
{
#[Test]
public function cast(): void
{
$user = create_user([
'preferences' => [
'lastfm_session_key' => 'foo',
],
]);
self::assertInstanceOf(UserPreferences::class, $user->preferences);
self::assertSame('foo', $user->preferences->lastFmSessionKey);
$user->preferences->lastFmSessionKey = 'bar';
$user->save();
self::assertSame('bar', $user->refresh()->preferences->lastFmSessionKey);
$user->preferences->lastFmSessionKey = null;
$user->save();
self::assertNull($user->refresh()->preferences->lastFmSessionKey);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Listeners/DeleteNonExistingRecordsPostSyncTest.php | tests/Integration/Listeners/DeleteNonExistingRecordsPostSyncTest.php | <?php
namespace Tests\Integration\Listeners;
use App\Enums\SongStorageType;
use App\Events\MediaScanCompleted;
use App\Listeners\DeleteNonExistingRecordsPostScan;
use App\Models\Song;
use App\Values\Scanning\ScanResult;
use App\Values\Scanning\ScanResultCollection;
use Illuminate\Database\Eloquent\Collection;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class DeleteNonExistingRecordsPostSyncTest extends TestCase
{
private DeleteNonExistingRecordsPostScan $listener;
public function setUp(): void
{
parent::setUp();
$this->listener = app(DeleteNonExistingRecordsPostScan::class);
}
#[Test]
public function handleDoesNotDeleteCloudEntries(): void
{
collect(SongStorageType::cases())
->filter(static fn ($type) => $type !== SongStorageType::LOCAL)
->each(function ($type): void {
$song = Song::factory()->create(['storage' => $type]);
$this->listener->handle(new MediaScanCompleted(ScanResultCollection::create()));
$this->assertModelExists($song);
});
}
#[Test]
public function handleDoesNotDeleteEpisodes(): void
{
$episode = Song::factory()->asEpisode()->create();
$this->listener->handle(new MediaScanCompleted(ScanResultCollection::create()));
$this->assertModelExists($episode);
}
#[Test]
public function handle(): void
{
/** @var Collection|array<array-key, Song> $songs */
$songs = Song::factory(4)->create();
self::assertCount(4, Song::all());
$syncResult = ScanResultCollection::create();
$syncResult->add(ScanResult::success($songs[0]->path));
$syncResult->add(ScanResult::skipped($songs[3]->path));
$this->listener->handle(new MediaScanCompleted($syncResult));
$this->assertModelExists($songs[0]);
$this->assertModelExists($songs[3]);
$this->assertModelMissing($songs[1]);
$this->assertModelMissing($songs[2]);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Observers/AlbumObserverTest.php | tests/Integration/Observers/AlbumObserverTest.php | <?php
namespace Tests\Integration\Observers;
use App\Facades\Dispatcher;
use App\Jobs\GenerateAlbumThumbnailJob;
use App\Models\Album;
use App\Observers\AlbumObserver;
use Mockery;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class AlbumObserverTest extends TestCase
{
#[Test]
public function dispatchJobToGenerateThumbnailUponCreation(): void
{
Dispatcher::expects('dispatch')->once()->with(Mockery::type(GenerateAlbumThumbnailJob::class));
self::restoreObserver();
Album::factory()->create();
}
#[Test]
public function dispatchJobToGenerateThumbnailUponUpdate(): void
{
Dispatcher::expects('dispatch')->once()->with(Mockery::type(GenerateAlbumThumbnailJob::class));
/** @var Album $album */
$album = Album::factory()->create();
self::restoreObserver();
$album->cover = 'new-cover.webp';
$album->save();
}
#[Test]
public function doNotDispatchJobToGenerateThumbnailIfCoverIsEmpty(): void
{
Dispatcher::expects('dispatch')->never();
/** @var Album $album */
$album = Album::factory()->create();
self::restoreObserver();
$album->cover = '';
$album->save();
// create another album to ensure the observer is still not triggered
Album::factory()->create(['cover' => '']);
}
private static function restoreObserver(): void
{
// restore the observer, as it's been "forgotten" during the parent setup
Album::observe(AlbumObserver::class);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/SettingServiceTest.php | tests/Integration/Services/SettingServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Models\Setting;
use App\Services\SettingService;
use App\Values\Branding;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class SettingServiceTest extends TestCase
{
private SettingService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(SettingService::class);
}
#[Test]
public function getBrandingForCommunityEdition(): void
{
$assert = function (): void {
$branding = $this->service->getBranding();
self::assertSame('Koel', $branding->name);
self::assertNull($branding->logo);
self::assertNull($branding->cover);
};
$assert();
Setting::set('branding', Branding::make(
name: 'Test Branding',
logo: 'test-logo.png',
cover: 'test-cover.png',
));
$assert();
}
#[Test]
public function updateMediaPath(): void
{
$this->service->updateMediaPath('/foo/bar/');
self::assertSame('/foo/bar', Setting::get('media_path'));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/SmartPlaylistServiceTest.php | tests/Integration/Services/SmartPlaylistServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Helpers\Uuid;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Genre;
use App\Models\Interaction;
use App\Models\Song;
use App\Models\User;
use App\Services\SmartPlaylistService;
use Illuminate\Database\Eloquent\Collection;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_playlist;
use function Tests\create_user;
class SmartPlaylistServiceTest extends TestCase
{
private SmartPlaylistService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(SmartPlaylistService::class);
}
#[Test]
public function titleIs(): void
{
$matches = Song::factory()->count(1)->create(['title' => 'Foo Something']);
Song::factory()->create(['title' => 'Bar Something']);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'title',
'operator' => 'is',
'value' => ['Foo Something'],
],
],
],
]);
}
#[Test]
public function titleIsNot(): void
{
$matches = Song::factory()->count(1)->create(['title' => 'Foo Something']);
Song::factory()->create(['title' => 'Bar Something']);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'title',
'operator' => 'isNot',
'value' => ['Bar Something'],
],
],
],
]);
}
#[Test]
public function titleContains(): void
{
$matches = Song::factory()->count(1)->create(['title' => 'Foo Something']);
Song::factory()->create(['title' => 'Foo Nothing']);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'title',
'operator' => 'contains',
'value' => ['Some'],
],
],
],
]);
}
#[Test]
public function titleDoesNotContain(): void
{
$matches = Song::factory()->count(1)->create(['title' => 'Foo Something']);
Song::factory()->create(['title' => 'Foo Nothing']);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'title',
'operator' => 'notContain',
'value' => ['Nothing'],
],
],
],
]);
}
#[Test]
public function titleBeginsWith(): void
{
$matches = Song::factory()->count(1)->create(['title' => 'Foo Something']);
Song::factory()->create(['title' => 'Bar Something']);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'title',
'operator' => 'beginsWith',
'value' => ['Foo'],
],
],
],
]);
}
#[Test]
public function titleEndsWith(): void
{
$matches = Song::factory()->count(1)->create(['title' => 'Foo Something']);
Song::factory()->create(['title' => 'Foo Nothing']);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'title',
'operator' => 'endsWith',
'value' => ['Something'],
],
],
],
]);
}
#[Test]
public function albumIs(): void
{
$album = Album::factory()->create(['name' => 'Foo Album']);
$matches = Song::factory()->count(1)->for($album)->create();
Song::factory()->create();
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'album.name',
'operator' => 'is',
'value' => ['Foo Album'],
],
],
],
]);
}
#[Test]
public function artistIs(): void
{
$matches = Song::factory()
->count(1)
->for(Artist::factory()->create(['name' => 'Foo Artist']))
->create([
'artist_name' => 'Foo Artist',
]);
Song::factory()->create();
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'artist.name',
'operator' => 'is',
'value' => ['Foo Artist'],
],
],
],
]);
}
#[Test]
public function genreIs(): void
{
$genre = Genre::factory()->create(['name' => 'Foo Genre']);
$matches = Song::factory()->count(1)->hasAttached($genre)->create();
Song::factory()->create();
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'genre',
'operator' => 'is',
'value' => ['Foo Genre'],
],
],
],
]);
}
#[Test]
public function genreIsNot(): void
{
$genre = Genre::factory()->create(['name' => 'Foo Genre']);
$matches = Song::factory()->count(1)->create();
Song::factory()->hasAttached($genre)->create();
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'genre',
'operator' => 'isNot',
'value' => ['Foo Genre'],
],
],
],
]);
}
#[Test]
public function yearIsGreaterThan(): void
{
$matches = Song::factory()->count(1)->create(['year' => 2030])
->merge(Song::factory()->count(1)->create(['year' => 2022]));
Song::factory()->create(['year' => 2020]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'year',
'operator' => 'isGreaterThan',
'value' => [2021],
],
],
],
]);
}
#[Test]
public function yearIsLessThan(): void
{
$matches = Song::factory()->count(1)->create(['year' => 1980])
->merge(Song::factory()->count(1)->create(['year' => 1978]));
Song::factory()->create(['year' => 1991]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'year',
'operator' => 'isLessThan',
'value' => [1981],
],
],
],
]);
}
#[Test]
public function yearIsBetween(): void
{
$matches = Song::factory()->count(1)->create(['year' => 1980])
->merge(Song::factory()->count(1)->create(['year' => 1978]));
Song::factory()->create(['year' => 1991]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'year',
'operator' => 'isBetween',
'value' => [1970, 1985],
],
],
],
]);
}
#[Test]
public function playCountIsGreaterThan(): void
{
$user = create_user();
$matches = Song::factory()->count(1)->create();
$notMatch = Song::factory()->create();
Interaction::factory()
->for($matches[0])
->for($user)
->create(['play_count' => 1000]);
Interaction::factory()
->for($user)
->for($notMatch)
->create(['play_count' => 500]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'interactions.play_count',
'operator' => 'isGreaterThan',
'value' => [999],
],
],
],
], $user);
}
#[Test]
public function lastPlayedAtIsInLast(): void
{
$user = create_user();
$matches = Song::factory()->count(1)->create();
$notMatch = Song::factory()->create();
Interaction::factory()
->for($matches[0])
->for($user)
->create(['last_played_at' => now()->subDays(2)]);
Interaction::factory()
->for($user)
->for($notMatch)
->create(['last_played_at' => now()->subDays(4)]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'interactions.last_played_at',
'operator' => 'inLast',
'value' => [3],
],
],
],
], $user);
}
#[Test]
public function lastPlayedNotInLast(): void
{
$user = create_user();
$matches = Song::factory()->count(1)->create();
$notMatch = Song::factory()->create();
Interaction::factory()
->for($matches[0])
->for($user)
->create(['last_played_at' => now()->subDays(3)]);
Interaction::factory()
->for($user)
->for($notMatch)
->create(['last_played_at' => now()->subDays(2)]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'interactions.last_played_at',
'operator' => 'notInLast',
'value' => [2],
],
],
],
], $user);
}
#[Test]
public function lastPlayedIs(): void
{
$user = create_user();
$matches = Song::factory()->count(1)->create();
$notMatch = Song::factory()->create();
Interaction::factory()
->for($matches[0])
->for($user)
->create(['last_played_at' => now()]);
Interaction::factory()
->for($user)
->for($notMatch)
->create(['last_played_at' => now()->subDays(4)]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'interactions.last_played_at',
'operator' => 'is',
'value' => [now()->format('Y-m-d')],
],
],
],
], $user);
}
#[Test]
public function lengthIsGreaterThan(): void
{
$matches = Song::factory()->count(1)->create(['length' => 300])
->merge(Song::factory()->count(1)->create(['length' => 200]));
Song::factory()->count(1)->create(['length' => 100]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'length',
'operator' => 'isGreaterThan',
'value' => [199],
],
],
],
]);
}
#[Test]
public function lengthIsInBetween(): void
{
$matches = Song::factory()->count(1)->create(['length' => 300])
->merge(Song::factory()->count(1)->create(['length' => 200]));
Song::factory()->count(1)->create(['length' => 100]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'length',
'operator' => 'isBetween',
'value' => [199, 301],
],
],
],
]);
}
#[Test]
public function dateAddedInLast(): void
{
$matches = Song::factory()->count(1)->create(['created_at' => now()->subDay()])
->merge(Song::factory()->count(1)->create(['created_at' => today()]));
Song::factory()->count(1)->create(['created_at' => now()->subDays(4)]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'created_at',
'operator' => 'inLast',
'value' => [3],
],
],
],
]);
}
#[Test]
public function dateAddedNotInLast(): void
{
$matches = Song::factory()->count(1)->create(['created_at' => now()->subDays(4)])
->merge(Song::factory()->count(1)->create(['created_at' => now()->subDays(5)]));
Song::factory()->create(['created_at' => now()->subDays(2)]);
$this->assertMatchesAgainstRules($matches, [
[
'id' => Uuid::generate(),
'rules' => [
[
'id' => Uuid::generate(),
'model' => 'created_at',
'operator' => 'notInLast',
'value' => [3],
],
],
],
]);
}
protected function assertMatchesAgainstRules(Collection $matches, array $rules, ?User $owner = null): void
{
$playlist = create_playlist(['rules' => $rules]);
if ($owner) {
$playlist->users()->detach();
$playlist->users()->attach($owner, ['role' => 'owner']);
}
self::assertEqualsCanonicalizing(
$matches->modelKeys(),
$this->service->getSongs($playlist, $playlist->owner)->modelKeys()
);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/MusicBrainzServiceTest.php | tests/Integration/Services/MusicBrainzServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Models\Album;
use App\Models\Artist;
use App\Pipelines\Encyclopedia\GetAlbumTracksUsingMbid;
use App\Pipelines\Encyclopedia\GetAlbumWikidataIdUsingReleaseGroupMbid;
use App\Pipelines\Encyclopedia\GetArtistWikidataIdUsingMbid;
use App\Pipelines\Encyclopedia\GetMbidForArtist;
use App\Pipelines\Encyclopedia\GetReleaseAndReleaseGroupMbidsForAlbum;
use App\Pipelines\Encyclopedia\GetWikipediaPageSummaryUsingPageTitle;
use App\Pipelines\Encyclopedia\GetWikipediaPageTitleUsingWikidataId;
use App\Services\MusicBrainzService;
use App\Values\Album\AlbumInformation;
use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use Mockery;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use Throwable;
use function Tests\create_user;
use function Tests\test_path;
class MusicBrainzServiceTest extends TestCase
{
private MusicBrainzService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(MusicBrainzService::class);
}
private function mockPipelinePipe(string $class, mixed $input, mixed $output): void
{
$expectation = $this->mock($class)
->expects('__invoke')
->with($input, Mockery::on(static fn ($next) => is_callable($next)));
if ($output instanceof Throwable) {
$expectation->andThrow($output);
} else {
$expectation->andReturnUsing(static fn ($_, $next) => $next($output));
}
}
#[Test]
public function getArtistInformation(): void
{
$this->mockPipelinePipe(GetMbidForArtist::class, 'Skid Row', 'sample-mbid');
$this->mockPipelinePipe(GetArtistWikidataIdUsingMbid::class, 'sample-mbid', 'Q123456');
$this->mockPipelinePipe(GetWikipediaPageTitleUsingWikidataId::class, 'Q123456', 'Skid Row (American band)');
$this->mockPipelinePipe(
GetWikipediaPageSummaryUsingPageTitle::class,
'Skid Row (American band)',
File::json(test_path('fixtures/wikipedia/artist-page-summary.json'))
);
/** @var Artist $artist */
$artist = Artist::factory()->create(['name' => 'Skid Row']);
$info = $this->service->getArtistInformation($artist);
self::assertSame([
'url' => 'https://en.wikipedia.org/wiki/Skid_Row_(American_band)',
'image' => 'https://upload.wikimedia.org/wikipedia/commons/thumb/3/3b/2023_Sweden_Rock_-_3330_%2853049443466%29.jpg/330px-2023_Sweden_Rock_-_3330_%2853049443466%29.jpg', // @phpcs-ignore
'bio' => [
'summary' => 'Skid Row is an American rock band formed in 1986…',
'full' => '<p><b>Skid Row</b> is an American rock band formed in 1986…</p>',
],
], $info->toArray());
}
#[Test]
public function getArtistInformationReturnsNullUponAnyErrorInThePipeline(): void
{
$this->mockPipelinePipe(GetMbidForArtist::class, 'Skid Row', 'sample-mbid');
$this->mockPipelinePipe(
GetArtistWikidataIdUsingMbid::class,
'sample-mbid',
new Exception('Something went wrong'),
);
/** @var Artist $artist */
$artist = Artist::factory()->create(['name' => 'Skid Row']);
self::assertNull($this->service->getArtistInformation($artist));
}
#[Test]
public function getAlbumInformation(): void
{
$recordingsJson = File::json(test_path('fixtures/musicbrainz/recordings.json'));
$tracks = [];
foreach (Arr::get($recordingsJson, 'media', []) as $media) {
array_push($tracks, ...Arr::get($media, 'tracks', []));
}
$this->mockPipelinePipe(
GetReleaseAndReleaseGroupMbidsForAlbum::class,
[
'album' => 'Slave to the Grind',
'artist' => 'Skid Row',
],
['sample-album-mbid', 'sample-release-group-mbid'],
);
$this->mockPipelinePipe(GetAlbumTracksUsingMbid::class, 'sample-album-mbid', $tracks);
$this->mockPipelinePipe(GetAlbumWikidataIdUsingReleaseGroupMbid::class, 'sample-release-group-mbid', 'Q123456');
$this->mockPipelinePipe(GetWikipediaPageTitleUsingWikidataId::class, 'Q123456', 'Slave to the Grind');
$this->mockPipelinePipe(
GetWikipediaPageSummaryUsingPageTitle::class,
'Slave to the Grind',
File::json(test_path('fixtures/wikipedia/album-page-summary.json'))
);
$user = create_user();
/** @var Album $album */
$album = Artist::factory() // @phpstan-ignore-line
->for($user)
->create(['name' => 'Skid Row'])
->albums()
->create([
'name' => 'Slave to the Grind',
'user_id' => $user->id,
]);
self::assertInstanceOf(AlbumInformation::class, $this->service->getAlbumInformation($album));
// eh, good enough
}
#[Test]
public function getAlbumInformationReturnsNullUponAnyErrorInThePipeline(): void
{
$this->mockPipelinePipe(
GetReleaseAndReleaseGroupMbidsForAlbum::class,
[
'album' => 'Slave to the Grind',
'artist' => 'Skid Row',
],
['sample-album-mbid', 'sample-release-group-mbid'],
);
$this->mockPipelinePipe(GetAlbumTracksUsingMbid::class, 'sample-album-mbid', new Exception('Oopsie'));
$user = create_user();
/** @var Album $album */
$album = Artist::factory() // @phpstan-ignore-line
->for($user)
->create(['name' => 'Skid Row'])
->albums()
->create([
'name' => 'Slave to the Grind',
'user_id' => $user->id,
]);
self::assertNull($this->service->getAlbumInformation($album));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/PodcastServiceTest.php | tests/Integration/Services/PodcastServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Events\UserUnsubscribedFromPodcast;
use App\Exceptions\UserAlreadySubscribedToPodcastException;
use App\Models\Podcast;
use App\Models\PodcastUserPivot;
use App\Models\Song;
use App\Services\PodcastService;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Http;
use PHPUnit\Framework\Attributes\Test;
use Psr\Http\Client\ClientInterface;
use Tests\TestCase;
use function Tests\create_user;
use function Tests\test_path;
class PodcastServiceTest extends TestCase
{
private PodcastService $service;
public function setUp(): void
{
parent::setUp();
$mock = new MockHandler([
new Response(200, [], file_get_contents(test_path('fixtures/podcast.xml'))),
]);
$handlerStack = HandlerStack::create($mock);
$this->instance(ClientInterface::class, new Client(['handler' => $handlerStack]));
$this->service = app(PodcastService::class);
}
#[Test]
public function addPodcast(): void
{
$url = 'https://example.com/feed.xml';
$user = create_user();
$podcast = $this->service->addPodcast($url, $user);
$this->assertDatabaseHas(Podcast::class, [
'url' => $url,
'title' => 'Podcast Feed Parser',
'description' => 'Parse podcast feeds with PHP following PSP-1 Podcast RSS Standard',
'image' => 'https://github.com/phanan.png',
'author' => 'Phan An (phanan)',
'language' => 'en-US',
'explicit' => false,
'added_by' => $user->id,
]);
self::assertCount(8, $podcast->episodes);
}
#[Test]
public function subscribeUserToPodcast(): void
{
/** @var Podcast $podcast */
$podcast = Podcast::factory()->create([
'url' => 'https://example.com/feed.xml',
'title' => 'My Cool Podcast',
]);
$user = create_user();
self::assertFalse($user->subscribedToPodcast($podcast));
$this->service->addPodcast('https://example.com/feed.xml', $user);
self::assertTrue($user->subscribedToPodcast($podcast));
// the title shouldn't have changed
self::assertSame('My Cool Podcast', $podcast->fresh()->title);
}
#[Test]
public function resubscribeUserToPodcastThrows(): void
{
self::expectException(UserAlreadySubscribedToPodcastException::class);
/** @var Podcast $podcast */
$podcast = Podcast::factory()->create([
'url' => 'https://example.com/feed.xml',
]);
$user = create_user();
$user->subscribeToPodcast($podcast);
$this->service->addPodcast('https://example.com/feed.xml', $user);
}
#[Test]
public function addingRefreshesObsoletePodcast(): void
{
self::expectException(UserAlreadySubscribedToPodcastException::class);
Http::fake([
'https://example.com/feed.xml' => Http::response(headers: ['Last-Modified' => now()->toRfc1123String()]),
]);
/** @var Podcast $podcast */
$podcast = Podcast::factory()->create([
'url' => 'https://example.com/feed.xml',
'title' => 'Shall be changed very sad',
'last_synced_at' => now()->subDays(3),
]);
self::assertCount(0, $podcast->episodes);
$user = create_user();
$user->subscribeToPodcast($podcast);
$this->service->addPodcast('https://example.com/feed.xml', $user);
self::assertCount(8, $podcast->episodes);
self::assertSame('Podcast Feed Parser', $podcast->title);
}
#[Test]
public function unsubscribeUserFromPodcast(): void
{
Event::fake(UserUnsubscribedFromPodcast::class);
/** @var Podcast $podcast */
$podcast = Podcast::factory()->create();
$user = create_user();
$user->subscribeToPodcast($podcast);
$this->service->unsubscribeUserFromPodcast($user, $podcast);
self::assertFalse($user->subscribedToPodcast($podcast));
Event::assertDispatched(
UserUnsubscribedFromPodcast::class,
static function (UserUnsubscribedFromPodcast $event) use ($user, $podcast) {
return $event->user->is($user) && $event->podcast->is($podcast);
},
);
}
#[Test]
public function podcastNotObsoleteIfSyncedRecently(): void
{
/** @var Podcast $podcast */
$podcast = Podcast::factory()->create([
'last_synced_at' => now()->subHours(6),
]);
self::assertFalse($this->service->isPodcastObsolete($podcast));
}
#[Test]
public function podcastObsoleteIfModifiedSinceLastSync(): void
{
Http::fake([
'https://example.com/feed.xml' => Http::response(headers: ['Last-Modified' => now()->toRfc1123String()]),
]);
/** @var Podcast $podcast */
$podcast = Podcast::factory()->create([
'url' => 'https://example.com/feed.xml',
'last_synced_at' => now()->subDays(1),
]);
self::assertTrue($this->service->isPodcastObsolete($podcast));
}
#[Test]
public function updateEpisodeProgress(): void
{
/** @var Song $episode */
$episode = Song::factory()->asEpisode()->create();
$user = create_user();
$user->subscribeToPodcast($episode->podcast);
$this->service->updateEpisodeProgress($user, $episode->refresh(), 123);
/** @var PodcastUserPivot $subscription */
$subscription = $episode->podcast->subscribers->sole('id', $user->id)->pivot;
self::assertSame($episode->id, $subscription->state->currentEpisode);
self::assertSame(123, $subscription->state->progresses[$episode->id]);
}
#[Test]
public function getStreamableUrl(): void
{
$mock = new MockHandler([
new Response(200, ['Access-Control-Allow-Origin' => '*']),
]);
$handlerStack = HandlerStack::create($mock);
$client = new Client(['handler' => $handlerStack]);
self::assertSame(
'https://example.com/episode.mp3',
$this->service->getStreamableUrl('https://example.com/episode.mp3', $client)
);
}
#[Test]
public function streamableUrlNotAvailable(): void
{
$mock = new MockHandler([new Response(200, [])]);
$handlerStack = HandlerStack::create($mock);
$client = new Client(['handler' => $handlerStack]);
self::assertNull($this->service->getStreamableUrl('https://example.com/episode.mp3', $client));
}
#[Test]
public function getStreamableUrlFollowsRedirects(): void
{
$mock = new MockHandler([
new Response(302, ['Location' => 'https://redir.example.com/track']),
new Response(302, ['Location' => 'https://assets.example.com/episode.mp3']),
new Response(200, ['Access-Control-Allow-Origin' => '*']),
]);
$handlerStack = HandlerStack::create($mock);
$client = new Client(['handler' => $handlerStack]);
self::assertSame(
'https://assets.example.com/episode.mp3',
$this->service->getStreamableUrl('https://example.com/episode.mp3', $client)
);
}
#[Test]
public function deletePodcast(): void
{
/** @var Podcast $podcast */
$podcast = Podcast::factory()->create();
$this->service->deletePodcast($podcast);
self::assertModelMissing($podcast);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/LastfmServiceTest.php | tests/Integration/Services/LastfmServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Http\Integrations\Lastfm\Requests\GetAlbumInfoRequest;
use App\Http\Integrations\Lastfm\Requests\GetArtistInfoRequest;
use App\Http\Integrations\Lastfm\Requests\ScrobbleRequest;
use App\Http\Integrations\Lastfm\Requests\ToggleLoveTrackRequest;
use App\Http\Integrations\Lastfm\Requests\UpdateNowPlayingRequest;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Song;
use App\Services\LastfmService;
use Illuminate\Support\Facades\File;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use Saloon\Http\Faking\MockResponse;
use Saloon\Laravel\Saloon;
use Tests\TestCase;
use function Tests\create_user;
use function Tests\test_path;
class LastfmServiceTest extends TestCase
{
private LastfmService $service;
public function setUp(): void
{
parent::setUp();
config([
'koel.services.lastfm.key' => 'key',
'koel.services.lastfm.secret' => 'secret',
]);
$this->service = app(LastfmService::class);
}
#[Test]
public function getArtistInformation(): void
{
/** @var Artist $artist */
$artist = Artist::factory()->make(['name' => 'Kamelot']);
Saloon::fake([
GetArtistInfoRequest::class => MockResponse::make(
body: File::get(test_path('fixtures/lastfm/artist.json'))
),
]);
$info = $this->service->getArtistInformation($artist);
Saloon::assertSent(static function (GetArtistInfoRequest $request): bool {
self::assertSame([
'method' => 'artist.getInfo',
'artist' => 'Kamelot',
'autocorrect' => 1,
'format' => 'json',
], $request->query()->all());
return true;
});
self::assertEquals([
'url' => 'https://www.last.fm/music/Kamelot',
'image' => null,
'bio' => [
'summary' => 'Quisque ut nisi.',
'full' => 'Quisque ut nisi. Vestibulum ullamcorper mauris at ligula.',
],
], $info->toArray());
}
#[Test]
public function getArtistInformationForNonExistentArtist(): void
{
/** @var Artist $artist */
$artist = Artist::factory()->make(['name' => 'bar']);
Saloon::fake([
GetArtistInfoRequest::class => MockResponse::make(
body: File::get(test_path('fixtures/lastfm/artist-notfound.json'))
),
]);
self::assertNull($this->service->getArtistInformation($artist));
}
#[Test]
public function getAlbumInformation(): void
{
/** @var Album $album */
$album = Album::factory()->for(Artist::factory()->create(['name' => 'Kamelot']))->create(['name' => 'Epica']);
Saloon::fake([
GetAlbumInfoRequest::class => MockResponse::make(body: File::get(test_path('fixtures/lastfm/album.json'))),
]);
$info = $this->service->getAlbumInformation($album);
Saloon::assertSent(static function (GetAlbumInfoRequest $request): bool {
self::assertSame([
'method' => 'album.getInfo',
'artist' => 'Kamelot',
'album' => 'Epica',
'autocorrect' => 1,
'format' => 'json',
], $request->query()->all());
return true;
});
self::assertEquals([
'url' => 'https://www.last.fm/music/Kamelot/Epica',
'cover' => null,
'tracks' => [
[
'title' => 'Track 1',
'url' => 'https://foo/track1',
'length' => 100,
],
[
'title' => 'Track 2',
'url' => 'https://foo/track2',
'length' => 150,
],
],
'wiki' => [
'summary' => 'Quisque ut nisi.',
'full' => 'Quisque ut nisi. Vestibulum ullamcorper mauris at ligula.',
],
], $info->toArray());
}
#[Test]
public function getAlbumInformationForNonExistentAlbum(): void
{
/** @var Album $album */
$album = Album::factory()->for(Artist::factory()->create(['name' => 'Kamelot']))->create(['name' => 'Foo']);
Saloon::fake([
GetAlbumInfoRequest::class => MockResponse::make(
body: File::get(test_path('fixtures/lastfm/album-notfound.json'))
),
]);
self::assertNull($this->service->getAlbumInformation($album));
}
#[Test]
public function scrobble(): void
{
$user = create_user([
'preferences' => [
'lastfm_session_key' => 'my_key',
],
]);
/** @var Song $song */
$song = Song::factory()->create();
Saloon::fake([ScrobbleRequest::class => MockResponse::make()]);
$this->service->scrobble($song, $user, 100);
Saloon::assertSent(static function (ScrobbleRequest $request) use ($song): bool {
self::assertSame([
'method' => 'track.scrobble',
'artist' => $song->artist->name,
'track' => $song->title,
'timestamp' => 100,
'sk' => 'my_key',
'album' => $song->album->name,
], $request->body()->all());
return true;
});
}
/** @return array<mixed> */
public static function provideToggleLoveTrackData(): array
{
return [[true, 'track.love'], [false, 'track.unlove']];
}
#[DataProvider('provideToggleLoveTrackData')]
#[Test]
public function toggleLoveTrack(bool $love, string $method): void
{
$user = create_user([
'preferences' => [
'lastfm_session_key' => 'my_key',
],
]);
/** @var Song $song */
$song = Song::factory()->create();
Saloon::fake([ToggleLoveTrackRequest::class => MockResponse::make()]);
$this->service->toggleLoveTrack($song, $user, $love);
Saloon::assertSent(static function (ToggleLoveTrackRequest $request) use ($song, $love): bool {
self::assertSame([
'method' => $love ? 'track.love' : 'track.unlove',
'sk' => 'my_key',
'artist' => $song->artist->name,
'track' => $song->title,
], $request->body()->all());
return true;
});
}
#[Test]
public function updateNowPlaying(): void
{
$user = create_user([
'preferences' => [
'lastfm_session_key' => 'my_key',
],
]);
/** @var Song $song */
$song = Song::factory()->for(Artist::factory()->create(['name' => 'foo']))->create(['title' => 'bar']);
Saloon::fake([UpdateNowPlayingRequest::class => MockResponse::make()]);
$this->service->updateNowPlaying($song, $user);
Saloon::assertSent(static function (UpdateNowPlayingRequest $request) use ($song): bool {
self::assertSame([
'method' => 'track.updateNowPlaying',
'artist' => $song->artist->name,
'track' => $song->title,
'duration' => $song->length,
'sk' => 'my_key',
'album' => $song->album->name,
], $request->body()->all());
return true;
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/QueueServiceTest.php | tests/Integration/Services/QueueServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Models\QueueState;
use App\Models\Song;
use App\Services\QueueService;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
class QueueServiceTest extends TestCase
{
private QueueService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(QueueService::class);
}
#[Test]
public function getQueueState(): void
{
/** @var Song $currentSong */
$currentSong = Song::factory()->create();
/** @var QueueState $state */
$state = QueueState::factory()->create([
'current_song_id' => $currentSong->id,
'playback_position' => 123,
]);
$dto = $this->service->getQueueState($state->user);
self::assertEqualsCanonicalizing($state->song_ids, $dto->playables->pluck('id')->toArray());
self::assertSame($currentSong->id, $dto->currentPlayable->id);
self::assertSame(123, $dto->playbackPosition);
}
#[Test]
public function createQueueState(): void
{
$user = create_user();
$this->assertDatabaseMissing(QueueState::class, [
'user_id' => $user->id,
]);
$songIds = Song::factory()->count(2)->create()->modelKeys();
$this->service->updateQueueState($user, $songIds);
/** @var QueueState $queueState */
$queueState = QueueState::query()->whereBelongsTo($user)->firstOrFail();
self::assertEqualsCanonicalizing($songIds, $queueState->song_ids);
self::assertNull($queueState->current_song_id);
self::assertSame(0, $queueState->playback_position);
}
#[Test]
public function updateQueueState(): void
{
/** @var QueueState $state */
$state = QueueState::factory()->create();
$songIds = Song::factory()->count(2)->create()->modelKeys();
$this->service->updateQueueState($state->user, $songIds);
$state->refresh();
self::assertEqualsCanonicalizing($songIds, $state->song_ids);
self::assertNull($state->current_song_id);
self::assertEquals(0, $state->playback_position);
}
#[Test]
public function updatePlaybackStatus(): void
{
/** @var QueueState $state */
$state = QueueState::factory()->create();
/** @var Song $song */
$song = Song::factory()->create();
$this->service->updatePlaybackStatus($state->user, $song, 123);
$state->refresh();
self::assertSame($song->id, $state->current_song_id);
self::assertSame(123, $state->playback_position);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/UserInvitationServiceTest.php | tests/Integration/Services/UserInvitationServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Enums\Acl\Role;
use App\Exceptions\InvitationNotFoundException;
use App\Mail\UserInvite;
use App\Models\User;
use App\Services\UserInvitationService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_admin;
class UserInvitationServiceTest extends TestCase
{
private UserInvitationService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(UserInvitationService::class);
}
#[Test]
public function invite(): void
{
Mail::fake();
$emails = ['foo@bar.com', 'bar@baz.io'];
$user = create_admin();
$this->service
->invite($emails, Role::ADMIN, $user)
->each(static function (User $prospect) use ($user): void {
self::assertSame(Role::ADMIN, $prospect->role);
self::assertTrue($prospect->invitedBy->is($user));
self::assertTrue($prospect->is_prospect);
self::assertNotNull($prospect->invitation_token);
self::assertNotNull($prospect->invited_at);
self::assertNull($prospect->invitation_accepted_at);
});
Mail::assertQueued(UserInvite::class, 2);
}
#[Test]
public function getUserProspectByToken(): void
{
$token = Str::uuid()->toString();
$user = create_admin();
$prospect = User::factory()->for($user, 'invitedBy')->create([
'invitation_token' => $token,
'invited_at' => now(),
]);
self::assertTrue($this->service->getUserProspectByToken($token)->is($prospect));
}
#[Test]
public function getUserProspectByTokenThrowsIfTokenNotFound(): void
{
$this->expectException(InvitationNotFoundException::class);
$this->service->getUserProspectByToken(Str::uuid()->toString());
}
#[Test]
public function revokeByEmail(): void
{
$user = create_admin();
/** @var User $prospect */
$prospect = User::factory()->for($user, 'invitedBy')->create([
'invitation_token' => Str::uuid()->toString(),
'invited_at' => now(),
]);
$this->service->revokeByEmail($prospect->email);
$this->assertModelMissing($prospect);
}
#[Test]
public function accept(): void
{
$admin = create_admin();
/** @var User $prospect */
$prospect = User::factory()->for($admin, 'invitedBy')->admin()->prospect()->create();
$user = $this->service->accept($prospect->invitation_token, 'Bruce Dickinson', 'SuperSecretPassword');
self::assertFalse($user->is_prospect);
self::assertSame(Role::ADMIN, $user->role);
self::assertNull($user->invitation_token);
self::assertNotNull($user->invitation_accepted_at);
self::assertTrue(Hash::check('SuperSecretPassword', $user->password));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/PlaylistServiceTest.php | tests/Integration/Services/PlaylistServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Enums\Placement;
use App\Models\PlaylistFolder;
use App\Models\Podcast;
use App\Models\Song;
use App\Services\PlaylistService;
use App\Values\Playlist\PlaylistCreateData;
use App\Values\Playlist\PlaylistUpdateData;
use App\Values\SmartPlaylist\SmartPlaylistRuleGroupCollection;
use PHPUnit\Framework\Attributes\Test;
use Tests\PlusTestCase;
use Tests\TestCase;
use function Tests\create_playlist;
use function Tests\create_user;
use function Tests\minimal_base64_encoded_image;
class PlaylistServiceTest extends TestCase
{
private PlaylistService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(PlaylistService::class);
}
#[Test]
public function createPlaylist(): void
{
$user = create_user();
$data = PlaylistCreateData::make(
name: 'foo',
description: 'bar',
cover: minimal_base64_encoded_image(),
);
$playlist = $this->service->createPlaylist($data, $user);
self::assertSame('foo', $playlist->name);
self::assertSame('bar', $playlist->description);
self::assertTrue($user->is($playlist->owner));
self::assertFalse($playlist->is_smart);
self::assertNotNull($playlist->cover);
}
#[Test]
public function createPlaylistWithSongs(): void
{
$songs = Song::factory(2)->create();
$user = create_user();
$data = PlaylistCreateData::make(
name: 'foo',
description: 'bar',
cover: minimal_base64_encoded_image(),
playableIds: $songs->modelKeys(),
);
$playlist = $this->service->createPlaylist($data, $user);
self::assertSame('foo', $playlist->name);
self::assertSame('bar', $playlist->description);
self::assertTrue($user->is($playlist->owner));
self::assertFalse($playlist->is_smart);
self::assertEqualsCanonicalizing($playlist->playables->modelKeys(), $songs->modelKeys());
}
#[Test]
public function createPlaylistWithoutCover(): void
{
$user = create_user();
$data = PlaylistCreateData::make(
name: 'foo',
description: 'bar',
);
$playlist = $this->service->createPlaylist($data, $user);
self::assertSame('foo', $playlist->name);
self::assertSame('bar', $playlist->description);
self::assertTrue($user->is($playlist->owner));
self::assertFalse($playlist->is_smart);
self::assertNull($playlist->cover);
}
#[Test]
public function createSmartPlaylist(): void
{
$rules = SmartPlaylistRuleGroupCollection::create([
[
'id' => '45368b8f-fec8-4b72-b826-6b295af0da65',
'rules' => [
[
'id' => '8cfa8700-fbc0-4078-b175-af31c20a3582',
'model' => 'title',
'operator' => 'is',
'value' => ['foo'],
],
],
],
]);
$user = create_user();
$data = PlaylistCreateData::make(
name: 'foo',
description: 'bar',
ruleGroups: $rules,
);
$playlist = $this->service->createPlaylist($data, $user);
self::assertSame('foo', $playlist->name);
self::assertSame('bar', $playlist->description);
self::assertTrue($user->is($playlist->owner));
self::assertTrue($playlist->is_smart);
}
#[Test]
public function createPlaylistInFolder(): void
{
/** @var PlaylistFolder $folder */
$folder = PlaylistFolder::factory()->create();
$data = PlaylistCreateData::make(
name: 'foo',
description: 'bar',
folderId: $folder->id,
);
$playlist = $this->service->createPlaylist($data, $folder->user);
self::assertSame('foo', $playlist->name);
self::assertSame('bar', $playlist->description);
self::assertTrue($folder->ownedBy($playlist->owner));
self::assertTrue($playlist->inFolder($folder));
}
#[Test]
public function updateSimplePlaylist(): void
{
$playlist = create_playlist(['name' => 'foo']);
$this->service->updatePlaylist($playlist, PlaylistUpdateData::make(
name: 'bar',
description: 'baz',
));
self::assertSame('bar', $playlist->name);
self::assertSame('baz', $playlist->description);
}
#[Test]
public function updateSmartPlaylist(): void
{
$rules = SmartPlaylistRuleGroupCollection::create([
[
'id' => '45368b8f-fec8-4b72-b826-6b295af0da65',
'rules' => [
[
'id' => '8cfa8700-fbc0-4078-b175-af31c20a3582',
'model' => 'title',
'operator' => 'is',
'value' => ['foo'],
],
],
],
]);
$playlist = create_playlist(['name' => 'foo', 'rules' => $rules]);
$data = PlaylistUpdateData::make(
name: 'bar',
description: 'baz',
ruleGroups: SmartPlaylistRuleGroupCollection::create([
[
'id' => '45368b8f-fec8-4b72-b826-6b295af0da65',
'rules' => [
[
'id' => '8cfa8700-fbc0-4078-b175-af31c20a3582',
'model' => 'title',
'operator' => 'is',
'value' => ['bar'],
],
],
],
]),
);
$this->service->updatePlaylist($playlist, $data);
$playlist->refresh();
self::assertSame('bar', $playlist->name);
self::assertSame('baz', $playlist->description);
self::assertTrue($playlist->is_smart);
self::assertSame($playlist->rule_groups->first()->rules->first()->value, ['bar']);
}
#[Test]
public function addSongsToPlaylist(): void
{
$playlist = create_playlist();
$playlist->addPlayables(Song::factory(2)->create());
$songs = Song::factory(2)->create();
$addedSongs = $this->service->addPlayablesToPlaylist($playlist, $songs, $playlist->owner);
$playlist->refresh();
self::assertCount(2, $addedSongs);
self::assertCount(4, $playlist->playables);
self::assertEqualsCanonicalizing($addedSongs->modelKeys(), $songs->modelKeys());
$songs->each(static fn (Song $song) => self::assertTrue($playlist->playables->contains($song)));
}
#[Test]
public function addEpisodesToPlaylist(): void
{
$playlist = create_playlist();
$playlist->addPlayables(Song::factory(2)->create());
/** @var Podcast $podcast */
$podcast = Podcast::factory()->create();
$episodes = Song::factory(2)->asEpisode()->for($podcast)->create();
$playlist->owner->subscribeToPodcast($podcast);
$addedEpisodes = $this->service->addPlayablesToPlaylist($playlist, $episodes, $playlist->owner);
$playlist->refresh();
self::assertCount(2, $addedEpisodes);
self::assertCount(4, $playlist->playables);
self::assertEqualsCanonicalizing($addedEpisodes->modelKeys(), $episodes->modelKeys());
}
#[Test]
public function addMixOfSongsAndEpisodesToPlaylist(): void
{
$playlist = create_playlist();
$playlist->addPlayables(Song::factory(2)->create());
$playables = Song::factory(2)->asEpisode()->create()
->merge(Song::factory(2)->create());
$addedEpisodes = $this->service->addPlayablesToPlaylist($playlist, $playables, $playlist->owner);
$playlist->refresh();
self::assertCount(4, $addedEpisodes);
self::assertCount(6, $playlist->playables);
self::assertEqualsCanonicalizing($addedEpisodes->modelKeys(), $playables->modelKeys());
}
#[Test]
public function privateSongsAreMadePublicWhenAddedToCollaborativePlaylist(): void
{
PlusTestCase::enablePlusLicense();
$playlist = create_playlist();
$user = create_user();
$playlist->collaborators()->attach($user);
$playlist->refresh();
self::assertTrue($playlist->is_collaborative);
$songs = Song::factory(2)->create(['is_public' => false]);
$this->service->addPlayablesToPlaylist($playlist, $songs, $user);
$songs->each(static fn (Song $song) => self::assertTrue($song->refresh()->is_public));
}
#[Test]
public function makePlaylistSongsPublic(): void
{
$playlist = create_playlist();
$playlist->addPlayables(Song::factory(2)->create(['is_public' => false]));
$this->service->makePlaylistContentPublic($playlist);
$playlist->playables->each(static fn (Song $song) => self::assertTrue($song->is_public));
}
#[Test]
public function moveSongsInPlaylist(): void
{
$playlist = create_playlist();
$songs = Song::factory(4)->create();
$ids = $songs->modelKeys();
$playlist->addPlayables($songs);
$this->service->movePlayablesInPlaylist($playlist, [$ids[2], $ids[3]], $ids[0], Placement::AFTER);
self::assertSame([$ids[0], $ids[2], $ids[3], $ids[1]], $playlist->refresh()->playables->modelKeys());
$this->service->movePlayablesInPlaylist($playlist, [$ids[0]], $ids[3], Placement::BEFORE);
self::assertSame([$ids[2], $ids[0], $ids[3], $ids[1]], $playlist->refresh()->playables->modelKeys());
// move to the first position
$this->service->movePlayablesInPlaylist($playlist, [$ids[0], $ids[1]], $ids[2], Placement::BEFORE);
self::assertSame([$ids[0], $ids[1], $ids[2], $ids[3]], $playlist->refresh()->playables->modelKeys());
// move to the last position
$this->service->movePlayablesInPlaylist($playlist, [$ids[0], $ids[1]], $ids[3], Placement::AFTER);
self::assertSame([$ids[2], $ids[3], $ids[0], $ids[1]], $playlist->refresh()->playables->modelKeys());
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/AlbumServiceTest.php | tests/Integration/Services/AlbumServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Exceptions\AlbumNameConflictException;
use App\Helpers\Ulid;
use App\Models\Album;
use App\Models\Song;
use App\Services\AlbumService;
use App\Services\ImageStorage;
use App\Values\Album\AlbumUpdateData;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\minimal_base64_encoded_image;
class AlbumServiceTest extends TestCase
{
private AlbumService $service;
private ImageStorage|MockInterface $imageStorage;
public function setUp(): void
{
parent::setUp();
$this->imageStorage = $this->mock(ImageStorage::class);
$this->service = app(AlbumService::class);
}
#[Test]
public function updateAlbum(): void
{
/** @var Album $album */
$album = Album::factory()->create([
'name' => 'Old Album Name',
'year' => 2020,
]);
$songs = Song::factory()->for($album)->count(2)->create();
$data = AlbumUpdateData::make(name: 'New Album Name', year: 2023);
$updatedAlbum = $this->service->updateAlbum($album, $data);
self::assertEquals('New Album Name', $updatedAlbum->name);
self::assertEquals(2023, $updatedAlbum->year);
$songs->each(static function (Song $song) use ($updatedAlbum): void {
self::assertEquals($updatedAlbum->name, $song->fresh()->album_name);
});
}
#[Test]
public function updateAlbumWithCover(): void
{
/** @var Album $album */
$album = Album::factory()->create([
'name' => 'Old Album Name',
'year' => 2020,
]);
$songs = Song::factory()->for($album)->count(2)->create();
$data = AlbumUpdateData::make(
name: 'New Album Name',
year: 2023,
cover: minimal_base64_encoded_image(),
);
$ulid = Ulid::freeze();
$this->imageStorage->expects('storeImage')->with(minimal_base64_encoded_image())->andReturn("$ulid.webp");
$updatedAlbum = $this->service->updateAlbum($album, $data);
self::assertEquals('New Album Name', $updatedAlbum->name);
self::assertEquals(2023, $updatedAlbum->year);
self::assertEquals("$ulid.webp", $updatedAlbum->cover);
$songs->each(static function (Song $song) use ($updatedAlbum): void {
self::assertEquals($updatedAlbum->name, $song->fresh()->album_name);
});
}
#[Test]
public function updateAlbumRemovingCover(): void
{
/** @var Album $album */
$album = Album::factory()->create();
$data = AlbumUpdateData::make(
name: 'New Album Name',
year: 2023,
cover: '',
);
$updatedAlbum = $this->service->updateAlbum($album, $data);
self::assertEquals('New Album Name', $updatedAlbum->name);
self::assertEquals(2023, $updatedAlbum->year);
self::assertEmpty($updatedAlbum->cover);
}
#[Test]
public function rejectUpdatingIfArtistAlreadyHasAnAlbumWithTheSameName(): void
{
/** @var Album $existingAlbum */
$existingAlbum = Album::factory()->create(['name' => 'Existing Album Name']);
/** @var Album $album */
$album = Album::factory()->for($existingAlbum->artist)->create(['name' => 'Old Album Name']);
$data = AlbumUpdateData::make(name: 'Existing Album Name', year: 2023);
$this->expectException(AlbumNameConflictException::class);
$this->service->updateAlbum($album, $data);
}
#[Test]
public function storeAlbumCover(): void
{
/** @var Album $album */
$album = Album::factory()->create();
$this->imageStorage
->expects('storeImage')
->with('dummy-src')
->andReturn('foo.webp');
$this->service->storeAlbumCover($album, 'dummy-src');
self::assertSame('foo.webp', $album->refresh()->cover);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/ApplicationInformationServiceTest.php | tests/Integration/Services/ApplicationInformationServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Services\ApplicationInformationService;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Illuminate\Support\Facades\File;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\test_path;
class ApplicationInformationServiceTest extends TestCase
{
#[Test]
public function getLatestVersionNumber(): void
{
$latestVersion = 'v1.1.2';
$mock = new MockHandler([
new Response(200, [], File::get(test_path('fixtures/github-tags.json'))),
]);
$client = new Client(['handler' => HandlerStack::create($mock)]);
$service = new ApplicationInformationService($client);
self::assertSame($latestVersion, $service->getLatestVersionNumber());
self::assertSame($latestVersion, cache()->get(cache_key('latest version number')));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/InteractionServiceTest.php | tests/Integration/Services/InteractionServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Models\Interaction;
use App\Services\InteractionService;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class InteractionServiceTest extends TestCase
{
private InteractionService $interactionService;
public function setUp(): void
{
parent::setUp();
$this->interactionService = new InteractionService();
}
#[Test]
public function increasePlayCount(): void
{
/** @var Interaction $interaction */
$interaction = Interaction::factory()->create();
$currentCount = $interaction->play_count;
$this->interactionService->increasePlayCount($interaction->song, $interaction->user);
self::assertSame($currentCount + 1, $interaction->refresh()->play_count);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/TokenManagerTest.php | tests/Integration/Services/TokenManagerTest.php | <?php
namespace Tests\Integration\Services;
use App\Services\TokenManager;
use Illuminate\Support\Facades\Cache;
use Laravel\Sanctum\PersonalAccessToken;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
class TokenManagerTest extends TestCase
{
private TokenManager $tokenManager;
public function setUp(): void
{
parent::setUp();
$this->tokenManager = app(TokenManager::class);
}
#[Test]
public function createTokenWithAllAbilities(): void
{
$token = $this->tokenManager->createToken(create_user());
self::assertTrue($token->accessToken->can('*'));
}
#[Test]
public function createTokenWithSpecificAbilities(): void
{
$token = $this->tokenManager->createToken(create_user(), ['audio']);
self::assertTrue($token->accessToken->can('audio'));
self::assertFalse($token->accessToken->can('video'));
self::assertFalse($token->accessToken->can('*'));
}
#[Test]
public function createCompositionToken(): void
{
$token = $this->tokenManager->createCompositeToken(create_user());
$this->assertModelExists(PersonalAccessToken::findToken($token->apiToken));
$audioTokenInstance = PersonalAccessToken::findToken($token->audioToken);
$this->assertModelExists($audioTokenInstance);
/** @var string $cachedAudioToken */
$cachedAudioToken = Cache::get("app.composite-tokens.$token->apiToken");
self::assertTrue($audioTokenInstance->is(PersonalAccessToken::findToken($cachedAudioToken)));
}
#[Test]
public function deleteCompositionToken(): void
{
$token = $this->tokenManager->createCompositeToken(create_user());
$this->tokenManager->deleteCompositionToken($token->apiToken);
self::assertNull(PersonalAccessToken::findToken($token->apiToken));
self::assertNull(PersonalAccessToken::findToken($token->audioToken));
self::assertNull(Cache::get("app.composite-tokens.$token->apiToken"));
}
#[Test]
public function destroyTokens(): void
{
$user = create_user();
$user->createToken('foo');
$user->createToken('bar');
self::assertSame(2, $user->tokens()->count());
$this->tokenManager->destroyTokens($user);
self::assertSame(0, $user->tokens()->count());
}
#[Test]
public function deleteTokenByPlainTextToken(): void
{
$token = $this->tokenManager->createToken(create_user());
$this->assertModelExists($token->accessToken);
$this->tokenManager->deleteTokenByPlainTextToken($token->plainTextToken);
$this->assertModelMissing($token->accessToken);
}
#[Test]
public function getUserFromPlainTextToken(): void
{
$user = create_user();
$token = $this->tokenManager->createToken($user);
self::assertTrue($user->is($this->tokenManager->getUserFromPlainTextToken($token->plainTextToken)));
}
#[Test]
public function replaceApiToken(): void
{
$oldToken = $this->tokenManager->createToken(create_user());
$newToken = $this->tokenManager->refreshApiToken($oldToken->plainTextToken);
$this->assertModelMissing($oldToken->accessToken);
$this->assertModelExists($newToken->accessToken);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/EmbedServiceTest.php | tests/Integration/Services/EmbedServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Playlist;
use App\Models\Song;
use App\Services\EmbedService;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
class EmbedServiceTest extends TestCase
{
private EmbedService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(EmbedService::class);
}
/** @return array<mixed> */
public static function provideEmbeddableData(): array
{
return [
['playable', Song::class],
['playlist', Playlist::class],
['album', Album::class],
['artist', Artist::class],
];
}
#[Test]
#[DataProvider('provideEmbeddableData')]
/** @param class-string<Song|Playlist|Album|Artist> $modelClass */
public function resolveEmbedForEmbeddable(string $type, string $modelClass): void
{
$embeddable = $modelClass::factory()->create();
$user = create_user();
$embed = $this->service->resolveEmbedForEmbeddable($embeddable, $user);
self::assertSame($type, $embed->embeddable_type);
self::assertTrue($embed->embeddable->is($embeddable));
self::assertTrue($embed->user->is($user));
$secondEmbed = $this->service->resolveEmbedForEmbeddable($embeddable, $user);
self::assertTrue($embed->is($secondEmbed));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/DispatcherTest.php | tests/Integration/Services/DispatcherTest.php | <?php
namespace Tests\Integration\Services;
use App\Services\Dispatcher;
use Illuminate\Support\Facades\Bus;
use PHPUnit\Framework\Attributes\Test;
use Tests\Fakes\FakeJob;
use Tests\TestCase;
class DispatcherTest extends TestCase
{
private string $queueConfig;
private string $broadcastingConfig;
public function setUp(): void
{
parent::setUp();
$this->queueConfig = config('queue.default');
$this->broadcastingConfig = config('broadcasting.default');
}
#[Test]
public function dispatchIfQueueSupported(): void
{
Bus::fake();
config(['queue.default' => 'redis']);
config(['broadcasting.default' => 'pusher']);
$dispatcher = app(Dispatcher::class);
$dispatcher->dispatch(new FakeJob());
Bus::assertDispatched(FakeJob::class);
}
#[Test]
public function executeJobSynchronouslyIfQueueNotSupported(): void
{
Bus::fake();
$dispatcher = app(Dispatcher::class);
$result = $dispatcher->dispatch(new FakeJob());
self::assertSame('Job executed', $result);
Bus::assertNotDispatched(FakeJob::class);
}
protected function tearDown(): void
{
config(['queue.default' => $this->queueConfig]);
config(['broadcasting.default' => $this->broadcastingConfig]);
parent::tearDown();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/ArtistServiceTest.php | tests/Integration/Services/ArtistServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Exceptions\ArtistNameConflictException;
use App\Helpers\Ulid;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Song;
use App\Services\ArtistService;
use App\Values\Artist\ArtistUpdateData;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\minimal_base64_encoded_image;
class ArtistServiceTest extends TestCase
{
private ArtistService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(ArtistService::class);
}
#[Test]
public function updateArtist(): void
{
/** @var Artist $artist */
$artist = Artist::factory()->create(['name' => 'Old Artist Name']);
$songs = Song::factory()->for($artist)->count(2)->create();
$albums = Album::factory()->for($artist)->count(2)->create();
$data = ArtistUpdateData::make(name: 'New Artist Name');
$updatedArtist = $this->service->updateArtist($artist, $data);
self::assertEquals('New Artist Name', $updatedArtist->name);
$songs->each(static function (Song $song) use ($updatedArtist): void {
self::assertEquals($updatedArtist->name, $song->fresh()->artist_name);
});
$albums->each(static function (Album $album) use ($updatedArtist): void {
self::assertEquals($updatedArtist->name, $album->fresh()->artist_name);
});
}
#[Test]
public function updateArtistWithImage(): void
{
/** @var Artist $artist */
$artist = Artist::factory()->create(['name' => 'Old Artist Name']);
$songs = Song::factory()->for($artist)->count(2)->create();
$albums = Album::factory()->for($artist)->count(2)->create();
$data = ArtistUpdateData::make(
name: 'New Artist Name',
image: minimal_base64_encoded_image(),
);
$ulid = Ulid::freeze();
$updatedArtist = $this->service->updateArtist($artist, $data);
self::assertEquals('New Artist Name', $updatedArtist->name);
self::assertEquals("$ulid.webp", $updatedArtist->image);
$songs->each(static function (Song $song) use ($updatedArtist): void {
self::assertEquals($updatedArtist->name, $song->fresh()->artist_name);
});
$albums->each(static function (Album $album) use ($updatedArtist): void {
self::assertEquals($updatedArtist->name, $album->fresh()->artist_name);
});
}
#[Test]
public function rejectUpdatingIfArtistAlreadyExistsForUser(): void
{
/** @var Artist $existingArtist */
$existingArtist = Artist::factory()->create(['name' => 'Existing Artist Name']);
/** @var Artist $artist */
$artist = Artist::factory()->for($existingArtist->user)->create(['name' => 'Old Artist Name']);
$data = ArtistUpdateData::make(name: 'Existing Artist Name');
$this->expectException(ArtistNameConflictException::class);
$this->service->updateArtist($artist, $data);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/MediaBrowserTest.php | tests/Integration/Services/MediaBrowserTest.php | <?php
namespace Tests\Integration\Services;
use App\Enums\SongStorageType;
use App\Models\Folder;
use App\Models\Setting;
use App\Models\Song;
use App\Services\MediaBrowser;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class MediaBrowserTest extends TestCase
{
private MediaBrowser $browser;
public function setUp(): void
{
parent::setUp();
$this->browser = app(MediaBrowser::class);
}
#[Test]
public function createFolderStructureForSong(): void
{
Setting::set('media_path', $this->mediaPath);
/** @var Song $song */
$song = Song::factory()->create([
'path' => "$this->mediaPath/foo/bar/baz.mp3",
'storage' => SongStorageType::LOCAL,
]);
self::assertNull($song->folder);
$this->browser->maybeCreateFolderStructureForSong($song);
/** @var Folder $foo */
$foo = Folder::query()->where('path', 'foo')->first();
/** @var Folder $bar */
$bar = Folder::query()->where(['path' => 'foo/bar', 'parent_id' => $foo->id])->first();
self::assertTrue($song->folder->is($bar));
// Make sure subsequent runs work too
/** @var Song $qux */
$qux = Song::factory()->create([
'path' => "$this->mediaPath/foo/bar/qux.mp3",
'storage' => SongStorageType::LOCAL,
]);
$this->browser->maybeCreateFolderStructureForSong($qux);
self::assertTrue($qux->folder->is($bar));
$songInRootPath = Song::factory()->create([
'path' => "$this->mediaPath/baz.mp3",
'storage' => SongStorageType::LOCAL,
]);
$this->browser->maybeCreateFolderStructureForSong($songInRootPath);
self::assertNull($songInRootPath->folder);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/AuthenticationServiceTest.php | tests/Integration/Services/AuthenticationServiceTest.php | <?php
namespace Tests\Integration\Services;
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 AuthenticationServiceTest extends TestCase
{
private AuthenticationService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(AuthenticationService::class);
}
#[Test]
public function tryResetPasswordUsingBroker(): void
{
Event::fake();
$user = create_user();
self::assertTrue(
$this->service->tryResetPasswordUsingBroker($user->email, 'new-password', Password::createToken($user))
);
self::assertTrue(Hash::check('new-password', $user->fresh()->password));
Event::assertDispatched(PasswordReset::class);
}
#[Test]
public function tryResetPasswordUsingBrokerWithInvalidToken(): void
{
Event::fake();
$user = create_user(['password' => Hash::make('old-password')]);
self::assertFalse($this->service->tryResetPasswordUsingBroker($user->email, 'new-password', 'invalid-token'));
self::assertTrue(Hash::check('old-password', $user->fresh()->password));
Event::assertNotDispatched(PasswordReset::class);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/YouTubeServiceTest.php | tests/Integration/Services/YouTubeServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Http\Integrations\YouTube\Requests\SearchVideosRequest;
use App\Models\Artist;
use App\Models\Song;
use App\Services\YouTubeService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use PHPUnit\Framework\Attributes\Test;
use Saloon\Http\Faking\MockResponse;
use Saloon\Laravel\Saloon;
use Tests\TestCase;
use function Tests\test_path;
class YouTubeServiceTest extends TestCase
{
private YouTubeService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(YouTubeService::class);
}
#[Test]
public function searchVideosRelatedToSong(): void
{
/** @var Song $song */
$song = Song::factory()->for(Artist::factory()->create(['name' => 'Slipknot']))->create(['title' => 'Snuff']);
Saloon::fake([
SearchVideosRequest::class => MockResponse::make(
body: File::get(test_path('fixtures/youtube/search.json')),
),
]);
$response = $this->service->searchVideosRelatedToSong($song, 'my-token');
self::assertSame('Slipknot - Snuff [OFFICIAL VIDEO]', $response->items[0]->snippet->title);
self::assertNotNull(Cache::get('43d0e04621642165c5a3052b884945b9'));
Saloon::assertSent(static function (SearchVideosRequest $request): bool {
self::assertSame([
'part' => 'snippet',
'type' => 'video',
'maxResults' => 10,
'pageToken' => 'my-token',
'q' => 'Snuff Slipknot',
], $request->query()->all());
return true;
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/FavoriteServiceTest.php | tests/Integration/Services/FavoriteServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Events\MultipleSongsLiked;
use App\Events\MultipleSongsUnliked;
use App\Events\SongFavoriteToggled;
use App\Models\Album;
use App\Models\Favorite;
use App\Models\Song;
use App\Services\FavoriteService;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Event;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
class FavoriteServiceTest extends TestCase
{
private FavoriteService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(FavoriteService::class);
}
#[Test]
public function toggleFavoriteToTrue(): void
{
Event::fake(SongFavoriteToggled::class);
$user = create_user();
/** @var Song $song */
$song = Song::factory()->create();
$this->service->toggleFavorite($song, $user);
$this->assertDatabaseHas(Favorite::class, [
'user_id' => $user->id,
'favoriteable_type' => 'playable',
'favoriteable_id' => $song->id,
]);
Event::assertDispatched(SongFavoriteToggled::class);
}
#[Test]
public function toggleFavoriteToFalse(): void
{
Event::fake(SongFavoriteToggled::class);
$user = create_user();
/** @var Favorite $favorite */
$favorite = Favorite::factory()->for($user)->create();
$this->service->toggleFavorite($favorite->favoriteable, $user);
$this->assertDatabaseMissing(Favorite::class, ['id' => $favorite->id]);
Event::assertDispatched(SongFavoriteToggled::class);
}
#[Test]
public function toggleFavoriteAlbum(): void
{
Event::fake(SongFavoriteToggled::class);
$user = create_user();
/** @var Album $album */
$album = Album::factory()->create();
$this->service->toggleFavorite($album, $user);
$this->assertDatabaseHas(Favorite::class, [
'user_id' => $user->id,
'favoriteable_type' => 'album',
'favoriteable_id' => $album->id,
]);
Event::assertNotDispatched(SongFavoriteToggled::class);
}
#[Test]
public function batchFavorite(): void
{
Event::fake(MultipleSongsLiked::class);
/** @var Collection<int, Song> $songs */
$songs = Song::factory()->count(2)->create();
$user = create_user();
$this->service->batchFavorite($songs, $user); // @phpstan-ignore-line
foreach ($songs as $song) {
$this->assertDatabaseHas(Favorite::class, [
'user_id' => $user->id,
'favoriteable_type' => 'playable',
'favoriteable_id' => $song->id,
]);
}
Event::assertDispatched(MultipleSongsLiked::class, static function (MultipleSongsLiked $event) use ($user) {
return $event->songs->count() === 2 && $event->user->is($user);
});
}
#[Test]
public function batchUndoFavorite(): void
{
Event::fake(MultipleSongsUnliked::class);
$user = create_user();
/** @var Collection<int, Favorite> $favorites */
$favorites = Favorite::factory()->for($user)->count(2)->create();
$this->service->batchUndoFavorite(
$favorites->map(static fn (Favorite $favorite) => $favorite->favoriteable),
$user,
);
foreach ($favorites as $favorite) {
$this->assertDatabaseMissing(Favorite::class, ['id' => $favorite->id]);
}
Event::assertDispatched(MultipleSongsUnliked::class, static function (MultipleSongsUnliked $event) use ($user) {
return $event->songs->count() === 2 && $event->user->is($user);
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/LicenseServiceTest.php | tests/Integration/Services/LicenseServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Exceptions\FailedToActivateLicenseException;
use App\Http\Integrations\LemonSqueezy\Requests\ActivateLicenseRequest;
use App\Http\Integrations\LemonSqueezy\Requests\DeactivateLicenseRequest;
use App\Http\Integrations\LemonSqueezy\Requests\ValidateLicenseRequest;
use App\Models\License;
use App\Services\LicenseService;
use App\Values\License\LicenseStatus;
use Illuminate\Http\Response;
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\TestCase;
use function Tests\test_path;
class LicenseServiceTest extends TestCase
{
private LicenseService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(LicenseService::class);
}
#[Test]
public function activateLicense(): void
{
config(['lemonsqueezy.store_id' => 42]);
$key = '38b1460a-5104-4067-a91d-77b872934d51';
Saloon::fake([
ActivateLicenseRequest::class => MockResponse::make(
body: File::get(test_path('fixtures/lemonsqueezy/license-activated-successful.json')),
),
]);
$license = $this->service->activate($key);
self::assertSame($key, $license->key);
self::assertNotEmpty($license->instance);
self::assertSame('Luke Skywalker', $license->meta->customerName);
self::assertSame('luke@skywalker.com', $license->meta->customerEmail);
/** @var LicenseStatus $cachedLicenseStatus */
$cachedLicenseStatus = Cache::get('license_status');
self::assertSame($license->key, $cachedLicenseStatus->license->key);
self::assertTrue($cachedLicenseStatus->isValid());
Saloon::assertSent(static function (ActivateLicenseRequest $request) use ($key): bool {
self::assertSame([
'license_key' => $key,
'instance_name' => 'Koel Plus',
], $request->body()->all());
return true;
});
}
#[Test]
public function activateLicenseFailsBecauseOfIncorrectStoreId(): void
{
$this->expectException(FailedToActivateLicenseException::class);
$this->expectExceptionMessage('This license key is not from Koel’s official store.');
config(['lemonsqueezy.store_id' => 43]);
$key = '38b1460a-5104-4067-a91d-77b872934d51';
Saloon::fake([
ActivateLicenseRequest::class => MockResponse::make(
body: File::get(test_path('fixtures/lemonsqueezy/license-activated-successful.json')),
),
]);
$this->service->activate($key);
}
#[Test]
public function activateLicenseFailsForInvalidLicenseKey(): void
{
$this->expectException(FailedToActivateLicenseException::class);
$this->expectExceptionMessage('license_key not found');
Saloon::fake([
ActivateLicenseRequest::class => MockResponse::make(
body: File::get(test_path('fixtures/lemonsqueezy/license-invalid.json')),
status: Response::HTTP_NOT_FOUND,
),
]);
$this->service->activate('invalid-key');
}
#[Test]
public function deactivateLicense(): void
{
/** @var License $license */
$license = License::factory()->create();
Saloon::fake([
DeactivateLicenseRequest::class => MockResponse::make(
body: File::get(test_path('fixtures/lemonsqueezy/license-deactivated-successful.json')),
status: Response::HTTP_NOT_FOUND,
),
]);
$this->service->deactivate($license);
$this->assertModelMissing($license);
self::assertFalse(Cache::has('license_status'));
Saloon::assertSent(static function (DeactivateLicenseRequest $request) use ($license): bool {
self::assertSame([
'license_key' => $license->key,
'instance_id' => $license->instance->id,
], $request->body()->all());
return true;
});
}
#[Test]
public function deactivateLicenseHandlesLeftoverRecords(): void
{
/** @var License $license */
$license = License::factory()->create();
Saloon::fake([DeactivateLicenseRequest::class => MockResponse::make(status: Response::HTTP_NOT_FOUND)]);
$this->service->deactivate($license);
$this->assertModelMissing($license);
}
#[Test]
public function deactivateLicenseFails(): void
{
$this->expectExceptionMessage('Unprocessable Entity (422) Response: Something went horrible wrong');
/** @var License $license */
$license = License::factory()->create();
Saloon::fake([
DeactivateLicenseRequest::class => MockResponse::make(
body: 'Something went horrible wrong',
status: Response::HTTP_UNPROCESSABLE_ENTITY
),
]);
$this->service->deactivate($license);
}
#[Test]
public function getLicenseStatusFromCache(): void
{
Saloon::fake([]);
/** @var License $license */
$license = License::factory()->create();
Cache::put('license_status', LicenseStatus::valid($license));
self::assertTrue($this->service->getStatus()->license->is($license));
self::assertTrue($this->service->getStatus()->isValid());
Saloon::assertNothingSent();
}
#[Test]
public function getLicenseStatusWithNoLicenses(): void
{
Saloon::fake([]);
License::query()->delete();
self::assertTrue($this->service->getStatus()->hasNoLicense());
Saloon::assertNothingSent();
}
#[Test]
public function getLicenseStatusValidatesWithApi(): void
{
/** @var License $license */
$license = License::factory()->create();
self::assertFalse(Cache::has('license_status'));
Saloon::fake([
ValidateLicenseRequest::class => MockResponse::make(
body: File::get(test_path('fixtures/lemonsqueezy/license-validated-successful.json')),
),
]);
self::assertTrue($this->service->getStatus()->isValid());
self::assertTrue(Cache::has('license_status'));
Saloon::assertSent(static function (ValidateLicenseRequest $request) use ($license): bool {
self::assertSame([
'license_key' => $license->key,
'instance_id' => $license->instance->id,
], $request->body()->all());
return true;
});
}
#[Test]
public function getLicenseStatusValidatesWithApiWithInvalidLicense(): void
{
License::factory()->create();
self::assertFalse(Cache::has('license_status'));
Saloon::fake([ValidateLicenseRequest::class => MockResponse::make(status: Response::HTTP_NOT_FOUND)]);
self::assertFalse($this->service->getStatus()->isValid());
self::assertTrue(Cache::has('license_status'));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/RadioServiceTest.php | tests/Integration/Services/RadioServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Models\RadioStation;
use App\Services\RadioService;
use App\Values\Radio\RadioStationCreateData;
use App\Values\Radio\RadioStationUpdateData;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
class RadioServiceTest extends TestCase
{
private RadioService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(RadioService::class);
}
#[Test]
public function createRadioStation(): void
{
$user = create_user();
$station = $this->service->createRadioStation(RadioStationCreateData::make(
url: 'https://example.com/stream',
name: 'Test Radio',
description: 'A test radio station',
isPublic: true,
), $user);
self::assertSame('Test Radio', $station->name);
self::assertSame('https://example.com/stream', $station->url);
self::assertTrue($station->is_public);
self::assertSame('A test radio station', $station->description);
self::assertSame($user->id, $station->user_id);
self::assertNull($station->logo);
}
#[Test]
public function updateRadioStation(): void
{
/** @var RadioStation $station */
$station = RadioStation::factory()->create();
$updatedStation = $this->service->updateRadioStation($station, RadioStationUpdateData::make(
name: 'Updated Radio',
url: 'https://example.com/new-stream',
description: 'An updated test radio station',
));
self::assertSame('Updated Radio', $updatedStation->name);
self::assertSame('https://example.com/new-stream', $updatedStation->url);
self::assertFalse($updatedStation->is_public);
self::assertSame('An updated test radio station', $updatedStation->description);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/ITunesServiceTest.php | tests/Integration/Services/ITunesServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Http\Integrations\iTunes\Requests\GetTrackRequest;
use App\Models\Album;
use App\Models\Artist;
use App\Services\ITunesService;
use Illuminate\Support\Facades\Cache;
use PHPUnit\Framework\Attributes\Test;
use Saloon\Http\Faking\MockResponse;
use Saloon\Laravel\Saloon;
use Tests\TestCase;
class ITunesServiceTest extends TestCase
{
private ITunesService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(ITunesService::class);
}
#[Test]
public function configuration(): void
{
config(['koel.services.itunes.enabled' => true]);
self::assertTrue($this->service::used());
config(['koel.services.itunes.enabled' => false]);
self::assertFalse($this->service::used());
}
#[Test]
public function getTrackUrl(): void
{
config(['koel.services.itunes.enabled' => true]);
config(['koel.services.itunes.affiliate_id' => 'foo']);
Saloon::fake([
GetTrackRequest::class => MockResponse::make(body: [
'resultCount' => 1,
'results' => [['trackViewUrl' => 'https://itunes.apple.com/bar']],
]),
]);
/** @var Album $album */
$album = Album::factory()
->for(Artist::factory()->create(['name' => 'Queen']))
->create(['name' => 'A Night at the Opera']);
self::assertSame(
'https://itunes.apple.com/bar?at=foo',
$this->service->getTrackUrl('Bohemian Rhapsody', $album)
);
self::assertSame('https://itunes.apple.com/bar?at=foo', Cache::get('8eca87872691f06f3cc6f2fbe6b3c528'));
Saloon::assertSent(static function (GetTrackRequest $request): bool {
self::assertSame([
'term' => 'Bohemian Rhapsody A Night at the Opera Queen',
'media' => 'music',
'entity' => 'song',
'limit' => 1,
], $request->query()->all());
return true;
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/ThemeServiceTest.php | tests/Integration/Services/ThemeServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Models\Theme;
use App\Services\ThemeService;
use App\Values\Theme\ThemeCreateData;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
use function Tests\minimal_base64_encoded_image;
class ThemeServiceTest extends TestCase
{
private ThemeService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(ThemeService::class);
}
#[Test]
public function createTheme(): void
{
$user = create_user();
$theme = $this->service->createTheme($user, ThemeCreateData::make(
name: 'One Theme to Rule Them All',
fgColor: '#ffffff',
bgColor: '#000000',
bgImage: minimal_base64_encoded_image(),
highlightColor: '#ff0000',
fontFamily: 'system-ui',
fontSize: 14.0,
));
self::assertSame('One Theme to Rule Them All', $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(14.0, $theme->properties->fontSize);
self::assertTrue($theme->user->is($user));
self::assertNotEmpty($theme->properties->bgImage);
}
#[Test]
public function createThemeWithoutABackgroundImage(): void
{
$user = create_user();
$theme = $this->service->createTheme($user, ThemeCreateData::make(
name: 'One Theme to Rule Them All',
fgColor: '#ffffff',
bgColor: '#000000',
bgImage: '',
highlightColor: '#ff0000',
fontFamily: 'system-ui',
fontSize: 14.0,
));
self::assertSame('One Theme to Rule Them All', $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(14.0, $theme->properties->fontSize);
self::assertTrue($theme->user->is($user));
self::assertEmpty($theme->properties->bgImage);
}
#[Test]
public function deleteTheme(): void
{
/** @var Theme $theme */
$theme = Theme::factory()->create();
$this->service->deleteTheme($theme);
self::assertModelMissing($theme);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/SongServiceTest.php | tests/Integration/Services/SongServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Facades\Dispatcher;
use App\Jobs\DeleteSongFilesJob;
use App\Jobs\DeleteTranscodeFilesJob;
use App\Jobs\ExtractSongFolderStructureJob;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Setting;
use App\Models\Song;
use App\Models\Transcode;
use App\Services\Scanners\FileScanner;
use App\Services\SongService;
use App\Values\Scanning\ScanConfiguration;
use App\Values\Song\SongUpdateData;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_admin;
use function Tests\create_user;
use function Tests\test_path;
class SongServiceTest extends TestCase
{
private SongService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(SongService::class);
$user = create_user();
$this->actingAs($user);
Setting::set('media_path', $this->mediaPath);
}
#[Test]
public function updateSingleSong(): void
{
/** @var Song $song */
$song = Song::factory()->create();
$data = SongUpdateData::make(
albumArtistName: 'Queen',
disc: 1,
lyrics: 'Is this the real life?',
);
$result = $this->service->updateSongs([$song->id], $data);
/** @var Song $updatedSong */
$updatedSong = $result->updatedSongs->first();
self::assertCount(1, $result->updatedSongs);
self::assertEquals(1, $updatedSong->disc);
self::assertEquals(0, $updatedSong->track);
self::assertEquals('Is this the real life?', $updatedSong->lyrics);
self::assertEquals('', $updatedSong->genre);
self::assertEquals('Queen', $updatedSong->album_artist->name);
// We changed the album artist name, so the old album should have been removed
self::assertCount(1, $result->removedAlbumIds);
}
#[Test]
public function updateSingleSongWithAlbumChanged(): void
{
/** @var Song $song */
$song = Song::factory()->create();
$artist = $song->artist;
$album = $song->album;
$data = SongUpdateData::make(
albumName: 'New Album',
);
$result = $this->service->updateSongs([$song->id], $data);
/** @var Song $updatedSong */
$updatedSong = $result->updatedSongs->first();
self::assertTrue($updatedSong->artist->is($artist));
self::assertFalse($updatedSong->album->is($album));
self::assertSame('New Album', $updatedSong->album->name);
self::assertSame('New Album', $updatedSong->album_name);
// The old album should have been removed
self::assertCount(1, $result->removedAlbumIds);
self::assertSame($album->id, $result->removedAlbumIds->first());
}
#[Test]
public function updateSongWithArtistChanged(): void
{
/** @var Song $song */
$song = Song::factory()->create();
$artist = $song->artist;
$album = $song->album;
$albumName = $song->album->name;
$data = SongUpdateData::make(
artistName: 'New Artist',
);
$result = $this->service->updateSongs([$song->id], $data);
/** @var Song $updatedSong */
$updatedSong = $result->updatedSongs->first();
self::assertFalse($updatedSong->artist->is($artist));
self::assertSame('New Artist', $updatedSong->artist->name);
self::assertSame('New Artist', $updatedSong->artist_name);
// The album changes to a new one with the same name
self::assertFalse($updatedSong->album->is($album));
self::assertTrue($updatedSong->album->artist->is($updatedSong->artist));
self::assertSame($albumName, $updatedSong->album->name);
// Old album and artist should have been removed
self::assertCount(1, $result->removedAlbumIds);
self::assertCount(1, $result->removedArtistIds);
self::assertSame($album->id, $result->removedAlbumIds->first());
self::assertSame($artist->id, $result->removedArtistIds->first());
}
#[Test]
public function updateMultipleSongsTrackProvided(): void
{
/** @var Song $song1 */
$song1 = Song::factory()->create(['track' => 1]);
/** @var Song $song2 */
$song2 = Song::factory()->create(['track' => 2]);
$data = SongUpdateData::make(
artistName: 'Queen',
albumArtistName: 'New Album Artist',
track: 5,
disc: 2,
genre: 'Pop',
year: 2023,
lyrics: 'Is this the real life?'
);
$result = $this->service->updateSongs([$song1->id, $song2->id], $data);
self::assertEquals(2, $result->updatedSongs->count());
/** @var Song $updatedSong */
foreach ($result->updatedSongs as $updatedSong) {
self::assertEquals(2, $updatedSong->disc);
self::assertEquals(5, $updatedSong->track);
self::assertSame(2023, $updatedSong->year);
self::assertEquals('Is this the real life?', $updatedSong->lyrics);
self::assertEquals('Pop', $updatedSong->genre);
self::assertSame('New Album Artist', $updatedSong->album_artist->name);
self::assertSame('Queen', $updatedSong->artist_name);
}
}
#[Test]
public function updateMultipleTracksWithoutProvidingTrack(): void
{
/** @var Song $song1 */
$song1 = Song::factory()->create(['track' => 1, 'disc' => 1]);
/** @var Song $song2 */
$song2 = Song::factory()->create(['track' => 2, 'disc' => 1]);
$data = SongUpdateData::make(
artistName: 'Queen',
genre: 'Rock',
lyrics: 'Is this the real life?',
);
$result = $this->service->updateSongs([$song1->id, $song2->id], $data);
$updatedSongs = $result->updatedSongs;
self::assertCount(2, $updatedSongs);
$updatedSongs->each(static function (Song $song): void {
self::assertEquals(1, $song->disc);
self::assertEquals('Is this the real life?', $song->lyrics);
self::assertEquals('Rock', $song->genre);
self::assertEquals('Queen', $song->artist_name);
self::assertEquals('Queen', $song->artist->name);
});
self::assertEquals(1, $updatedSongs[0]->track);
self::assertEquals(2, $updatedSongs[1]->track);
}
#[Test]
public function deleteSongs(): void
{
$songs = Song::factory()->count(2)->create();
Dispatcher::expects('dispatch')
->with(DeleteSongFilesJob::class)
->andReturnUsing(static function (DeleteSongFilesJob $job) use ($songs): void {
self::assertEqualsCanonicalizing(
$job->files->pluck('location')->toArray(),
$songs->pluck('path')->toArray(),
);
});
Dispatcher::expects('dispatch')->with(DeleteTranscodeFilesJob::class)->never();
$this->service->deleteSongs($songs->pluck('id')->toArray());
$songs->each(fn (Song $song) => $this->assertDatabaseMissing(Song::class, ['id' => $song->id]));
}
#[Test]
public function deleteSongsWithTranscodes(): void
{
$transcodes = Transcode::factory()->count(2)->create();
$songs = $transcodes->map(static fn (Transcode $transcode) => $transcode->song); // @phpstan-ignore-line
Dispatcher::expects('dispatch')
->with(DeleteSongFilesJob::class)
->andReturnUsing(static function (DeleteSongFilesJob $job) use ($songs): void {
self::assertEqualsCanonicalizing(
$job->files->pluck('location')->toArray(),
$songs->pluck('path')->toArray(),
);
});
Dispatcher::expects('dispatch')
->with(DeleteTranscodeFilesJob::class)
->andReturnUsing(static function (DeleteTranscodeFilesJob $job) use ($transcodes): void {
self::assertEqualsCanonicalizing(
$job->files->pluck('location')->toArray(),
$transcodes->pluck('location')->toArray(),
);
});
$this->service->deleteSongs($transcodes->pluck('song_id')->toArray());
$transcodes->each(function (Transcode $transcode): void {
$this->assertDatabaseMissing(Song::class, ['id' => $transcode->song_id]);
$this->assertDatabaseMissing(Transcode::class, ['id' => $transcode->id]);
});
}
#[Test]
public function createOrUpdateFromScan(): void
{
Dispatcher::expects('dispatch')->with(ExtractSongFolderStructureJob::class);
$info = app(FileScanner::class)->scan(test_path('songs/full.mp3'));
$song = $this->service->createOrUpdateSongFromScan($info, ScanConfiguration::make(owner: create_admin()));
self::assertArraySubset([
'title' => 'Amet',
'track' => 5,
'disc' => 3,
'lyrics' => "Foo\rbar",
'mtime' => filemtime(test_path('songs/full.mp3')),
'year' => 2015,
'is_public' => false,
'artist_name' => 'Koel',
'album_name' => 'Koel Testing Vol. 1',
'file_size' => 72_081,
], $song->getAttributes());
self::assertSame(2015, $song->album->year);
}
#[Test]
public function creatingOrUpdatingFromScanSetsAlbumReleaseYearIfApplicable(): void
{
Dispatcher::expects('dispatch')->with(ExtractSongFolderStructureJob::class);
$owner = create_admin();
/** @var Artist $artist */
$artist = Artist::factory(['name' => 'Koel'])->for($owner)->create();
/** @var Album $album */
$album = Album::factory([
'name' => 'Koel Testing Vol. 1',
'year' => null,
])
->for($owner)
->for($artist)
->create();
self::assertNull($album->year);
$info = app(FileScanner::class)->scan(test_path('songs/full.mp3'));
$this->service->createOrUpdateSongFromScan($info, ScanConfiguration::make(owner: $owner));
self::assertSame(2015, $album->refresh()->year);
}
#[Test]
public function creatingOrUpdatingFromScanSetsAlbumReleaseYearIfItAlreadyExists(): void
{
Dispatcher::expects('dispatch')->with(ExtractSongFolderStructureJob::class);
$owner = create_admin();
/** @var Artist $artist */
$artist = Artist::factory(['name' => 'Koel'])->for($owner)->create();
/** @var Album $album */
$album = Album::factory([
'name' => 'Koel Testing Vol. 1',
'year' => 2018,
])
->for($owner)
->for($artist)
->create();
$info = app(FileScanner::class)->scan(test_path('songs/full.mp3'));
$song = $this->service->createOrUpdateSongFromScan($info, ScanConfiguration::make(owner: $owner));
self::assertTrue($song->album->is($album));
self::assertSame(2018, $album->refresh()->year);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/UserServiceTest.php | tests/Integration/Services/UserServiceTest.php | <?php
namespace Tests\Integration\Services;
use App\Enums\Acl\Role;
use App\Exceptions\UserProspectUpdateDeniedException;
use App\Services\UserService;
use App\Values\User\UserCreateData;
use App\Values\User\UserUpdateData;
use Illuminate\Support\Facades\Hash;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_admin;
use function Tests\create_user;
use function Tests\create_user_prospect;
use function Tests\minimal_base64_encoded_image;
class UserServiceTest extends TestCase
{
private UserService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(UserService::class);
}
#[Test]
public function createUser(): void
{
$user = $this->service->createUser(UserCreateData::make(
name: 'Bruce Dickinson',
email: 'bruce@dickison.com',
plainTextPassword: 'FearOfTheDark',
role: Role::ADMIN,
avatar: minimal_base64_encoded_image(),
));
$this->assertModelExists($user);
self::assertTrue(Hash::check('FearOfTheDark', $user->password));
self::assertSame(Role::ADMIN, $user->role);
self::assertFileExists(image_storage_path($user->getRawOriginal('avatar')));
}
#[Test]
public function createUserWithEmptyAvatarHasGravatar(): void
{
$user = $this->service->createUser(UserCreateData::make(
name: 'Bruce Dickinson',
email: 'bruce@dickison.com',
plainTextPassword: 'FearOfTheDark',
));
$this->assertModelExists($user);
self::assertTrue(Hash::check('FearOfTheDark', $user->password));
self::assertSame(Role::USER, $user->role);
self::assertStringStartsWith('https://www.gravatar.com/avatar/', $user->avatar);
}
#[Test]
public function createUserWithNoPassword(): void
{
$user = $this->service->createUser(UserCreateData::make(
name: 'Bruce Dickinson',
email: 'bruce@dickison.com',
plainTextPassword: '',
));
$this->assertModelExists($user);
self::assertEmpty($user->password);
}
#[Test]
public function updateUser(): void
{
$user = create_user();
$this->service->updateUser($user, UserUpdateData::make(
name: 'Steve Harris',
email: 'steve@iron.com',
plainTextPassword: 'TheTrooper',
role: Role::ADMIN,
avatar: minimal_base64_encoded_image(),
));
$user->refresh();
self::assertSame('Steve Harris', $user->name);
self::assertSame('steve@iron.com', $user->email);
self::assertTrue(Hash::check('TheTrooper', $user->password));
self::assertSame(Role::ADMIN, $user->role);
self::assertFileExists(image_storage_path($user->getRawOriginal('avatar')));
}
#[Test]
public function updateUserWithoutSettingPasswordOrRole(): void
{
$user = create_admin(['password' => Hash::make('TheTrooper')]);
self::assertSame(Role::ADMIN, $user->role);
$this->service->updateUser($user, UserUpdateData::make(
name: 'Steve Harris',
email: 'steve@iron.com'
));
$user->refresh();
self::assertSame('Steve Harris', $user->name);
self::assertSame('steve@iron.com', $user->email);
self::assertTrue(Hash::check('TheTrooper', $user->password));
self::assertSame(Role::ADMIN, $user->role); // shouldn't change
}
#[Test]
public function updateProspectUserIsNotAllowed(): void
{
$this->expectException(UserProspectUpdateDeniedException::class);
$this->service->updateUser(create_user_prospect(), UserUpdateData::make(
name: 'Steve Harris',
email: 'steve@iron.com',
));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/Transcoding/LocalTranscodingStrategyTest.php | tests/Integration/Services/Transcoding/LocalTranscodingStrategyTest.php | <?php
namespace Tests\Integration\Services\Transcoding;
use App\Helpers\Ulid;
use App\Models\Song;
use App\Models\Transcode;
use App\Services\Transcoding\LocalTranscodingStrategy;
use App\Services\Transcoding\Transcoder;
use Illuminate\Support\Facades\File;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class LocalTranscodingStrategyTest extends TestCase
{
private LocalTranscodingStrategy $strategy;
private MockInterface|Transcoder $transcoder;
public function setUp(): void
{
parent::setUp();
$this->transcoder = $this->mock(Transcoder::class);
$this->strategy = app(LocalTranscodingStrategy::class);
}
#[Test]
public function getTranscodedLocation(): void
{
/** @var Song $song */
$song = Song::factory()->create(['path' => '/path/to/song.flac']);
$ulid = Ulid::freeze();
$destination = artifact_path("transcodes/128/$ulid.m4a", ensureDirectoryExists: false);
$this->transcoder->expects('transcode')->with('/path/to/song.flac', $destination, 128);
File::expects('hash')->with($destination)->andReturn('mocked-checksum');
File::expects('ensureDirectoryExists')->with(dirname($destination));
File::expects('size')->with($destination)->andReturn(1_024);
$transcodedPath = $this->strategy->getTranscodeLocation($song, 128);
$this->assertDatabaseHas(Transcode::class, [
'song_id' => $song->id,
'location' => $destination,
'bit_rate' => 128,
'hash' => 'mocked-checksum',
'file_size' => 1_024,
]);
self::assertSame($transcodedPath, $destination);
}
#[Test]
public function getFromDatabaseRecord(): void
{
$this->transcoder->expects('transcode')->never();
/** @var Transcode $transcode */
$transcode = Transcode::factory()->create([
'location' => '/path/to/transcode.m4a',
'bit_rate' => 128,
'hash' => 'mocked-checksum',
]);
File::expects('isReadable')
->with('/path/to/transcode.m4a')
->andReturn(true);
File::expects('hash')
->with('/path/to/transcode.m4a')
->andReturn('mocked-checksum');
$transcodedPath = $this->strategy->getTranscodeLocation($transcode->song, $transcode->bit_rate);
self::assertSame($transcode->location, $transcodedPath);
}
#[Test]
public function retranscodeIfRecordIsInvalid(): void
{
$song = Song::factory()->create(['path' => '/path/to/song.flac']);
$ulid = Ulid::freeze();
/** @var Transcode $transcode */
$transcode = Transcode::factory()->for($song)->create([
'location' => '/path/to/transcode.m4a',
'bit_rate' => 128,
'hash' => 'mocked-checksum',
]);
$destination = artifact_path("transcodes/128/$ulid.m4a", ensureDirectoryExists: false);
File::expects('isReadable')->with('/path/to/transcode.m4a')->andReturn(false);
File::expects('delete')->with('/path/to/transcode.m4a');
File::expects('hash')->with($destination)->andReturn('mocked-checksum');
File::expects('ensureDirectoryExists')->with(dirname($destination));
File::expects('size')->with($destination)->andReturn(1_024);
$this->transcoder->expects('transcode')->with('/path/to/song.flac', $destination, 128);
$transcodedLocation = $this->strategy->getTranscodeLocation($song, 128);
self::assertSame($destination, $transcodedLocation);
self::assertSame($transcode->refresh()->location, $transcodedLocation);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/Transcoding/SfpTranscodingStrategyTest.php | tests/Integration/Services/Transcoding/SfpTranscodingStrategyTest.php | <?php
namespace Tests\Integration\Services\Transcoding;
use App\Enums\SongStorageType;
use App\Helpers\Ulid;
use App\Models\Song;
use App\Models\Transcode;
use App\Services\SongStorages\SftpStorage;
use App\Services\Transcoding\SftpTranscodingStrategy;
use App\Services\Transcoding\Transcoder;
use Illuminate\Support\Facades\File;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class SfpTranscodingStrategyTest extends TestCase
{
private MockInterface|Transcoder $transcoder;
private SftpTranscodingStrategy $strategy;
public function setUp(): void
{
parent::setUp();
$this->transcoder = $this->mock(Transcoder::class);
$this->strategy = app(SftpTranscodingStrategy::class);
}
#[Test]
public function getTranscodeLocation(): void
{
/** @var Song $song */
$song = Song::factory()->create([
'path' => 'sftp://remote/path/to/song.flac',
'storage' => SongStorageType::SFTP,
]);
$ulid = Ulid::freeze();
$destination = artifact_path("transcodes/128/$ulid.m4a", ensureDirectoryExists: false);
$storage = $this->mock(SftpStorage::class);
$storage->expects('copyToLocal')->with('remote/path/to/song.flac')->andReturn('/tmp/song.flac');
File::expects('ensureDirectoryExists')->with(dirname($destination));
File::expects('size')->with($destination)->andReturn(1_024);
$this->transcoder->expects('transcode')->with('/tmp/song.flac', $destination, 128);
File::expects('hash')->with($destination)->andReturn('mocked-checksum');
File::expects('delete')->with('/tmp/song.flac');
$this->strategy->getTranscodeLocation($song, 128);
$this->assertDatabaseHas(Transcode::class, [
'song_id' => $song->id,
'location' => $destination,
'bit_rate' => 128,
'hash' => 'mocked-checksum',
'file_size' => 1_024,
]);
}
#[Test]
public function getFromDatabaseRecord(): void
{
$this->transcoder->expects('transcode')->never();
/** @var Transcode $transcode */
$transcode = Transcode::factory()->create([
'location' => '/path/to/transcode.m4a',
'bit_rate' => 128,
'hash' => 'mocked-checksum',
]);
File::expects('isReadable')
->with('/path/to/transcode.m4a')
->andReturn(true);
File::expects('hash')
->with('/path/to/transcode.m4a')
->andReturn('mocked-checksum');
$transcodedPath = $this->strategy->getTranscodeLocation($transcode->song, $transcode->bit_rate);
self::assertSame($transcode->location, $transcodedPath);
}
#[Test]
public function retranscodeIfRecordIsInvalid(): void
{
$song = Song::factory()->create([
'path' => 'sftp://remote/path/to/song.flac',
'storage' => SongStorageType::SFTP,
]);
$ulid = Ulid::freeze();
/** @var Transcode $transcode */
$transcode = Transcode::factory()->for($song)->create([
'location' => '/path/to/transcode.m4a',
'bit_rate' => 128,
'hash' => 'mocked-checksum',
]);
File::expects('isReadable')->with('/path/to/transcode.m4a')->andReturn(false);
File::expects('delete')->with('/path/to/transcode.m4a');
$storage = $this->mock(SftpStorage::class);
$storage->expects('copyToLocal')->with('remote/path/to/song.flac')->andReturn('/tmp/song.flac');
$destination = artifact_path("transcodes/128/$ulid.m4a", ensureDirectoryExists: false);
File::expects('ensureDirectoryExists')->with(dirname($destination));
$this->transcoder->expects('transcode')->with('/tmp/song.flac', $destination, 128);
File::expects('hash')->with($destination)->andReturn('mocked-checksum');
File::expects('size')->with($destination)->andReturn(1_024);
File::expects('delete')->with('/tmp/song.flac');
$this->strategy->getTranscodeLocation($song, 128);
self::assertSame($destination, $transcode->refresh()->location);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/Transcoding/CloudTranscodingStrategyTest.php | tests/Integration/Services/Transcoding/CloudTranscodingStrategyTest.php | <?php
namespace Tests\Integration\Services\Transcoding;
use App\Enums\SongStorageType;
use App\Helpers\Ulid;
use App\Models\Song;
use App\Models\Transcode;
use App\Services\SongStorages\S3CompatibleStorage;
use App\Services\Transcoding\CloudTranscodingStrategy;
use App\Services\Transcoding\Transcoder;
use Illuminate\Support\Facades\File;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class CloudTranscodingStrategyTest extends TestCase
{
private CloudTranscodingStrategy $strategy;
private MockInterface|Transcoder $transcoder;
public function setUp(): void
{
parent::setUp();
$this->transcoder = $this->mock(Transcoder::class);
$this->strategy = app(CloudTranscodingStrategy::class);
}
#[Test]
public function getTranscodeLocation(): void
{
/** @var Song $song */
$song = Song::factory()->create([
'path' => 's3://bucket/key.flac',
'storage' => SongStorageType::S3,
]);
$storage = $this->mock(S3CompatibleStorage::class);
$ulid = Ulid::freeze();
$songPresignedUrl = 'https://s3.song.presigned.url/key.flac';
$tmpDestination = artifact_path("tmp/$ulid.m4a", ensureDirectoryExists: false);
$transcodeKey = "transcodes/128/$ulid.m4a";
$transcodePresignedUrl = "https://s3.song.presigned.url/transcodes/128/$ulid.m4a";
$storage->expects('getPresignedUrl')->with('key.flac')->andReturn($songPresignedUrl);
$storage->expects('getPresignedUrl')->with($transcodeKey)->andReturn($transcodePresignedUrl);
$storage->expects('uploadToStorage')->with($transcodeKey, $tmpDestination);
$this->transcoder->expects('transcode')->with($songPresignedUrl, $tmpDestination, 128);
File::expects('ensureDirectoryExists')->with(dirname($tmpDestination));
File::expects('hash')->with($tmpDestination)->andReturn('mocked-checksum');
File::expects('delete')->with($tmpDestination);
File::expects('size')->with($tmpDestination)->andReturn(1_024);
$transcodedPath = $this->strategy->getTranscodeLocation($song, 128);
self::assertSame($transcodePresignedUrl, $transcodedPath);
$this->assertDatabaseHas(Transcode::class, [
'song_id' => $song->id,
'location' => $transcodeKey,
'bit_rate' => 128,
'hash' => 'mocked-checksum',
'file_size' => 1_024,
]);
}
#[Test]
public function getFromDatabaseRecord(): void
{
/** @var Song $song */
$song = Song::factory()->create([
'path' => 's3://bucket/key.flac',
'storage' => SongStorageType::S3,
]);
Transcode::factory()->for($song)->create([
'location' => 'transcodes/128/some-ulid.m4a',
'bit_rate' => 128,
]);
$storage = $this->mock(S3CompatibleStorage::class);
$storage->expects('getPresignedUrl')
->with('transcodes/128/some-ulid.m4a')
->andReturn('https://s3.song.presigned.url/transcodes/128/some-ulid.m4a');
$this->transcoder->expects('transcode')->never();
self::assertSame(
'https://s3.song.presigned.url/transcodes/128/some-ulid.m4a',
$this->strategy->getTranscodeLocation($song, 128)
);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/SongStorages/LocalStorageTest.php | tests/Integration/Services/SongStorages/LocalStorageTest.php | <?php
namespace Tests\Integration\Services\SongStorages;
use App\Exceptions\MediaPathNotSetException;
use App\Models\Setting;
use App\Services\SongStorages\LocalStorage;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Mockery;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
use function Tests\test_path;
class LocalStorageTest extends TestCase
{
private LocalStorage $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(LocalStorage::class);
}
#[Test]
public function storeUploadedFileWithMediaPathNotSet(): void
{
Setting::set('media_path', '');
$this->expectException(MediaPathNotSetException::class);
$this->service->storeUploadedFile(Mockery::mock(UploadedFile::class), create_user());
}
#[Test]
public function storeUploadedFile(): void
{
Setting::set('media_path', public_path('sandbox/media'));
File::copy(test_path('songs/full.mp3'), artifact_path('tmp/random/full.mp3'));
$user = create_user();
$reference = $this->service->storeUploadedFile(artifact_path('tmp/random/full.mp3'), $user);
self::assertSame(public_path("sandbox/media/__KOEL_UPLOADS_\${$user->id}__/full.mp3"), $reference->location);
self::assertSame($reference->location, $reference->localPath);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/Streamer/StreamerTest.php | tests/Integration/Services/Streamer/StreamerTest.php | <?php
namespace Tests\Integration\Services\Streamer;
use App\Enums\SongStorageType;
use App\Exceptions\KoelPlusRequiredException;
use App\Models\Song;
use App\Services\Streamer\Adapters\LocalStreamerAdapter;
use App\Services\Streamer\Adapters\PhpStreamerAdapter;
use App\Services\Streamer\Adapters\PodcastStreamerAdapter;
use App\Services\Streamer\Adapters\S3CompatibleStreamerAdapter;
use App\Services\Streamer\Adapters\TranscodingStreamerAdapter;
use App\Services\Streamer\Adapters\XAccelRedirectStreamerAdapter;
use App\Services\Streamer\Adapters\XSendFileStreamerAdapter;
use App\Services\Streamer\Streamer;
use App\Values\RequestedStreamingConfig;
use Illuminate\Support\Facades\Http;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\test_path;
class StreamerTest extends TestCase
{
#[Test]
public function resolveAdapters(): void
{
// prevent real HTTP calls from being made, e.g., from DropboxStorage
Http::fake();
collect(SongStorageType::cases())
->each(function (SongStorageType $type): void {
/** @var Song $song */
$song = Song::factory()->make(['storage' => $type]);
switch ($type) {
case SongStorageType::S3:
case SongStorageType::DROPBOX:
$this->expectException(KoelPlusRequiredException::class);
new Streamer($song);
break;
case SongStorageType::S3_LAMBDA:
self::assertInstanceOf(S3CompatibleStreamerAdapter::class, (new Streamer($song))->getAdapter());
break;
case SongStorageType::LOCAL:
self::assertInstanceOf(LocalStreamerAdapter::class, (new Streamer($song))->getAdapter());
break;
default:
self::fail("Storage type not covered by tests: $type->value");
}
});
}
#[Test]
public function doNotUseTranscodingAdapterToPlayFlacIfConfiguredSo(): void
{
$backup = config('koel.streaming.transcode_flac');
config(['koel.streaming.transcode_flac' => false]);
/** @var Song $song */
$song = Song::factory()->create([
'storage' => SongStorageType::LOCAL,
'path' => '/tmp/test.flac',
'mime_type' => 'audio/flac',
]);
$streamer = new Streamer($song, null);
self::assertInstanceOf(LocalStreamerAdapter::class, $streamer->getAdapter());
config(['koel.streaming.transcode_flac' => $backup]);
}
#[Test]
public function useTranscodingAdapterToPlayFlacIfConfiguredSo(): void
{
/** @var Song $song */
$song = Song::factory()->create(['storage' => SongStorageType::LOCAL]);
$streamer = new Streamer($song, null, RequestedStreamingConfig::make(transcode: true));
self::assertInstanceOf(TranscodingStreamerAdapter::class, $streamer->getAdapter());
}
#[Test]
public function useTranscodingAdapterIfSongMimeTypeRequiresTranscoding(): void
{
$backupConfig = config('koel.streaming.transcode_required_mime_types');
config(['koel.streaming.transcode_required_mime_types' => ['audio/aif']]);
/** @var Song $song */
$song = Song::factory()->create([
'storage' => SongStorageType::LOCAL,
'path' => '/tmp/test.aiff',
'mime_type' => 'audio/aif',
]);
$streamer = new Streamer($song, null);
self::assertInstanceOf(TranscodingStreamerAdapter::class, $streamer->getAdapter());
config(['koel.streaming.transcode_required_mime_types' => $backupConfig]);
}
/** @return array<mixed> */
public static function provideStreamConfigData(): array
{
return [
PhpStreamerAdapter::class => [null, PhpStreamerAdapter::class],
XSendFileStreamerAdapter::class => ['x-sendfile', XSendFileStreamerAdapter::class],
XAccelRedirectStreamerAdapter::class => ['x-accel-redirect', XAccelRedirectStreamerAdapter::class],
];
}
#[DataProvider('provideStreamConfigData')]
#[Test]
public function resolveLocalAdapter(?string $config, string $expectedClass): void
{
config(['koel.streaming.method' => $config]);
/** @var Song $song */
$song = Song::factory()->make(['path' => test_path('songs/blank.mp3')]);
self::assertInstanceOf($expectedClass, (new Streamer($song))->getAdapter());
config(['koel.streaming.method' => null]);
}
#[Test]
public function resolvePodcastAdapter(): void
{
/** @var Song $song */
$song = Song::factory()->asEpisode()->create();
$streamer = new Streamer($song);
self::assertInstanceOf(PodcastStreamerAdapter::class, $streamer->getAdapter());
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/Scanners/FileScannerTest.php | tests/Integration/Services/Scanners/FileScannerTest.php | <?php
namespace Tests\Integration\Services\Scanners;
use App\Helpers\Ulid;
use App\Models\Setting;
use App\Services\Scanners\FileScanner;
use getID3;
use Illuminate\Support\Facades\File;
use Mockery;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\test_path;
class FileScannerTest extends TestCase
{
private FileScanner $scanner;
public function setUp(): void
{
parent::setUp();
Setting::set('media_path', $this->mediaPath);
$this->scanner = app(FileScanner::class);
}
protected function tearDown(): void
{
Setting::set('media_path', '');
parent::tearDown();
}
#[Test]
public function getFileInfo(): void
{
$info = $this->scanner->scan(test_path('songs/full.mp3'));
$expectedData = [
'artist' => 'Koel',
'album' => 'Koel Testing Vol. 1',
'title' => 'Amet',
'track' => 5,
'disc' => 3,
'lyrics' => "Foo\rbar",
'cover' => [
'data' => File::get(test_path('fixtures/cover.png')),
'image_mime' => 'image/png',
'image_width' => 512,
'image_height' => 512,
'imagetype' => 'PNG',
'picturetype' => 'Other',
'description' => '',
'datalength' => 7627,
],
'path' => test_path('songs/full.mp3'),
'mtime' => filemtime(test_path('songs/full.mp3')),
'albumartist' => '',
'year' => 2015,
'mime_type' => 'audio/mpeg',
'file_size' => 72_081,
];
self::assertArraySubset($expectedData, $info->toArray());
self::assertEqualsWithDelta(10, $info->length, 0.1);
}
#[Test]
public function getFileInfoVorbisCommentsFlac(): void
{
$flacPath = test_path('songs/full-vorbis-comments.flac');
$info = $this->scanner->scan($flacPath);
$expectedData = [
'artist' => 'Koel',
'album' => 'Koel Testing Vol. 1',
'albumartist' => 'Koel',
'title' => 'Amet',
'track' => 5,
'disc' => 3,
'lyrics' => "Foo\r\nbar",
'cover' => [
'data' => File::get(test_path('fixtures/cover.png')),
'image_mime' => 'image/png',
'image_width' => 512,
'image_height' => 512,
'picturetype' => 'Other',
'datalength' => 7627,
],
'path' => realpath($flacPath),
'mtime' => filemtime($flacPath),
'mime_type' => 'audio/flac',
'file_size' => 532_201,
];
self::assertArraySubset($expectedData, $info->toArray());
self::assertEqualsWithDelta(10, $info->length, 0.1);
}
#[Test]
public function songWithoutTitleHasFileNameAsTitle(): void
{
self::assertSame('blank', $this->scanner->scan(test_path('songs/blank.mp3'))->title);
}
#[Test]
public function ignoreLrcFileIfEmbeddedLyricsAvailable(): void
{
$base = sys_get_temp_dir() . '/' . Ulid::generate();
$mediaFile = $base . '.mp3';
$lrcFile = $base . '.lrc';
File::copy(test_path('songs/full.mp3'), $mediaFile);
File::copy(test_path('fixtures/simple.lrc'), $lrcFile);
self::assertSame("Foo\rbar", $this->scanner->scan($mediaFile)->lyrics);
}
#[Test]
public function readLrcFileIfEmbeddedLyricsNotAvailable(): void
{
$base = sys_get_temp_dir() . '/' . Ulid::generate();
$mediaFile = $base . '.mp3';
$lrcFile = $base . '.lrc';
File::copy(test_path('songs/blank.mp3'), $mediaFile);
File::copy(test_path('fixtures/simple.lrc'), $lrcFile);
self::assertSame("Line 1\nLine 2\nLine 3", $this->scanner->scan($mediaFile)->lyrics);
}
#[Test]
public function htmlEntities(): void
{
$path = test_path('songs/blank.mp3');
$analyzed = [
'filenamepath' => $path,
'tags' => [
'id3v2' => [
'title' => ['水谷広実'],
'album' => ['小岩井こ Random'],
'artist' => ['佐倉綾音 Unknown'],
],
],
'encoding' => 'UTF-8',
'playtime_seconds' => 100,
];
$this->swap(
getID3::class,
Mockery::mock(getID3::class, [
'CopyTagsToComments' => $analyzed,
'analyze' => $analyzed,
])
);
/** @var FileScanner $fileScanner */
$fileScanner = app(FileScanner::class);
$info = $fileScanner->scan($path);
self::assertSame('佐倉綾音 Unknown', $info->artistName);
self::assertSame('小岩井こ Random', $info->albumName);
self::assertSame('水谷広実', $info->title);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/Scanners/DirectoryScannerTest.php | tests/Integration/Services/Scanners/DirectoryScannerTest.php | <?php
namespace Tests\Integration\Services\Scanners;
use App\Events\MediaScanCompleted;
use App\Facades\Dispatcher;
use App\Jobs\ExtractSongFolderStructureJob;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Setting;
use App\Models\Song;
use App\Services\Scanners\DirectoryScanner;
use App\Values\Scanning\ScanConfiguration;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Event;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_admin;
class DirectoryScannerTest extends TestCase
{
private DirectoryScanner $scanner;
public function setUp(): void
{
parent::setUp();
Setting::set('media_path', realpath($this->mediaPath));
$this->scanner = app(DirectoryScanner::class);
}
private function path(string $subPath): string
{
return realpath($this->mediaPath . $subPath);
}
#[Test]
public function scan(): void
{
Event::fake([MediaScanCompleted::class]);
Dispatcher::shouldReceive('dispatch')->with(ExtractSongFolderStructureJob::class)->atLeast();
$owner = create_admin();
$this->scanner->scan($this->mediaPath, ScanConfiguration::make(owner: $owner));
// Standard mp3 files under the root path should be recognized
$this->assertDatabaseHas(Song::class, [
'path' => $this->path('/full.mp3'),
'track' => 5,
'owner_id' => $owner->id,
]);
// Ogg files and audio files in subdirectories should be recognized
$this->assertDatabaseHas(Song::class, [
'path' => $this->path('/subdir/back-in-black.ogg'),
'owner_id' => $owner->id,
]);
// GitHub issue #380. folder.png should be copied and used as the cover for files
// under subdir/
/** @var Song $song */
$song = Song::query()->where('path', $this->path('/subdir/back-in-black.ogg'))->first();
self::assertNotEmpty($song->album->cover);
// File search shouldn't be case-sensitive.
$this->assertDatabaseHas(Song::class, ['path' => $this->path('/subdir/no-name.mp3')]);
// Non-audio files shouldn't be recognized
$this->assertDatabaseMissing(Song::class, ['path' => $this->path('/rubbish.log')]);
// Broken/corrupted audio files shouldn't be recognized
$this->assertDatabaseMissing(Song::class, ['path' => $this->path('/fake.mp3')]);
// Artists should be created
$this->assertDatabaseHas(Artist::class, [
'name' => 'Cuckoo',
'user_id' => $owner->id,
]);
$this->assertDatabaseHas(Artist::class, [
'name' => 'Koel',
'user_id' => $owner->id,
]);
// Albums should be created
$this->assertDatabaseHas(Album::class, ['name' => 'Koel Testing Vol. 1']);
// Albums and artists should be correctly linked
/** @var Album $album */
$album = Album::query()->where('name', 'Koel Testing Vol. 1')->first();
self::assertSame('Koel', $album->artist->name);
// Compilation albums, artists and songs must be recognized
/** @var Song $song */
$song = Song::query()->where('title', 'This song belongs to a compilation')->first();
self::assertFalse($song->album_artist->is($song->artist));
self::assertSame('Koel', $song->album_artist->name);
self::assertSame('Cuckoo', $song->artist->name);
// An event should be dispatched to indicate the scan is completed
Event::assertDispatched(MediaScanCompleted::class);
}
#[Test]
public function modifiedFileIsRescanned(): void
{
Event::fake([MediaScanCompleted::class]);
Dispatcher::shouldReceive('dispatch')->with(ExtractSongFolderStructureJob::class)->atLeast();
$config = ScanConfiguration::make(owner: create_admin());
$this->scanner->scan($this->mediaPath, $config);
/** @var Song $song */
$song = Song::query()->latest()->first();
$mtime = $song->mtime;
$song->update(['mtime' => $mtime + 1000]);
$this->scanner->scan($this->mediaPath, $config);
self::assertSame($mtime, $song->refresh()->mtime);
}
#[Test]
public function rescanWithoutForceDoesNotResetData(): void
{
Event::fake([MediaScanCompleted::class]);
Dispatcher::shouldReceive('dispatch')->with(ExtractSongFolderStructureJob::class)->atLeast();
$config = ScanConfiguration::make(owner: create_admin());
$this->scanner->scan($this->mediaPath, $config);
/** @var Song $song */
$song = Song::query()->latest()->first();
$song->update([
'title' => "It's John Cena!",
'lyrics' => 'Booom Wroooom',
]);
$this->scanner->scan($this->mediaPath, $config);
$song->refresh();
self::assertSame("It's John Cena!", $song->title);
self::assertSame('Booom Wroooom', $song->lyrics);
}
#[Test]
public function forceScanResetsData(): void
{
Event::fake([MediaScanCompleted::class]);
Dispatcher::shouldReceive('dispatch')->with(ExtractSongFolderStructureJob::class)->atLeast();
$owner = create_admin();
$this->scanner->scan($this->mediaPath, ScanConfiguration::make(owner: $owner));
/** @var Song $song */
$song = Song::query()->first();
$song->update([
'title' => "It's John Cena!",
'lyrics' => 'Booom Wroooom',
]);
$this->scanner->scan($this->mediaPath, ScanConfiguration::make(owner: create_admin(), force: true));
$song->refresh();
self::assertNotSame("It's John Cena!", $song->title);
self::assertNotSame('Booom Wroooom', $song->lyrics);
// make sure the user is not changed
self::assertSame($owner->id, $song->owner_id);
self::assertSame($owner->id, $song->artist->user_id);
self::assertSame($owner->id, $song->album->user_id);
}
#[Test]
public function ignoredTagsAreIgnoredEvenWithForceRescanning(): void
{
Event::fake([MediaScanCompleted::class]);
Dispatcher::shouldReceive('dispatch')->with(ExtractSongFolderStructureJob::class)->atLeast();
$owner = create_admin();
$this->scanner->scan($this->mediaPath, ScanConfiguration::make(owner: $owner));
/** @var Song $song */
$song = Song::query()->first();
$song->update([
'title' => "It's John Cena!",
'lyrics' => 'Booom Wroooom',
]);
$this->scanner->scan($this->mediaPath, ScanConfiguration::make(owner: $owner, ignores: ['title'], force: true));
$song->refresh();
self::assertSame("It's John Cena!", $song->title);
self::assertNotSame('Booom Wroooom', $song->lyrics);
}
#[Test]
public function scanAllTagsForNewFilesRegardlessOfIgnoredOption(): void
{
Event::fake([MediaScanCompleted::class]);
Dispatcher::shouldReceive('dispatch')->with(ExtractSongFolderStructureJob::class)->atLeast();
$owner = create_admin();
$this->scanner->scan($this->mediaPath, ScanConfiguration::make(owner: $owner));
/** @var Song $song */
$song = Song::query()->first();
$song->delete();
$this->scanner->scan(
$this->mediaPath,
ScanConfiguration::make(
owner: $owner,
ignores: ['title', 'disc', 'track'],
force: true
)
);
$ignores = [
'id',
'created_at',
'updated_at',
];
// Song should be added back with all info
self::assertEquals(
Arr::except(Song::query()->where('path', $song->path)->first()->withoutRelations()->toArray(), $ignores),
Arr::except($song->withoutRelations()->toArray(), $ignores)
);
}
#[Test]
public function hiddenFilesAndFoldersAreIgnoredIfConfiguredSo(): void
{
Event::fake([MediaScanCompleted::class]);
Dispatcher::shouldReceive('dispatch')->with(ExtractSongFolderStructureJob::class)->atLeast();
$config = ScanConfiguration::make(owner: create_admin());
config(['koel.ignore_dot_files' => true]);
$this->scanner->scan($this->mediaPath, $config);
$this->assertDatabaseMissing(Album::class, ['name' => 'Hidden Album']);
}
#[Test]
public function hiddenFilesAndFoldersAreScannedIfConfiguredSo(): void
{
Event::fake([MediaScanCompleted::class]);
Dispatcher::shouldReceive('dispatch')->with(ExtractSongFolderStructureJob::class)->atLeast();
$config = ScanConfiguration::make(owner: create_admin());
config(['koel.ignore_dot_files' => false]);
$this->scanner->scan($this->mediaPath, $config);
$this->assertDatabaseHas(Album::class, ['name' => 'Hidden Album']);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Services/Scanners/WatchRecordScannerTest.php | tests/Integration/Services/Scanners/WatchRecordScannerTest.php | <?php
namespace Tests\Integration\Services\Scanners;
use App\Events\MediaScanCompleted;
use App\Models\Setting;
use App\Models\Song;
use App\Services\Scanners\DirectoryScanner;
use App\Services\Scanners\WatchRecordScanner;
use App\Values\Scanning\ScanConfiguration;
use App\Values\WatchRecord\InotifyWatchRecord;
use Illuminate\Support\Facades\Event;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_admin;
class WatchRecordScannerTest extends TestCase
{
private WatchRecordScanner $scanner;
public function setUp(): void
{
parent::setUp();
Setting::set('media_path', realpath($this->mediaPath));
$this->scanner = app(WatchRecordScanner::class);
}
private function path(string $subPath): string
{
return realpath($this->mediaPath . $subPath);
}
#[Test]
public function scanAddedSongViaWatch(): void
{
$path = $this->path('/blank.mp3');
$this->scanner->scan(
new InotifyWatchRecord("CLOSE_WRITE,CLOSE $path"),
ScanConfiguration::make(owner: create_admin())
);
$this->assertDatabaseHas(Song::class, ['path' => $path]);
}
#[Test]
public function scanDeletedSongViaWatch(): void
{
/** @var Song $song */
$song = Song::factory()->create();
$this->scanner->scan(
new InotifyWatchRecord("DELETE $song->path"),
ScanConfiguration::make(owner: create_admin())
);
$this->assertModelMissing($song);
}
#[Test]
public function scanDeletedDirectoryViaWatch(): void
{
Event::fake(MediaScanCompleted::class);
$config = ScanConfiguration::make(owner: create_admin());
app(DirectoryScanner::class)->scan($this->mediaPath, $config);
$this->scanner->scan(new InotifyWatchRecord("MOVED_FROM,ISDIR $this->mediaPath/subdir"), $config);
$this->assertDatabaseMissing(Song::class, ['path' => $this->path('/subdir/sic.mp3')]);
$this->assertDatabaseMissing(Song::class, ['path' => $this->path('/subdir/no-name.mp3')]);
$this->assertDatabaseMissing(Song::class, ['path' => $this->path('/subdir/back-in-black.mp3')]);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/KoelPlus/Services/SettingServiceTest.php | tests/Integration/KoelPlus/Services/SettingServiceTest.php | <?php
namespace Tests\Integration\KoelPlus\Services;
use App\Models\Setting;
use App\Services\SettingService;
use App\Values\Branding;
use PHPUnit\Framework\Attributes\Test;
use Tests\PlusTestCase;
class SettingServiceTest extends PlusTestCase
{
private SettingService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(SettingService::class);
}
#[Test]
public function getBrandingForPlusEdition(): void
{
$branding = $this->service->getBranding();
self::assertSame('Koel', $branding->name);
self::assertNull($branding->logo);
self::assertNull($branding->cover);
Setting::set('branding', Branding::make(
name: 'Test Branding',
logo: 'test-logo.png',
cover: 'test-cover.png',
));
$branding = $this->service->getBranding();
self::assertSame('Test Branding', $branding->name);
self::assertSame(image_storage_url('test-logo.png'), $branding->logo);
self::assertSame(image_storage_url('test-cover.png'), $branding->cover);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/KoelPlus/Services/PlaylistCollaborationServiceTest.php | tests/Integration/KoelPlus/Services/PlaylistCollaborationServiceTest.php | <?php
namespace Tests\Integration\KoelPlus\Services;
use App\Events\NewPlaylistCollaboratorJoined;
use App\Exceptions\CannotRemoveOwnerFromPlaylistException;
use App\Exceptions\NotAPlaylistCollaboratorException;
use App\Exceptions\OperationNotApplicableForSmartPlaylistException;
use App\Exceptions\PlaylistCollaborationTokenExpiredException;
use App\Models\PlaylistCollaborationToken;
use App\Services\PlaylistCollaborationService;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Event;
use PHPUnit\Framework\Attributes\Test;
use Tests\PlusTestCase;
use function Tests\create_playlist;
use function Tests\create_user;
class PlaylistCollaborationServiceTest extends PlusTestCase
{
private PlaylistCollaborationService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(PlaylistCollaborationService::class);
}
#[Test]
public function createToken(): void
{
$playlist = create_playlist();
$token = $this->service->createToken($playlist);
self::assertNotEmpty($token->token);
self::assertFalse($token->expired);
self::assertSame($playlist->id, $token->playlist_id);
}
#[Test]
public function createTokenFailsIfPlaylistIsSmart(): void
{
$this->expectException(OperationNotApplicableForSmartPlaylistException::class);
$this->service->createToken(create_playlist(smart: true));
}
#[Test]
public function acceptUsingToken(): void
{
Event::fake(NewPlaylistCollaboratorJoined::class);
/** @var PlaylistCollaborationToken $token */
$token = PlaylistCollaborationToken::factory()->create();
$user = create_user();
self::assertFalse($token->playlist->collaborators->contains($user));
$this->service->acceptUsingToken($token->token, $user);
self::assertTrue($token->refresh()->playlist->collaborators->contains($user));
Event::assertDispatched(NewPlaylistCollaboratorJoined::class);
}
#[Test]
public function failsToAcceptExpiredToken(): void
{
$this->expectException(PlaylistCollaborationTokenExpiredException::class);
Event::fake(NewPlaylistCollaboratorJoined::class);
/** @var PlaylistCollaborationToken $token */
$token = PlaylistCollaborationToken::factory()->create();
$user = create_user();
$this->travel(8)->days();
$this->service->acceptUsingToken($token->token, $user);
self::assertFalse($token->refresh()->playlist->collaborators->contains($user));
Event::assertNotDispatched(NewPlaylistCollaboratorJoined::class);
}
#[Test]
public function getCollaboratorsExcludingOwner(): void
{
$playlist = create_playlist();
$user = create_user();
$playlist->addCollaborator($user);
$collaborators = $this->service->getCollaborators(playlist: $playlist->refresh());
self::assertEqualsCanonicalizing([$user->public_id], Arr::pluck($collaborators->toArray(), 'id'));
}
#[Test]
public function getCollaboratorsIncludingOwner(): void
{
$playlist = create_playlist();
$user = create_user();
$playlist->addCollaborator($user);
$collaborators = $this->service->getCollaborators(playlist: $playlist->refresh(), includingOwner: true);
self::assertEqualsCanonicalizing(
[$playlist->owner->public_id, $user->public_id],
Arr::pluck($collaborators->toArray(), 'id')
);
}
#[Test]
public function removeCollaborator(): void
{
$playlist = create_playlist();
$user = create_user();
$playlist->addCollaborator($user);
self::assertTrue($playlist->refresh()->hasCollaborator($user));
$this->service->removeCollaborator($playlist, $user);
self::assertFalse($playlist->refresh()->hasCollaborator($user));
}
#[Test]
public function cannotRemoveNonExistingCollaborator(): void
{
$this->expectException(NotAPlaylistCollaboratorException::class);
$playlist = create_playlist();
$user = create_user();
$this->service->removeCollaborator($playlist, $user);
}
#[Test]
public function cannotRemoveOwner(): void
{
$this->expectException(CannotRemoveOwnerFromPlaylistException::class);
$playlist = create_playlist();
$this->service->removeCollaborator($playlist, $playlist->owner);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/KoelPlus/Services/TestingDropboxStorage.php | tests/Integration/KoelPlus/Services/TestingDropboxStorage.php | <?php
namespace Tests\Integration\KoelPlus\Services;
use Illuminate\Support\Facades\Http;
trait TestingDropboxStorage
{
private static function mockDropboxRefreshAccessTokenCall(string $token = 'free-bird', int $expiresIn = 3600): void
{
Http::preventStrayRequests();
Http::fake([
'https://api.dropboxapi.com/oauth2/token' => Http::response([
'access_token' => $token,
'expires_in' => $expiresIn,
]),
]);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/KoelPlus/Services/UserServiceTest.php | tests/Integration/KoelPlus/Services/UserServiceTest.php | <?php
namespace Tests\Integration\KoelPlus\Services;
use App\Enums\Acl\Role;
use App\Models\User;
use App\Services\UserService;
use App\Values\User\SsoUser;
use App\Values\User\UserCreateData;
use App\Values\User\UserUpdateData;
use Illuminate\Support\Facades\Hash;
use Laravel\Socialite\Two\User as SocialiteUser;
use Mockery;
use PHPUnit\Framework\Attributes\Test;
use Tests\PlusTestCase;
use function Tests\create_user;
class UserServiceTest extends PlusTestCase
{
private UserService $service;
public function setUp(): void
{
parent::setUp();
$this->service = app(UserService::class);
}
#[Test]
public function createUserViaSsoProvider(): void
{
$user = $this->service->createUser(UserCreateData::make(
name: 'Bruce Dickinson',
email: 'bruce@dickison.com',
plainTextPassword: '',
role: Role::ADMIN,
avatar: 'https://lh3.googleusercontent.com/a/vatar',
ssoId: '123',
ssoProvider: 'Google'
));
$this->assertModelExists($user);
self::assertSame('Google', $user->sso_provider);
self::assertSame('123', $user->sso_id);
self::assertSame('https://lh3.googleusercontent.com/a/vatar', $user->avatar);
}
#[Test]
public function createUserFromSso(): void
{
$this->assertDatabaseMissing(User::class, ['email' => 'bruce@iron.com']);
$socialiteUser = Mockery::mock(SocialiteUser::class, [
'getId' => '123',
'getEmail' => 'bruce@iron.com',
'getName' => 'Bruce Dickinson',
'getAvatar' => 'https://lh3.googleusercontent.com/a/vatar',
]);
$user = $this->service->createOrUpdateUserFromSso(SsoUser::fromSocialite($socialiteUser, 'Google'));
$this->assertModelExists($user);
self::assertSame('Google', $user->sso_provider);
self::assertSame('Bruce Dickinson', $user->name);
self::assertSame('bruce@iron.com', $user->email);
self::assertSame('123', $user->sso_id);
self::assertSame('https://lh3.googleusercontent.com/a/vatar', $user->avatar);
}
#[Test]
public function updateUserFromSsoId(): void
{
$user = create_user([
'email' => 'bruce@iron.com',
'name' => 'Bruce Dickinson',
'sso_id' => '123',
'sso_provider' => 'Google',
]);
$socialiteUser = Mockery::mock(SocialiteUser::class, [
'getId' => '123',
'getEmail' => 'steve@iron.com',
'getName' => 'Steve Harris',
'getAvatar' => 'https://lh3.googleusercontent.com/a/vatar',
]);
$this->service->createOrUpdateUserFromSso(SsoUser::fromSocialite($socialiteUser, 'Google'));
$user->refresh();
self::assertSame('Bruce Dickinson', $user->name); // Name should not be updated
self::assertSame('https://lh3.googleusercontent.com/a/vatar', $user->avatar);
self::assertSame('bruce@iron.com', $user->email); // Email should not be updated
self::assertSame('Google', $user->sso_provider);
}
#[Test]
public function updateUserFromSsoEmail(): void
{
$user = create_user([
'email' => 'bruce@iron.com',
'name' => 'Bruce Dickinson',
]);
$socialiteUser = Mockery::mock(SocialiteUser::class, [
'getId' => '123',
'getEmail' => 'bruce@iron.com',
'getName' => 'Steve Harris',
'getAvatar' => 'https://lh3.googleusercontent.com/a/vatar',
]);
$this->service->createOrUpdateUserFromSso(SsoUser::fromSocialite($socialiteUser, 'Google'));
$user->refresh();
self::assertSame('Bruce Dickinson', $user->name); // Name should not be updated
self::assertSame('https://lh3.googleusercontent.com/a/vatar', $user->avatar);
self::assertSame('Google', $user->sso_provider);
}
#[Test]
public function updateSsoUserCannotChangeProfileDetails(): void
{
$user = create_user([
'email' => 'bruce@iron.com',
'name' => 'Bruce Dickinson',
'sso_provider' => 'Google',
]);
$this->service->updateUser($user, UserUpdateData::make(
name: 'Steve Harris',
email: 'steve@iron.com',
plainTextPassword: 'TheTrooper',
role: Role::MANAGER,
));
$user->refresh();
self::assertSame('bruce@iron.com', $user->email);
self::assertFalse(Hash::check('TheTrooper', $user->password));
self::assertSame(Role::MANAGER, $user->role);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/KoelPlus/Services/SongStorages/DropboxStorageTest.php | tests/Integration/KoelPlus/Services/SongStorages/DropboxStorageTest.php | <?php
namespace Tests\Integration\KoelPlus\Services\SongStorages;
use App\Filesystems\DropboxFilesystem;
use App\Helpers\Ulid;
use App\Models\Song;
use App\Services\SongStorages\DropboxStorage;
use App\Values\UploadReference;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Mockery;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Dropbox\Client;
use Spatie\FlysystemDropbox\DropboxAdapter;
use Tests\Integration\KoelPlus\Services\TestingDropboxStorage;
use Tests\PlusTestCase;
use function Tests\create_user;
use function Tests\test_path;
class DropboxStorageTest extends PlusTestCase
{
use TestingDropboxStorage;
private MockInterface|DropboxFilesystem $filesystem;
private MockInterface|Client $client;
private string $uploadedFilePath;
public function setUp(): void
{
parent::setUp();
config([
'koel.storage_driver' => 'dropbox',
'filesystems.disks.dropbox' => [
'app_key' => 'dropbox-key',
'app_secret' => 'dropbox-secret',
'refresh_token' => 'coca-cola',
],
]);
$this->client = $this->mock(Client::class);
$this->filesystem = $this->mock(DropboxFilesystem::class);
$this->filesystem->allows('getAdapter')->andReturn(
Mockery::mock(DropboxAdapter::class, ['getClient' => $this->client])
);
self::mockDropboxRefreshAccessTokenCall();
File::copy(test_path('songs/full.mp3'), artifact_path('/tmp/random/song.mp3'));
$this->uploadedFilePath = artifact_path('/tmp/random/song.mp3');
}
#[Test]
public function storeUploadedFile(): void
{
Ulid::freeze('random');
$this->client->expects('setAccessToken')->with('free-bird');
/** @var DropboxStorage $service */
$service = app(DropboxStorage::class);
Http::assertSent(static function (Request $request) {
return $request->hasHeader('Authorization', 'Basic ' . base64_encode('dropbox-key:dropbox-secret'))
&& $request->isForm()
&& $request['refresh_token'] === 'coca-cola'
&& $request['grant_type'] === 'refresh_token';
});
$user = create_user();
$this->filesystem->expects('writeStream');
$reference = $service->storeUploadedFile($this->uploadedFilePath, $user);
self::assertSame("dropbox://{$user->id}__random__song.mp3", $reference->location);
self::assertSame(artifact_path("tmp/random/song.mp3"), $reference->localPath);
self::assertSame('free-bird', Cache::get('dropbox_access_token'));
}
#[Test]
public function undoUpload(): void
{
$this->filesystem->expects('delete')->with('koel/song.mp3');
File::expects('delete')->with('/tmp/random/song.mp3');
$reference = UploadReference::make(
location: 'dropbox://koel/song.mp3',
localPath: '/tmp/random/song.mp3',
);
$this->client->expects('setAccessToken')->with('free-bird');
/** @var DropboxStorage $service */
$service = app(DropboxStorage::class);
$service->undoUpload($reference);
}
#[Test]
public function accessTokenCache(): void
{
Cache::put('dropbox_access_token', 'cached-token', now()->addHour());
$this->client->expects('setAccessToken')->with('cached-token');
app(DropboxStorage::class);
self::assertSame('cached-token', Cache::get('dropbox_access_token'));
Http::assertNothingSent();
}
#[Test]
public function getSongPresignedUrl(): void
{
$this->client->allows('setAccessToken');
/** @var Song $song */
$song = Song::factory()->create(['path' => 'dropbox://song.mp3', 'storage' => 'dropbox']);
/** @var DropboxStorage $service */
$service = app(DropboxStorage::class);
$this->filesystem->expects('temporaryUrl')
->with('song.mp3')
->andReturn('https://dropbox.com/song.mp3?token=123');
self::assertSame(
'https://dropbox.com/song.mp3?token=123',
$service->getPresignedUrl($song->storage_metadata->getPath())
);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/KoelPlus/Services/SongStorages/S3CompatibleStorageTest.php | tests/Integration/KoelPlus/Services/SongStorages/S3CompatibleStorageTest.php | <?php
namespace Tests\Integration\KoelPlus\Services\SongStorages;
use App\Helpers\Ulid;
use App\Services\SongStorages\S3CompatibleStorage;
use App\Values\UploadReference;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use PHPUnit\Framework\Attributes\Test;
use Tests\PlusTestCase;
use function Tests\create_user;
use function Tests\test_path;
class S3CompatibleStorageTest extends PlusTestCase
{
private S3CompatibleStorage $service;
private string $uploadedFilePath;
public function setUp(): void
{
parent::setUp();
Storage::fake('s3');
$this->service = app(S3CompatibleStorage::class);
File::copy(test_path('songs/full.mp3'), artifact_path('tmp/random/full.mp3'));
$this->uploadedFilePath = artifact_path('tmp/random/full.mp3');
}
#[Test]
public function storeUploadedFile(): void
{
Ulid::freeze('random');
$user = create_user();
$reference = $this->service->storeUploadedFile($this->uploadedFilePath, $user);
Storage::disk('s3')->assertExists(Str::after($reference->location, 's3://koel/')); // 'koel' is the bucket name
self::assertSame("s3://koel/{$user->id}__random__full.mp3", $reference->location);
self::assertSame(artifact_path('tmp/random/full.mp3'), $reference->localPath);
}
#[Test]
public function undoUpload(): void
{
Storage::disk('s3')->put('123__random__song.mp3', 'fake content');
File::expects('delete')->with('/tmp/random/song.mp3');
$reference = UploadReference::make(
location: 's3://koel/123__random__song.mp3', // 'koel' is the bucket name
localPath: '/tmp/random/song.mp3',
);
$this->service->undoUpload($reference);
Storage::disk('s3')->assertMissing('123__random__song.mp3');
}
#[Test]
public function deleteWithNoBackup(): void
{
Storage::disk('s3')->put('full.mp3', 'fake content');
$this->service->delete('full.mp3');
Storage::disk('s3')->assertMissing('full.mp3');
}
#[Test]
public function deleteWithBackup(): void
{
Storage::disk('s3')->put('full.mp3', 'fake content');
$this->service->delete(location: 'full.mp3', backup: true);
Storage::disk('s3')->assertMissing('full.mp3');
Storage::disk('s3')->assertExists('backup/full.mp3.bak');
}
#[Test]
public function getPresignedUrl(): void
{
$reference = $this->service->storeUploadedFile($this->uploadedFilePath, create_user());
$url = $this->service->getPresignedUrl(Str::after($reference->location, 's3://koel/'));
self::assertStringContainsString(Str::after($reference->location, 's3://koel/'), $url);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/KoelPlus/Services/SongStorages/SftpStorageTest.php | tests/Integration/KoelPlus/Services/SongStorages/SftpStorageTest.php | <?php
namespace Tests\Integration\KoelPlus\Services\SongStorages;
use App\Helpers\Ulid;
use App\Services\SongStorages\SftpStorage;
use App\Values\UploadReference;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use PHPUnit\Framework\Attributes\Test;
use Tests\PlusTestCase;
use function Tests\create_user;
use function Tests\test_path;
class SftpStorageTest extends PlusTestCase
{
private SftpStorage $service;
private string $uploadedFilePath;
public function setUp(): void
{
parent::setUp();
Storage::fake('sftp');
$this->service = app(SftpStorage::class);
File::copy(test_path('songs/full.mp3'), artifact_path('tmp/random/song.mp3'));
$this->uploadedFilePath = artifact_path('tmp/random/song.mp3');
}
#[Test]
public function storeUploadedFile(): void
{
Ulid::freeze('random');
$user = create_user();
$reference = $this->service->storeUploadedFile($this->uploadedFilePath, $user);
Storage::disk('sftp')->assertExists(Str::after($reference->location, 'sftp://'));
self::assertSame("sftp://{$user->id}__random__song.mp3", $reference->location);
self::assertSame(artifact_path('tmp/random/song.mp3'), $reference->localPath);
}
#[Test]
public function undoUpload(): void
{
Storage::disk('sftp')->put('123__random__song.mp3', 'fake content');
File::expects('delete')->with('/tmp/random/song.mp3');
$reference = UploadReference::make(
location: 'sftp://123__random__song.mp3',
localPath: '/tmp/random/song.mp3',
);
$this->service->undoUpload($reference);
}
#[Test]
public function deleteSong(): void
{
$reference = $this->service->storeUploadedFile($this->uploadedFilePath, create_user());
$remotePath = Str::after($reference->location, 'sftp://');
Storage::disk('sftp')->assertExists($remotePath);
$this->service->delete($remotePath);
Storage::disk('sftp')->assertMissing($remotePath);
}
#[Test]
public function copyToLocal(): void
{
// Put a fake file on the fake SFTP disk
Storage::disk('sftp')->put('music/test-song.mp3', 'fake mp3 content');
$localPath = $this->service->copyToLocal('music/test-song.mp3');
self::assertStringEqualsFile($localPath, 'fake mp3 content');
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/KoelPlus/Services/Streamer/StreamerTest.php | tests/Integration/KoelPlus/Services/Streamer/StreamerTest.php | <?php
namespace Tests\Integration\KoelPlus\Services\Streamer;
use App\Enums\SongStorageType;
use App\Models\Song;
use App\Services\Streamer\Adapters\DropboxStreamerAdapter;
use App\Services\Streamer\Adapters\LocalStreamerAdapter;
use App\Services\Streamer\Adapters\S3CompatibleStreamerAdapter;
use App\Services\Streamer\Adapters\SftpStreamerAdapter;
use App\Services\Streamer\Streamer;
use PHPUnit\Framework\Attributes\Test;
use Tests\Integration\KoelPlus\Services\TestingDropboxStorage;
use Tests\PlusTestCase;
class StreamerTest extends PlusTestCase
{
use TestingDropboxStorage;
#[Test]
public function resolveAdapters(): void
{
collect(SongStorageType::cases())
->each(static function (SongStorageType $type): void {
/** @var Song $song */
$song = Song::factory()->create(['storage' => $type]);
if ($type === SongStorageType::DROPBOX) {
self::mockDropboxRefreshAccessTokenCall();
}
$streamer = new Streamer($song);
switch ($type) {
case SongStorageType::S3:
case SongStorageType::S3_LAMBDA:
self::assertInstanceOf(S3CompatibleStreamerAdapter::class, $streamer->getAdapter());
break;
case SongStorageType::DROPBOX:
self::assertInstanceOf(DropboxStreamerAdapter::class, $streamer->getAdapter());
break;
case SongStorageType::LOCAL:
self::assertInstanceOf(LocalStreamerAdapter::class, $streamer->getAdapter());
break;
case SongStorageType::SFTP:
self::assertInstanceOf(SftpStreamerAdapter::class, $streamer->getAdapter());
break;
default:
self::fail("Storage type not covered by tests: $type->value");
}
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/KoelPlus/Enums/SongStorageTypeTest.php | tests/Integration/KoelPlus/Enums/SongStorageTypeTest.php | <?php
namespace Tests\Integration\KoelPlus\Enums;
use App\Enums\SongStorageType;
use PHPUnit\Framework\Attributes\Test;
use Tests\PlusTestCase;
class SongStorageTypeTest extends PlusTestCase
{
#[Test]
public function supported(): void
{
self::assertTrue(collect(SongStorageType::cases())->every(
static fn (SongStorageType $type) => $type->supported()
));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/KoelPlus/Repositories/FolderRepositoryTest.php | tests/Integration/KoelPlus/Repositories/FolderRepositoryTest.php | <?php
namespace Tests\Integration\KoelPlus\Repositories;
use App\Models\Folder;
use App\Repositories\FolderRepository;
use PHPUnit\Framework\Attributes\Test;
use Tests\PlusTestCase;
use function Tests\create_user;
class FolderRepositoryTest extends PlusTestCase
{
private FolderRepository $repository;
public function setUp(): void
{
parent::setUp();
$this->repository = app(FolderRepository::class);
}
#[Test]
public function getByPaths(): void
{
$user = create_user(['id' => 99]);
/** @var Folder $foo */
$foo = Folder::factory()->create(['path' => 'foo']);
/** @var Folder $bar */
$bar = Folder::factory()->create(['path' => 'foo/bar']);
// This folder is not browsable by the user and should not be returned
Folder::factory()->create(['path' => '__KOEL_UPLOADS_$1__']);
$results = $this->repository->getByPaths(['foo', 'foo/bar', '__KOEL_UPLOADS_$1__'], $user);
self::assertEqualsCanonicalizing($results->pluck('id')->toArray(), [$foo->id, $bar->id]);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Geolocation/IPinfoServiceTest.php | tests/Integration/Geolocation/IPinfoServiceTest.php | <?php
namespace Tests\Integration\Geolocation;
use App\Http\Integrations\IPinfo\Requests\GetLiteDataRequest;
use App\Services\Geolocation\IPinfoService;
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\TestCase;
use function Tests\test_path;
class IPinfoServiceTest extends TestCase
{
private IPinfoService $service;
public function setUp(): void
{
parent::setUp();
config(['koel.services.ipinfo.token' => 'ipinfo-token']);
$this->service = app(IPinfoService::class);
}
#[Test]
public function getCountryCodeFromIp(): void
{
Saloon::fake([
GetLiteDataRequest::class => MockResponse::make(
body: File::json(test_path('fixtures/ipinfo/lite-data.json')),
),
]);
$countryCode = $this->service->getCountryCodeFromIp('172.16.31.10');
self::assertSame('DE', $countryCode);
Saloon::assertSent(static fn (GetLiteDataRequest $request) => $request->ip === '172.16.31.10');
}
#[Test]
public function getCountryCodeFromCache(): void
{
Saloon::fake([]);
Cache::put(cache_key('IP to country code', '172.16.31.10'), 'VN', now()->addDay());
self::assertSame('VN', $this->service->getCountryCodeFromIp('172.16.31.10'));
Saloon::assertNothingSent();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Enums/SongStorageTypeTest.php | tests/Integration/Enums/SongStorageTypeTest.php | <?php
namespace Tests\Integration\Enums;
use App\Enums\SongStorageType;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class SongStorageTypeTest extends TestCase
{
#[Test]
public function supported(): void
{
self::assertTrue(SongStorageType::LOCAL->supported());
self::assertTrue(SongStorageType::S3_LAMBDA->supported());
self::assertFalse(SongStorageType::SFTP->supported());
self::assertFalse(SongStorageType::DROPBOX->supported());
self::assertFalse(SongStorageType::S3->supported());
}
#[Test]
public function supportsFolderStructureExtraction(): void
{
self::assertTrue(SongStorageType::LOCAL->supportsFolderStructureExtraction());
self::assertFalse(SongStorageType::S3_LAMBDA->supportsFolderStructureExtraction());
self::assertFalse(SongStorageType::SFTP->supportsFolderStructureExtraction());
self::assertFalse(SongStorageType::DROPBOX->supportsFolderStructureExtraction());
self::assertFalse(SongStorageType::S3->supportsFolderStructureExtraction());
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Models/SongZipArchiveTest.php | tests/Integration/Models/SongZipArchiveTest.php | <?php
namespace Tests\Integration\Models;
use App\Models\Song;
use App\Models\SongZipArchive;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\test_path;
class SongZipArchiveTest extends TestCase
{
#[Test]
public function addSongIntoArchive(): void
{
/** @var Song $song */
$song = Song::factory()->create(['path' => test_path('songs/full.mp3')]);
$songZipArchive = new SongZipArchive();
$songZipArchive->addSong($song);
self::assertSame(1, $songZipArchive->getArchive()->numFiles);
self::assertSame('full.mp3', $songZipArchive->getArchive()->getNameIndex(0));
}
#[Test]
public function addMultipleSongsIntoArchive(): void
{
$songs = collect([
Song::factory()->create(['path' => test_path('songs/full.mp3')]),
Song::factory()->create(['path' => test_path('songs/lorem.mp3')]),
]);
$songZipArchive = new SongZipArchive();
$songZipArchive->addSongs($songs);
self::assertSame(2, $songZipArchive->getArchive()->numFiles);
self::assertSame('full.mp3', $songZipArchive->getArchive()->getNameIndex(0));
self::assertSame('lorem.mp3', $songZipArchive->getArchive()->getNameIndex(1));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Integration/Repositories/SongRepositoryTest.php | tests/Integration/Repositories/SongRepositoryTest.php | <?php
namespace Tests\Integration\Repositories;
use App\Models\Song;
use App\Repositories\SongRepository;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class SongRepositoryTest extends TestCase
{
private SongRepository $songRepository;
public function setUp(): void
{
parent::setUp();
$this->songRepository = app(SongRepository::class);
}
#[Test]
public function getOneByPath(): void
{
/** @var Song $song */
$song = Song::factory()->create(['path' => 'foo']);
self::assertSame($song->id, $this->songRepository->findOneByPath('foo')->id);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Fakes/FakePlusLicenseService.php | tests/Fakes/FakePlusLicenseService.php | <?php
namespace Tests\Fakes;
use App\Exceptions\MethodNotImplementedException;
use App\Models\License;
use App\Services\License\Contracts\LicenseServiceInterface;
use App\Values\License\LicenseStatus;
class FakePlusLicenseService implements LicenseServiceInterface
{
public function activate(string $key): License
{
throw MethodNotImplementedException::method(__METHOD__);
}
public function deactivate(License $license): void
{
throw MethodNotImplementedException::method(__METHOD__);
}
public function getStatus(bool $checkCache = true): LicenseStatus
{
throw MethodNotImplementedException::method(__METHOD__);
}
public function isPlus(): bool
{
return true;
}
public function isCommunity(): bool
{
return false;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Fakes/FakeJob.php | tests/Fakes/FakeJob.php | <?php
namespace Tests\Fakes;
use Illuminate\Contracts\Queue\ShouldQueue;
class FakeJob implements ShouldQueue
{
public function handle(): string
{
return 'Job executed';
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/QueueTest.php | tests/Feature/QueueTest.php | <?php
namespace Tests\Feature;
use App\Http\Resources\SongResource;
use App\Models\QueueState;
use App\Models\Song;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
class QueueTest extends TestCase
{
public const QUEUE_STATE_JSON_STRUCTURE = [
'current_song',
'songs' => ['*' => SongResource::JSON_STRUCTURE],
'playback_position',
];
#[Test]
public function getEmptyState(): void
{
$this->getAs('api/queue/state')
->assertJsonStructure(self::QUEUE_STATE_JSON_STRUCTURE);
}
#[Test]
public function getExistingState(): void
{
/** @var QueueState $queueState */
$queueState = QueueState::factory()->create([
'current_song_id' => Song::factory(),
'playback_position' => 123,
]);
$this->getAs('api/queue/state', $queueState->user)
->assertJsonStructure(self::QUEUE_STATE_JSON_STRUCTURE);
}
#[Test]
public function updateStateWithoutExistingState(): void
{
$user = create_user();
$this->assertDatabaseMissing(QueueState::class, ['user_id' => $user->id]);
$songIds = Song::factory(2)->create()->modelKeys();
$this->putAs('api/queue/state', ['songs' => $songIds], $user)
->assertNoContent();
/** @var QueueState $queue */
$queue = QueueState::query()->whereBelongsTo($user)->firstOrFail();
self::assertEqualsCanonicalizing($songIds, $queue->song_ids);
}
#[Test]
public function updatePlaybackStatus(): void
{
/** @var QueueState $state */
$state = QueueState::factory()->create();
/** @var Song $song */
$song = Song::factory()->create();
$this->putAs('api/queue/playback-status', ['song' => $song->id, 'position' => 123], $state->user)
->assertNoContent();
$state->refresh();
self::assertSame($song->id, $state->current_song_id);
self::assertSame(123, $state->playback_position);
/** @var Song $anotherSong */
$anotherSong = Song::factory()->create();
$this->putAs('api/queue/playback-status', ['song' => $anotherSong->id, 'position' => 456], $state->user)
->assertNoContent();
$state->refresh();
self::assertSame($anotherSong->id, $state->current_song_id);
self::assertSame(456, $state->playback_position);
}
#[Test]
public function fetchSongs(): void
{
Song::factory(10)->create();
$this->getAs('api/queue/fetch?order=rand&limit=5')
->assertJsonStructure([0 => SongResource::JSON_STRUCTURE])
->assertJsonCount(5, '*');
$this->getAs('api/queue/fetch?order=asc&sort=title&limit=5')
->assertJsonStructure([0 => SongResource::JSON_STRUCTURE])
->assertJsonCount(5, '*');
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/EpisodeTest.php | tests/Feature/EpisodeTest.php | <?php
namespace Tests\Feature;
use App\Http\Resources\SongResource;
use App\Models\Song;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class EpisodeTest extends TestCase
{
#[Test]
public function fetchEpisode(): void
{
/** @var Song $episode */
$episode = Song::factory()->asEpisode()->create();
$this->getAs("api/songs/{$episode->id}")
->assertJsonStructure(SongResource::JSON_STRUCTURE);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/ArtistTest.php | tests/Feature/ArtistTest.php | <?php
namespace Tests\Feature;
use App\Helpers\Ulid;
use App\Http\Resources\ArtistResource;
use App\Models\Artist;
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 ArtistTest extends TestCase
{
#[Test]
public function index(): void
{
Artist::factory(10)->create();
$this->getAs('api/artists')
->assertJsonStructure(ArtistResource::PAGINATION_JSON_STRUCTURE);
$this->getAs('api/artists?sort=name&order=asc')
->assertJsonStructure(ArtistResource::PAGINATION_JSON_STRUCTURE);
$this->getAs('api/artists?sort=created_at&order=desc&page=2')
->assertJsonStructure(ArtistResource::PAGINATION_JSON_STRUCTURE);
}
#[Test]
public function show(): void
{
$this->getAs('api/artists/' . Artist::factory()->create()->id)
->assertJsonStructure(ArtistResource::JSON_STRUCTURE);
}
#[Test]
public function updateWithImage(): void
{
/** @var Artist $artist */
$artist = Artist::factory()->create();
$ulid = Ulid::freeze();
$this->putAs(
"api/artists/{$artist->id}",
[
'name' => 'Updated Artist Name',
'image' => minimal_base64_encoded_image(),
],
create_admin()
)->assertJsonStructure(ArtistResource::JSON_STRUCTURE)
->assertOk();
$artist->refresh();
self::assertEquals('Updated Artist Name', $artist->name);
self::assertEquals("$ulid.webp", $artist->image);
}
#[Test]
public function updateKeepingImageIntact(): void
{
/** @var Artist $artist */
$artist = Artist::factory()->create(['image' => 'neat-pose.webp']);
$this->putAs(
"api/artists/{$artist->id}",
[
'name' => 'Updated Artist Name',
],
create_admin()
)->assertJsonStructure(ArtistResource::JSON_STRUCTURE)
->assertOk();
self::assertEquals('neat-pose.webp', $artist->refresh()->image);
}
#[Test]
public function updateRemovingImage(): void
{
/** @var Artist $artist */
$artist = Artist::factory()->create(['image' => 'neat-pose.webp']);
$this->putAs(
"api/artists/{$artist->id}",
[
'name' => 'Updated Artist Name',
'image' => '',
],
create_admin()
)->assertJsonStructure(ArtistResource::JSON_STRUCTURE)
->assertOk();
self::assertEmpty($artist->refresh()->image);
}
#[Test]
public function updatingToExistingNameFails(): void
{
/** @var Artist $existingArtist */
$existingArtist = Artist::factory()->create(['name' => 'Maydup Nem']);
/** @var Artist $artist */
$artist = Artist::factory()->for($existingArtist->user)->create();
$this->putAs(
"api/artists/{$artist->id}",
[
'name' => 'Maydup Nem',
],
create_admin()
)
->assertJsonValidationErrors([
'name' => 'An artist with the same name already exists.',
]);
}
#[Test]
public function nonAdminCannotUpdateArtist(): void
{
/** @var Artist $artist */
$artist = Artist::factory()->create();
$this->putAs(
"api/artists/{$artist->id}",
[
'name' => 'Updated Name',
],
create_user()
)->assertForbidden();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/GenreTest.php | tests/Feature/GenreTest.php | <?php
namespace Tests\Feature;
use App\Http\Resources\GenreResource;
use App\Http\Resources\SongResource;
use App\Models\Genre;
use App\Models\Song;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class GenreTest extends TestCase
{
#[Test]
public function getAllGenres(): void
{
/** @var Genre $rock */
$rock = Genre::factory()->has(Song::factory()->count(2))->create(['name' => 'Rock']);
/** @var Genre $pop */
$pop = Genre::factory()->has(Song::factory()->count(1))->create(['name' => 'Pop']);
Song::factory()->count(2)->create();
$this->getAs('api/genres')
->assertJsonCount(3)
->assertJsonStructure([0 => GenreResource::JSON_STRUCTURE])
->assertJsonFragment(['name' => $rock->name, 'song_count' => 2])
->assertJsonFragment(['name' => $pop->name, 'song_count' => 1])
->assertJsonFragment(['name' => '', 'song_count' => 2]);
}
#[Test]
public function getOneGenre(): void
{
/** @var Genre $rock */
$rock = Genre::factory()->has(Song::factory()->count(2))->create(['name' => 'Rock']);
$this->getAs('api/genres/' . $rock->public_id)
->assertJsonStructure(GenreResource::JSON_STRUCTURE)
->assertJsonFragment(['name' => 'Rock', 'song_count' => 2]);
}
#[Test]
public function getNonExistingGenreThrowsNotFound(): void
{
$this->getAs('api/genres/NonExistingGenre')->assertNotFound();
}
#[Test]
public function paginateSongsInGenre(): void
{
/** @var Genre $rock */
$rock = Genre::factory()->has(Song::factory()->count(2))->create(['name' => 'Rock']);
$this->getAs("api/genres/$rock->public_id/songs")
->assertJsonStructure(SongResource::PAGINATION_JSON_STRUCTURE);
}
#[Test]
public function getSongsInGenre(): void
{
/** @var Genre $rock */
$rock = Genre::factory()->has(Song::factory()->count(2))->create(['name' => 'Rock']);
$this->getAs("api/genres/$rock->public_id/songs/queue?limit=500&random=false")
->assertJsonCount(2)
->assertJsonStructure([0 => SongResource::JSON_STRUCTURE]);
}
#[Test]
public function getRandomSongsInGenre(): void
{
/** @var Genre $rock */
$rock = Genre::factory()->has(Song::factory()->count(2))->create(['name' => 'Rock']);
$this->getAs("api/genres/$rock->public_id/songs/queue?limit=500&random=true")
->assertJsonCount(2)
->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/YouTubeTest.php | tests/Feature/YouTubeTest.php | <?php
namespace Tests\Feature;
use App\Models\Song;
use App\Services\YouTubeService;
use Mockery;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class YouTubeTest extends TestCase
{
private MockInterface $youTubeService;
public function setUp(): void
{
parent::setUp();
$this->youTubeService = $this->mock(YouTubeService::class);
}
#[Test]
public function searchYouTubeVideos(): void
{
/** @var Song $song */
$song = Song::factory()->create();
$this->youTubeService
->expects('searchVideosRelatedToSong')
->with(Mockery::on(static fn (Song $retrievedSong) => $song->is($retrievedSong)), 'foo');
$this->getAs("/api/youtube/search/song/{$song->id}?pageToken=foo")
->assertOk();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/OverviewTest.php | tests/Feature/OverviewTest.php | <?php
namespace Tests\Feature;
use App\Http\Resources\AlbumResource;
use App\Http\Resources\ArtistResource;
use App\Http\Resources\SongResource;
use App\Models\Interaction;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
class OverviewTest extends TestCase
{
#[Test]
public function index(): void
{
$user = create_user();
Interaction::factory(20)->for($user)->create();
$this->getAs('api/overview', $user)
->assertJsonStructure([
'most_played_songs' => [0 => SongResource::JSON_STRUCTURE],
'recently_played_songs' => [0 => SongResource::JSON_STRUCTURE],
'recently_added_albums' => [0 => AlbumResource::JSON_STRUCTURE],
'recently_added_songs' => [0 => SongResource::JSON_STRUCTURE],
'most_played_artists' => [0 => ArtistResource::JSON_STRUCTURE],
'most_played_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/ProfileTest.php | tests/Feature/ProfileTest.php | <?php
namespace Tests\Feature;
use Illuminate\Support\Facades\Hash;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
use function Tests\minimal_base64_encoded_image;
class ProfileTest extends TestCase
{
#[Test]
public function updateProfileRequiresCurrentPassword(): void
{
$this->putAs('api/me', [
'name' => 'Foo',
'email' => 'bar@baz.com',
])
->assertUnprocessable();
}
#[Test]
public function updateProfileWithoutNewPassword(): void
{
$user = create_user(['password' => Hash::make('secret')]);
$this->putAs('api/me', [
'name' => 'Foo',
'email' => 'bar@baz.com',
'current_password' => 'secret',
], $user);
$user->refresh();
self::assertSame('Foo', $user->name);
self::assertSame('bar@baz.com', $user->email);
self::assertTrue(Hash::check('secret', $user->password));
}
#[Test]
public function updateProfileWithNewPassword(): void
{
$user = create_user(['password' => Hash::make('secret')]);
$token = $this->putAs('api/me', [
'name' => 'Foo',
'email' => 'bar@baz.com',
'new_password' => 'new-secret',
'current_password' => 'secret',
], $user)
->headers
->get('Authorization');
$user->refresh();
self::assertNotNull($token);
self::assertSame('Foo', $user->name);
self::assertSame('bar@baz.com', $user->email);
self::assertTrue(Hash::check('new-secret', $user->password));
}
#[Test]
public function updateProfileWithAvatar(): void
{
$user = create_user(['password' => Hash::make('secret')]);
self::assertNull($user->getRawOriginal('avatar'));
$this->putAs('api/me', [
'name' => 'Foo',
'email' => 'bar@baz.com',
'current_password' => 'secret',
'avatar' => minimal_base64_encoded_image(),
], $user)
->assertOk();
$user->refresh();
self::assertFileExists(image_storage_path($user->getRawOriginal('avatar')));
}
#[Test]
public function updateProfileRemovingAvatar(): void
{
$user = create_user([
'password' => Hash::make('secret'),
'email' => 'foo@bar.com',
'avatar' => 'foo.jpg',
]);
$this->putAs('api/me', [
'name' => 'Foo',
'email' => 'foo@bar.com',
'current_password' => 'secret',
], $user)
->assertOk();
$user->refresh();
self::assertNull($user->getRawOriginal('avatar'));
}
#[Test]
public function disabledInDemo(): void
{
config(['koel.misc.demo' => true]);
$user = create_user(['password' => Hash::make('secret')]);
$this->putAs('api/me', [
'name' => 'Foo',
'email' => 'bar@baz.com',
'current_password' => 'secret',
], $user)
->assertNoContent();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/ArtistInformationTest.php | tests/Feature/ArtistInformationTest.php | <?php
namespace Tests\Feature;
use App\Models\Artist;
use App\Services\EncyclopediaService;
use App\Values\Artist\ArtistInformation;
use Mockery;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
class ArtistInformationTest extends TestCase
{
#[Test]
public function getInformation(): void
{
config(['koel.services.lastfm.key' => 'foo']);
config(['koel.services.lastfm.secret' => 'geheim']);
/** @var Artist $artist */
$artist = Artist::factory()->create();
$lastfm = $this->mock(EncyclopediaService::class);
$lastfm->expects('getArtistInformation')
->with(Mockery::on(static fn (Artist $a) => $a->is($artist)))
->andReturn(ArtistInformation::make(
url: 'https://lastfm.com/artist/foo',
image: 'https://lastfm.com/image/foo',
bio: [
'summary' => 'foo',
'full' => 'bar',
],
));
$this->getAs("api/artists/{$artist->id}/information")
->assertJsonStructure(ArtistInformation::JSON_STRUCTURE);
}
#[Test]
public function getWithoutLastfmStillReturnsValidStructure(): void
{
config(['koel.services.lastfm.key' => null]);
config(['koel.services.lastfm.secret' => null]);
$this->getAs('api/artists/' . Artist::factory()->create()->id . '/information')
->assertJsonStructure(ArtistInformation::JSON_STRUCTURE);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/LastfmTest.php | tests/Feature/LastfmTest.php | <?php
namespace Tests\Feature;
use App\Services\LastfmService;
use App\Services\TokenManager;
use Laravel\Sanctum\NewAccessToken;
use Laravel\Sanctum\PersonalAccessToken;
use Mockery;
use Mockery\MockInterface;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_user;
class LastfmTest extends TestCase
{
#[Test]
public function setSessionKey(): void
{
$user = create_user();
$this->postAs('api/lastfm/session-key', ['key' => 'foo'], $user)
->assertNoContent();
self::assertSame('foo', $user->refresh()->preferences->lastFmSessionKey);
}
#[Test]
public function connectToLastfm(): void
{
$user = create_user();
$token = $user->createToken('Koel')->plainTextToken;
/** @var NewAccessToken|MockInterface $temporaryToken */
$temporaryToken = Mockery::mock(NewAccessToken::class);
$temporaryToken->plainTextToken = 'tmp-token';
/** @var TokenManager|MockInterface $tokenManager */
$tokenManager = $this->mock(TokenManager::class);
$tokenManager->expects('getUserFromPlainTextToken')
->with($token)
->andReturn($user);
$tokenManager->expects('createToken')
->with($user)
->andReturn($temporaryToken);
$this->get('lastfm/connect?api_token=' . $token)
->assertRedirect(
'https://www.last.fm/api/auth/?api_key=foo&cb=http%3A%2F%2Flocalhost%2Flastfm%2Fcallback%3Fapi_token%3Dtmp-token' // @phpcs-ignore-line
);
}
#[Test]
public function testCallback(): void
{
$user = create_user();
$token = $user->createToken('Koel')->plainTextToken;
self::assertNotNull(PersonalAccessToken::findToken($token));
/** @var LastfmService|MockInterface $lastfm */
$lastfm = Mockery::mock(LastfmService::class)->makePartial();
$lastfm->expects('getSessionKey')
->with('lastfm-token')
->andReturn('my-session-key');
app()->instance(LastfmService::class, $lastfm);
$this->get('lastfm/callback?token=lastfm-token&api_token=' . urlencode($token))
->assertOk();
self::assertSame('my-session-key', $user->refresh()->preferences->lastFmSessionKey);
// make sure the user's api token is deleted
self::assertNull(PersonalAccessToken::findToken($token));
}
#[Test]
public function retrieveAndStoreSessionKey(): void
{
$user = create_user();
/** @var LastfmService|MockInterface $lastfm */
$lastfm = Mockery::mock(LastfmService::class)->makePartial();
$lastfm->expects('getSessionKey')
->with('foo')
->andReturn('my-session-key');
app()->instance(LastfmService::class, $lastfm);
$tokenManager = $this->mock(TokenManager::class);
$tokenManager->expects('getUserFromPlainTextToken')
->with('my-token')
->andReturn($user);
$tokenManager->expects('deleteTokenByPlainTextToken');
$this->get('lastfm/callback?token=foo&api_token=my-token');
self::assertSame('my-session-key', $user->refresh()->preferences->lastFmSessionKey);
}
#[Test]
public function disconnectUser(): void
{
$user = create_user();
self::assertNotNull($user->preferences->lastFmSessionKey);
$this->deleteAs('api/lastfm/disconnect', [], $user);
$user->refresh();
self::assertNull($user->preferences->lastFmSessionKey);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/AlbumTest.php | tests/Feature/AlbumTest.php | <?php
namespace Tests\Feature;
use App\Helpers\Ulid;
use App\Http\Resources\AlbumResource;
use App\Models\Album;
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 AlbumTest extends TestCase
{
#[Test]
public function index(): void
{
Album::factory(10)->create();
$this->getAs('api/albums')
->assertJsonStructure(AlbumResource::PAGINATION_JSON_STRUCTURE);
$this->getAs('api/albums?sort=artist_name&order=asc')
->assertJsonStructure(AlbumResource::PAGINATION_JSON_STRUCTURE);
$this->getAs('api/albums?sort=year&order=desc&page=2')
->assertJsonStructure(AlbumResource::PAGINATION_JSON_STRUCTURE);
$this->getAs('api/albums?sort=created_at&order=desc&page=1')
->assertJsonStructure(AlbumResource::PAGINATION_JSON_STRUCTURE);
}
#[Test]
public function show(): void
{
$this->getAs('api/albums/' . Album::factory()->create()->id)
->assertJsonStructure(AlbumResource::JSON_STRUCTURE);
}
#[Test]
public function updateWithCover(): void
{
/** @var Album $album */
$album = Album::factory()->create();
$ulid = Ulid::freeze();
$this->putAs(
"api/albums/{$album->id}",
[
'name' => 'Updated Album Name',
'year' => 2023,
'cover' => minimal_base64_encoded_image(),
],
create_admin()
)->assertJsonStructure(AlbumResource::JSON_STRUCTURE)
->assertOk();
$album->refresh();
self::assertEquals('Updated Album Name', $album->name);
self::assertEquals(2023, $album->year);
self::assertEquals("$ulid.webp", $album->cover);
}
#[Test]
public function updateKeepingCoverIntact(): void
{
/** @var Album $album */
$album = Album::factory()->create(['cover' => 'neat-cover.webp']);
$this->putAs(
"api/albums/{$album->id}",
[
'name' => 'Updated Album Name',
'year' => 2023,
],
create_admin()
)->assertJsonStructure(AlbumResource::JSON_STRUCTURE)
->assertOk();
self::assertEquals('neat-cover.webp', $album->refresh()->cover);
}
#[Test]
public function updateRemovingCover(): void
{
/** @var Album $album */
$album = Album::factory()->create(['cover' => 'neat-cover.webp']);
$this->putAs(
"api/albums/{$album->id}",
[
'name' => 'Updated Album Name',
'year' => 2023,
'cover' => '',
],
create_admin()
)->assertJsonStructure(AlbumResource::JSON_STRUCTURE)
->assertOk();
self::assertEmpty($album->refresh()->cover);
}
#[Test]
public function updatingToExistingNameFails(): void
{
/** @var Album $existingAlbum */
$existingAlbum = Album::factory()->create(['name' => 'Black Album']);
/** @var Album $album */
$album = Album::factory()->for($existingAlbum->artist)->create();
$this->putAs(
"api/albums/{$album->id}",
[
'name' => 'Black Album',
'year' => 2023,
],
create_admin()
)
->assertJsonValidationErrors([
'name' => 'An album with the same name already exists for this artist.',
]);
}
#[Test]
public function nonAdminCannotUpdateAlbum(): void
{
/** @var Album $album */
$album = Album::factory()->create();
$this->putAs(
"api/albums/{$album->id}",
[
'name' => 'Updated Album Name',
'year' => 2023,
],
create_user()
)->assertForbidden();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/PlaylistTest.php | tests/Feature/PlaylistTest.php | <?php
namespace Tests\Feature;
use App\Helpers\Ulid;
use App\Http\Resources\PlaylistResource;
use App\Models\Playlist;
use App\Models\Song;
use App\Values\SmartPlaylist\SmartPlaylistRule;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_playlist;
use function Tests\create_playlists;
use function Tests\create_user;
use function Tests\minimal_base64_encoded_image;
class PlaylistTest extends TestCase
{
#[Test]
public function listing(): void
{
$user = create_user();
create_playlists(count: 3, owner: $user);
$this->getAs('api/playlists', $user)
->assertJsonStructure([0 => PlaylistResource::JSON_STRUCTURE])
->assertJsonCount(3, '*');
}
#[Test]
public function creatingPlaylist(): void
{
$user = create_user();
$songs = Song::factory(2)->create();
$ulid = Ulid::freeze();
$this->postAs('api/playlists', [
'name' => 'Foo Bar',
'description' => 'Foo Bar Description',
'songs' => $songs->modelKeys(),
'rules' => [],
'cover' => minimal_base64_encoded_image(),
], $user)
->assertJsonStructure(PlaylistResource::JSON_STRUCTURE);
$playlist = Playlist::query()->latest()->first();
self::assertSame('Foo Bar', $playlist->name);
self::assertSame('Foo Bar Description', $playlist->description);
self::assertTrue($playlist->ownedBy($user));
self::assertNull($playlist->getFolder());
self::assertEqualsCanonicalizing($songs->modelKeys(), $playlist->playables->modelKeys());
self::assertSame("$ulid.webp", $playlist->cover);
}
#[Test]
public function createPlaylistWithoutCover(): void
{
$user = create_user();
$this->postAs('api/playlists', [
'name' => 'Foo Bar',
'description' => 'Foo Bar Description',
'songs' => [],
'rules' => [],
], $user)
->assertJsonStructure(PlaylistResource::JSON_STRUCTURE);
$playlist = Playlist::query()->latest()->first();
self::assertSame('Foo Bar', $playlist->name);
self::assertSame('Foo Bar Description', $playlist->description);
self::assertTrue($playlist->ownedBy($user));
self::assertNull($playlist->getFolder());
self::assertEmpty($playlist->cover);
}
#[Test]
public function createPlaylistWithoutDescription(): void
{
$user = create_user();
$this->postAs('api/playlists', [
'name' => 'Foo Bar',
'description' => '',
'songs' => [],
'rules' => [],
], $user)
->assertJsonStructure(PlaylistResource::JSON_STRUCTURE);
$playlist = Playlist::query()->latest()->first();
self::assertSame('Foo Bar', $playlist->name);
self::assertSame('', $playlist->description);
}
#[Test]
public function creatingSmartPlaylist(): void
{
$user = create_user();
$rule = SmartPlaylistRule::make([
'model' => 'artist.name',
'operator' => 'is',
'value' => ['Bob Dylan'],
]);
$this->postAs('api/playlists', [
'name' => 'Smart Foo Bar',
'description' => 'Smart Foo Bar Description',
'rules' => [
[
'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026',
'rules' => [$rule->toArray()],
],
],
'cover' => minimal_base64_encoded_image(),
], $user)->assertJsonStructure(PlaylistResource::JSON_STRUCTURE);
$playlist = Playlist::query()->latest()->first();
self::assertSame('Smart Foo Bar', $playlist->name);
self::assertSame('Smart Foo Bar Description', $playlist->description);
self::assertTrue($playlist->ownedBy($user));
self::assertTrue($playlist->is_smart);
self::assertCount(1, $playlist->rule_groups);
self::assertNull($playlist->getFolder());
self::assertTrue($rule->equals($playlist->rule_groups[0]->rules[0]));
self::assertNotNull($playlist->cover);
}
#[Test]
public function creatingSmartPlaylistFailsIfSongsProvided(): void
{
$this->postAs('api/playlists', [
'name' => 'Smart Foo Bar',
'description' => 'Smart Foo Bar Description',
'rules' => [
[
'id' => '2a4548cd-c67f-44d4-8fec-34ff75c8a026',
'rules' => [
SmartPlaylistRule::make([
'model' => 'artist.name',
'operator' => 'is',
'value' => ['Bob Dylan'],
])->toArray(),
],
],
],
'songs' => Song::factory(2)->create()->modelKeys(),
])->assertUnprocessable();
}
#[Test]
public function creatingPlaylistWithNonExistentSongsFails(): void
{
$this->postAs('api/playlists', [
'name' => 'Foo Bar',
'description' => 'Foo Bar Description',
'rules' => [],
'songs' => ['foo'],
])
->assertUnprocessable();
}
#[Test]
public function updateKeepingCoverIntact(): void
{
$playlist = create_playlist([
'cover' => 'neat-cover.webp',
]);
$this->putAs("api/playlists/{$playlist->id}", [
'name' => 'Bar',
'description' => 'Bar Description',
], $playlist->owner)
->assertJsonStructure(PlaylistResource::JSON_STRUCTURE);
self::assertSame('Bar', $playlist->refresh()->name);
self::assertSame('Bar Description', $playlist->description);
self::assertSame('neat-cover.webp', $playlist->cover);
}
#[Test]
public function updateReplacingCover(): void
{
$playlist = create_playlist([
'cover' => 'neat-cover.webp',
]);
$ulid = Ulid::freeze();
$this->putAs("api/playlists/{$playlist->id}", [
'name' => 'Bar',
'description' => 'Bar Description',
'cover' => minimal_base64_encoded_image(),
], $playlist->owner)
->assertSuccessful()
->assertJsonStructure(PlaylistResource::JSON_STRUCTURE);
self::assertSame("$ulid.webp", $playlist->refresh()->cover);
}
#[Test]
public function updateRemovingCover(): void
{
$playlist = create_playlist([
'cover' => 'neat-cover.webp',
]);
$this->putAs("api/playlists/{$playlist->id}", [
'name' => 'Bar',
'description' => 'Bar Description',
'cover' => '',
], $playlist->owner)
->assertSuccessful()
->assertJsonStructure(PlaylistResource::JSON_STRUCTURE);
self::assertEmpty($playlist->refresh()->cover);
}
#[Test]
public function updateWithoutDescription(): void
{
$playlist = create_playlist(['name' => 'Foo', 'description' => 'Bar Description']);
$this->putAs("api/playlists/{$playlist->id}", [
'name' => 'Bar',
'description' => '',
], $playlist->owner)
->assertJsonStructure(PlaylistResource::JSON_STRUCTURE);
self::assertSame('Bar', $playlist->refresh()->name);
self::assertSame('', $playlist->description);
}
#[Test]
public function nonOwnerCannotUpdatePlaylist(): void
{
$playlist = create_playlist(['name' => 'Foo']);
$this->putAs("api/playlists/{$playlist->id}", [
'name' => 'Qux',
'description' => 'Qux Description',
])->assertForbidden();
self::assertSame('Foo', $playlist->refresh()->name);
}
#[Test]
public function deletePlaylist(): void
{
$playlist = create_playlist();
$this->deleteAs("api/playlists/{$playlist->id}", [], $playlist->owner);
$this->assertModelMissing($playlist);
}
#[Test]
public function nonOwnerCannotDeletePlaylist(): void
{
$playlist = create_playlist();
$this->deleteAs("api/playlists/{$playlist->id}")->assertForbidden();
$this->assertModelExists($playlist);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/tests/Feature/SongVisibilityTest.php | tests/Feature/SongVisibilityTest.php | <?php
namespace Tests\Feature;
use App\Models\Song;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use function Tests\create_admin;
class SongVisibilityTest extends TestCase
{
#[Test]
public function changingVisibilityIsForbiddenInCommunityEdition(): void
{
$owner = create_admin();
Song::factory(2)->create();
$this->putAs('api/songs/publicize', ['songs' => Song::query()->get()->modelKeys()], $owner)
->assertNotFound();
$this->putAs('api/songs/privatize', ['songs' => Song::query()->get()->modelKeys()], $owner)
->assertNotFound();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.