public async Task ItShouldValidateClientId() { var optionsMonitor = CreateOptionsMonitor(); var signatureBodySourceBuilderMock = new Mock <ISignatureBodySourceBuilder>(); var signatureBodySignerMock = new Mock <ISignatureBodySigner>(); var service = new RequestsSignatureValidationService( optionsMonitor, signatureBodySourceBuilderMock.Object, signatureBodySignerMock.Object); var httpRequest = new DefaultHttpRequest(new DefaultHttpContext()); httpRequest.Headers[optionsMonitor.CurrentValue.HeaderName] = "WrongClientId:asdf:0:asdf"; var result = await service.Validate(httpRequest); result.Status.Should().Be(SignatureValidationResultStatus.ClientIdNotFound); result.SignatureValue.Should().Be(httpRequest.Headers[optionsMonitor.CurrentValue.HeaderName]); result.ClientId.Should().Be("WrongClientId"); }
public async Task PostCdnReturnsBadRequestWhenNullBody() { // Arrange const HttpStatusCode expectedResult = HttpStatusCode.BadRequest; var request = new DefaultHttpRequest(new DefaultHttpContext()); var function = new CdnUpdatePostHttpTrigger(fakeLogger, fakeDocumentService, fakeUpdateScriptHashCodes); // Act var result = await function.Run(request).ConfigureAwait(false); // Assert A.CallTo(() => fakeDocumentService.GetAsync(A <Expression <Func <AppRegistrationModel, bool> > > .Ignored)).MustNotHaveHappened(); A.CallTo(() => fakeDocumentService.UpsertAsync(A <AppRegistrationModel> .Ignored)).MustNotHaveHappened(); A.CallTo(() => fakeUpdateScriptHashCodes.UpdateAllAsync(A <string> .Ignored)).MustNotHaveHappened(); var statusResult = Assert.IsType <BadRequestResult>(result); Assert.Equal((int)expectedResult, statusResult.StatusCode); }
public async Task ThenItShouldReturnBadRequestIfBodyNotJson() { var httpRequest = new DefaultHttpRequest(new DefaultHttpContext()) { Body = new MemoryStream(Encoding.UTF8.GetBytes("not-json")), }; var actual = await _function.RunAsync(httpRequest, _cancellationToken); Assert.IsNotNull(actual); Assert.IsInstanceOf <HttpErrorBodyResult>(actual); Assert.AreEqual(HttpStatusCode.BadRequest, ((HttpErrorBodyResult)actual).StatusCode); var errorBody = (HttpErrorBody)((FormattedJsonResult)actual).Value; Assert.AreEqual(HttpStatusCode.BadRequest, errorBody.StatusCode); Assert.AreEqual(Errors.GetLearningProvidersMalformedRequest.Code, errorBody.ErrorIdentifier); Assert.AreEqual(Errors.GetLearningProvidersMalformedRequest.Message, errorBody.Message); }
private static HttpRequest CreateHttpPostRequest(string inputId, DtmfRequest dtmf = null) { HttpContext httpContext = new DefaultHttpContext(); HttpRequest request = new DefaultHttpRequest(httpContext); InitiateCallRequest requestObj = new InitiateCallRequest() { InputId = inputId, Dtmf = dtmf, }; Stream contentBytes = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(requestObj))); request.Body = contentBytes; return(request); }
public async Task ReturnsBadRequestWithInvalidJson() { var body = JsonConvert.SerializeObject("{ invalidjson }"); var bodyArray = Encoding.UTF8.GetBytes(body); var bodyStream = new MemoryStream(bodyArray); var shiftService = new Mock <IShiftService>(MockBehavior.Strict).Object; var function = new UpdateShift(shiftService, AuthenticationHelperMock.GetAuthenticationHelper()); var request = new DefaultHttpRequest(new DefaultHttpContext()); request.Headers.Add("Authorization", AuthenticationHelperMock.GoodHeader); request.Body = bodyStream; var result = await function.Run(request, NullLogger.Instance); result.Should().BeOfType <BadRequestResult>(); }
/// <summary> /// Creates an HTTP POST request for the DeleteRecordings function. /// </summary> /// <param name="inputId">The inputId to set in the content.</param> /// <param name="callSid">The callSid to set in the content.</param> /// <returns>The content.</returns> private static HttpRequest CreatePullHttpPostRequest(string inputId, string callSid) { HttpContext httpContext = new DefaultHttpContext(); HttpRequest request = new DefaultHttpRequest(httpContext); PullRecordingRequest requestObj = new PullRecordingRequest() { InputId = inputId, CallSid = callSid, }; Stream contentBytes = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(requestObj))); request.Body = contentBytes; return(request); }
public void ComposeEmailBuildsMessageWithRequestInformation() { var exception = new Exception("This is an exception!"); var httpContext = new DefaultHttpContext { Request = { Scheme = "http", Path = "/some-path", Method = HttpMethod.Get.ToString() } }; var request = new DefaultHttpRequest(httpContext); var message = new ExceptionMessageBuilder(exception, _notifierOptions, request).ComposeContent(); Assert.Contains("------------------\nException Message:\n------------------\n\nThis is an exception!", message); Assert.Contains("--------\nRequest:\n--------\n\n", message); Assert.Contains("-----------\nStacktrace:\n-----------\n\n", message); }
public void DeconstructEventGridMessage_ParsesSingleEvent() { // arrange var requestBody = "[{\r\n \"id\": \"eventid\",\r\n \"topic\": \"topicid\",\r\n \"subject\": \"fakeuserid/fakeitemid\",\r\n \"data\": {},\r\n \"eventType\": \"AudioCreated\",\r\n \"eventTime\": \"2018-01-25T22:12:19.4556811Z\",\r\n \"metadataVersion\": \"1\",\r\n \"dataVersion\": \"1\"\r\n}]"; var req = new DefaultHttpRequest(new DefaultHttpContext()) { Body = GetStreamFromString(requestBody) }; var service = new EventGridSubscriberService(); // act var result = service.DeconstructEventGridMessage(req); // assert Assert.Equal("fakeuserid", result.userId); Assert.Equal("fakeitemid", result.itemId); Assert.NotNull(result.eventGridEvent); Assert.IsType <AudioCreatedEventData>(result.eventGridEvent.Data); }
private string ReadFromQueryString(DefaultHttpRequest req) { try { var keys = req.Query.Keys; Dictionary <string, object> keyValuePairs = new Dictionary <string, object>(); foreach (var key in keys) { keyValuePairs.Add(key, req.Query[key]); } return(DictionaryToJson(keyValuePairs)); } catch (Exception ex) { return(string.Empty); } }
public async void Should_Return_OK() { var wordAsBase64 = Convert.ToBase64String(await File.ReadAllBytesAsync("test.docx")); var inputJson = $@" {{ ""document"":""{wordAsBase64}"", ""data"": {{ ""Company"":""Hololux"", ""Street"":""Europaallee 27d"", ""City"":""Saarbruecken"", ""Items"":[ {{ ""Article"":""4711"", ""Quantity"":""2"", ""Price"":""5"", ""Sum"":""10"" }}, {{ ""Article"":""4712"", ""Quantity"":""1"", ""Price"":8, ""Sum"":8 }} ] }} }}"; var request = new DefaultHttpRequest(new DefaultHttpContext()) { Body = new MemoryStream(Encoding.UTF8.GetBytes(inputJson)) }; var logger = NullLoggerFactory.Instance.CreateLogger("Null Logger"); var response = await ProcessTemplate.Run(request, logger); Assert.IsType <OkObjectResult>(response); var tempPath = Path.GetTempFileName() + ".docx"; File.WriteAllBytes(tempPath, Convert.FromBase64String((response as OkObjectResult).Value.ToString())); _testOutputHelper.WriteLine("Generated Word Document: " + tempPath); }
private string ReadFromBody(DefaultHttpRequest req) { var copyBuffer = new MemoryStream(); req.Body.CopyToAsync(copyBuffer); //if there was no stream if (copyBuffer == Stream.Null) { return(string.Empty); } copyBuffer.Position = 0; using (StreamReader stream = new StreamReader(copyBuffer)) { return(stream.ReadToEndAsync().Result); } }
/// <inheritdoc/> public async Task <IRestResponse> ExecuteAsync(IRestRequest request, CancellationToken cancellationToken = default) { var method = request.Route.BaseRoute.Method; var uri = new Uri(request.Route.Path, UriKind.Relative); var content = request.GetOrCreateHttpContent(ApiClient); var httpRequest = new DefaultHttpRequest(method, uri, content); if (request.Options?.Headers != null) { foreach (var header in request.Options.Headers) { httpRequest.Headers.Add(header.Key, header.Value); } } var response = await HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); return(new DefaultRestResponse(response)); }
public void Retries_request_with_throttling_on_HTTP_429() { // Set up a fake HttpClient that always returns HTTP 429 var failingHttpClient = GetSynchronousClient( new DefaultHttpResponse(429, null, new HttpHeaders(), null, null, transportError: false)); var defaultBackoffStrategy = GetFakeBackoffStrategy(); var throttlingBackoffStrategy = GetFakeBackoffStrategy(); var requestExecutor = GetRequestExecutor(failingHttpClient, defaultBackoffStrategy, throttlingBackoffStrategy); var dummyRequest = new DefaultHttpRequest(HttpMethod.Delete, new CanonicalUri("http://api.foo.bar/foo")); var response = requestExecutor.Execute(dummyRequest); response.IsClientError().ShouldBeTrue(); // Used throttling backoff strategy to pause after each retry (4 times) defaultBackoffStrategy.DidNotReceiveWithAnyArgs().GetDelayMilliseconds(0); throttlingBackoffStrategy.ReceivedWithAnyArgs(4).GetDelayMilliseconds(0); }
private static HttpRequest CreateHttpPostRequest(string callSid, string recordingUrl) { HttpContext httpContext = new DefaultHttpContext(); HttpRequest request = new DefaultHttpRequest(httpContext); TranscribeCallRequest requestObj = new TranscribeCallRequest() { CallSid = callSid, RecordingUri = recordingUrl, }; Stream contentBytes = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(requestObj))); request.Body = contentBytes; return(request); }
public async Task Run_ReturnsErrorOnServerError() { var handler = new Mock <IQueryHandler <GetTaskQuery, TaskDTO> >(); var container = new Container(); var logger = new Mock <ILogger>().Object; var listid = Guid.NewGuid().ToString(); var taskid = Guid.NewGuid().ToString(); var request = new DefaultHttpRequest(new DefaultHttpContext()); handler.Setup(h => h.Execute(It.IsAny <GetTaskQuery>())) .ThrowsAsync(new Exception()); container.RegisterInstance(handler.Object); container.RegisterInstance(_telemetryClient); GetTask.Container = container; var result = await GetTask.Run(request, listid, taskid, logger) as InternalServerErrorResult; Assert.IsNotNull(result); }
public void TestWatchFunctionSuccess() { var httpContext = new DefaultHttpContext(); var queryStringValue = "abc"; var request = new DefaultHttpRequest(new DefaultHttpContext()) { Query = new QueryCollection ( new System.Collections.Generic.Dictionary <string, StringValues>() { { "model", queryStringValue } } ) }; var logger = NullLoggerFactory.Instance.CreateLogger("Null Logger"); WatchPortalFunction.Watchproperties watchinfo = new WatchPortalFunction.Watchproperties { Manufacturer = "Abc", Casetype = "Solid", Bezel = "Titanium", Dial = "Roman", Casefinish = "Silver", Jewels = 15, Type = "watch" }; var response = WatchPortalFunction.WatchInfo.Run(request, watchinfo, logger); response.Wait(); // Check that the response is an "OK" response Assert.IsAssignableFrom <OkObjectResult>(response.Result); // Check that the contents of the response are the expected contents var result = (OkObjectResult)response.Result; Assert.Equal(watchinfo, result.Value); }
public void SentinelTest_ThisOneShouldntPassButDoes() { TestingUtils.ResetSentinel(); TestingUtils.ResetRoutesRepository(); var routesRepository = new RoutesRepository(); routesRepository.RegisterRoutesAsync(new List <IRouteDefinitions>() { new SpecialRouteTemplateRoutes() }).Wait(); var httpContext = new DefaultHttpContext(); httpContext.Response.Body = new MemoryStream(); var request = new DefaultHttpRequest(httpContext) { Method = HttpMethod.Post.Method, Path = "/v1/yolo/nolo/thisIsDefinitelyNotAnInteger", Query = new QueryCollection(new Dictionary <string, Microsoft.Extensions.Primitives.StringValues>() { { "No", "true" } }), Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new TestingType() { Yo = "lo", No = "low" }))) }; httpContext.Items.Add("ExpectedClaims", new List <Claim>() { new Claim("PityTheFoolType", "low"), new Claim("PityTheFoolJsonPath", "low"), new Claim("PityTheFoolKeyValue", "true"), new Claim("PityTheFoolRegex", "yolo"), }); var sentinel = new Sentinel(reqDelegate, routesRepository); var result = sentinel.Invoke(httpContext); Assert.NotNull(request); Assert.NotNull(result); Assert.Equal((int)HttpStatusCode.Created, httpContext.Response.StatusCode); }
public void TestWatchFunctionFailureNoModel() { var httpContext = new DefaultHttpContext(); var queryStringValue = ""; var request = new DefaultHttpRequest(new DefaultHttpContext()) { Query = new QueryCollection ( new System.Collections.Generic.Dictionary <string, StringValues>() { { "no-model", queryStringValue } } ) }; var logger = NullLoggerFactory.Instance.CreateLogger("Null Logger"); WatchPortalFunction.Watchproperties watchinfo = new WatchPortalFunction.Watchproperties { /* * Manufacturer = "Abc", * Casetype = "Solid", * Bezel = "Titanium", * Dial = "Roman", * Casefinish = "Silver", * Jewels = 15, * Type = "watch" */ }; var response = WatchPortalFunction.WatchInfo.Run(request, watchinfo, logger); response.Wait(); // Check that the response is an "Bad" response Assert.IsAssignableFrom <BadRequestObjectResult>(response.Result); // Check that the contents of the response are the expected contents var result = (BadRequestObjectResult)response.Result; Assert.Equal(new { message = "Please provide a watch model in the query string" }.ToString(), result.Value.ToString()); }
public async Task ReturnSuccessStatusCodeWhenPostRelayIsCalledAsync() { // Arrange IRelayManagementService relayManagementService = A.Fake <IRelayManagementService>(); ILogger logger = A.Fake <ILogger>(); var sut = new ShieldManagementApi(relayManagementService); var httpContext = new DefaultHttpContext(); var httpRequest = new DefaultHttpRequest(httpContext) { Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(TestHelper.GetCreateRelayStorageDto()))) }; A.CallTo(() => relayManagementService.StoreRelayAsync(TestHelper.GetCreateRelayStorageDto())).WithAnyArguments().Returns(TestHelper.GetHybridConnectionDto()); // Act IActionResult actual = await sut.PostRelayInformationAsync(httpRequest, logger); // Assert Assert.IsType <ListenerDto>(((ObjectResult)actual).Value); Assert.Equal(HttpStatusCode.OK, (HttpStatusCode)((ObjectResult)actual).StatusCode); }
public async Task ThenItShouldDeserializeCommonSchema(string eventName, string eventDescription) { var requestDocument = BuildRequestDocument(eventName: eventName, eventDescription: eventDescription, useCommonEventSchema: true); var request = new DefaultHttpRequest(new DefaultHttpContext()) { Body = new MemoryStream(Encoding.UTF8.GetBytes(requestDocument)), }; await _function.RunAsync(request, _cancellationToken); var expectedSchema = "{\"$ref\":\"#/definitions/test-object\",\"definitions\":{\"test-object\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"}}}}}"; _publisherManagerMock.Verify(m => m.UpdatePublishedEventsAsync( It.Is <Publisher>(p => p.Events.Length == 1 && p.Events[0].Name == eventName && p.Events[0].Description == eventDescription && p.Events[0].Schema == expectedSchema), _cancellationToken), Times.Once); }
private HttpRequest SetupGetRequest(string[] parts = null) { DefaultHttpContext httpCtx = new DefaultHttpContext(); DefaultHttpRequest httpReq = new DefaultHttpRequest(httpCtx); if (parts != null) { StringBuilder builder = new StringBuilder("?"); for (int i = 0; i < parts.Length; i++) { builder.Append(parts[i]); builder.Append(i % 2 == 0 ? "=" : "&"); } httpReq.QueryString = new QueryString(builder.ToString()); } return(httpReq); }
public async Task should_return_OkObjectResult_if_name_is_present_in_query_string() { var name = "Tom"; var expected = $"Hello, {name}"; var context = new DefaultHttpContext(); var request = new DefaultHttpRequest(context) { QueryString = new QueryString($"?name={name}") }; var logger = NullLoggerFactory.Instance.CreateLogger("null logger"); var response = await PureHttpFunc.Run(request, logger); Assert.NotNull(response); var obj = Assert.IsType <OkObjectResult>(response); Assert.Equal(expected, obj.Value); }
public async Task BeAbleToGetCustomerAsync() { // Arrange ICustomerManagementService customerManagementService = A.Fake <ICustomerManagementService>(); ILogger logger = A.Fake <ILogger>(); var sut = new CustomerManagementFunctions(customerManagementService); var httpContext = new DefaultHttpContext(); var httpRequest = new DefaultHttpRequest(httpContext); A.CallTo(() => customerManagementService.GetCustomerInformationAsync(TestHelper.CustomerId)) .Returns(TestHelper.GetCustomerInfoWithTestHelperDefaultValues()); // Act IActionResult actual = await sut.GetCustomerAsync(httpRequest, TestHelper.CustomerId.ToString(), logger); // Assert Assert.Equal(HttpStatusCode.OK, (HttpStatusCode)((ObjectResult)actual).StatusCode); Assert.Equal(TestHelper.GetCustomerInfoWithTestHelperDefaultValues().CustomerId, ((CustomerInfo)((ObjectResult)actual).Value).CustomerId); Assert.Equal(TestHelper.GetCustomerInfoWithTestHelperDefaultValues().TenantId, ((CustomerInfo)((ObjectResult)actual).Value).TenantId); }
public async Task ThenItShouldSyncDeserializedManagementGroup(ManagementGroup managementGroup, string source) { var request = new DefaultHttpRequest(new DefaultHttpContext()) { Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(managementGroup))), }; await _function.RunAsync(request, source, _cancellationToken); _searchManagerMock.Verify(m => m.SyncAsync( It.Is <ManagementGroup>(lp => lp.Name == managementGroup.Name && lp.Code == managementGroup.Code && lp.Type == managementGroup.Type && lp.Identifier == managementGroup.Identifier && lp.CompaniesHouseNumber == managementGroup.CompaniesHouseNumber), source, _cancellationToken), Times.Once()); }
public async Task MissingSettings() { Environment.SetEnvironmentVariable(TextAnalyticsForHealth.textAnalyticsApiEndpointSetting, "https://testendpoint.com"); var payload = new { document = "World" }; var jsonContent = new StringContent(Helpers.BuildPayload(payload), null, "application/json"); var request = new DefaultHttpRequest(new DefaultHttpContext()) { ContentType = "application/json; charset=utf-8", Body = await jsonContent.ReadAsStreamAsync(), Method = "POST" }; var response = await Helpers.CurrySkillFunction(TextAnalyticsForHealth.Run)(request) as ObjectResult; var expectedResponse = "unitTestFunction - TextAnalyticsForHealth API key or Endpoint is missing. Make sure to set it in the Environment Variables."; Assert.AreEqual(expectedResponse, response.Value); }
public void TestWithParameter() { QueryBuilder qb = new QueryBuilder(); qb.Add("key1", "value1"); qb.Add("key2", "value2"); qb.Add("key3", "value3"); var request = new DefaultHttpRequest(new DefaultHttpContext()); request.QueryString = qb.ToQueryString(); _builder = new CustomQueryStringBuilder(request.Query); var str1 = _builder.GetQueryStringWithParameter("key4", "value4"); Assert.AreEqual(str1, "?key1=value1&key2=value2&key3=value3&key4=value4"); str1 = _builder.GetQueryStringWithParameter("key4", "value4new"); Assert.AreEqual(str1, "?key1=value1&key2=value2&key3=value3&key4=value4new"); }
public async Task ReturnsNotFoundRequestIfNoShift() { var fixture = new Fixture(); var testShift = fixture.Create <Shift>(); var shiftServiceMock = new Mock <IShiftService>(MockBehavior.Strict); shiftServiceMock.Setup(s => s.GetShift(AuthenticationHelperMock.GoodUserId, testShift.Id)).Returns(Task.FromResult <Shift>(null)); var shiftService = shiftServiceMock.Object; var function = new GetJobs(shiftService, AuthenticationHelperMock.GetAuthenticationHelper()); var request = new DefaultHttpRequest(new DefaultHttpContext()); request.Headers.Add("Authorization", AuthenticationHelperMock.GoodHeader); request.QueryString = new QueryString($"?shiftId={testShift.Id}"); var result = await function.Run(request, NullLogger.Instance); result.Should().BeOfType <NotFoundResult>(); }
static DefaultHttpRequest GetHttpRequest(string method, string content = null, Dictionary <string, string> query = null) { var httpContext = new DefaultHttpContext(); if (content != null) { httpContext.Features.Get <IHttpRequestFeature>().Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)); } var request = new DefaultHttpRequest(httpContext) { Method = method }; if (query != null) { request.QueryString = new QueryString(QueryHelpers.AddQueryString("", query)); } return(request); }
public async Task Version_2018_12_16_Preview_Returns_Bad_Request_If_Version_0_2_Is_Requested() { var request = new DefaultHttpRequest(new DefaultHttpContext()) { Query = new QueryCollection(new Dictionary <string, Microsoft.Extensions.Primitives.StringValues> { }), }; var actual = await DeviceGetter.Run(request, NullLogger.Instance, new ExecutionContext(), ApiVersion.Version_2018_12_16_Preview); Assert.NotNull(actual); Assert.IsType <BadRequestObjectResult>(actual); var badRequestResult = (BadRequestObjectResult)actual; Assert.Equal("Incompatible versions (requested: '0.2 or earlier', current: '2018-12-16-preview')", badRequestResult.Value.ToString()); // Ensure current version is added to response Assert.Contains(ApiVersion.HttpHeaderName, request.HttpContext.Response.Headers); Assert.Equal("2018-12-16-preview", request.HttpContext.Response.Headers[ApiVersion.HttpHeaderName].FirstOrDefault()); }
public void EncodeChunkedContent() { IHttpRequest req = new DefaultHttpRequest(HttpVersion.Http11, HttpMethod.Post, "/"); HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(req, false); int length = 8077 + 8096; string longText = new string('a', length); encoder.AddBodyAttribute("data", longText); encoder.AddBodyAttribute("moreData", "abcd"); Assert.NotNull(encoder.FinalizeRequest()); while (!encoder.IsEndOfInput) { encoder.ReadChunk((IByteBufferAllocator)null).Release(); } Assert.True(encoder.IsEndOfInput); encoder.CleanFiles(); }
public void ShouldMapWithRequestShouldWorkCorrectly() { var request = new DefaultHttpRequest(new DefaultHttpContext()); request.Path = "/Normal/FromServicesAction"; MyMvc .Routes() .ShouldMap(request) .To<NormalController>(c => c.FromServicesAction(From.Services<IActionSelector>())); }
protected override void UninitializeHttpRequest(HttpRequest instance) { _pooledHttpRequest = instance as DefaultHttpRequest; _pooledHttpRequest?.Uninitialize(); }