|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Linq; |
| 7 | +using System.Net; |
| 8 | +using System.Text; |
| 9 | +using System.Threading.Tasks; |
| 10 | +using Microsoft.Extensions.Logging.Abstractions; |
| 11 | + |
| 12 | +namespace Microsoft.NET.Build.Containers.UnitTests |
| 13 | +{ |
| 14 | + public class FallbackToHttpMessageHandlerTests |
| 15 | + { |
| 16 | + [Theory] |
| 17 | + [InlineData("mcr.microsoft.com", 80)] |
| 18 | + [InlineData("mcr.microsoft.com:443", 443)] |
| 19 | + [InlineData("mcr.microsoft.com:80", 80)] |
| 20 | + [InlineData("mcr.microsoft.com:5555", 5555)] |
| 21 | + public async Task FallBackToHttpPortShouldAsExpected(string registry, int expectedPort) |
| 22 | + { |
| 23 | + var uri = new UriBuilder($"https://{registry}").Uri; |
| 24 | + var handler = new FallbackToHttpMessageHandler( |
| 25 | + registry, |
| 26 | + uri.Host, |
| 27 | + uri.Port, |
| 28 | + new ServerMessageHandler(request => |
| 29 | + { |
| 30 | + // only accept http requests, reject https requests with a secure connection error |
| 31 | + |
| 32 | + if (request.RequestUri!.Scheme == Uri.UriSchemeHttps) |
| 33 | + { |
| 34 | + throw new HttpRequestException( |
| 35 | + httpRequestError: HttpRequestError.SecureConnectionError |
| 36 | + ); |
| 37 | + } |
| 38 | + else |
| 39 | + { |
| 40 | + return new HttpResponseMessage(HttpStatusCode.OK) |
| 41 | + { |
| 42 | + RequestMessage = request, |
| 43 | + }; |
| 44 | + } |
| 45 | + }), |
| 46 | + NullLogger.Instance |
| 47 | + ); |
| 48 | + using var httpClient = new HttpClient(handler); |
| 49 | + var response = await httpClient.GetAsync(uri); |
| 50 | + Assert.Equal(expectedPort, response.RequestMessage?.RequestUri?.Port); |
| 51 | + } |
| 52 | + |
| 53 | + private sealed class ServerMessageHandler : HttpMessageHandler |
| 54 | + { |
| 55 | + private readonly Func<HttpRequestMessage, HttpResponseMessage> _server; |
| 56 | + |
| 57 | + public ServerMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> server) |
| 58 | + { |
| 59 | + _server = server; |
| 60 | + } |
| 61 | + |
| 62 | + protected override Task<HttpResponseMessage> SendAsync( |
| 63 | + HttpRequestMessage request, |
| 64 | + CancellationToken cancellationToken |
| 65 | + ) |
| 66 | + { |
| 67 | + return Task.FromResult(_server(request)); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments