Summary

Class:WireMock.ResponseBuilders.Response
Assembly:WireMock.Net
File(s):C:\Users\azureuser\Documents\Github\WireMock.Net\src\WireMock.Net\ResponseBuilders\Response.cs
Covered lines:152
Uncovered lines:31
Coverable lines:183
Total lines:397
Line coverage:83%
Branch coverage:84%

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
.ctor(...)0010
ProvideResponseAsync()000.8080.722

File(s)

C:\Users\azureuser\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>
 9429        public TimeSpan? Delay { get; private set; }
 30
 31        /// <summary>
 32        /// Gets a value indicating whether [use transformer].
 33        /// </summary>
 12134        public bool UseTransformer { get; private set; }
 35
 36        /// <summary>
 37        /// The Proxy URL to use.
 38        /// </summary>
 8939        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>
 62949        public ResponseMessage ResponseMessage { get; }
 50
 51        /// <summary>
 52        /// A delegate to execute to generate the response
 53        /// </summary>
 9654        public Func<RequestMessage, ResponseMessage> Callback { get; private set; }
 55
 56        /// <summary>
 57        /// Creates this instance.
 58        /// </summary>
 59        /// <param name="responseMessage">ResponseMessage</param>
 60        /// <returns>A <see cref="IResponseBuilder"/>.</returns>
 61        [PublicAPI]
 62        public static IResponseBuilder Create([CanBeNull] ResponseMessage responseMessage = null)
 10063        {
 10064            var message = responseMessage ?? new ResponseMessage { StatusCode = (int)HttpStatusCode.OK };
 10065            return new Response(message);
 10066        }
 67
 68        /// <summary>
 69        /// Creates this instance with the specified function.
 70        /// </summary>
 71        /// <param name="func">The callback function.</param>
 72        /// <returns>A <see cref="IResponseBuilder"/>.</returns>
 73        [PublicAPI]
 74        public static IResponseBuilder Create([NotNull] Func<ResponseMessage> func)
 175        {
 176            Check.NotNull(func, nameof(func));
 77
 178            return new Response(func());
 179        }
 80
 81        /// <summary>
 82        /// Initializes a new instance of the <see cref="Response"/> class.
 83        /// </summary>
 84        /// <param name="responseMessage">
 85        /// The response.
 86        /// </param>
 10187        private Response(ResponseMessage responseMessage)
 10188        {
 10189            ResponseMessage = responseMessage;
 10190        }
 91
 92        /// <summary>
 93        /// The with status code.
 94        /// </summary>
 95        /// <param name="code">The code.</param>
 96        /// <returns>A <see cref="IResponseBuilder"/>.</returns>\
 97        [PublicAPI]
 98        public IResponseBuilder WithStatusCode(int code)
 2499        {
 24100            ResponseMessage.StatusCode = code;
 24101            return this;
 24102        }
 103
 104        /// <summary>
 105        /// The with status code.
 106        /// </summary>
 107        /// <param name="code">The code.</param>
 108        /// <returns>A <see cref="IResponseBuilder"/>.</returns>
 109        [PublicAPI]
 110        public IResponseBuilder WithStatusCode(HttpStatusCode code)
 0111        {
 0112            return WithStatusCode((int)code);
 0113        }
 114
 115        /// <summary>
 116        /// The with Success status code (200).
 117        /// </summary>
 118        /// <returns>A <see cref="IResponseBuilder"/>.</returns>
 119        [PublicAPI]
 120        public IResponseBuilder WithSuccess()
 1121        {
 1122            return WithStatusCode((int)HttpStatusCode.OK);
 1123        }
 124
 125        /// <summary>
 126        /// The with NotFound status code (404).
 127        /// </summary>
 128        /// <returns>The <see cref="IResponseBuilder"/>.</returns>
 129        [PublicAPI]
 130        public IResponseBuilder WithNotFound()
 0131        {
 0132            return WithStatusCode((int)HttpStatusCode.NotFound);
 0133        }
 134
 135        /// <inheritdoc cref="IHeadersResponseBuilder.WithHeader(string, string[])"/>
 136        public IResponseBuilder WithHeader(string name, params string[] values)
 103137        {
 103138            Check.NotNull(name, nameof(name));
 139
 103140            ResponseMessage.AddHeader(name, values);
 103141            return this;
 103142        }
 143
 144        /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string})"/>
 145        public IResponseBuilder WithHeaders(IDictionary<string, string> headers)
 1146        {
 1147            Check.NotNull(headers, nameof(headers));
 148
 3149            ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(head
 1150            return this;
 1151        }
 152
 153        /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, string[]})"/>
 154        public IResponseBuilder WithHeaders(IDictionary<string, string[]> headers)
 1155        {
 1156            Check.NotNull(headers, nameof(headers));
 157
 3158            ResponseMessage.Headers = headers.ToDictionary(header => header.Key, header => new WireMockList<string>(head
 1159            return this;
 1160        }
 161
 162        /// <inheritdoc cref="IHeadersResponseBuilder.WithHeaders(IDictionary{string, WireMockList{string}})"/>
 163        public IResponseBuilder WithHeaders(IDictionary<string, WireMockList<string>> headers)
 1164        {
 1165            ResponseMessage.Headers = headers;
 1166            return this;
 1167        }
 168
 169        /// <inheritdoc cref="IBodyResponseBuilder.WithBody(Func{RequestMessage, string}, string, Encoding)"/>
 170        public IResponseBuilder WithBody(Func<RequestMessage, string> bodyFactory, string destination = BodyDestinationF
 2171        {
 2172            Check.NotNull(bodyFactory, nameof(bodyFactory));
 173
 4174            return WithCallback(req => new ResponseMessage
 4175            {
 4176                Body = bodyFactory(req),
 4177                BodyDestination = destination,
 4178                BodyEncoding = encoding ?? Encoding.UTF8
 4179            });
 2180        }
 181
 182        /// <inheritdoc cref="IBodyResponseBuilder.WithBody(byte[], string, Encoding)"/>
 183        public IResponseBuilder WithBody(byte[] body, string destination = BodyDestinationFormat.SameAsSource, Encoding 
 3184        {
 3185            Check.NotNull(body, nameof(body));
 186
 3187            ResponseMessage.BodyDestination = destination;
 188
 3189            switch (destination)
 190            {
 191                case BodyDestinationFormat.String:
 1192                    var enc = encoding ?? Encoding.UTF8;
 1193                    ResponseMessage.BodyAsBytes = null;
 1194                    ResponseMessage.Body = enc.GetString(body);
 1195                    ResponseMessage.BodyEncoding = enc;
 1196                    break;
 197
 198                default:
 2199                    ResponseMessage.BodyAsBytes = body;
 2200                    ResponseMessage.BodyEncoding = null;
 2201                    break;
 202            }
 203
 3204            return this;
 3205        }
 206
 207        /// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromFile"/>
 208        public IResponseBuilder WithBodyFromFile(string filename, bool cache = true)
 3209        {
 3210            Check.NotNull(filename, nameof(filename));
 211
 3212            ResponseMessage.BodyEncoding = null;
 3213            ResponseMessage.BodyAsFileIsCached = cache;
 214
 3215            if (cache)
 3216            {
 3217                ResponseMessage.Body = null;
 3218                ResponseMessage.BodyAsBytes = File.ReadAllBytes(filename);
 3219                ResponseMessage.BodyAsFile = null;
 3220            }
 221            else
 0222            {
 0223                ResponseMessage.Body = null;
 0224                ResponseMessage.BodyAsBytes = null;
 0225                ResponseMessage.BodyAsFile = filename;
 0226            }
 227
 3228            return this;
 3229        }
 230
 231        /// <inheritdoc cref="IBodyResponseBuilder.WithBody(string, string, Encoding)"/>
 232        public IResponseBuilder WithBody(string body, string destination = BodyDestinationFormat.SameAsSource, Encoding 
 57233        {
 57234            Check.NotNull(body, nameof(body));
 235
 57236            encoding = encoding ?? Encoding.UTF8;
 237
 57238            ResponseMessage.BodyDestination = destination;
 57239            ResponseMessage.BodyEncoding = encoding;
 240
 57241            switch (destination)
 242            {
 243                case BodyDestinationFormat.Bytes:
 1244                    ResponseMessage.Body = null;
 1245                    ResponseMessage.BodyAsJson = null;
 1246                    ResponseMessage.BodyAsBytes = encoding.GetBytes(body);
 1247                    break;
 248
 249                case BodyDestinationFormat.Json:
 1250                    ResponseMessage.Body = null;
 1251                    ResponseMessage.BodyAsJson = JsonConvert.DeserializeObject(body);
 1252                    ResponseMessage.BodyAsBytes = null;
 1253                    break;
 254
 255                default:
 55256                    ResponseMessage.Body = body;
 55257                    ResponseMessage.BodyAsJson = null;
 55258                    ResponseMessage.BodyAsBytes = null;
 55259                    break;
 260            }
 261
 57262            return this;
 57263        }
 264
 265        /// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson(object, Encoding, bool?)"/>
 266        public IResponseBuilder WithBodyAsJson(object body, Encoding encoding = null, bool? indented = null)
 17267        {
 17268            Check.NotNull(body, nameof(body));
 269
 17270            ResponseMessage.BodyDestination = null;
 17271            ResponseMessage.BodyAsJson = body;
 17272            ResponseMessage.BodyEncoding = encoding;
 17273            ResponseMessage.BodyAsJsonIndented = indented;
 274
 17275            return this;
 17276        }
 277
 278        /// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson(object, bool)"/>
 279        public IResponseBuilder WithBodyAsJson(object body, bool indented)
 1280        {
 1281            return WithBodyAsJson(body, null, indented);
 1282        }
 283
 284        /// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromBase64"/>
 285        public IResponseBuilder WithBodyFromBase64(string bodyAsbase64, Encoding encoding = null)
 1286        {
 1287            Check.NotNull(bodyAsbase64, nameof(bodyAsbase64));
 288
 1289            encoding = encoding ?? Encoding.UTF8;
 290
 1291            ResponseMessage.BodyDestination = null;
 1292            ResponseMessage.Body = encoding.GetString(Convert.FromBase64String(bodyAsbase64));
 1293            ResponseMessage.BodyEncoding = encoding;
 294
 1295            return this;
 1296        }
 297
 298        /// <inheritdoc cref="ITransformResponseBuilder.WithTransformer"/>
 299        public IResponseBuilder WithTransformer()
 32300        {
 32301            UseTransformer = true;
 32302            return this;
 32303        }
 304
 305        /// <inheritdoc cref="IDelayResponseBuilder.WithDelay(TimeSpan)"/>
 306        public IResponseBuilder WithDelay(TimeSpan delay)
 1307        {
 2308            Check.Condition(delay, d => d > TimeSpan.Zero, nameof(delay));
 309
 1310            Delay = delay;
 1311            return this;
 1312        }
 313
 314        /// <inheritdoc cref="IDelayResponseBuilder.WithDelay(int)"/>
 315        public IResponseBuilder WithDelay(int milliseconds)
 0316        {
 0317            return WithDelay(TimeSpan.FromMilliseconds(milliseconds));
 0318        }
 319
 320        /// <inheritdoc cref="IProxyResponseBuilder.WithProxy(string, string)"/>
 321        public IResponseBuilder WithProxy(string proxyUrl, string clientX509Certificate2ThumbprintOrSubjectName = null)
 0322        {
 0323            Check.NotNullOrEmpty(proxyUrl, nameof(proxyUrl));
 324
 0325            ProxyUrl = proxyUrl;
 0326            ClientX509Certificate2ThumbprintOrSubjectName = clientX509Certificate2ThumbprintOrSubjectName;
 0327            _httpClientForProxy = HttpClientHelper.CreateHttpClient(clientX509Certificate2ThumbprintOrSubjectName);
 0328            return this;
 0329        }
 330
 331        /// <inheritdoc cref="IProxyResponseBuilder.WithProxy(IProxyAndRecordSettings)"/>
 332        public IResponseBuilder WithProxy(IProxyAndRecordSettings settings)
 0333        {
 0334            Check.NotNull(settings, nameof(settings));
 335
 0336            return WithProxy(settings.Url, settings.ClientX509Certificate2ThumbprintOrSubjectName);
 0337        }
 338
 339        /// <inheritdoc cref="ICallbackResponseBuilder.WithCallback"/>
 340        public IResponseBuilder WithCallback(Func<RequestMessage, ResponseMessage> callbackHandler)
 3341        {
 3342            Check.NotNull(callbackHandler, nameof(callbackHandler));
 343
 3344            Callback = callbackHandler;
 345
 3346            return this;
 3347        }
 348
 349        /// <summary>
 350        /// The provide response.
 351        /// </summary>
 352        /// <param name="requestMessage">The request.</param>
 353        /// <returns>The <see cref="ResponseMessage"/>.</returns>
 354        public async Task<ResponseMessage> ProvideResponseAsync(RequestMessage requestMessage)
 90355        {
 90356            Check.NotNull(requestMessage, nameof(requestMessage));
 357
 90358            if (Delay != null)
 1359            {
 1360                await Task.Delay(Delay.Value);
 1361            }
 362
 90363            if (Callback != null)
 3364            {
 3365                var callbackResponseMessage = Callback(requestMessage);
 366
 367                // Copy StatusCode from ResponseMessage
 3368                callbackResponseMessage.StatusCode = ResponseMessage.StatusCode;
 369
 370                // Copy Headers from ResponseMessage (if defined)
 3371                if (ResponseMessage.Headers != null)
 3372                {
 3373                    callbackResponseMessage.Headers = ResponseMessage.Headers;
 3374                }
 375
 3376                return callbackResponseMessage;
 377            }
 378
 87379            if (ProxyUrl != null && _httpClientForProxy != null)
 0380            {
 0381                var requestUri = new Uri(requestMessage.Url);
 0382                var proxyUri = new Uri(ProxyUrl);
 0383                var proxyUriWithRequestPathAndQuery = new Uri(proxyUri, requestUri.PathAndQuery);
 384
 0385                return await HttpClientHelper.SendAsync(_httpClientForProxy, requestMessage, proxyUriWithRequestPathAndQ
 386            }
 387
 87388            if (UseTransformer)
 32389            {
 32390                return ResponseMessageTransformer.Transform(requestMessage, ResponseMessage);
 391            }
 392
 393            // Just return normal defined ResponseMessage
 55394            return ResponseMessage;
 85395        }
 396    }
 397}