JellyfinApplicationFactory.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Globalization;
  4. using System.IO;
  5. using Emby.Server.Implementations;
  6. using Jellyfin.Server.Extensions;
  7. using Jellyfin.Server.Helpers;
  8. using Jellyfin.Server.ServerSetupApp;
  9. using MediaBrowser.Common;
  10. using MediaBrowser.Common.Configuration;
  11. using Microsoft.AspNetCore.Hosting;
  12. using Microsoft.AspNetCore.Mvc.Testing;
  13. using Microsoft.Extensions.Configuration;
  14. using Microsoft.Extensions.DependencyInjection;
  15. using Microsoft.Extensions.Hosting;
  16. using Microsoft.Extensions.Logging;
  17. using Microsoft.Extensions.Logging.Abstractions;
  18. using Moq;
  19. using Serilog;
  20. using Serilog.Core;
  21. using Serilog.Extensions.Logging;
  22. namespace Jellyfin.Server.Integration.Tests
  23. {
  24. /// <summary>
  25. /// Factory for bootstrapping the Jellyfin application in memory for functional end to end tests.
  26. /// </summary>
  27. public class JellyfinApplicationFactory : WebApplicationFactory<Startup>
  28. {
  29. private static readonly string _testPathRoot = Path.Combine(Path.GetTempPath(), "jellyfin-test-data");
  30. private readonly ConcurrentBag<IDisposable> _disposableComponents = new ConcurrentBag<IDisposable>();
  31. /// <summary>
  32. /// Initializes static members of the <see cref="JellyfinApplicationFactory"/> class.
  33. /// </summary>
  34. static JellyfinApplicationFactory()
  35. {
  36. // Perform static initialization that only needs to happen once per test-run
  37. Log.Logger = new LoggerConfiguration()
  38. .WriteTo.Console(formatProvider: CultureInfo.InvariantCulture)
  39. .CreateLogger();
  40. StartupHelpers.PerformStaticInitialization();
  41. }
  42. /// <inheritdoc/>
  43. protected override IHostBuilder CreateHostBuilder()
  44. {
  45. return new HostBuilder();
  46. }
  47. /// <inheritdoc/>
  48. protected override void ConfigureWebHost(IWebHostBuilder builder)
  49. {
  50. // Skip ffmpeg check for testing
  51. Environment.SetEnvironmentVariable("JELLYFIN_FFMPEG__NOVALIDATION", "true");
  52. // Specify the startup command line options
  53. var commandLineOpts = new StartupOptions();
  54. // Use a temporary directory for the application paths
  55. var webHostPathRoot = Path.Combine(_testPathRoot, "test-host-" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
  56. Directory.CreateDirectory(Path.Combine(webHostPathRoot, "logs"));
  57. Directory.CreateDirectory(Path.Combine(webHostPathRoot, "config"));
  58. Directory.CreateDirectory(Path.Combine(webHostPathRoot, "cache"));
  59. Directory.CreateDirectory(Path.Combine(webHostPathRoot, "jellyfin-web"));
  60. var appPaths = new ServerApplicationPaths(
  61. webHostPathRoot,
  62. Path.Combine(webHostPathRoot, "logs"),
  63. Path.Combine(webHostPathRoot, "config"),
  64. Path.Combine(webHostPathRoot, "cache"),
  65. Path.Combine(webHostPathRoot, "jellyfin-web"));
  66. // Create the logging config file
  67. // TODO: We shouldn't need to do this since we are only logging to console
  68. StartupHelpers.InitLoggingConfigFile(appPaths).GetAwaiter().GetResult();
  69. // Create a copy of the application configuration to use for startup
  70. var startupConfig = Program.CreateAppConfiguration(commandLineOpts, appPaths);
  71. ILoggerFactory loggerFactory = new SerilogLoggerFactory();
  72. _disposableComponents.Add(loggerFactory);
  73. // Create the app host and initialize it
  74. var appHost = new TestAppHost(
  75. appPaths,
  76. loggerFactory,
  77. commandLineOpts,
  78. startupConfig);
  79. _disposableComponents.Add(appHost);
  80. builder.ConfigureServices(services => appHost.Init(services))
  81. .ConfigureWebHostBuilder(appHost, startupConfig, appPaths, NullLogger.Instance)
  82. .ConfigureAppConfiguration((context, builder) =>
  83. {
  84. builder
  85. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  86. .AddInMemoryCollection(ConfigurationOptions.DefaultConfiguration)
  87. .AddEnvironmentVariables("JELLYFIN_")
  88. .AddInMemoryCollection(commandLineOpts.ConvertToConfig());
  89. })
  90. .ConfigureServices(e => e
  91. .AddSingleton<IStartupLogger, NullStartupLogger<object>>()
  92. .AddTransient(typeof(IStartupLogger<>), typeof(NullStartupLogger<>))
  93. .AddSingleton(e));
  94. }
  95. /// <inheritdoc/>
  96. protected override IHost CreateHost(IHostBuilder builder)
  97. {
  98. var host = builder.Build();
  99. var appHost = (TestAppHost)host.Services.GetRequiredService<IApplicationHost>();
  100. appHost.ServiceProvider = host.Services;
  101. var applicationPaths = appHost.ServiceProvider.GetRequiredService<IApplicationPaths>();
  102. Program.ApplyStartupMigrationAsync((ServerApplicationPaths)applicationPaths, appHost.ServiceProvider.GetRequiredService<IConfiguration>()).GetAwaiter().GetResult();
  103. Program.ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.CoreInitialisation).GetAwaiter().GetResult();
  104. appHost.InitializeServices(Mock.Of<IConfiguration>()).GetAwaiter().GetResult();
  105. Program.ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.AppInitialisation).GetAwaiter().GetResult();
  106. host.Start();
  107. appHost.RunStartupTasksAsync().GetAwaiter().GetResult();
  108. return host;
  109. }
  110. /// <inheritdoc/>
  111. protected override void Dispose(bool disposing)
  112. {
  113. foreach (var disposable in _disposableComponents)
  114. {
  115. disposable.Dispose();
  116. }
  117. _disposableComponents.Clear();
  118. base.Dispose(disposing);
  119. }
  120. private sealed class NullStartupLogger<TCategory> : IStartupLogger<TCategory>
  121. {
  122. public StartupLogTopic? Topic => throw new NotImplementedException();
  123. public IStartupLogger BeginGroup(FormattableString logEntry)
  124. {
  125. return this;
  126. }
  127. public IStartupLogger<TCategory1> BeginGroup<TCategory1>(FormattableString logEntry)
  128. {
  129. return new NullStartupLogger<TCategory1>();
  130. }
  131. public IDisposable? BeginScope<TState>(TState state)
  132. where TState : notnull
  133. {
  134. return NullLogger.Instance.BeginScope(state);
  135. }
  136. public bool IsEnabled(LogLevel logLevel)
  137. {
  138. return NullLogger.Instance.IsEnabled(logLevel);
  139. }
  140. public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
  141. {
  142. NullLogger.Instance.Log(logLevel, eventId, state, exception, formatter);
  143. }
  144. public Microsoft.Extensions.Logging.ILogger With(Microsoft.Extensions.Logging.ILogger logger)
  145. {
  146. return this;
  147. }
  148. public IStartupLogger<TCategory1> With<TCategory1>(Microsoft.Extensions.Logging.ILogger logger)
  149. {
  150. return new NullStartupLogger<TCategory1>();
  151. }
  152. IStartupLogger<TCategory> IStartupLogger<TCategory>.BeginGroup(FormattableString logEntry)
  153. {
  154. return new NullStartupLogger<TCategory>();
  155. }
  156. IStartupLogger IStartupLogger.With(Microsoft.Extensions.Logging.ILogger logger)
  157. {
  158. return this;
  159. }
  160. IStartupLogger<TCategory> IStartupLogger<TCategory>.With(Microsoft.Extensions.Logging.ILogger logger)
  161. {
  162. return this;
  163. }
  164. }
  165. }
  166. }