Summary

Class:WireMock.Owin.AspNetCoreSelfHost
Assembly:WireMock.Net
File(s):C:\Users\azureuser\Documents\Github\WireMock.Net\src\WireMock.Net\Owin\AspNetCoreSelfHost.cs
Covered lines:88
Uncovered lines:5
Coverable lines:93
Total lines:157
Line coverage:94.6%
Branch coverage:75%

Metrics

MethodCyclomatic complexity NPath complexity Sequence coverage Branch coverage
StartAsync()0010
StartServers()000.6880
StopAsync()0010
.ctor(...)0010.75

File(s)

C:\Users\azureuser\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
 53129        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
 43335        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 Task.Run(() =>
 94107            {
 94108                StartServers();
 49109            }, _cts.Token);
 47110        }
 111
 112        private void StartServers()
 47113        {
 114            try
 47115            {
 47116                var appLifetime = (IApplicationLifetime)_host.Services.GetService(typeof(IApplicationLifetime));
 94117                appLifetime.ApplicationStarted.Register(() => IsStarted = true);
 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
 127#if NETSTANDARD1_3
 128                _host.Run(_cts.Token);
 129#else
 47130                _host.RunAsync(_cts.Token).Wait();
 131#endif
 2132            }
 0133            catch (Exception e)
 0134            {
 0135                _runningException = e;
 0136                _logger.Error(e.ToString());
 0137            }
 138            finally
 2139            {
 2140                IsStarted = false;
 2141            }
 2142        }
 143
 144        public Task StopAsync()
 2145        {
 2146            _cts.Cancel();
 147
 2148            IsStarted = false;
 149#if NETSTANDARD1_3
 150            return Task.FromResult(true);
 151#else
 2152            return _host.StopAsync();
 153#endif
 2154        }
 155    }
 156}
 157#endif