Summary

Class:WireMock.Owin.AspNetCoreSelfHost
Assembly:WireMock.Net
File(s):C:\Users\StefHeyenrath\Documents\GitHub\WireMock.Net\src\WireMock.Net\Owin\AspNetCoreSelfHost.cs
Covered lines:83
Uncovered lines:7
Coverable lines:90
Total lines:159
Line coverage:92.2%
Branch coverage:75%

Metrics

MethodCyclomatic complexity NPath complexity Sequence coverage Branch coverage
StartAsync()0010
RunHost(...)000.6250
StopAsync()0010
.ctor(...)0010.75

File(s)

C:\Users\StefHeyenrath\Documents\GitHub\WireMock.Net\src\WireMock.Net\Owin\AspNetCoreSelfHost.cs

#LineLine coverage
 1#if USE_ASPNETCORE
 2using System;
 3using System.Collections.Generic;
 4using System.Linq;
 5using System.Threading;
 6using System.Threading.Tasks;
 7using JetBrains.Annotations;
 8using Microsoft.AspNetCore.Builder;
 9using Microsoft.AspNetCore.Hosting;
 10using Microsoft.Extensions.DependencyInjection;
 11using WireMock.HttpsCertificate;
 12using WireMock.Logging;
 13using WireMock.Owin.Mappers;
 14using WireMock.Util;
 15using WireMock.Validation;
 16
 17namespace WireMock.Owin
 18{
 19    internal class AspNetCoreSelfHost : IOwinSelfHost
 20    {
 4721        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
 22        private readonly IWireMockMiddlewareOptions _options;
 23        private readonly string[] _urls;
 24        private readonly IWireMockLogger _logger;
 25        private Exception _runningException;
 26
 27        private IWebHost _host;
 28
 9629        public bool IsStarted { get; private set; }
 30
 9431        public List<string> Urls { get; } = new List<string>();
 32
 14133        public List<int> Ports { get; } = new List<int>();
 34
 035        public Exception RunningException => _runningException;
 36
 4737        public AspNetCoreSelfHost([NotNull] IWireMockMiddlewareOptions options, [NotNull] params string[] uriPrefixes)
 4738        {
 4739            Check.NotNull(options, nameof(options));
 4740            Check.NotNullOrEmpty(uriPrefixes, nameof(uriPrefixes));
 41
 4742            _logger = options.Logger ?? new WireMockConsoleLogger();
 43
 23544            foreach (string uriPrefix in uriPrefixes)
 4745            {
 4746                Urls.Add(uriPrefix);
 47
 4748                PortUtils.TryExtract(uriPrefix, out string protocol, out string host, out int port);
 4749                Ports.Add(port);
 4750            }
 51
 4752            _options = options;
 4753            _urls = uriPrefixes;
 4754        }
 55
 56        public Task StartAsync()
 4757        {
 4758            _host = new WebHostBuilder()
 4759                .ConfigureServices(services =>
 9460                {
 9461                    services.AddSingleton<IWireMockMiddlewareOptions>(_options);
 9462                    services.AddSingleton<IMappingMatcher, MappingMatcher>();
 9463                    services.AddSingleton<IOwinRequestMapper, OwinRequestMapper>();
 9464                    services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>();
 9465                })
 4766                .Configure(appBuilder =>
 9467                {
 9468                    appBuilder.UseMiddleware<GlobalExceptionMiddleware>();
 4769
 9470                    _options.PreWireMockMiddlewareInit?.Invoke(appBuilder);
 4771
 9472                    appBuilder.UseMiddleware<WireMockMiddleware>();
 4773
 9474                    _options.PostWireMockMiddlewareInit?.Invoke(appBuilder);
 9475                })
 4776                .UseKestrel(options =>
 9477                {
 4778#if NETSTANDARD1_3
 4779                    if (_urls.Any(u => u.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
 4780                    {
 4781                        options.UseHttps(PublicCertificateHelper.GetX509Certificate2());
 4782                    }
 4783#else
 4784                    // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?tabs=aspnetcore2x
 32985                    foreach (string url in _urls.Where(u => u.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
 9486                    {
 9487                        PortUtils.TryExtract(url, out string protocol, out string host, out int port);
 9488                        options.Listen(System.Net.IPAddress.Any, port);
 9489                    }
 4790
 23591                    foreach (string url in _urls.Where(u => u.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
 4792                    {
 4793                        PortUtils.TryExtract(url, out string protocol, out string host, out int port);
 4794                        options.Listen(System.Net.IPAddress.Any, port, listenOptions =>
 4795                        {
 4796                            listenOptions.UseHttps(PublicCertificateHelper.GetX509Certificate2());
 4797                        });
 4798                    }
 4799#endif
 94100                })
 47101#if NETSTANDARD1_3
 47102                .UseUrls(_urls)
 47103#endif
 47104                .Build();
 105
 47106            return RunHost(_cts.Token);
 47107        }
 108
 109        private Task RunHost(CancellationToken token)
 47110        {
 111            try
 47112            {
 47113                var appLifetime = (IApplicationLifetime)_host.Services.GetService(typeof(IApplicationLifetime));
 47114                appLifetime.ApplicationStarted.Register(() =>
 94115                {
 94116                    IsStarted = true;
 94117                });
 118
 119#if NETSTANDARD1_3
 120                _logger.Info("WireMock.Net server using netstandard1.3");
 121#elif NETSTANDARD2_0
 47122                _logger.Info("WireMock.Net server using netstandard2.0");
 123#elif NET46
 124                _logger.Info("WireMock.Net server using .net 4.6.1 or higher");
 125#endif
 126#if NETSTANDARD1_3
 127                return Task.Run(() =>
 128                {
 129                    _host.Run(token);
 130                });
 131#else
 47132                return _host.RunAsync(token);
 133#endif
 134            }
 0135            catch (Exception e)
 0136            {
 0137                _runningException = e;
 0138                _logger.Error(e.ToString());
 139
 0140                IsStarted = false;
 141
 0142                return Task.CompletedTask;
 143            }
 47144        }
 145
 146        public Task StopAsync()
 2147        {
 2148            _cts.Cancel();
 149
 2150            IsStarted = false;
 151#if NETSTANDARD1_3
 152            return Task.FromResult(true);
 153#else
 2154            return _host.StopAsync();
 155#endif
 2156        }
 157    }
 158}
 159#endif