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:81
Uncovered lines:5
Coverable lines:86
Total lines:148
Line coverage:94.1%
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 WireMock.HttpsCertificate;
 11using WireMock.Logging;
 12using WireMock.Util;
 13using WireMock.Validation;
 14
 15namespace WireMock.Owin
 16{
 17    internal class AspNetCoreSelfHost : IOwinSelfHost
 18    {
 4919        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
 20        private readonly WireMockMiddlewareOptions _options;
 21        private readonly string[] _urls;
 22        private readonly IWireMockLogger _logger;
 23        private Exception _runningException;
 24
 25        private IWebHost _host;
 26
 43727        public bool IsStarted { get; private set; }
 28
 9829        public List<string> Urls { get; } = new List<string>();
 30
 14731        public List<int> Ports { get; } = new List<int>();
 32
 33333        public Exception RunningException => _runningException;
 34
 4935        public AspNetCoreSelfHost([NotNull] WireMockMiddlewareOptions options, [NotNull] params string[] uriPrefixes)
 4936        {
 4937            Check.NotNull(options, nameof(options));
 4938            Check.NotNullOrEmpty(uriPrefixes, nameof(uriPrefixes));
 39
 4940            _logger = options.Logger ?? new WireMockConsoleLogger();
 41
 24542            foreach (string uriPrefix in uriPrefixes)
 4943            {
 4944                Urls.Add(uriPrefix);
 45
 4946                PortUtils.TryExtractProtocolAndPort(uriPrefix, out string host, out int port);
 4947                Ports.Add(port);
 4948            }
 49
 4950            _options = options;
 4951            _urls = uriPrefixes;
 4952        }
 53
 54        public Task StartAsync()
 4955        {
 4956            _host = new WebHostBuilder()
 4957                .Configure(appBuilder =>
 9858                {
 9859                    appBuilder.UseMiddleware<GlobalExceptionMiddleware>(_options);
 4960
 9861                    _options.PreWireMockMiddlewareInit?.Invoke(appBuilder);
 4962
 9863                    appBuilder.UseMiddleware<WireMockMiddleware>(_options);
 4964
 9865                    _options.PostWireMockMiddlewareInit?.Invoke(appBuilder);
 9866                })
 4967                .UseKestrel(options =>
 9868                {
 4969#if NETSTANDARD1_3
 4970                    if (_urls.Any(u => u.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
 4971                    {
 4972                        options.UseHttps(PublicCertificateHelper.GetX509Certificate2());
 4973                    }
 4974#else
 4975                    // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?tabs=aspnetcore2x
 34376                    foreach (string url in _urls.Where(u => u.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
 9877                    {
 9878                        PortUtils.TryExtractProtocolAndPort(url, out string host, out int port);
 9879                        options.Listen(System.Net.IPAddress.Any, port);
 9880                    }
 4981
 24582                    foreach (string url in _urls.Where(u => u.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
 4983                    {
 4984                        PortUtils.TryExtractProtocolAndPort(url, out string host, out int port);
 4985                        options.Listen(System.Net.IPAddress.Any, port, listenOptions =>
 4986                        {
 4987                            listenOptions.UseHttps(PublicCertificateHelper.GetX509Certificate2());
 4988                        });
 4989                    }
 4990#endif
 9891                })
 4992#if NETSTANDARD1_3
 4993                .UseUrls(_urls)
 4994#endif
 4995                .Build();
 96
 4997            return Task.Run(() =>
 9898            {
 9899                StartServers();
 52100            }, _cts.Token);
 49101        }
 102
 103        private void StartServers()
 49104        {
 105            try
 49106            {
 49107                var appLifetime = (IApplicationLifetime) _host.Services.GetService(typeof(IApplicationLifetime));
 98108                appLifetime.ApplicationStarted.Register(() => IsStarted = true);
 109
 110#if NETSTANDARD1_3
 111                _logger.Info("WireMock.Net server using netstandard1.3");
 112#elif NETSTANDARD2_0
 49113                _logger.Info("WireMock.Net server using netstandard2.0");
 114#elif NET46
 115                _logger.Info("WireMock.Net server using .net 4.6.1 or higher");
 116#endif
 117
 118#if NETSTANDARD1_3
 119                _host.Run(_cts.Token);
 120#else
 49121                _host.RunAsync(_cts.Token).Wait();
 122#endif
 3123            }
 0124            catch (Exception e)
 0125            {
 0126                _runningException = e;
 0127                _logger.Error(e.ToString());
 0128            }
 129            finally
 3130            {
 3131                IsStarted = false;
 3132            }
 3133        }
 134
 135        public Task StopAsync()
 3136        {
 3137            _cts.Cancel();
 138
 3139            IsStarted = false;
 140#if NETSTANDARD1_3
 141            return Task.FromResult(true);
 142#else
 3143            return _host.StopAsync();
 144#endif
 3145        }
 146    }
 147}
 148#endif