Summary

Class:WireMock.ResponseBuilders.Response
Assembly:WireMock.Net
File(s):C:\Users\StefHeyenrath\Documents\GitHub\WireMock.Net\src\WireMock.Net\ResponseBuilders\Response.cs
Covered lines:161
Uncovered lines:31
Coverable lines:192
Total lines:414
Line coverage:83.8%
Branch coverage:84.7%

Metrics

MethodCyclomatic complexity NPath complexity Sequence coverage Branch coverage
Create(...)0011
Create(...)0010
WithStatusCode(...)0010
WithStatusCode(...)0000
WithSuccess()0010
WithNotFound()0000
WithHeader(...)0010
WithHeaders(...)0011
WithHeaders(...)0011
WithHeaders(...)0010
WithBody(...)0010
WithBody(...)0010.75
WithBodyFromFile(...)000.7060.5
WithBody(...)0011
WithBodyAsJson(...)0010
WithBodyAsJson(...)0010
WithBodyFromBase64(...)0011
WithTransformer()0010
WithDelay(...)0011
WithDelay(...)0000
WithProxy(...)0000
WithProxy(...)0000
WithCallback(...)0010
WithCallbackInternal(...)0010
.ctor(...)0010
ProvideResponseAsync()000.8280.75

File(s)

C:\Users\StefHeyenrath\Documents\GitHub\WireMock.Net\src\WireMock.Net\ResponseBuilders\Response.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.Linq;
 5using System.Net;
 6using System.Net.Http;
 7using System.Text;
 8using System.Threading.Tasks;
 9using JetBrains.Annotations;
 10using Newtonsoft.Json;
 11using WireMock.Http;
 12using WireMock.Settings;
 13using WireMock.Transformers;
 14using WireMock.Util;
 15using WireMock.Validation;
 16
 17namespace WireMock.ResponseBuilders
 18{
 19    /// <summary>
 20    /// The Response.
 21    /// </summary>
 22    public class Response : IResponseBuilder
 23    {
 24        private HttpClient _httpClientForProxy;
 25
 26        /// <summary>
 27        /// The delay
 28        /// </summary>
 8029        public TimeSpan? Delay { get; private set; }
 30
 31        /// <summary>
 32        /// Gets a value indicating whether [use transformer].
 33        /// </summary>
 10834        public bool UseTransformer { get; private set; }
 35
 36        /// <summary>
 37        /// The Proxy URL to use.
 38        /// </summary>
 7639        public string ProxyUrl { get; private set; }
 40
 41        /// <summary>
 42        /// The client X509Certificate2 Thumbprint or SubjectName to use.
 43        /// </summary>
 044        public string ClientX509Certificate2ThumbprintOrSubjectName { get; private set; }
 45
 46        /// <summary>
 47        /// Gets the response message.
 48        /// </summary>
 55049        public ResponseMessage ResponseMessage { get; }
 50
 51        /// <summary>
 52        /// A delegate to execute to generate the response.
 53        /// </summary>
 8054        public Func<RequestMessage, ResponseMessage> Callback { get; private set; }
 55
 56        /// <summary>
 57        /// Defines if the method WithCallback(...) is used.
 58        /// </summary>
 459        public bool WithCallbackUsed { get; private set; }
 60
 61        /// <summary>
 62        /// Creates this instance.
 63        /// </summary>
 64        /// <param name="responseMessage">ResponseMessage</param>
 65        /// <returns>A <see cref="IResponseBuilder"/>.</returns>
 66        [PublicAPI]
 67        public static IResponseBuilder Create([CanBeNull] ResponseMessage responseMessage = null)
 8768        {
 8769            var message = responseMessage ?? new ResponseMessage { StatusCode = (int)HttpStatusCode.OK };
 8770            return new Response(message);
 8771        }
 72
 73        /// <summary>
 74        /// Creates this instance with the specified function.
 75        /// </summary>
 76        /// <param name="func">The callback function.</param>
 77        /// <returns>A <see cref="IResponseBuilder"/>.</returns>
 78        [PublicAPI]
 79        public static IResponseBuilder Create([NotNull] Func<ResponseMessage> func)
 180        {
 181            Check.NotNull(func, nameof(func));
 82
 183            return new Response(func());
 184        }
 85
 86        /// <summary>
 87        /// Initializes a new instance of the <see cref="Response"/> class.
 88        /// </summary>
 89        /// <param name="responseMessage">
 90        /// The response.
 91        /// </param>
 8892        private Response(ResponseMessage responseMessage)
 8893        {
 8894            ResponseMessage = responseMessage;
 8895        }
 96
 97        /// <summary>
 98        /// The with status code.
 99        /// </summary>
 100        /// <param name="code">The code.</param>
 101        /// <returns>A <see cref="IResponseBuilder"/>.</returns>\
 102        [PublicAPI]
 103        public IResponseBuilder WithStatusCode(int code)
 22104        {
 22105            ResponseMessage.StatusCode = code;
 22106            return this;
 22107        }
 108
 109        /// <summary>
 110        /// The with status code.
 111        /// </summary>
 112        /// <param name="code">The code.</param>
 113        /// <returns>A <see cref="IResponseBuilder"/>.</returns>
 114        [PublicAPI]
 115        public IResponseBuilder WithStatusCode(HttpStatusCode code)
 0116        {
 0117            return WithStatusCode((int)code);
 0118        }
 119
 120        /// <summary>
 121        /// The with Success status code (200).
 122        /// </summary>
 123        /// <returns>A <see cref="IResponseBuilder"/>.</returns>
 124        [PublicAPI]
 125        public IResponseBuilder WithSuccess()
 1126        {
 1127            return WithStatusCode((int)HttpStatusCode.OK);
 1128        }
 129
 130        /// <summary>
 131        /// The with NotFound status code (404).
 132        /// </summary>
 133        /// <returns>The <see cref="IResponseBuilder"/>.</returns>
 134        [PublicAPI]
 135        public IResponseBuilder WithNotFound()
 0136        {
 0137            return WithStatusCode((int)HttpStatusCode.NotFound);
 0138        }
 139
 140        /// <inheritdoc cref="IHeadersResponseBuilder.WithHeader(string, string[])"/>
 141        public IResponseBuilder WithHeader(string name, params string[] values)
 102142        {
 102143            Check.NotNull(name, nameof(name));
 144
 102145            ResponseMessage.AddHeader(name, values);
 102146            return this;
 102147        }
 148
 149        /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string})"/>
 150        public IResponseBuilder WithHeaders(IDictionary<string, string> headers)
 1151        {
 1152            Check.NotNull(headers, nameof(headers));
 153
 3154            ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(head
 1155            return this;
 1156        }
 157
 158        /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string[]})"/>
 159        public IResponseBuilder WithHeaders(IDictionary<string, string[]> headers)
 1160        {
 1161            Check.NotNull(headers, nameof(headers));
 162
 3163            ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(head
 1164            return this;
 1165        }
 166
 167        /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, WireMockList{string}})"/>
 168        public IResponseBuilder WithHeaders(IDictionary<string, WireMockList<string>> headers)
 1169        {
 1170            ResponseMessage.Headers = headers;
 1171            return this;
 1172        }
 173
 174        /// <inheritdoc cref="IBodyResponseBuilder.WithBody(Func{RequestMessage, string}, string, Encoding)"/>
 175        public IResponseBuilder WithBody(Func<RequestMessage, string> bodyFactory, string destination = BodyDestinationF
 1176        {
 1177            Check.NotNull(bodyFactory, nameof(bodyFactory));
 178
 2179            return WithCallbackInternal(false, req => new ResponseMessage
 2180            {
 2181                Body = bodyFactory(req),
 2182                BodyDestination = destination,
 2183                BodyEncoding = encoding ?? Encoding.UTF8
 2184            });
 1185        }
 186
 187        /// <inheritdoc cref="IBodyResponseBuilder.WithBody(byte[], string, Encoding)"/>
 188        public IResponseBuilder WithBody(byte[] body, string destination = BodyDestinationFormat.SameAsSource, Encoding 
 2189        {
 2190            Check.NotNull(body, nameof(body));
 191
 2192            ResponseMessage.BodyDestination = destination;
 193
 2194            switch (destination)
 195            {
 196                case BodyDestinationFormat.String:
 1197                    var enc = encoding ?? Encoding.UTF8;
 1198                    ResponseMessage.BodyAsBytes = null;
 1199                    ResponseMessage.Body = enc.GetString(body);
 1200                    ResponseMessage.BodyEncoding = enc;
 1201                    break;
 202
 203                default:
 1204                    ResponseMessage.BodyAsBytes = body;
 1205                    ResponseMessage.BodyEncoding = null;
 1206                    break;
 207            }
 208
 2209            return this;
 2210        }
 211
 212        /// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromFile"/>
 213        public IResponseBuilder WithBodyFromFile(string filename, bool cache = true)
 3214        {
 3215            Check.NotNull(filename, nameof(filename));
 216
 3217            ResponseMessage.BodyEncoding = null;
 3218            ResponseMessage.BodyAsFileIsCached = cache;
 219
 3220            if (cache)
 3221            {
 3222                ResponseMessage.Body = null;
 3223                ResponseMessage.BodyAsBytes = File.ReadAllBytes(filename);
 3224                ResponseMessage.BodyAsFile = null;
 3225            }
 226            else
 0227            {
 0228                ResponseMessage.Body = null;
 0229                ResponseMessage.BodyAsBytes = null;
 0230                ResponseMessage.BodyAsFile = filename;
 0231            }
 232
 3233            return this;
 3234        }
 235
 236        /// <inheritdoc cref="IBodyResponseBuilder.WithBody(string, string, Encoding)"/>
 237        public IResponseBuilder WithBody(string body, string destination = BodyDestinationFormat.SameAsSource, Encoding 
 47238        {
 47239            Check.NotNull(body, nameof(body));
 240
 47241            encoding = encoding ?? Encoding.UTF8;
 242
 47243            ResponseMessage.BodyDestination = destination;
 47244            ResponseMessage.BodyEncoding = encoding;
 245
 47246            switch (destination)
 247            {
 248                case BodyDestinationFormat.Bytes:
 1249                    ResponseMessage.Body = null;
 1250                    ResponseMessage.BodyAsJson = null;
 1251                    ResponseMessage.BodyAsBytes = encoding.GetBytes(body);
 1252                    break;
 253
 254                case BodyDestinationFormat.Json:
 1255                    ResponseMessage.Body = null;
 1256                    ResponseMessage.BodyAsJson = JsonConvert.DeserializeObject(body);
 1257                    ResponseMessage.BodyAsBytes = null;
 1258                    break;
 259
 260                default:
 45261                    ResponseMessage.Body = body;
 45262                    ResponseMessage.BodyAsJson = null;
 45263                    ResponseMessage.BodyAsBytes = null;
 45264                    break;
 265            }
 266
 47267            return this;
 47268        }
 269
 270        /// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson(object, Encoding, bool?)"/>
 271        public IResponseBuilder WithBodyAsJson(object body, Encoding encoding = null, bool? indented = null)
 16272        {
 16273            Check.NotNull(body, nameof(body));
 274
 16275            ResponseMessage.BodyDestination = null;
 16276            ResponseMessage.BodyAsJson = body;
 16277            ResponseMessage.BodyEncoding = encoding;
 16278            ResponseMessage.BodyAsJsonIndented = indented;
 279
 16280            return this;
 16281        }
 282
 283        /// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson(object, bool)"/>
 284        public IResponseBuilder WithBodyAsJson(object body, bool indented)
 1285        {
 1286            return WithBodyAsJson(body, null, indented);
 1287        }
 288
 289        /// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromBase64"/>
 290        public IResponseBuilder WithBodyFromBase64(string bodyAsbase64, Encoding encoding = null)
 1291        {
 1292            Check.NotNull(bodyAsbase64, nameof(bodyAsbase64));
 293
 1294            encoding = encoding ?? Encoding.UTF8;
 295
 1296            ResponseMessage.BodyDestination = null;
 1297            ResponseMessage.Body = encoding.GetString(Convert.FromBase64String(bodyAsbase64));
 1298            ResponseMessage.BodyEncoding = encoding;
 299
 1300            return this;
 1301        }
 302
 303        /// <inheritdoc cref="ITransformResponseBuilder.WithTransformer"/>
 304        public IResponseBuilder WithTransformer()
 32305        {
 32306            UseTransformer = true;
 32307            return this;
 32308        }
 309
 310        /// <inheritdoc cref="IDelayResponseBuilder.WithDelay(TimeSpan)"/>
 311        public IResponseBuilder WithDelay(TimeSpan delay)
 1312        {
 2313            Check.Condition(delay, d => d > TimeSpan.Zero, nameof(delay));
 314
 1315            Delay = delay;
 1316            return this;
 1317        }
 318
 319        /// <inheritdoc cref="IDelayResponseBuilder.WithDelay(int)"/>
 320        public IResponseBuilder WithDelay(int milliseconds)
 0321        {
 0322            return WithDelay(TimeSpan.FromMilliseconds(milliseconds));
 0323        }
 324
 325        /// <inheritdoc cref="IProxyResponseBuilder.WithProxy(string, string)"/>
 326        public IResponseBuilder WithProxy(string proxyUrl, string clientX509Certificate2ThumbprintOrSubjectName = null)
 0327        {
 0328            Check.NotNullOrEmpty(proxyUrl, nameof(proxyUrl));
 329
 0330            ProxyUrl = proxyUrl;
 0331            ClientX509Certificate2ThumbprintOrSubjectName = clientX509Certificate2ThumbprintOrSubjectName;
 0332            _httpClientForProxy = HttpClientHelper.CreateHttpClient(clientX509Certificate2ThumbprintOrSubjectName);
 0333            return this;
 0334        }
 335
 336        /// <inheritdoc cref="IProxyResponseBuilder.WithProxy(IProxyAndRecordSettings)"/>
 337        public IResponseBuilder WithProxy(IProxyAndRecordSettings settings)
 0338        {
 0339            Check.NotNull(settings, nameof(settings));
 340
 0341            return WithProxy(settings.Url, settings.ClientX509Certificate2ThumbprintOrSubjectName);
 0342        }
 343
 344        /// <inheritdoc cref="ICallbackResponseBuilder.WithCallback"/>
 345        public IResponseBuilder WithCallback(Func<RequestMessage, ResponseMessage> callbackHandler)
 1346        {
 1347            Check.NotNull(callbackHandler, nameof(callbackHandler));
 348
 1349            return WithCallbackInternal(true, callbackHandler);
 1350        }
 351
 352        /// <inheritdoc cref="ICallbackResponseBuilder.WithCallback"/>
 353        private IResponseBuilder WithCallbackInternal(bool withCallbackUsed, Func<RequestMessage, ResponseMessage> callb
 2354        {
 2355            Check.NotNull(callbackHandler, nameof(callbackHandler));
 356
 2357            WithCallbackUsed = withCallbackUsed;
 2358            Callback = callbackHandler;
 359
 2360            return this;
 2361        }
 362
 363        /// <summary>
 364        /// The provide response.
 365        /// </summary>
 366        /// <param name="requestMessage">The request.</param>
 367        /// <returns>The <see cref="ResponseMessage"/>.</returns>
 368        public async Task<ResponseMessage> ProvideResponseAsync(RequestMessage requestMessage)
 76369        {
 76370            Check.NotNull(requestMessage, nameof(requestMessage));
 371
 76372            if (Delay != null)
 1373            {
 1374                await Task.Delay(Delay.Value);
 1375            }
 376
 76377            if (Callback != null)
 2378            {
 2379                var callbackResponseMessage = Callback(requestMessage);
 380
 2381                if (!WithCallbackUsed)
 1382                {
 383                    // Copy StatusCode from ResponseMessage
 1384                    callbackResponseMessage.StatusCode = ResponseMessage.StatusCode;
 385
 386                    // Copy Headers from ResponseMessage (if defined)
 1387                    if (ResponseMessage.Headers != null)
 1388                    {
 1389                        callbackResponseMessage.Headers = ResponseMessage.Headers;
 1390                    }
 1391                }
 392
 2393                return callbackResponseMessage;
 394            }
 395
 74396            if (ProxyUrl != null && _httpClientForProxy != null)
 0397            {
 0398                var requestUri = new Uri(requestMessage.Url);
 0399                var proxyUri = new Uri(ProxyUrl);
 0400                var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery);
 401
 0402                return await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequestPathAndQ
 403            }
 404
 74405            if (UseTransformer)
 32406            {
 32407                return ResponseMessageTransformer.Transform(requestMessage, ResponseMessage);
 408            }
 409
 410            // Just return normal defined ResponseMessage
 42411            return ResponseMessage;
 71412        }
 413    }
 414}