public void OrdinalInsensitiveKeyComparison() { var headerDict = new HeaderDictionary(); headerDict.Add("Name", new string[1] { "Value" }); Assert.Throws<ArgumentException>(() => headerDict.Add("nAmE", new string[1] { "whatever" })); }
public void HeaderDictionaryWithNoKeysCanIncludeAKey() { var subject = new HeaderDictionary(); subject.Include("k", "v"); Assert.That(subject["k"], Is.EquivalentTo(new[]{"v"})); }
public void HeaderDictionaryWithExistingKeyCanResetAKeysValue() { var subject = new HeaderDictionary(); subject.Include("k", "v1"); subject.Include("k", "v2"); subject.Set("k", "v0"); Assert.That(subject["k"], Is.EquivalentTo(new[]{"v0"})); }
public ResponseFeature() { Headers = new HeaderDictionary(); Body = new MemoryStream(); // 200 is the default status code all the way down to the host, so we set it // here to be consistent with the rest of the hosts when writing tests. StatusCode = 200; }
private static HttpResponse GetResponseWithHeader(string headerName, string headerValue) { var headers = new HeaderDictionary(); if (headerValue != null) { headers.Add(headerName, headerValue); } return CreateResponse(headers); }
public void GetAddresses_FiveCommasOnly_ReturnsNoEmailAddresses() { var headerDictionary = new HeaderDictionary { { "From", new HeaderValue(@",,,,,")} }; var mailAddresses = headerDictionary.GetMailAddresses("From"); Assert.AreEqual(0, mailAddresses.Length); }
public void GetAddresses_EmptyHeader_ReturnsNoEmailAddresses() { var headerDictionary = new HeaderDictionary { { "From", new HeaderValue(@"")} }; var mailAddresses = headerDictionary.GetMailAddresses("From"); Assert.Equal(0, mailAddresses.Length); }
public void GetAddresses_OnlyOneSemicolon_ReturnsNoEmailAddresses() { var headerDictionary = new HeaderDictionary { { "From", new HeaderValue(@";")} }; var mailAddresses = headerDictionary.GetMailAddresses("From"); Assert.AreEqual(0, mailAddresses.Length); }
public void GetAddresses_Rubbish_ReturnsNoEmailAddresses() { var headerDictionary = new HeaderDictionary { { "From", new HeaderValue(@"<<<<,783459@")} }; var mailAddresses = headerDictionary.GetMailAddresses("From"); Assert.Equal(0, mailAddresses.Length); }
public RequestFeature() { Body = Stream.Null; Headers = new HeaderDictionary(); Method = "GET"; Path = ""; PathBase = ""; Protocol = "HTTP/1.1"; QueryString = ""; Scheme = "http"; }
public void GetAddresses_PipelineInDisplayName_ParsesCorrectAddressAndDisplayName() { var headerDictionary = new HeaderDictionary { { "From", new HeaderValue(@"Test | Testenstein <*****@*****.**>")} }; var mailAddresses = headerDictionary.GetMailAddresses("From"); Assert.AreEqual(1, mailAddresses.Length); var mailAddress = mailAddresses.First(); Assert.AreEqual("*****@*****.**", mailAddress.Address); Assert.AreEqual("Test | Testenstein", mailAddress.DisplayName); }
public void HeadersValuesAreArrayCopies() { var headerDict = new HeaderDictionary(); headerDict.Add("Name", new string[1] { "Value" }); string[] copy = headerDict["Name"]; Assert.AreEqual("Value", copy [0]); // Change and make sure it is still the same in the original! copy [0] = "Something different"; string[] copy2 = headerDict["Name"]; Assert.AreEqual("Value", copy2 [0]); }
private IHeaderDictionary PrepareResponseHeaders(Guid id, HttpWebResponse newResponse, string fileName) { IHeaderDictionary headers = new HeaderDictionary(); if (string.IsNullOrWhiteSpace(fileName)) { //try get file name from Content Disposition header: var contentDisposition = newResponse.Headers[HeaderNames.ContentDisposition]; if (contentDisposition != null) { fileName = downloadSpkService.GetFileNameFromContentDisposition(contentDisposition); } fileName = fileName ?? $"{id}.spk"; } headers.Add(HeaderNames.ContentDisposition, $"attachment; filename=\"{fileName}\""); var lengthStr = newResponse.Headers[HeaderNames.ContentLength]; if (Int64.TryParse(lengthStr, out var length) && length > 0) { headers.Add(HeaderNames.ContentLength, length.ToString()); } return(headers); }
public void Success() { var mr = new MockRepository(MockBehavior.Strict); var ab = mr.Create <IApplicationBuilder>(); var httpResponse = mr.Create <HttpResponse>(); var hd = new HeaderDictionary() { { "Content-Security-Policy", "default-src: self;" } }; httpResponse.Setup(a => a.Headers).Returns(hd); var httpContext = mr.Create <HttpContext>(); httpContext.Setup(s => s.Response).Returns(httpResponse.Object); ab.Setup(a => a.Use(It.IsAny <Func <RequestDelegate, RequestDelegate> >())) .Returns <Func <RequestDelegate, RequestDelegate> >(a => { a(_ => Task.CompletedTask)(httpContext.Object); return(ab.Object); }); ab.Object.UseXContentSecurityPolicy(); mr.VerifyAll(); hd.Count.Should().Be(2); }
private HttpRequest createRequest(string correlationId, string requestIdHeader, string requestIdTrace) { var context = new Mock <HttpContext>(); var request = new Mock <HttpRequest>(); var headers = new HeaderDictionary { { CorrelationHeaderInfo.CorrelationIdHeaderName, new[] { correlationId } } }; if (requestIdHeader != null) { headers.Add(CorrelationHeaderInfo.RequestIdHeaderName, requestIdHeader); } request.SetupGet(r => r.Headers).Returns(headers); if (requestIdTrace != null) { context.SetupGet(r => r.TraceIdentifier).Returns(requestIdTrace); } request.SetupGet(r => r.HttpContext).Returns(context.Object); return(request.Object); }
public void WriteTrailers_MultiValueTrailer_WrittenToOutput() { // Arrange var trailers = new HeaderDictionary(); trailers.Add("one", new StringValues(new[] { "two", "three" })); var output = new ArrayBufferWriter <byte>(); // Act GrpcWebProtocolHelpers.WriteTrailers(trailers, output); // Assert Assert.AreEqual(27, output.WrittenSpan.Length); Assert.AreEqual(128, output.WrittenSpan[0]); Assert.AreEqual(0, output.WrittenSpan[1]); Assert.AreEqual(0, output.WrittenSpan[2]); Assert.AreEqual(0, output.WrittenSpan[3]); Assert.AreEqual(22, output.WrittenSpan[4]); var text = Encoding.ASCII.GetString(output.WrittenSpan.Slice(5)); Assert.AreEqual("one: two\r\none: three\r\n", text); }
public void TestExtractCustomMetricDataPoints() { var responseFeatureMock = new Mock <IHttpResponseFeature>(); var headerDictionary = new HeaderDictionary(); responseFeatureMock.SetupGet(m => m.Headers).Returns(headerDictionary); List <DataPoint> actualDataPoints = responseFeatureMock.Object.ExtractCustomMetricDataPoints(); Assert.Null(actualDataPoints); Assert.Empty(headerDictionary); var httpResponseMock = new Mock <HttpResponse>(); httpResponseMock.SetupGet(m => m.Headers).Returns(headerDictionary); httpResponseMock.Object.AddMetricDataPoint(BuildDataPoint()); Assert.Single(headerDictionary); actualDataPoints = responseFeatureMock.Object.ExtractCustomMetricDataPoints(); Assert.Single(actualDataPoints); Assert.Equal(BuildDataPoint().metric, actualDataPoints[0].metric); Assert.Empty(headerDictionary); }
public void ConstructorWithContextHavingIdValuesExceptIsSampled() { // Arrange var fixture = new Fixture(); var traceId = Convert.ToString(fixture.Create <long>(), 16); var spanId = Convert.ToString(fixture.Create <long>(), 16); var parentSpanId = Convert.ToString(fixture.Create <long>(), 16); var context = MockRepository.GenerateStub <IOwinContext>(); var request = MockRepository.GenerateStub <IOwinRequest>(); var headers = new HeaderDictionary(new Dictionary <string, string[]> { { TraceProvider.TraceIdHeaderName, new [] { traceId } }, { TraceProvider.SpanIdHeaderName, new [] { spanId } }, { TraceProvider.ParentSpanIdHeaderName, new [] { parentSpanId } }, }); var environment = new Dictionary <string, object>(); request.Stub(x => x.Headers).Return(headers); context.Stub(x => x.Request).Return(request); context.Stub(x => x.Environment).Return(environment); var expectedIsSampled = fixture.Create <bool>(); var sampleFilter = MockRepository.GenerateStub <IZipkinConfig>(); sampleFilter.Expect(x => x.ShouldBeSampled(context, null)).Return(expectedIsSampled); // Act var sut = new TraceProvider(sampleFilter, context); // Assert Assert.AreEqual(traceId, sut.TraceId); Assert.AreEqual(spanId, sut.SpanId); Assert.AreEqual(parentSpanId, sut.ParentSpanId); Assert.AreEqual(expectedIsSampled, sut.IsSampled); }
private async Task FeatureCollectionSetResponseFeatures(HttpContext ctx) { try { Assert.Equal(200, ctx.Response.StatusCode); ctx.Response.StatusCode = 404; Assert.Equal(404, ctx.Response.StatusCode); ctx.Response.StatusCode = 200; Assert.Null(ctx.Features.Get <IHttpResponseFeature>().ReasonPhrase); ctx.Features.Get <IHttpResponseFeature>().ReasonPhrase = "Set Response"; Assert.Equal("Set Response", ctx.Features.Get <IHttpResponseFeature>().ReasonPhrase); Assert.NotNull(ctx.Response.Headers); var headers = new HeaderDictionary(); ctx.Features.Get <IHttpResponseFeature>().Headers = headers; Assert.Same(headers, ctx.Features.Get <IHttpResponseFeature>().Headers); var originalBody = ctx.Response.Body; Assert.NotNull(originalBody); var body = new MemoryStream(); ctx.Response.Body = body; Assert.Same(body, ctx.Response.Body); ctx.Response.Body = originalBody; await ctx.Response.WriteAsync("Success"); return; } catch (Exception exception) { ctx.Response.StatusCode = 500; await ctx.Response.WriteAsync(exception.ToString()); } await ctx.Response.WriteAsync("_Failure"); }
private Mock <HttpContext> GetHttpContextMock(HeaderDictionary headers = null, Mock <HttpResponse> responseMock = null) { var requestMock = new Mock <HttpRequest>(); requestMock.Setup(x => x.Scheme).Returns("https"); requestMock.Setup(x => x.Host).Returns(new HostString("web.lvh.me")); requestMock.Setup(x => x.Path).Returns(new PathString("/test")); requestMock.Setup(x => x.PathBase).Returns(new PathString("/")); requestMock.Setup(x => x.Method).Returns("GET"); requestMock.Setup(x => x.Body).Returns(new MemoryStream()); requestMock.Setup(x => x.QueryString).Returns(new QueryString("?param1=2")); if (headers != null) { requestMock.Setup(x => x.Headers).Returns(headers); } var contextMock = new Mock <HttpContext>(); contextMock.Setup(x => x.Request).Returns(requestMock.Object); if (responseMock != null) { contextMock.Setup(x => x.Response).Returns(responseMock.Object); } return(contextMock); }
public void ShouldExtractCorrelationIdFromHttpHeader() { // Arrange const string correlationId = "myCorrelationId"; var headers = new HeaderDictionary(new Dictionary <string, StringValues> { { "X-Correlation-Id", correlationId } }); var options = Options.Create(new DataverseODataClientOptions()); var httpContextAccessor = A.Fake <IHttpContextAccessor>(); A.CallTo(() => httpContextAccessor.HttpContext.Request.Headers) .Returns(headers); var sut = new HttpHeaderCorrelationIdProvider(httpContextAccessor, options); // Act var result = sut.GetCorrelationId(); // Assert result.Should().Be(correlationId); }
public void WriteTrailers_OneTrailerMixedCase_WrittenToOutputLowerCase() { // Arrange var trailers = new HeaderDictionary(); trailers.Add("One", "Two"); var output = new ArrayBufferWriter <byte>(); // Act GrpcWebProtocolHelpers.WriteTrailers(trailers, output); // Assert Assert.AreEqual(15, output.WrittenSpan.Length); Assert.AreEqual(128, output.WrittenSpan[0]); Assert.AreEqual(0, output.WrittenSpan[1]); Assert.AreEqual(0, output.WrittenSpan[2]); Assert.AreEqual(0, output.WrittenSpan[3]); Assert.AreEqual(10, output.WrittenSpan[4]); var text = Encoding.ASCII.GetString(output.WrittenSpan.Slice(5)); Assert.AreEqual("one: Two\r\n", text); }
public void HttpObjects_JsonBody(string expectedContentType, string body, bool rcpHttpBodyOnly) { var logger = MockNullLoggerFactory.CreateLogger(); var capabilities = new Capabilities(logger); if (rcpHttpBodyOnly) { capabilities.UpdateCapabilities(new MapField <string, string> { { LanguageWorkerConstants.RpcHttpBodyOnly, rcpHttpBodyOnly.ToString() } }); } var headers = new HeaderDictionary(); headers.Add("content-type", expectedContentType); HttpRequest request = HttpTestHelpers.CreateHttpRequest("GET", "http://localhost/api/httptrigger-scenarios", headers, body); var rpcRequestObject = request.ToRpc(logger, capabilities); if (rcpHttpBodyOnly) { Assert.Equal(null, rpcRequestObject.Http.RawBody); Assert.Equal(body.ToString(), rpcRequestObject.Http.Body.String); } else { Assert.Equal(body.ToString(), rpcRequestObject.Http.RawBody.String); Assert.Equal(JsonConvert.DeserializeObject(body), JsonConvert.DeserializeObject(rpcRequestObject.Http.Body.Json)); } string contentType; rpcRequestObject.Http.Headers.TryGetValue("content-type", out contentType); Assert.Equal(expectedContentType, contentType); }
public static void CreateHttpContext(IServiceProvider resolver) { var contentType = "application/json"; var request = new Mock <HttpRequest>(); var response = new Mock <HttpResponse>(); var items = new Dictionary <object, object>(); var cookies = new Dictionary <string, string>(); var headers = new Mock <IHeaderDictionary>(); var responseHeaders = new HeaderDictionary(); request.SetupGet(x => x.Cookies).Returns(new RequestCookieCollection(cookies)); request.SetupGet(r => r.Headers).Returns(headers.Object); request.SetupGet(f => f.ContentType).Returns(contentType); response.SetupGet(r => r.Headers).Returns(responseHeaders); var httpContext = new Mock <HttpContext>(); httpContext.Setup(c => c.RequestServices).Returns(resolver); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Items).Returns(items); httpContext.Setup(c => c.Response).Returns(response.Object); HttpContext = httpContext.Object; }
public async Task HttpTrigger_Post_ByteArray(string contentType) { TestHelpers.ClearFunctionLogs("HttpTriggerByteArray"); IHeaderDictionary headers = new HeaderDictionary(); headers.Add("Content-Type", contentType); byte[] inputBytes = new byte[] { 1, 2, 3, 4, 5 }; var content = inputBytes; HttpRequest request = HttpTestHelpers.CreateHttpRequest("POST", "http://localhost/api/httptriggerbytearray", headers, content); Dictionary <string, object> arguments = new Dictionary <string, object> { { "req", request } }; await Fixture.Host.CallAsync("HttpTriggerByteArray", arguments); var result = (IActionResult)request.HttpContext.Items[ScriptConstants.AzureFunctionsHttpResponseKey]; RawScriptResult objectResult = result as RawScriptResult; Assert.NotNull(objectResult); Assert.Equal(200, objectResult.StatusCode); JObject body = (JObject)objectResult.Content; Assert.True((bool)body["isBuffer"]); Assert.Equal(5, body["length"]); var rawBody = Encoding.UTF8.GetBytes((string)body["rawBody"]); Assert.Equal(inputBytes, rawBody); }
private static RouteJsController CreateController() { // Mock Response.Headers var headers = new HeaderDictionary(); var response = new Mock <HttpResponse>(); response.Setup(x => x.Headers).Returns(headers); var httpContext = new Mock <HttpContext>(); httpContext.Setup(x => x.Response).Returns(response.Object); // Mock RouteJs var routeJs = new Mock <IRouteJs>(); routeJs.Setup(x => x.GetJavaScript(true)).Returns("SampleDebug"); routeJs.Setup(x => x.GetJavaScript(false)).Returns("SampleProd"); return(new RouteJsController(routeJs.Object) { ControllerContext = new ControllerContext { HttpContext = httpContext.Object } }); }
public static Mock <HttpRequest> CreateMockRequest(object body, string jwt) { var ms = new MemoryStream(); var sw = new StreamWriter(ms); var json = JsonConvert.SerializeObject(body); sw.Write(json); sw.Flush(); ms.Position = 0; var mockRequest = new Mock <HttpRequest>(); mockRequest.Setup(x => x.Body).Returns(ms); var headers = new HeaderDictionary(); headers.Add("Authorization", jwt); mockRequest.Setup(x => x.Headers).Returns(headers); return(mockRequest); }
/// <summary> /// Initializes a new instance of the <see cref="Connection" /> class. /// </summary> /// <param name="url">The url to connect to.</param> /// <param name="queryString">The query string data to pass to the server.</param> public Connection(string url, string queryString) { if (url == null) { throw new ArgumentNullException("url"); } if (url.Contains("?")) { throw new ArgumentException( "Url cannot contain QueryString directly. Pass QueryString values in using available overload.", "url"); } if (!url.EndsWith("/", StringComparison.Ordinal)) { url += "/"; } Url = url; QueryString = queryString; Groups = new List<string>(); Items = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); State = ConnectionState.Disconnected; TraceWriter = new DebugTextWriter(); Headers = new HeaderDictionary(this); }
public async Task RunAsyncMethod( bool isValidRoute, bool isValidDevice, string contentLength, string jsonFileName, int expectedStatusCode, int expectedSavedItemCount ) { // preparation var eventLogRepository = new Mock <IEventLogRepository>(); var validationServer = new Mock <IValidationServerService>(); var deviceValidationService = new Mock <IDeviceValidationService>(); var logger = new Mock.LoggerMock <V1EventLog>(); var eventLogApi = new V1EventLog( eventLogRepository.Object, validationServer.Object, deviceValidationService.Object, logger ); if (isValidRoute) { validationServer .Setup(x => x.Validate(It.IsAny <HttpRequest>())) .Returns(IValidationServerService.ValidateResult.Success); } else { validationServer .Setup(x => x.Validate(It.IsAny <HttpRequest>())) .Returns(IValidationServerService.ValidateResult.InvalidAzureFrontDoorId); } deviceValidationService .Setup(x => x.Validation(It.IsAny <string>(), It.IsAny <IDeviceVerification>(), It.IsAny <DateTimeOffset>())) .ReturnsAsync(isValidDevice); var context = new Mock <HttpContext>(); // Conetnt-Length header context.Setup(_ => _.Request.Headers).Returns(new HeaderDictionary()); if (contentLength != null) { IHeaderDictionary headers = new HeaderDictionary() { { "Content-Length", contentLength } }; context.Setup(_ => _.Request.Headers).Returns(headers); } // body string bodyString = GetTestJson(jsonFileName); using var stream = new MemoryStream(); using (var writer = new StreamWriter(stream, leaveOpen: true)) { await writer.WriteAsync(bodyString); await writer.FlushAsync(); } stream.Seek(0, SeekOrigin.Begin); context.Setup(x => x.Request.Body).Returns(stream); // action var result = await eventLogApi.RunAsync(context.Object.Request); Assert.IsTrue(result is StatusCodeResult); if (result is StatusCodeResult statusCodeResult) { Assert.AreEqual(expectedStatusCode, statusCodeResult.StatusCode); } eventLogRepository .Verify(x => x.UpsertAsync(It.IsAny <EventLogModel>()), Times.Exactly(expectedSavedItemCount)); }
public void ContainingHeadersWithHeadersDictionaryShouldThrowExceptionWithInvalidMultipleCount() { var headers = new HeaderDictionary { ["TestHeader"] = "Test", ["Set-Cookie"] = new[] { "TestCookie=TestCookieValue; expires=Thu, 31 Dec 2015 23:01:01 GMT; domain=testdomain.com; path=/; secure; httponly", "AnotherCookie=TestCookieValue; expires=Thu, 31 Dec 2015 23:01:01 GMT; domain=testdomain.com; path=/; secure; httponly" }, }; Test.AssertException<HttpResponseAssertionException>( () => { MyMvc .Controller<MvcController>() .Calling(c => c.CustomVoidResponseAction()) .ShouldHave() .HttpResponse(response => response.ContainingHeaders(headers)); }, "When calling CustomVoidResponseAction action in MvcController expected HTTP response headers to have 2 items, but instead found 6."); }
/// <summary> /// Initializes a new instance of the <see cref="Connection"/> class. /// </summary> /// <param name="url">The url to connect to.</param> /// <param name="queryString">The query string data to pass to the server.</param> public Connection(string url, string queryString) { if (url == null) { throw new ArgumentNullException("url"); } if (url.Contains("?")) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.Error_UrlCantContainQueryStringDirectly), "url"); } if (!url.EndsWith("/", StringComparison.Ordinal)) { url += "/"; } Url = url; QueryString = queryString; _disconnectTimeoutOperation = DisposableAction.Empty; _connectingMessageBuffer = new ConnectingMessageBuffer(this, OnMessageReceived); Items = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); State = ConnectionState.Disconnected; TraceLevel = TraceLevels.All; TraceWriter = new DebugTextWriter(); Headers = new HeaderDictionary(this); TransportConnectTimeout = TimeSpan.Zero; // Current client protocol Protocol = new Version(1, 3); }
public Task StartAsync <TContext>(IHttpApplication <TContext> application, CancellationToken cancellationToken) { SetHttpHandler(new Action <dynamic, dynamic>(async(req, res) => { var resourceName = GetCurrentResourceName(); var bodyStream = (req.method != "GET" && req.method != "HEAD") ? await GetBodyStream(req) : Stream.Null; var oldSc = SynchronizationContext.Current; SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); var cts = new CancellationTokenSource(); req.setCancelHandler(new Action(() => { cts.Cancel(); })); await Task.Factory.StartNew(async() => { var owinEnvironment = new Dictionary <string, object>(); owinEnvironment["owin.RequestBody"] = bodyStream; var headers = new HeaderDictionary(); foreach (var headerPair in req.headers) { headers.Add(headerPair.Key, new string[] { headerPair.Value.ToString() }); } owinEnvironment["owin.RequestHeaders"] = headers; owinEnvironment["owin.RequestMethod"] = req.method; owinEnvironment["owin.RequestPath"] = req.path.Split('?')[0]; owinEnvironment["owin.RequestPathBase"] = "/" + resourceName; owinEnvironment["owin.RequestProtocol"] = "HTTP/1.0"; owinEnvironment["owin.RequestQueryString"] = (req.path.Contains('?')) ? req.path.Split('?', 2)[1] : ""; owinEnvironment["owin.RequestScheme"] = "http"; var outStream = new HttpOutStream(owinEnvironment, res); owinEnvironment["owin.ResponseBody"] = outStream; var outHeaders = new Dictionary <string, string[]>(); owinEnvironment["owin.ResponseHeaders"] = outHeaders; owinEnvironment["owin.CallCancelled"] = cts.Token; owinEnvironment["owin.Version"] = "1.0"; var ofc = new FxOwinFeatureCollection(owinEnvironment); var context = application.CreateContext(new FeatureCollection(ofc)); try { await application.ProcessRequestAsync(context); await ofc.InvokeOnStarting(); } catch (Exception ex) { Debug.WriteLine($"Exception while handling request. {ex}"); await ofc.InvokeOnCompleted(); application.DisposeContext(context, ex); var errorText = Encoding.UTF8.GetBytes("Error."); owinEnvironment["owin.ResponseStatusCode"] = 500; await outStream.WriteAsync(errorText, 0, errorText.Length); await outStream.EndStream(); return; } application.DisposeContext(context, null); await outStream.EndStream(); await ofc.InvokeOnCompleted(); }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); SynchronizationContext.SetSynchronizationContext(oldSc); })); return(Task.CompletedTask); }
public async Task RuntimeExeptionHandler_HandlesException() { var wc = new WorkContext { CurrentUserId = "cur-user-id", CurrentClientId = "cur-client-id", IpAddress = "this is ip-address", }; const string traceId = "exeption-id", exMsg = "msg-1", exRuntimeType = "ex-runtime-type", path = "this-is-path", method = "GET"; var headers = new HeaderDictionary { { "key1", new StringValues("value1") }, { "key2", new StringValues("value2") }, }; var queryString = new QueryString("?query-string-value"); var host = new HostString("host", 123); var expRequest = new { url = host.Value, port = host.Port, method = method, path = path, headers = headers.Select(x => $"[{x.Key}:{x.Value}]").Aggregate((f, s) => $"{f}\n{s}"), query = queryString.Value, }; var logRecord = new LogRecord { Level = LogRecordLevel.Error, ClientId = wc.CurrentClientId, UserId = wc.CurrentUserId, TraceId = traceId, ExceptionRuntimeType = exRuntimeType, ExceptionRuntimeMessage = exMsg, Message = "some-clevermessage", IpAddress = wc.IpAddress, RequestPath = path, RequestHeaders = expRequest.headers, HttpMethod = method, Request = expRequest.ToJsonString(), }; var ded = new DomainEvent { Data = new { exception = new Exception(), logRecord = logRecord }, PerformedByUserId = wc.CurrentUserId, WorkContext = wc, }; var sp = new Mock <IServiceProvider>(); var lm = new Mock <ILogRecordManager>(); sp.Setup(p => p.GetService(typeof(ILogRecordManager))).Returns(lm.Object); var reh = new RepositoryExceptionHandler(sp.Object); await reh.InsertRecord(ded); lm.Verify(r => r.InsertLogRecord(It.Is <LogRecord>(lRec => lRec.Level == LogRecordLevel.Error && lRec.ClientId == wc.CurrentClientId && lRec.UserId == wc.CurrentUserId && lRec.TraceId == traceId && lRec.ExceptionRuntimeType == exRuntimeType && lRec.ExceptionRuntimeMessage == exMsg && lRec.Message.HasValue() && lRec.IpAddress == wc.IpAddress && lRec.RequestPath == path && lRec.RequestHeaders == expRequest.headers && lRec.HttpMethod == method && lRec.Request == expRequest.ToJsonString() && lRec.CreatedOnUtc == default )), Times.Once); }
public void SetInDistributionCache_IfValidRequestNotCached_WithInflight(string httpMethod, string idempotencyKey) { // Arrange // Prepare the body and headers for the Request and Response: string distributedCacheKey = _distributedCacheKeysPrefix + idempotencyKey; string requestBodyString = @"{""message"":""This is a dummy message""}"; var requestHeaders = new HeaderDictionary(); requestHeaders.Add("Content-Type", "application/json"); requestHeaders.Add(_headerKeyName, idempotencyKey); // Execution Result var controllerExecutionResult = new OkObjectResult(new ResponseModelBasic() { Id = 1, CreatedOn = new DateTime(2019, 10, 12, 5, 25, 25) }); var responseHeaders = new HeaderDictionary(); responseHeaders.Add(new KeyValuePair <string, StringValues>("CustomHeader01", new StringValues("CustomHeaderValue01"))); responseHeaders.Add(new KeyValuePair <string, StringValues>("CustomHeader02", new StringValues("CustomHeaderValue02"))); var actionContext = ArrangeActionContextMock(httpMethod, requestHeaders, requestBodyString, responseHeaders, controllerExecutionResult); var actionExecutingContext = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(), new Dictionary <string, object>(), Mock.Of <Controller>() ); var inflightExecutingContext = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(), new Dictionary <string, object>(), Mock.Of <Controller>() ); var resultExecutedContext = new ResultExecutedContext( actionContext, new List <IFilterMetadata>(), controllerExecutionResult, Mock.Of <Controller>()); var idempotencyAttributeFilter = new IdempotencyAttributeFilter(_sharedDistributedCache.Cache, _loggerFactory, true, 1, _headerKeyName, _distributedCacheKeysPrefix); var idempotencyAttributeFilterRequest2 = new IdempotencyAttributeFilter(_sharedDistributedCache.Cache, _loggerFactory, true, 1, _headerKeyName, _distributedCacheKeysPrefix); // Act Part 1 (check cache): idempotencyAttributeFilter.OnActionExecuting(actionExecutingContext); // Assert Part 1: Assert.Null(actionExecutingContext.Result); // Act Part 2 - since we haven't called OnResultExecuted the result of the first request should still be inflight and we should have a 409 result idempotencyAttributeFilterRequest2.OnActionExecuting(inflightExecutingContext); Assert.NotNull(inflightExecutingContext.Result); Assert.Equal(typeof(ConflictResult), inflightExecutingContext.Result.GetType()); Assert.Equal(409, ((ConflictResult)inflightExecutingContext.Result).StatusCode); // Act Part 3: idempotencyAttributeFilter.OnResultExecuted(resultExecutedContext); // Assert Part 3: byte[] cachedData = _sharedDistributedCache.Cache.Get(distributedCacheKey); Assert.NotNull(cachedData); // Act 4 rerun the request that failed cause the first was in flight idempotencyAttributeFilterRequest2.OnActionExecuting(inflightExecutingContext); //Assert : Part 4 // The result of the above should be coming from the cache so we should have a result Assert.Equal(typeof(OkObjectResult), inflightExecutingContext.Result.GetType()); Assert.Equal(typeof(ResponseModelBasic), ((OkObjectResult)inflightExecutingContext.Result).Value.GetType()); Assert.Equal(200, ((OkObjectResult)inflightExecutingContext.Result).StatusCode); }
public ResponseWrapper() { buffer = new MemoryStream(); headers = new HeaderDictionary(); }
public ResponseFeature() { Headers = new HeaderDictionary(); Reset(); }
public void GetAddresses_SimpleWithoutQuotesAroundDisplayName_ParsesCorrectAddressAndDisplayName() { var headerDictionary = new HeaderDictionary { { "From", new HeaderValue(@"Test van Testenstein <*****@*****.**>")} }; var mailAddresses = headerDictionary.GetMailAddresses("From"); Assert.Equal(1, mailAddresses.Length); var mailAddress = mailAddresses.First(); Assert.Equal("*****@*****.**", mailAddress.Address); Assert.Equal("Test van Testenstein", mailAddress.DisplayName); }
public void GetAddresses_WithTwoAddresses_ParsesCorrectAddressesAndDisplayName() { var headerDictionary = new HeaderDictionary { { "To", new HeaderValue(@"Firstname Lastname <*****@*****.**>, [email protected]")} }; var mailAddresses = headerDictionary.GetMailAddresses("To"); Assert.AreEqual(2, mailAddresses.Length); var firstMailAddress = mailAddresses.First(); Assert.AreEqual("*****@*****.**", firstMailAddress.Address); Assert.AreEqual("Firstname Lastname", firstMailAddress.DisplayName); var secondMailAddress = mailAddresses.Last(); Assert.AreEqual("*****@*****.**", secondMailAddress.Address); Assert.AreEqual("", secondMailAddress.DisplayName); }
public void GetAddresses_WithThreeAddresses_ParsesCorrectAddressesAndDisplayName() { var headerDictionary = new HeaderDictionary { { "To", new HeaderValue(@"<*****@*****.**>, <*****@*****.**>, <*****@*****.**>")} }; var mailAddresses = headerDictionary.GetMailAddresses("To"); Assert.AreEqual(3, mailAddresses.Length); var firstMailAddress = mailAddresses.ElementAt(0); Assert.AreEqual("*****@*****.**", firstMailAddress.Address); Assert.AreEqual("", firstMailAddress.DisplayName); var secondMailAddress = mailAddresses.ElementAt(1); Assert.AreEqual("*****@*****.**", secondMailAddress.Address); Assert.AreEqual("", secondMailAddress.DisplayName); var thirdMailAddress = mailAddresses.ElementAt(2); Assert.AreEqual("*****@*****.**", thirdMailAddress.Address); Assert.AreEqual("", thirdMailAddress.DisplayName); }
public void GetAddresses_WithCommaInDispayName_ParsesCorrectAddressAndDisplayName() { var headerDictionary = new HeaderDictionary { { "From", new HeaderValue(@"""lastname, firstname"" <*****@*****.**>")} }; var mailAddresses = headerDictionary.GetMailAddresses("From"); Assert.AreEqual(1, mailAddresses.Length); var mailAddress = mailAddresses.First(); Assert.AreEqual("*****@*****.**", mailAddress.Address); Assert.AreEqual("lastname, firstname", mailAddress.DisplayName); }
public HttpResponseFeature() { StatusCode = 200; Headers = new HeaderDictionary(); Body = Stream.Null; }
public Task <TResponse> GetByIdAsync <TId, TResponse>(TId id, HeaderDictionary headers = null) { throw new NotImplementedException(); }
private ActionContext ArrangeActionContextMock(string httpMethod, HeaderDictionary requestHeaders) { return(ArrangeActionContextMock(httpMethod, requestHeaders, string.Empty, new HeaderDictionary(), null)); }
public Task <string> GetByIdAsync <TId>(TId id, HeaderDictionary headers = null) { throw new NotImplementedException(); }
private ActionContext ArrangeActionContextMock(string httpMethod, HeaderDictionary requestHeaders, object requestBody, HeaderDictionary responseHeaders, IStatusCodeActionResult actionResult) { // Mock Post Request: var request = new Mock <HttpRequest>(); request.Setup(r => r.Method).Returns(httpMethod); // Mock Request's Headers (if any): request.Setup(r => r.Headers).Returns(requestHeaders); // Set the Content-Type based on the request headers. string contentType = "json object"; if (requestHeaders.ContainsKey("Content-Type")) { contentType = requestHeaders["Content-Type"]; } switch (requestBody) { case string requestBodyString: if (!string.IsNullOrEmpty(requestBodyString)) { request.SetupGet(r => r.Path).Returns("/resource"); request.SetupGet(r => r.QueryString).Returns(new QueryString()); request.SetupGet(c => c.ContentLength).Returns(requestBodyString.Length); request.SetupGet(r => r.Body).Returns(new MemoryStream(Encoding.UTF8.GetBytes(requestBodyString))); request.SetupGet(r => r.ContentType).Returns(contentType); // The Form throws an exception when the Content-Type is not supported. request.SetupGet(r => r.HasFormContentType).Returns(false); request.SetupGet(r => r.Form).Throws(new InvalidOperationException($"Incorrect Content-Type: {contentType}")); } break; // Mock Request's File: case FormFile requestBodyFile: if (requestBodyFile != null) { request.SetupGet(r => r.Path).Returns("/resource"); request.SetupGet(r => r.QueryString).Returns(new QueryString()); request.SetupGet(c => c.ContentLength).Returns(requestBodyFile.Length); request.Setup(r => r.Form.Files).Returns(new FormFileCollection() { requestBodyFile }); request.SetupGet(r => r.ContentType).Returns("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); } break; } // Mock Request's File: //FormFile txtFile = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")), 0, 0, "Data", "dummy.txt"); //txtFile.Length //request.Setup(r => r.Form.Files).Returns(new FormFileCollection() { txtFile }); // Mock HttpContext Request: var httpContext = new Mock <HttpContext>(); httpContext.Setup(x => x.Request).Returns(request.Object); // Mock HttpContext Response: var httpResponse = new Mock <HttpResponse>(); httpResponse.Setup(r => r.Headers).Returns(responseHeaders); if (actionResult != null) { httpResponse.SetupGet(c => c.StatusCode).Returns(actionResult.StatusCode.HasValue ? actionResult.StatusCode.Value : 500); httpResponse.SetupGet(c => c.ContentLength).Returns(actionResult is ObjectResult ? ((ObjectResult)actionResult).Value.Serialize().Length : 0); httpResponse.SetupGet(r => r.ContentType).Returns(contentType); } httpContext.SetupGet(c => c.Response).Returns(() => httpResponse.Object); var actionContext = new ActionContext( httpContext.Object, Mock.Of <RouteData>(), Mock.Of <ActionDescriptor>() ); return(actionContext); }
public Task <TResponse> PostAsync <TRequest, TResponse>(TRequest request, HeaderDictionary headers = null) { throw new NotImplementedException(); }
public ControlRequest() { Headers = new HeaderDictionary(); }
public Task <string> PostAsync <TRequest>(string uri, TRequest request, HeaderDictionary headers = null) { throw new NotImplementedException(); }
private static ActionContext GetActionContext( MediaTypeHeaderValue contentType, MemoryStream responseStream = null) { var request = new Mock<HttpRequest>(); var headers = new HeaderDictionary(); request.Setup(r => r.ContentType).Returns(contentType.ToString()); request.SetupGet(r => r.Headers).Returns(headers); headers[HeaderNames.AcceptCharset] = contentType.Charset; var response = new Mock<HttpResponse>(); response.SetupGet(f => f.Body).Returns(responseStream ?? new MemoryStream()); var httpContext = new Mock<HttpContext>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Response).Returns(response.Object); return new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor()); }
public Task <string> PostAsync(string uri, string content, HeaderDictionary headers = null) { throw new NotImplementedException(); }
public void TestEmptyHeader() { var headers = new HeaderDictionary(); IsFalse(IsValid(headers)); }
public void ContainingHeadersWithHeadersDictionaryShouldWorkCorrectly() { var headers = new HeaderDictionary { ["TestHeader"] = "TestHeaderValue", ["AnotherTestHeader"] = "AnotherTestHeaderValue", ["MultipleTestHeader"] = new[] { "FirstMultipleTestHeaderValue", "AnotherMultipleTestHeaderValue" }, ["Content-Type"] = "application/json", ["Content-Length"] = "100", ["Set-Cookie"] = new[] { "TestCookie=TestCookieValue; expires=Thu, 31 Dec 2015 23:01:01 GMT; domain=testdomain.com; path=/; secure; httponly", "AnotherCookie=TestCookieValue; expires=Thu, 31 Dec 2015 23:01:01 GMT; domain=testdomain.com; path=/; secure; httponly" }, }; MyMvc .Controller<MvcController>() .Calling(c => c.CustomVoidResponseAction()) .ShouldHave() .HttpResponse(response => response.ContainingHeaders(headers)); }
private static HttpContext GetHttpContext(string contentType) { var request = new Mock<HttpRequest>(); var headers = new HeaderDictionary(); headers["Accept-Charset"] = MediaTypeHeaderValue.Parse(contentType).Charset; request.Setup(r => r.ContentType).Returns(contentType); request.SetupGet(r => r.Headers).Returns(headers); var response = new Mock<HttpResponse>(); response.SetupGet(f => f.Body).Returns(new MemoryStream()); var httpContext = new Mock<HttpContext>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Response).Returns(response.Object); return httpContext.Object; }
public MockResponseFeature() { Headers = new HeaderDictionary(); }
public void GetAddresses_SimpleWithQuotesAroundDisplayName_ParsesCorrectAddressAndDisplayName() { var headerDictionary = new HeaderDictionary { { "From", new HeaderValue(@"""name"" <*****@*****.**>")} }; var mailAddresses = headerDictionary.GetMailAddresses("From"); Assert.AreEqual(1, mailAddresses.Length); var mailAddress = mailAddresses.First(); Assert.AreEqual("*****@*****.**", mailAddress.Address); Assert.AreEqual("name", mailAddress.DisplayName); }