public void Loop_CustomInterceptor() { //Arrange const string initialValue = "33"; var maxInt = int.MaxValue.ToString(CultureInfo.InvariantCulture); var initialValues = new List <string> { "1", "2", "3", "4", maxInt, "6" }; var request = new RequestMock(initialValue, RequestStepMock.Step1, initialValues, new TimeSpan(0, 0, 3)); var customErrorHandler = new SubErrorHandlerMock(); var interceptor = new SubInterceptorMock(); const RequestStepMock passedSteps = RequestStepMock.Step1 | RequestStepMock.Step2 | RequestStepMock.Step3 | RequestStepMock.Step4 | RequestStepMock.Step5; //Act RequestPipelineMock.ExecuteLoop(request, new TimeSpan(0, 0, 2), null, null, customErrorHandler, interceptor); //Assert Assert.IsTrue(request.Done, "Заявка должна была дойти до конца."); Assert.IsFalse(interceptor.DefaultMethod, "Должен был отработать кастомный интерсептор."); Assert.AreEqual(interceptor.LastStep, passedSteps, "Должны перехватываться все предыдущие шаги в цепочке."); }
public void InvokeChain_CustomErrorHandler() { //Arrange var initialValue = int.MaxValue.ToString(CultureInfo.InvariantCulture); var request = new RequestMock(initialValue, RequestStepMock.Step1); var defaultHandler = new ErrorHandlerMock(); var customHandler = new ErrorHandlerMock(); //Act RequestPipelineMock.ExecuteChain( request, new TimeSpan(0, 0, 2), TimeoutLifetime.Step, defaultHandler, customErrorHandler: customHandler); //Assert Assert.IsFalse(request.Done, "Цепочка вызовов не должна была дойти до конца."); Assert.AreEqual(request.StrValue, initialValue, "Инициализация не выполнилась."); Assert.IsNull(defaultHandler.Error, "Обработчик по умолчанию не должен был отработать."); Assert.IsNotNull(customHandler.Error, "Кастомный обработчик отработал неправильно."); Assert.IsTrue(customHandler.Error is OverflowException, "IStepExecutor должен возвращать исходную ошибку."); Assert.IsTrue(customHandler.Error.Message == "Arithmetic operation resulted in an overflow."); }
public void InvokeChain_Continue() { //Arrange const string initialValue = "11"; var request = new RequestMock(initialValue, RequestStepMock.Step3) { Value = 6 }; var customHandler = new ErrorHandlerMock(); var interceptor = new InterceptorMock(); const RequestStepMock passedSteps = RequestStepMock.Step3 | RequestStepMock.Step4 | RequestStepMock.Done; //Act RequestPipelineMock.ExecuteChain(request, new TimeSpan(0, 60, 1), TimeoutLifetime.Step, null, null, customHandler, interceptor); //Assert Assert.IsNull(customHandler.Error, "Ошибок быть не должно."); Assert.IsFalse(interceptor.DefaultMethod, "Должен был отработать кастомный интерсептор."); Assert.IsTrue(request.Default == initialValue, "Заявка должна быть правильно прионициализированна."); Assert.IsTrue(request.StrValue.IsNullOrEmpty(), "Первый шаг не должен был пройти"); Assert.IsTrue(request.Value == 12, "Неправильный результат заявки."); Assert.AreEqual(interceptor.LastStep, passedSteps, "Должны перехватываться все предыдущие шаги в цепочке."); }
public void InvokeChain() { //Arrange var request = new RequestMock("3", RequestStepMock.Step1); //Act RequestPipelineMock.ExecuteChain(request, new TimeSpan(0, 0, 2), TimeoutLifetime.Step); //Assert Assert.IsTrue(request.Done, "Цепочка вызовов не дошла до конца."); Assert.AreEqual(request.StrValue, "3", "Инициализация не выполнилась."); Assert.AreEqual(request.Value, 6, "Парсинг или умножение прошло не по плану"); }
public void InvokeChain_Timeout() { //Arrange const string initialValue = "33"; var request = new RequestMock(initialValue, RequestStepMock.Step1, null, new TimeSpan(0, 0, 2)); var customHandler = new ErrorHandlerMock(); //Act RequestPipelineMock.ExecuteChain(request, new TimeSpan(0, 0, 1), TimeoutLifetime.Step, customErrorHandler: customHandler); //Assert Assert.IsFalse(request.Done, "Цепочка вызовов не должна была дойти до конца."); Assert.IsNotNull(customHandler.Error, "Кастомный обработчик отработал неправильно."); Assert.IsTrue(customHandler.Error is OperationCanceledException, "IStepExecutor должен возвращать исходную ошибку."); Assert.IsTrue(customHandler.Error.Message == "The operation was canceled."); }
public void ExecuteSubFunction_WithPostRequest() { PrivateInvoke.SetNonPublicField(FunctionState, "_postBackID", 100); RequestMock.Stub(stub => stub.HttpMethod).Return("POST").Repeat.Any(); using (MockRepository.Ordered()) { ExecutionStateContextMock.Expect(mock => mock.SetReturnState(SubFunction, false, null)); ExecutionStateContextMock.Expect(mock => mock.SetExecutionState(NullExecutionState.Null)); } MockRepository.ReplayAll(); _executionState.ExecuteSubFunction(WxeContext); MockRepository.VerifyAll(); }
public void Loop_AllOk() { //Arrange const string initialValue = "33"; var initialValues = new List <string> { "1", "2", "9", "4", "5", "6" }; var request = new RequestMock(initialValue, RequestStepMock.Step1, initialValues, new TimeSpan(0, 0, 2)); //Act RequestPipelineMock.ExecuteLoop(request, new TimeSpan(0, 0, 3)); //Assert Assert.IsTrue(request.Done, "Заявка должна была дойти до конца."); Assert.IsFalse(request.Strings == null || request.Strings.Count < 1, "Инициализация строк прошла неудачно."); Assert.IsFalse(request.Values == null || request.Values.Count < 1, "Цикл не прошел совсем."); Assert.IsTrue(request.Strings.Count == request.Values.Count, "Количество строк и значений различаются."); }
public void InvokeChain_DefaultErrorHandler() { //Arrange var initialValue = int.MaxValue.ToString(CultureInfo.InvariantCulture); var request = new RequestMock(initialValue, RequestStepMock.Step1); var handler = new ErrorHandlerMock(); //Act RequestPipelineMock.ExecuteChain(request, new TimeSpan(0, 0, 2), TimeoutLifetime.Step, handler); //Assert Assert.IsFalse(request.Done, "Цепочка вызовов не должна была дойти до конца."); Assert.AreEqual(request.StrValue, initialValue, "Инициализация не выполнилась."); Assert.IsNull(request.Error, "Кастомный обработчик не должен был обработать исключение."); Assert.IsNotNull(handler.Error, "Исключение перехватить не удалось."); Assert.IsTrue(handler.Error is OverflowException, "Исполнитель должен возвращать исходную ошибку."); Assert.IsTrue(handler.Error.Message == "Arithmetic operation resulted in an overflow."); }
public void ExecuteSubFunction_WithGetRequest() { PrivateInvoke.SetNonPublicField(FunctionState, "_postBackID", 100); RequestMock.Stub(stub => stub.HttpMethod).Return("GET").Repeat.Any(); using (MockRepository.Ordered()) { ExecutionStateContextMock.Expect(mock => mock.SetReturnState(SubFunction, true, PostBackCollection)); ExecutionStateContextMock.Expect(mock => mock.SetExecutionState(NullExecutionState.Null)); } MockRepository.ReplayAll(); _executionState.ExecuteSubFunction(WxeContext); MockRepository.VerifyAll(); Assert.That(PostBackCollection[WxePageInfo.PostBackSequenceNumberID], Is.EqualTo("100")); }
public override void SetUp () { base.SetUp(); UrlMappingConfiguration.Current.Mappings.Add (new UrlMappingEntry (RootFunction.GetType(), "~/root.wxe")); UrlMappingConfiguration.Current.Mappings.Add (new UrlMappingEntry (SubFunction.GetType(), "~/sub.wxe")); Uri uri = new Uri ("http://localhost/root.wxe"); ResponseMock.Stub (stub => stub.ApplyAppPathModifier ("~/sub.wxe")).Return ("/session/sub.wxe").Repeat.Any(); ResponseMock.Stub (stub => stub.ApplyAppPathModifier ("/session/sub.wxe")).Return ("/session/sub.wxe").Repeat.Any (); ResponseMock.Stub (stub => stub.ApplyAppPathModifier ("~/root.wxe")).Return ("/session/root.wxe").Repeat.Any (); ResponseMock.Stub (stub => stub.ApplyAppPathModifier ("/root.wxe")).Return ("/session/root.wxe").Repeat.Any(); ResponseMock.Stub (stub => stub.ApplyAppPathModifier ("/session/root.wxe")).Return ("/session/root.wxe").Repeat.Any(); ResponseMock.Stub (stub => stub.ContentEncoding).Return (Encoding.Default).Repeat.Any(); RequestMock.Stub (stub => stub.Url).Return (uri).Repeat.Any(); RequestMock.Stub (stub => stub.ContentEncoding).Return (Encoding.Default).Repeat.Any(); }
public void InvokeChain_DefaultInterceptor() { //Arrange const string initialValue = "11"; var request = new RequestMock(initialValue, RequestStepMock.Step1, null, new TimeSpan(0, 0, 2)); var customHandler = new ErrorHandlerMock(); var interceptor = new InterceptorMock(); const RequestStepMock passedSteps = RequestStepMock.Step1 | RequestStepMock.Step2 | RequestStepMock.Step3 | RequestStepMock.Step4; //Act RequestPipelineMock.ExecuteChain(request, new TimeSpan(0, 0, 1), TimeoutLifetime.Step, null, interceptor, customHandler); //Assert Assert.IsNotNull(customHandler.Error, "Кастомный обработчик отработал неправильно."); Assert.IsTrue(customHandler.Error is OperationCanceledException, "IStepExecutor должен возвращать исходную ошибку."); Assert.IsFalse(interceptor.DefaultMethod, "Должен был отработать кастомный интерсептор."); Assert.AreEqual(interceptor.LastStep, passedSteps, "Должны перехватываться все предыдущие шаги в цепочке."); }
public void Loop_CustomErrorHandler() { //Arrange const string initialValue = "33"; var maxInt = int.MaxValue.ToString(CultureInfo.InvariantCulture); var initialValues = new List <string> { "1", "2", "3", "4", maxInt, "6" }; var request = new RequestMock(initialValue, RequestStepMock.Step1, initialValues, new TimeSpan(0, 0, 3)); var customErrorHandler = new SubErrorHandlerMock(); //Act RequestPipelineMock.ExecuteLoop(request, new TimeSpan(0, 0, 2), null, customErrorHandler: customErrorHandler); //Assert Assert.IsTrue(request.Done, "Заявка должна была дойти до конца."); Assert.IsFalse(request.Strings == null || request.Strings.Count < 1, "Инициализация строк прошла неудачно."); Assert.IsFalse(request.Values == null || request.Values.Count < 1, "Цикл не прошел совсем."); Assert.IsTrue(request.Values.Count == request.Strings.Count - 2, "При возникновении ошибки цикл должен пережодить на следующую итерацию."); Assert.IsTrue(customErrorHandler.Errors.Count == 2, "Цикл должен обрабатывать ошибки каждой итерации."); Assert.IsTrue(customErrorHandler.Errors[0] is OperationCanceledException, "Сначала должен быть таймаут"); Assert.IsTrue(customErrorHandler.Errors[1] is OverflowException, "Потом должено быть переполнение"); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var httpResponse = new HttpResponseMessage(this.serverRequestsState.DefaultRespondStatusCode); string requestContent = await request.Content.ReadAsStringAsync(); RequestMock requestMock = this.FindExpectationForRequest(request, requestContent); // ?? this.FindBehaviorForRequest(request, requestContent); if (requestMock != null) { if (requestMock.IsRequestTimedOut) { Thread.Sleep(120000); return(httpResponse); } BuildResponseFromRequestMock(requestMock, request, ref httpResponse); return(httpResponse); } this.AddUnexpectedRequest(request); return(httpResponse); }
public void SetUp() { responseMock = new ResponseMock(); requestMock = new RequestMock(responseMock); requestFactoryMock = new RequestFactoryMock(requestMock); }
public static RequestMock ArrangePut(this RequestMock requestMock, Action <IRequestBuilder, IResponseBuilder> configure) { return(requestMock.Arrange("PUT", configure)); }
////private RequestMock FindBehaviorForRequest(HttpRequestMessage request, string requestContent) ////{ //// foreach (var behavior in this.serverRequestsState.RequestBehaviors) //// { //// if (!IsMockForRequest(behavior, request, requestContent)) //// { //// continue; //// } //// behavior.IncrementRequestMockCall(); //// return behavior; //// } //// return null; ////} private static void BuildResponseFromRequestMock(RequestMock mock, HttpRequestMessage httpRequest, ref HttpResponseMessage httpResponse) { if (mock.Response.ResponseBuilder != null) { httpResponse = mock.Response.ResponseBuilder(httpRequest); return; } httpResponse.StatusCode = mock.Response.ResponseStatusCode; if (mock.Response.ResponseContent != null) { // TODO: In the future it must return any content type. if (Helper.IsJsonRequest(mock.Response.ResponseContentType)) { string responseContent; if (mock.Response.ResponseContent is string) { responseContent = ((string)mock.Response.ResponseContent); } else { responseContent = JsonConvert.SerializeObject(mock.Response.ResponseContent); } httpResponse.Content = new StringContent(responseContent, Encoding.UTF8, ConvertFromHContentTypeToString(HttpRequestContentType.Json)); } else if (Helper.IsXmlRequest(mock.Response.ResponseContentType)) { // TODO: Shit code. It must be improved. At this moment, it works but it's a shit. // ---------------------------------------------------------------------------------------------------------------------- string responseContent; if (mock.Response.ResponseContent is string) { responseContent = ((string)mock.Response.ResponseContent); } else { responseContent = JsonConvert.SerializeObject(mock.Response.ResponseContent); responseContent = JsonConvert.DeserializeXNode(responseContent, "Root").ToString(); } httpResponse.Content = new StringContent(responseContent, Encoding.UTF8, ConvertFromHContentTypeToString(HttpRequestContentType.Xml)); // ---------------------------------------------------------------------------------------------------------------------- } else { // TODO: Throw an exception??? } } else { httpResponse.Content = new ByteArrayContent(new byte[0]); } foreach (var responseHeader in mock.Response.ResponseHeaders) { if (httpResponse.Headers.TryAddWithoutValidation(responseHeader.Key, responseHeader.Value) == false) { if (httpResponse.Content != null && httpResponse.Content.Headers != null) { httpResponse.Content.Headers.TryAddWithoutValidation(responseHeader.Key, responseHeader.Value); } } } }
public void MemcacheSocketTest([Values(0, 2, 10)] int maxByteSentByServer) { using (var serverMock = new ServerMock()) { var endPoint = serverMock.ListenEndPoint; serverMock.MaxSent = maxByteSentByServer; // random header var requestHeader = new MemcacheRequestHeader { Cas = 1, DataType = 2, ExtraLength = 5, KeyLength = 3, Opaque = 42, Opcode = Opcode.Increment, TotalBodyLength = 12, }; // body with the size defined in the header var requestBody = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; // build the request buffer var requestBuffer = new byte[MemcacheRequestHeader.Size + requestHeader.TotalBodyLength]; requestHeader.ToData(requestBuffer); Array.Copy(requestBody, 0, requestBuffer, MemcacheRequestHeader.Size, requestHeader.TotalBodyLength); // build the response header var responseHeader = new MemcacheResponseHeader { Cas = 8, DataType = 12, ExtraLength = 3, KeyLength = 0, // must be the same or it will crash : TODO add a test to ensure we detect this fail Opaque = requestHeader.Opaque, Status = Status.UnknownCommand, Opcode = Opcode.Prepend, TotalBodyLength = 15, }; // body with the size defined in the header var responseExtra = new byte[] { 1, 2, 3 }; var responseMessage = new byte[] { 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; // build the request buffer var responseBody = new byte[responseHeader.TotalBodyLength]; Array.Copy(responseExtra, 0, responseBody, 0, responseHeader.ExtraLength); Array.Copy(responseMessage, 0, responseBody, responseHeader.ExtraLength, responseHeader.TotalBodyLength - responseHeader.ExtraLength); // set the things to answer to the server serverMock.ResponseBody = responseBody; responseHeader.ToData(serverMock.ResponseHeader); var request = new RequestMock { QueryBuffer = requestBuffer, RequestId = requestHeader.Opaque /*ResponseHeader = responseHeader, * Message = responseMessage, * Extra = responseExtra,*/ }; using (var transport = new MemcacheTransport(endPoint, new MemcacheClientConfiguration(), _ => { }, _ => { }, false, null)) { Assert.IsTrue(transport.TrySend(request)); Assert.IsTrue(request.Mutex.Wait(TimeSpan.FromSeconds(10)), "The request has not been completed on less than 10 sec"); // and now, assert that we sent what we had to send and we received what the server sent Assert.AreEqual(requestHeader, serverMock.LastReceivedHeader, "Sent header differ from header received by the server"); CollectionAssert.AreEqual(requestBody, serverMock.LastReceivedBody, "Sent body is different than received by the server"); Assert.AreEqual(responseHeader, request.ResponseHeader, "Received header differ from header sent by the server"); CollectionAssert.AreEqual(responseExtra, request.Extra, "Received extra is different than sent by the server"); CollectionAssert.AreEqual(responseMessage, request.Message, "Received message is different than sent by the server"); } } }
public RequestFactoryMock(RequestMock requestMock) { this.requestMock = requestMock; }
public static RequestMock ArrangeAny(this RequestMock requestMock, Action <IRequestBuilder, IResponseBuilder> configure) { return(requestMock.Arrange(RequestMock.AnyMethod, configure)); }
public static RequestMock ArrangeDelete(this RequestMock requestMock, Action <IRequestBuilder, IResponseBuilder> configure) { return(requestMock.Arrange("DELETE", configure)); }
private static bool IsMockForRequest(RequestMock mock, HttpRequestMessage request, string requestContent) { // It checks if the request method is the expected. if (mock.RequestHttpMethod.ToString() != request.Method.Method) { return(false); } // It validates the URI. if (mock.IsRequestUriARegex) { if (!mock.RequestRegex.IsMatch(request.RequestUri.PathAndQuery)) { return(false); } } else { // https://msdn.microsoft.com/en-us/library/system.uri.pathandquery(v=vs.110).aspx var comparisonResult = Uri.Compare( mock.RequestUri, request.RequestUri, UriComponents.PathAndQuery, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase); if (comparisonResult != 0) { return(false); } // https://msdn.microsoft.com/en-us/library/system.uri.userinfo(v=vs.110).aspx comparisonResult = Uri.Compare( mock.RequestUri, request.RequestUri, UriComponents.UserInfo, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase); if (comparisonResult != 0) { return(false); } // https://msdn.microsoft.com/en-us/library/system.uri.fragment(v=vs.110).aspx comparisonResult = Uri.Compare( mock.RequestUri, request.RequestUri, UriComponents.Fragment, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase); if (comparisonResult != 0) { return(false); } } // It validates the request headers. foreach (var expectedHeader in mock.ExpectedRequestHeaders) { IEnumerable <string> headerValues; if (request.Headers.TryGetValues(expectedHeader.Key, out headerValues) || request.Content.Headers.TryGetValues(expectedHeader.Key, out headerValues)) { if (headerValues.Contains(expectedHeader.Value)) { continue; } } return(false); } // It validates the request content type. if (string.IsNullOrWhiteSpace(mock.ExpectedRequestContentType) == false) { if (request.Content.Headers.ContentType == null) { return(false); } var expectedContentTypes = mock.ExpectedRequestContentType.Split(','); if (!expectedContentTypes.Contains(request.Content.Headers.ContentType.ToString())) { return(false); } ////if (!request.Content.Headers.ContentType.Equals(new MediaTypeHeaderValue(mock.ExpectedRequestContentType))) ////{ //// return false; ////} } // It validates the expected request content. // TODO: At this moment, it only compares JSON requests, in the future, it should be able to compare XML, FormUrlEncode and Text requests. if (mock.ExpectedRequestContent != null) { if (string.IsNullOrWhiteSpace(requestContent)) { return(false); } if (Helper.IsJsonRequest(request.Content.Headers.ContentType.ToString())) { var requestJson = JToken.Parse(requestContent); JToken expectedJson; if (mock.ExpectedRequestContent is string) { expectedJson = JToken.Parse(((string)mock.ExpectedRequestContent)); } else { expectedJson = JToken.FromObject(mock.ExpectedRequestContent); } if (!JToken.DeepEquals(requestJson, expectedJson)) { return(false); } } else if (Helper.IsXmlRequest(request.Content.Headers.ContentType.ToString())) { // TODO: Shit code. It must be improved. At this moment, it works but it's a shit. // ---------------------------------------------------------------------------------------------------------------------- JToken expectedJson; if (mock.ExpectedRequestContent is string) { var xmlContent = XDocument.Parse((string)mock.ExpectedRequestContent); expectedJson = JToken.Parse(JsonConvert.SerializeXNode(xmlContent.Root)).First.First; } else { var xmlContent = JsonConvert.DeserializeXNode(JsonConvert.SerializeObject(mock.ExpectedRequestContent), "Root"); expectedJson = JToken.Parse(JsonConvert.SerializeXNode(xmlContent.Root)).First.First; } var requestJson = JToken.Parse(JsonConvert.SerializeXNode(XDocument.Parse(requestContent))).First.First; if (!JToken.DeepEquals(requestJson, expectedJson)) { return(false); } // ---------------------------------------------------------------------------------------------------------------------- } else { if (mock.ExpectedRequestContent is string) { if (requestContent != mock.ExpectedRequestContent.ToString()) { return(false); } } // TODO: Throw an exception??? } ////case HContentType.FormUrlEncoded: //// { //// // TODO: Shit code. It must be improved. At this moment, it works but it's a shit. //// // ---------------------------------------------------------------------------------------------------------------------- //// var urlEncodedContent = request.Content.ReadAsFormDataAsync().Result; //// for (int i = 0; i < urlEncodedContent.Count; i++) //// { //// } //// var json = JToken.Parse(JsonConvert.SerializeObject(urlEncodedContent)); //// break; //// // ---------------------------------------------------------------------------------------------------------------------- //// } } // It executes the custom request validator configured by the user. if (mock.RequestValidator != null && !mock.RequestValidator(request)) { return(false); } return(true); }