diff options
Diffstat (limited to 'tests')
6 files changed, 687 insertions, 1 deletions
diff --git a/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs index 1f06e8fde6..5f5f273f12 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs +++ b/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs @@ -1,5 +1,9 @@ using System; +using System.Threading; +using System.Threading.Tasks; using Jellyfin.Api.Controllers; +using MediaBrowser.Controller.MediaEncoding; +using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace Jellyfin.Api.Tests.Controllers @@ -41,5 +45,77 @@ namespace Jellyfin.Api.Tests.Controllers return data; } + + [Fact] + public async Task WaitForActiveTranscodingRequests_WaitsUntilRequestCompletes() + { + var job = new TranscodingJob(NullLogger<TranscodingJob>.Instance) + { + ActiveRequestCount = 1 + }; + + var waitTask = DynamicHlsController.WaitForActiveTranscodingRequests(job, CancellationToken.None); + Assert.False(waitTask.IsCompleted); + + job.DecrementActiveRequestCount(); + + await waitTask; + } + + [Fact] + public async Task WaitForActiveTranscodingRequests_WaitsForEveryRequest() + { + var job = new TranscodingJob(NullLogger<TranscodingJob>.Instance) + { + ActiveRequestCount = 2 + }; + + var waitTask = DynamicHlsController.WaitForActiveTranscodingRequests(job, CancellationToken.None); + job.DecrementActiveRequestCount(); + + await Task.Delay(150, TestContext.Current.CancellationToken); + Assert.False(waitTask.IsCompleted); + + job.DecrementActiveRequestCount(); + + await waitTask; + } + + [Fact] + public async Task WaitForActiveTranscodingRequests_ReturnsWithoutAnActiveRequest() + { + var job = new TranscodingJob(NullLogger<TranscodingJob>.Instance); + + await DynamicHlsController.WaitForActiveTranscodingRequests(job, CancellationToken.None); + await DynamicHlsController.WaitForActiveTranscodingRequests(null, CancellationToken.None); + } + + [Fact] + public async Task WaitForActiveTranscodingRequests_ObservesCancellation() + { + var job = new TranscodingJob(NullLogger<TranscodingJob>.Instance) + { + ActiveRequestCount = 1 + }; + using var cancellationTokenSource = new CancellationTokenSource(); + + var waitTask = DynamicHlsController.WaitForActiveTranscodingRequests(job, cancellationTokenSource.Token); + await cancellationTokenSource.CancelAsync(); + + await Assert.ThrowsAnyAsync<OperationCanceledException>(() => waitTask); + } + + [Fact] + public async Task ActiveRequestCount_UpdatesAtomically() + { + const int RequestCount = 1000; + var job = new TranscodingJob(NullLogger<TranscodingJob>.Instance); + + await Task.WhenAll( + Task.Run(() => Parallel.For(0, RequestCount, _ => job.IncrementActiveRequestCount())), + Task.Run(() => Parallel.For(0, RequestCount, _ => job.DecrementActiveRequestCount()))); + + Assert.Equal(0, job.ActiveRequestCount); + } } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Dto/DtoServiceImageInheritanceTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Dto/DtoServiceImageInheritanceTests.cs index 6b6240e116..d18f8c6cff 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Dto/DtoServiceImageInheritanceTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Dto/DtoServiceImageInheritanceTests.cs @@ -14,6 +14,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Trickplay; using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Querying; using Moq; using Xunit; @@ -155,6 +156,55 @@ public class DtoServiceImageInheritanceTests libraryManager.Verify(x => x.GetArtist(It.IsAny<string>(), It.IsAny<DtoOptions>()), Times.Never); } + [Fact] + public void GetBaseItemDtos_Items_ResolvePeopleFromBatch_WithoutPerItemLookup() + { + static MusicAlbum MakeAlbum() => new MusicAlbum + { + Id = Guid.NewGuid(), + Name = "Album", + ImageInfos = [] + }; + + var albumOne = MakeAlbum(); + var albumTwo = MakeAlbum(); + + var libraryManager = new Mock<ILibraryManager>(); + + // DtoService resolves people for every item in ONE batch (GetPeopleByItems) before the + // per-item loop. A regression to the per-item path would call GetPeople(BaseItem) once per + // item (the N+1); it is intentionally left unset so such a regression fails here. + libraryManager + .Setup(x => x.GetPeopleByItems(It.IsAny<IReadOnlyList<Guid>>())) + .Returns(new Dictionary<Guid, IReadOnlyList<PersonInfo>> + { + [albumOne.Id] = [new PersonInfo { ItemId = albumOne.Id, Name = "Some Actor", Type = PersonKind.Actor }], + [albumTwo.Id] = [new PersonInfo { ItemId = albumTwo.Id, Name = "Some Actor", Type = PersonKind.Actor }] + }); + + // AttachPeople still resolves each distinct name to its Person entity to attach images. + libraryManager + .Setup(x => x.GetPerson("Some Actor")) + .Returns(new Person { Id = Guid.NewGuid(), Name = "Some Actor" }); + + var dtoService = BuildDtoService(libraryManager); + + var options = new DtoOptions(false) { Fields = [ItemFields.People] }; + var dtos = dtoService.GetBaseItemDtos([albumOne, albumTwo], options); + + Assert.Equal(2, dtos.Count); + foreach (var dto in dtos) + { + Assert.NotNull(dto.People); + Assert.Single(dto.People); + Assert.Equal("Some Actor", dto.People[0].Name); + } + + // People are batched once for the whole set, never once per item. + libraryManager.Verify(x => x.GetPeopleByItems(It.IsAny<IReadOnlyList<Guid>>()), Times.Once); + libraryManager.Verify(x => x.GetPeople(It.IsAny<BaseItem>()), Times.Never); + } + private static DtoService BuildDtoService(BaseItem displayParent) { var libraryManager = new Mock<ILibraryManager>(); diff --git a/tests/Jellyfin.Server.Implementations.Tests/Item/BaseItemRepositoryByNameTotalCountTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Item/BaseItemRepositoryByNameTotalCountTests.cs new file mode 100644 index 0000000000..f675621e21 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Item/BaseItemRepositoryByNameTotalCountTests.cs @@ -0,0 +1,199 @@ +using System; +using System.Linq; +using Emby.Server.Implementations.Data; +using Jellyfin.Database.Implementations; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Database.Implementations.Locking; +using Jellyfin.Database.Providers.Sqlite; +using Jellyfin.Server.Implementations.Item; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Configuration; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; +using BaseItemKind = Jellyfin.Data.Enums.BaseItemKind; + +namespace Jellyfin.Server.Implementations.Tests.Item; + +/// <summary> +/// The by-name endpoints (artists, album artists, genres, studios) all funnel through +/// <c>GetItemValues</c>. A query without a <c>Limit</c> used to have its total record count +/// silently disabled, so callers got a populated <c>Items</c> array next to a zero total. +/// </summary> +public sealed class BaseItemRepositoryByNameTotalCountTests : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly DbContextOptions<JellyfinDbContext> _dbOptions; + private readonly BaseItemRepository _repository; + private readonly ItemTypeLookup _itemTypeLookup; + + public BaseItemRepositoryByNameTotalCountTests() + { + _connection = new SqliteConnection("Data Source=:memory:"); + _connection.Open(); + + _dbOptions = new DbContextOptionsBuilder<JellyfinDbContext>() + .UseSqlite(_connection) + .Options; + + using (var ctx = CreateDbContext()) + { + ctx.Database.EnsureCreated(); + } + + var factory = new Mock<IDbContextFactory<JellyfinDbContext>>(); + factory.Setup(f => f.CreateDbContext()).Returns(CreateDbContext); + + _itemTypeLookup = new ItemTypeLookup(); + + var serverConfigurationManager = new Mock<IServerConfigurationManager>(); + serverConfigurationManager.Setup(c => c.Configuration).Returns(new ServerConfiguration()); + + _repository = new BaseItemRepository( + factory.Object, + new Mock<IServerApplicationHost>().Object, + _itemTypeLookup, + serverConfigurationManager.Object, + NullLogger<BaseItemRepository>.Instance); + } + + public void Dispose() + { + _connection.Dispose(); + } + + [Fact] + public void GetArtists_WithoutLimit_ReportsTotalRecordCount() + { + SeedArtists(3); + + var result = _repository.GetArtists(CreateQuery(limit: null)); + + Assert.Equal(3, result.Items.Count); + Assert.Equal(3, result.TotalRecordCount); + } + + [Fact] + public void GetArtists_WithLimit_ReportsTotalBeyondThePage() + { + SeedArtists(3); + + var result = _repository.GetArtists(CreateQuery(limit: 2)); + + Assert.Equal(2, result.Items.Count); + Assert.Equal(3, result.TotalRecordCount); + } + + [Fact] + public void GetArtists_TotalRecordCountDisabled_StaysZero() + { + SeedArtists(3); + + var query = CreateQuery(limit: null); + query.EnableTotalRecordCount = false; + + var result = _repository.GetArtists(query); + + Assert.Equal(3, result.Items.Count); + Assert.Equal(0, result.TotalRecordCount); + } + + [Fact] + public void GetArtists_WithoutLimit_DoesNotMutateCallerQuery() + { + SeedArtists(1); + + var query = CreateQuery(limit: null); + Assert.True(query.EnableTotalRecordCount); + + _repository.GetArtists(query); + + // The repository used to flip this flag on the caller's own query object, so a + // reused query silently lost its total on every subsequent call. + Assert.True(query.EnableTotalRecordCount); + } + + private static InternalItemsQuery CreateQuery(int? limit) + { + return new InternalItemsQuery(new User("test", "auth", "reset")) + { + Limit = limit + }; + } + + /// <summary> + /// Creates <paramref name="count"/> artists, each credited on one song, which is what + /// makes them visible to the item-value join behind the by-name endpoints. + /// </summary> + private void SeedArtists(int count) + { + using var ctx = CreateDbContext(); + + for (var i = 0; i < count; i++) + { + var name = $"Artist {i}"; + var cleanName = name.ToLowerInvariant(); + + var artistId = Guid.Parse($"aaaaaaaa-0000-0000-0000-{i:D12}"); + var songId = Guid.Parse($"55555555-0000-0000-0000-{i:D12}"); + var valueId = Guid.Parse($"cccccccc-0000-0000-0000-{i:D12}"); + + var artist = new BaseItemEntity + { + Id = artistId, + Type = _itemTypeLookup.BaseItemKindNames[BaseItemKind.MusicArtist], + Name = name, + CleanName = cleanName, + PresentationUniqueKey = artistId.ToString("N"), + IsFolder = true, + IsVirtualItem = false + }; + + var song = new BaseItemEntity + { + Id = songId, + Type = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Audio], + Name = $"Song {i}", + CleanName = $"song {i}", + PresentationUniqueKey = songId.ToString("N"), + MediaType = "Audio", + IsFolder = false, + IsVirtualItem = false + }; + + var itemValue = new ItemValue + { + ItemValueId = valueId, + Type = ItemValueType.Artist, + Value = name, + CleanValue = cleanName + }; + + ctx.BaseItems.Add(artist); + ctx.BaseItems.Add(song); + ctx.ItemValues.Add(itemValue); + ctx.ItemValuesMap.Add(new ItemValueMap + { + ItemId = songId, + ItemValueId = valueId, + Item = song, + ItemValue = itemValue + }); + } + + ctx.SaveChanges(); + } + + private JellyfinDbContext CreateDbContext() + { + return new JellyfinDbContext( + _dbOptions, + NullLogger<JellyfinDbContext>.Instance, + new SqliteDatabaseProvider(null!, NullLogger<SqliteDatabaseProvider>.Instance), + new NoLockBehavior(NullLogger<NoLockBehavior>.Instance)); + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Item/ItemPersistenceOwnedRowTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Item/ItemPersistenceOwnedRowTests.cs new file mode 100644 index 0000000000..6324706452 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Item/ItemPersistenceOwnedRowTests.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Jellyfin.Database.Implementations; +using Jellyfin.Database.Implementations.Locking; +using Jellyfin.Database.Providers.Sqlite; +using Jellyfin.Server.Implementations.Item; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Item; + +public sealed class ItemPersistenceOwnedRowTests : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly DbContextOptions<JellyfinDbContext> _dbOptions; + private readonly ItemPersistenceService _service; + private readonly IApplicationPaths _applicationPaths; + private readonly ILibraryManager? _previousLibraryManager; + private readonly IServerConfigurationManager? _previousConfigurationManager; + + public ItemPersistenceOwnedRowTests() + { + _applicationPaths = new Mock<IApplicationPaths>().Object; + + _connection = new SqliteConnection("Data Source=:memory:"); + _connection.Open(); + + _dbOptions = new DbContextOptionsBuilder<JellyfinDbContext>() + .UseSqlite(_connection) + .Options; + + using (var ctx = CreateDbContext()) + { + ctx.Database.EnsureCreated(); + } + + // BaseItem resolves these through process-wide statics; restored in Dispose. + _previousLibraryManager = BaseItem.LibraryManager; + _previousConfigurationManager = BaseItem.ConfigurationManager; + + var libraryManager = new Mock<ILibraryManager>(); + libraryManager.Setup(l => l.GetCollectionFolders(It.IsAny<BaseItem>())) + .Returns([]); + BaseItem.LibraryManager = libraryManager.Object; + + var configurationManager = new Mock<IServerConfigurationManager>(); + configurationManager.Setup(c => c.Configuration).Returns(new ServerConfiguration()); + BaseItem.ConfigurationManager = configurationManager.Object; + + var factory = new Mock<IDbContextFactory<JellyfinDbContext>>(); + factory.Setup(f => f.CreateDbContext()).Returns(CreateDbContext); + + _service = new ItemPersistenceService( + factory.Object, + new Mock<IServerApplicationHost>().Object, + NullLogger<ItemPersistenceService>.Instance); + } + + public void Dispose() + { + BaseItem.LibraryManager = _previousLibraryManager!; + BaseItem.ConfigurationManager = _previousConfigurationManager!; + _connection.Dispose(); + } + + [Fact] + public void SaveItems_UpdateExistingItem_ReplacesOwnedRows() + { + var id = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"); + + _service.SaveItems( + [CreateBook(id, new() { ["Imdb"] = "tt0001", ["Tmdb"] = "555" }, [MetadataField.Name])], + CancellationToken.None); + + using (var ctx = CreateDbContext()) + { + Assert.Equal(2, ctx.BaseItemProviders.Count(e => e.ItemId.Equals(id))); + Assert.Equal(1, ctx.BaseItemImageInfos.Count(e => e.ItemId.Equals(id))); + Assert.Equal(1, ctx.BaseItemMetadataFields.Count(e => e.ItemId.Equals(id))); + } + + // Re-save with different owned rows: the update path rewrites all three tables wholesale. + _service.SaveItems( + [CreateBook(id, new() { ["Imdb"] = "tt9999" }, [MetadataField.Name, MetadataField.Genres])], + CancellationToken.None); + + using (var ctx = CreateDbContext()) + { + var providers = ctx.BaseItemProviders.Where(e => e.ItemId.Equals(id)).ToList(); + Assert.Equal("tt9999", Assert.Single(providers).ProviderValue); + + Assert.Equal(1, ctx.BaseItemImageInfos.Count(e => e.ItemId.Equals(id))); + Assert.Equal(2, ctx.BaseItemMetadataFields.Count(e => e.ItemId.Equals(id))); + } + } + + [Fact] + public void SaveItems_MixedNewAndExistingBatch_ReplacesOnlyExistingOwnedRows() + { + var existing = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"); + var fresh = Guid.Parse("cccccccc-cccc-cccc-cccc-cccccccccccc"); + + _service.SaveItems([CreateBook(existing, new() { ["Imdb"] = "tt0001" }, [])], CancellationToken.None); + + // One already-persisted item and one brand new item in the same batch. + _service.SaveItems( + [ + CreateBook(existing, new() { ["Imdb"] = "tt0002" }, []), + CreateBook(fresh, new() { ["Tmdb"] = "777" }, []) + ], + CancellationToken.None); + + using var ctx = CreateDbContext(); + Assert.Equal("tt0002", Assert.Single(ctx.BaseItemProviders.Where(e => e.ItemId.Equals(existing))).ProviderValue); + Assert.Equal("777", Assert.Single(ctx.BaseItemProviders.Where(e => e.ItemId.Equals(fresh))).ProviderValue); + } + + private static Book CreateBook(Guid id, Dictionary<string, string> providerIds, MetadataField[] lockedFields) + { + var book = new Book + { + Id = id, + Name = "Book", + ProviderIds = providerIds, + LockedFields = lockedFields + }; + + book.SetImage(new ItemImageInfo { Path = "/img/primary.jpg", Type = ImageType.Primary }, 0); + return book; + } + + private JellyfinDbContext CreateDbContext() => new( + _dbOptions, + NullLogger<JellyfinDbContext>.Instance, + new SqliteDatabaseProvider(_applicationPaths, NullLogger<SqliteDatabaseProvider>.Instance), + new NoLockBehavior(NullLogger<NoLockBehavior>.Instance)); +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs index ede9e61536..265b6a7f43 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs @@ -293,7 +293,84 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins Assert.Equal(packageInfo.Versions[0].Version, result.Version); } - private PackageInfo GenerateTestPackage() + [Fact] + public async Task DisablePlugin_CatalogRefresh_StaysDisabled() + { + var pluginRoot = Path.Combine(_tempPath, "plugins"); + var pluginDir = CreateTestPlugin(pluginRoot, "Disable Me", PluginStatus.Active); + + var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, pluginRoot, new Version(1, 0)); + var plugin = Assert.Single(pluginManager.Plugins); + + pluginManager.DisablePlugin(plugin); + + Assert.Equal(PluginStatus.Disabled, pluginManager.LoadManifest(pluginDir).Manifest.Status); + + // The web shows that a restart is required, but the persisted state must not change. + Assert.Equal(PluginStatus.Restart, plugin.GetPluginInfo().Status); + Assert.Equal(PluginStatus.Disabled, plugin.Manifest.Status); + Assert.True(plugin.Manifest.AutoUpdate); + + // Every catalog fetch rewrites the manifests of installed plugins from the in-memory status. + var packageInfo = GenerateTestPackage(plugin.Id); + await pluginManager.PopulateManifest(packageInfo, new Version(1, 0), pluginDir, plugin.Manifest.Status); + + Assert.Equal(PluginStatus.Disabled, pluginManager.LoadManifest(pluginDir).Manifest.Status); + } + + [Fact] + public void Constructor_DisabledPluginSortingBeforeEnabledPlugin_IsNotDeleted() + { + var pluginRoot = Path.Combine(_tempPath, "plugins"); + var disabledDir = CreateTestPlugin(pluginRoot, "AAA Disabled", PluginStatus.Disabled); + CreateTestPlugin(pluginRoot, "ZZZ Active", PluginStatus.Active); + + var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, pluginRoot, new Version(1, 0)); + + Assert.True(Directory.Exists(disabledDir)); + Assert.Contains(pluginManager.Plugins, p => string.Equals(p.Name, "AAA Disabled", StringComparison.Ordinal)); + } + + [Fact] + public void LoadAssemblies_DisabledPluginWithSupersededVersion_DoesNotRevertToOldVersion() + { + var pluginRoot = Path.Combine(_tempPath, "plugins"); + var id = Guid.NewGuid(); + var oldDir = CreateTestPlugin(pluginRoot, "Two Versions", PluginStatus.Superseded, new Version(1, 0), id); + var newDir = CreateTestPlugin(pluginRoot, "Two Versions_2.0", PluginStatus.Disabled, new Version(2, 0), id, "Two Versions"); + + var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, pluginRoot, new Version(1, 0)); + + Assert.Empty(pluginManager.LoadAssemblies()); + + // Neither version may be touched: the old one stays superseded instead of being loaded + // as a stand-in for the version the user disabled. + Assert.Equal(PluginStatus.Superseded, pluginManager.LoadManifest(oldDir).Manifest.Status); + Assert.Equal(PluginStatus.Disabled, pluginManager.LoadManifest(newDir).Manifest.Status); + } + + private string CreateTestPlugin(string root, string folderName, PluginStatus status, Version? version = null, Guid? id = null, string? name = null) + { + var dir = Path.Combine(root, folderName); + Directory.CreateDirectory(dir); + FileHelper.CreateEmpty(Path.Combine(dir, "some.dll")); + + var manifest = new PluginManifest + { + Id = id ?? Guid.NewGuid(), + Name = name ?? folderName, + Status = status, + AutoUpdate = true, + TargetAbi = "1.0", + Version = (version ?? new Version(1, 0)).ToString() + }; + + File.WriteAllText(Path.Combine(dir, "meta.json"), JsonSerializer.Serialize(manifest, _options)); + + return dir; + } + + private PackageInfo GenerateTestPackage(Guid? id = null) { var fixture = new Fixture(); fixture.Customize<PackageInfo>(c => c.Without(x => x.Versions).Without(x => x.ImageUrl)); @@ -305,6 +382,10 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins var packageInfo = fixture.Create<PackageInfo>(); packageInfo.Versions = new[] { versionInfo }; + if (id.HasValue) + { + packageInfo.Id = id.Value; + } return packageInfo; } diff --git a/tests/Jellyfin.Server.Integration.Tests/ImageProcessorTests.cs b/tests/Jellyfin.Server.Integration.Tests/ImageProcessorTests.cs new file mode 100644 index 0000000000..a1149ac9be --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/ImageProcessorTests.cs @@ -0,0 +1,131 @@ +using System; +using System.Globalization; +using System.IO; +using Jellyfin.Drawing; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Drawing; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Integration.Tests; + +public sealed class ImageProcessorTests : IDisposable +{ + private const string CacheRoot = "image-cache"; + private const string OriginalPath = "/media/poster.jpg"; + private const string NoOverlayCacheKey = "/media/poster.jpg,quality=90,datemodified=638800000000000000,f=Jpg,width=200,height=300,maxwidth=400,maxheight=500,fillwidth=600,fillheight=700,blur=2,b=000000,fl=layer,v=4"; + private static readonly DateTime _dateModified = new(638800000000000000, DateTimeKind.Utc); + private readonly ImageProcessor _imageProcessor; + + public ImageProcessorTests() + { + var applicationPaths = new Mock<IServerApplicationPaths>(); + applicationPaths.SetupGet(paths => paths.ImageCachePath).Returns(CacheRoot); + + var configurationManager = new Mock<IServerConfigurationManager>(); + configurationManager + .SetupGet(manager => manager.Configuration) + .Returns(new ServerConfiguration { ParallelImageEncodingLimit = 1 }); + + _imageProcessor = new ImageProcessor( + NullLogger<ImageProcessor>.Instance, + applicationPaths.Object, + Mock.Of<IFileSystem>(), + Mock.Of<IImageEncoder>(), + configurationManager.Object); + } + + [Fact] + public void GetCacheFilePath_DifferentOverlayTypes_ReturnDifferentPaths() + { + var percentPlayedPath = GetCacheFilePath(percentPlayed: 1); + var unwatchedCountPath = GetCacheFilePath(unwatchedCount: 1); + + Assert.NotEqual(percentPlayedPath, unwatchedCountPath); + } + + [Fact] + public void GetCacheFilePath_DifferentPercentPlayedValues_ReturnDifferentPaths() + { + var firstPath = GetCacheFilePath(percentPlayed: 12.5); + var secondPath = GetCacheFilePath(percentPlayed: 75.5); + + Assert.NotEqual(firstPath, secondPath); + } + + [Fact] + public void GetCacheFilePath_DifferentUnwatchedCountValues_ReturnDifferentPaths() + { + var firstPath = GetCacheFilePath(unwatchedCount: 1); + var secondPath = GetCacheFilePath(unwatchedCount: 2); + + Assert.NotEqual(firstPath, secondPath); + } + + [Fact] + public void GetCacheFilePath_DifferentCultures_ReturnSamePath() + { + var originalCulture = CultureInfo.CurrentCulture; + + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); + var expectedPath = GetCacheFilePath(percentPlayed: 12.5); + + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR"); + var actualPath = GetCacheFilePath(percentPlayed: 12.5); + + Assert.Equal(expectedPath, actualPath); + } + finally + { + CultureInfo.CurrentCulture = originalCulture; + } + } + + [Fact] + public void GetCacheFilePath_NoOverlay_UsesVersionFourWithExistingSerialization() + { + var expectedPath = _imageProcessor.GetCachePath( + Path.Combine(CacheRoot, "resized-images"), + NoOverlayCacheKey, + ".jpg"); + + Assert.Equal(expectedPath, GetCacheFilePath()); + } + + public void Dispose() + { + _imageProcessor.Dispose(); + } + + private string GetCacheFilePath(double percentPlayed = 0, int? unwatchedCount = null) + { + var options = new ImageProcessingOptions + { + Width = 200, + Height = 300, + MaxWidth = 400, + MaxHeight = 500, + FillWidth = 600, + FillHeight = 700, + Quality = 90, + PercentPlayed = percentPlayed, + UnplayedCount = unwatchedCount, + Blur = 2, + BackgroundColor = "000000", + ForegroundLayer = "layer" + }; + + return _imageProcessor.GetCacheFilePath( + OriginalPath, + _dateModified, + ImageFormat.Jpg, + options); + } +} |
