JellyfinApplicationFactory.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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.AddSingleton<IStartupLogger, NullStartupLogger>().AddSingleton(e));
  91. }
  92. /// <inheritdoc/>
  93. protected override IHost CreateHost(IHostBuilder builder)
  94. {
  95. var host = builder.Build();
  96. var appHost = (TestAppHost)host.Services.GetRequiredService<IApplicationHost>();
  97. appHost.ServiceProvider = host.Services;
  98. var applicationPaths = appHost.ServiceProvider.GetRequiredService<IApplicationPaths>();
  99. Program.ApplyStartupMigrationAsync((ServerApplicationPaths)applicationPaths, appHost.ServiceProvider.GetRequiredService<IConfiguration>()).GetAwaiter().GetResult();
  100. Program.ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.CoreInitialisation).GetAwaiter().GetResult();
  101. appHost.InitializeServices(Mock.Of<IConfiguration>()).GetAwaiter().GetResult();
  102. Program.ApplyCoreMigrationsAsync(appHost.ServiceProvider, Migrations.Stages.JellyfinMigrationStageTypes.AppInitialisation).GetAwaiter().GetResult();
  103. host.Start();
  104. appHost.RunStartupTasksAsync().GetAwaiter().GetResult();
  105. return host;
  106. }
  107. /// <inheritdoc/>
  108. protected override void Dispose(bool disposing)
  109. {
  110. foreach (var disposable in _disposableComponents)
  111. {
  112. disposable.Dispose();
  113. }
  114. _disposableComponents.Clear();
  115. base.Dispose(disposing);
  116. }
  117. private sealed class NullStartupLogger : IStartupLogger
  118. {
  119. public IStartupLogger BeginGroup(FormattableString logEntry)
  120. {
  121. return this;
  122. }
  123. public IDisposable? BeginScope<TState>(TState state)
  124. where TState : notnull
  125. {
  126. return NullLogger.Instance.BeginScope(state);
  127. }
  128. public bool IsEnabled(LogLevel logLevel)
  129. {
  130. return NullLogger.Instance.IsEnabled(logLevel);
  131. }
  132. public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
  133. {
  134. NullLogger.Instance.Log(logLevel, eventId, state, exception, formatter);
  135. }
  136. public Microsoft.Extensions.Logging.ILogger With(Microsoft.Extensions.Logging.ILogger logger)
  137. {
  138. return this;
  139. }
  140. IStartupLogger IStartupLogger.With(Microsoft.Extensions.Logging.ILogger logger)
  141. {
  142. return this;
  143. }
  144. }
  145. }
  146. }