|
| 1 | +using Grand.Data; |
| 2 | +using Grand.Web.Common.Infrastructure; |
| 3 | +using Microsoft.AspNetCore.Hosting; |
| 4 | +using Microsoft.AspNetCore.Http; |
| 5 | +using Microsoft.AspNetCore.Http.Features; |
| 6 | +using Microsoft.Extensions.DependencyInjection; |
| 7 | +using Microsoft.Extensions.FileProviders; |
| 8 | +using Microsoft.Extensions.Logging.Abstractions; |
| 9 | +using Microsoft.Net.Http.Headers; |
| 10 | +using Microsoft.VisualStudio.TestTools.UnitTesting; |
| 11 | +using MongoDB.Driver; |
| 12 | +using MongoDB.Driver.Core.Clusters; |
| 13 | +using MongoDB.Driver.Core.Connections; |
| 14 | +using MongoDB.Driver.Core.Servers; |
| 15 | +using Moq; |
| 16 | +using System.Net; |
| 17 | + |
| 18 | +namespace Grand.Web.Common.Tests.Infrastructure; |
| 19 | + |
| 20 | +[TestClass] |
| 21 | +public class GrandExceptionHandlerTests |
| 22 | +{ |
| 23 | + private GrandExceptionHandler _handler = null!; |
| 24 | + private string _webRoot = null!; |
| 25 | + |
| 26 | + [TestInitialize] |
| 27 | + public void Init() |
| 28 | + { |
| 29 | + DataSettingsManager.Initialize(Path.Join(Path.GetTempPath(), "grand-exception-handler-tests-settings.json")); |
| 30 | + DataSettingsManager.Instance.LoadDataSettings(new DataSettings { ConnectionString = "mongodb://localhost" }); |
| 31 | + |
| 32 | + _webRoot = Path.Combine(Path.GetTempPath(), "errorpage-" + Guid.NewGuid().ToString("N")); |
| 33 | + Directory.CreateDirectory(_webRoot); |
| 34 | + File.WriteAllText(Path.Combine(_webRoot, "errorpage.htm"), "<h1>INTERNAL ERROR</h1>"); |
| 35 | + |
| 36 | + _handler = new GrandExceptionHandler(NullLogger<GrandExceptionHandler>.Instance); |
| 37 | + } |
| 38 | + |
| 39 | + [TestCleanup] |
| 40 | + public void Cleanup() |
| 41 | + { |
| 42 | + Directory.Delete(_webRoot, true); |
| 43 | + } |
| 44 | + |
| 45 | + private HttpContext CreateContext() |
| 46 | + { |
| 47 | + var env = new Mock<IWebHostEnvironment>(); |
| 48 | + env.SetupProperty(e => e.WebRootFileProvider, new PhysicalFileProvider(_webRoot)); |
| 49 | + var services = new ServiceCollection(); |
| 50 | + services.AddSingleton(env.Object); |
| 51 | + |
| 52 | + var context = new DefaultHttpContext { RequestServices = services.BuildServiceProvider() }; |
| 53 | + context.Request.Path = "/category"; |
| 54 | + context.Response.Body = new MemoryStream(); |
| 55 | + return context; |
| 56 | + } |
| 57 | + |
| 58 | + private static string ReadBody(HttpContext context) |
| 59 | + { |
| 60 | + context.Response.Body.Position = 0; |
| 61 | + return new StreamReader(context.Response.Body).ReadToEnd(); |
| 62 | + } |
| 63 | + |
| 64 | + [TestMethod] |
| 65 | + public async Task TryHandleAsync_WebRequest_Writes500WithStaticErrorPage() |
| 66 | + { |
| 67 | + var context = CreateContext(); |
| 68 | + |
| 69 | + var handled = await _handler.TryHandleAsync(context, new InvalidOperationException(), CancellationToken.None); |
| 70 | + |
| 71 | + Assert.IsTrue(handled); |
| 72 | + Assert.AreEqual(StatusCodes.Status500InternalServerError, context.Response.StatusCode); |
| 73 | + Assert.AreEqual("no-store", context.Response.Headers[HeaderNames.CacheControl].ToString()); |
| 74 | + Assert.IsFalse(context.Response.Headers.ContainsKey(HeaderNames.Location)); |
| 75 | + Assert.IsFalse(context.Response.Headers.ContainsKey(HeaderNames.RetryAfter)); |
| 76 | + StringAssert.StartsWith(context.Response.ContentType, "text/html"); |
| 77 | + Assert.AreEqual("<h1>INTERNAL ERROR</h1>", ReadBody(context)); |
| 78 | + } |
| 79 | + |
| 80 | + [TestMethod] |
| 81 | + public async Task TryHandleAsync_MongoServerSelectionTimeout_Writes503WithRetryAfter() |
| 82 | + { |
| 83 | + var context = CreateContext(); |
| 84 | + |
| 85 | + var handled = await _handler.TryHandleAsync(context, new TimeoutException("server selection"), CancellationToken.None); |
| 86 | + |
| 87 | + Assert.IsTrue(handled); |
| 88 | + Assert.AreEqual(StatusCodes.Status503ServiceUnavailable, context.Response.StatusCode); |
| 89 | + Assert.AreEqual("30", context.Response.Headers[HeaderNames.RetryAfter].ToString()); |
| 90 | + Assert.AreEqual("<h1>INTERNAL ERROR</h1>", ReadBody(context)); |
| 91 | + } |
| 92 | + |
| 93 | + [TestMethod] |
| 94 | + public async Task TryHandleAsync_MongoConnectionException_Writes503() |
| 95 | + { |
| 96 | + var context = CreateContext(); |
| 97 | + var connectionId = new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27017))); |
| 98 | + |
| 99 | + await _handler.TryHandleAsync(context, new MongoConnectionException(connectionId, "refused"), CancellationToken.None); |
| 100 | + |
| 101 | + Assert.AreEqual(StatusCodes.Status503ServiceUnavailable, context.Response.StatusCode); |
| 102 | + } |
| 103 | + |
| 104 | + [TestMethod] |
| 105 | + public async Task TryHandleAsync_ApiRequest_WritesProblemDetails500() |
| 106 | + { |
| 107 | + var context = CreateContext(); |
| 108 | + context.Request.Headers[HeaderNames.Authorization] = "Bearer token"; |
| 109 | + |
| 110 | + var handled = await _handler.TryHandleAsync(context, new TimeoutException(), CancellationToken.None); |
| 111 | + |
| 112 | + Assert.IsTrue(handled); |
| 113 | + Assert.AreEqual(StatusCodes.Status500InternalServerError, context.Response.StatusCode); |
| 114 | + Assert.IsFalse(context.Response.Headers.ContainsKey(HeaderNames.RetryAfter)); |
| 115 | + StringAssert.Contains(ReadBody(context), "An error occurred while processing your request"); |
| 116 | + } |
| 117 | + |
| 118 | + [TestMethod] |
| 119 | + public async Task TryHandleAsync_ResponseStarted_ReturnsFalse() |
| 120 | + { |
| 121 | + var context = CreateContext(); |
| 122 | + var responseFeature = new Mock<IHttpResponseFeature>(); |
| 123 | + responseFeature.Setup(f => f.HasStarted).Returns(true); |
| 124 | + context.Features.Set(responseFeature.Object); |
| 125 | + |
| 126 | + var handled = await _handler.TryHandleAsync(context, new InvalidOperationException(), CancellationToken.None); |
| 127 | + |
| 128 | + Assert.IsFalse(handled); |
| 129 | + } |
| 130 | +} |
0 commit comments