Esempio n. 1
0
        public void SingleArrayOfObjectParam()
        {
            // Arrange
            var handler = new FakeHandler();
            var method  = handler.GetType().GetMethod("SingleArrayOfObjectParam");
            var miw     = new MethodInfoWrapper <FakeHandler>(method);
            var input   = new
            {
                queryData = new[] {
                    new FakeObject {
                        Prop1 = "val1", Prop2 = 10, Prop3 = 10.5
                    },
                    new FakeObject {
                        Prop1 = "val2", Prop2 = 20, Prop3 = 20.5
                    },
                    new FakeObject {
                        Prop1 = "val3", Prop2 = 30, Prop3 = 30.5
                    }
                }
            };

            // Act
            miw.BindValues(JObject.FromObject(input));
            dynamic output = miw.Invoke(handler);

            // Assert
            Assert.AreEqual(1, miw.MatchedParameters());
            Assert.AreEqual(input.queryData, output);
        }
Esempio n. 2
0
        public void ShouldTakeMimeTypeFromDownload()
        {
            var handler = new FakeHandler {
                RepeatLastHandler = true
            };
            var client  = new HttpClient(handler);
            var browser = new Browser(client)
            {
                AutoDownloadResources = true
            };

            handler.RequestHandlers.Add((request) =>
            {
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(File.ReadAllText("Content/simple_resources.html"))
                };
                response.Content.Headers.ContentType.MediaType = "text/html";
                return(response);
            });

            var page = browser.Open("http://example.com/simple_resources.html").Result;

            var resources = page.Resources.ToArray();

            resources.Length.Is(4);

            resources.Select(x => x.GuessMimeType.Split(';').First())
            .All(x => x == "text/html").IsTrue();


            handler.Requests.Count.Is(5);
        }
Esempio n. 3
0
        public void SubmitShouldCaptureAllFormFields()
        {
            var fakeHandler = new FakeHandler();
            var client = new HttpClient(fakeHandler);
            var browser = new Browser(client);


            fakeHandler.RequestHandlers.Add((request) => new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(File.ReadAllText("Content/simple_form.html"))
            });
            var page = browser.Open("http://google.com/testpage.html").Result;

            var form = page.GetForm("form");


            fakeHandler.RequestHandlers.Add((request) =>
            {
                var requestcontent = request.Content.ReadAsStringAsync().Result;

                requestcontent.Is("id=50&name=&email=&betreff=Hilfe&text=&submit=absenden");

                return new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("Everything worked if this is returned")
                };
            });

            var waitForRequestToFinish = form.Submit().Result;

            waitForRequestToFinish.ToString().Is("Everything worked if this is returned");

        }
        public async Task AccessTokenWithHeadersCredential()
        {
            var mockClock     = new MockClock();
            var tokenResponse = new TokenResponse
            {
                AccessToken      = "ACCESS_TOKEN",
                ExpiresInSeconds = 60 * 10,
                IssuedUtc        = DateTime.Now,
                RefreshToken     = "REFRESH_TOKEN",
            };
            var flowMock = new Mock <IAuthorizationCodeFlow>(MockBehavior.Strict);

            flowMock
            .Setup(flow => flow.Clock)
            .Returns(mockClock);
            flowMock
            .Setup(flow => flow.AccessMethod)
            .Returns(new AuthorizationHeaderAccessMethod());

            var         userCred = new UserCredential(flowMock.Object, "USER_ID", tokenResponse, "QUOTA_PROJECT");
            ICredential cred     = new GoogleCredential(userCred);

            var httpHandler = new FakeHandler();
            var httpClient  = new Http.ConfigurableHttpClient(new Http.ConfigurableMessageHandler(httpHandler));

            cred.Initialize(httpClient);
            await httpClient.GetAsync("http://localhost/TestRequest");

            Assert.Equal("Bearer", httpHandler.RequestHeaders.Authorization.Scheme);
            Assert.Equal("ACCESS_TOKEN", httpHandler.RequestHeaders.Authorization.Parameter);

            Assert.True(httpHandler.RequestHeaders.TryGetValues("x-goog-user-project", out var values));
            Assert.Single(values);
            Assert.Equal("QUOTA_PROJECT", values.First());
        }
        protected override async Task <Bus> Given()
        {
            _largeMessageBodyTempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Guid.NewGuid().ToString());

            _fakeHandler        = new FakeHandler(NumMessagesToSend);
            _dependencyResolver = new FakeDependencyResolver(_fakeHandler);
            _timeout            = TimeSpan.FromSeconds(300); //FIXME set to 30 seconds
            _typeProvider       = new TestHarnessTypeProvider(new[] { GetType().Assembly }, new[] { GetType().Namespace });

            _logger = TestHarnessLoggerFactory.Create();
            //_logger = new NullLogger();

            var largeMessageBodyStorage = new FileSystemStorageBuilder().Configure()
                                          .WithStorageDirectory(_largeMessageBodyTempPath)
                                          .WithLogger(_logger)
                                          .Build();

            var bus = new BusBuilder().Configure()
                      .WithNames("ThroughputTestSuite", Environment.MachineName)
                      .WithLogger(_logger)
                      .WithConnectionString(CommonResources.ServiceBusConnectionString)
                      .WithTypesFrom(_typeProvider)
                      .WithDependencyResolver(_dependencyResolver)
                      .WithLargeMessageStorage(c => c.WithLargeMessageBodyStore(largeMessageBodyStorage)
                                               .WithMaxSmallMessageSize(4096))
                      .WithDebugOptions(dc => dc.RemoveAllExistingNamespaceElementsOnStartup(
                                            "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                      .Build();
            await bus.Start();

            return(bus);
        }
        public async Task TestHttpClientWithRetryIntercept()
        {
            // The fake handler lets us track the number of 'actual' requests
            var innerHandler = new FakeHandler();

            var retryHandler = new RetryDelegatingHandler
            {
                InnerHandler   = innerHandler,
                RetryIntercept = async delegate(HttpRequestMessage request, HttpResponseMessage responseMessage)
                {
                    if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        // Predent we authenticate
                        var retryClient = new HttpClient(innerHandler);

                        var authorizeResponse = await retryClient.GetAsync("http://hello.world/authorize?a=bcd");

                        return(authorizeResponse.IsSuccessStatusCode);
                    }

                    return(false);
                }
            };

            var client = new HttpClient(retryHandler);

            var response = await client.GetAsync("http://hello.world/test");

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            Assert.AreEqual(1, innerHandler.FailedCount);
            Assert.AreEqual(1, innerHandler.AuthorizationAttempts);
            Assert.AreEqual(1, innerHandler.OkCount);
        }
        public async void TestHttpClientWithRetryIntercept()
        {
            // The fake handler lets us track the number of 'actual' requests
            var innerHandler = new FakeHandler();

            var retryHandler = new RetryDelegatingHandler
            {
                InnerHandler = innerHandler,
                RetryIntercept = async delegate(HttpResponseMessage responseMessage)
                {
                    if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        // Predent we authenticate
                        var retryClient = new HttpClient(innerHandler);

                        var authorizeResponse = await retryClient.GetAsync("http://hello.world/authorize?a=bcd");

                        return authorizeResponse.IsSuccessStatusCode;
                    }

                    return false;
                }
            };

            var client = new HttpClient(retryHandler);

            var response = await client.GetAsync("http://hello.world/test");

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            Assert.AreEqual(1, innerHandler.FailedCount);
            Assert.AreEqual(1, innerHandler.AuthorizationAttempts);
            Assert.AreEqual(1, innerHandler.OkCount);
        }
Esempio n. 8
0
        public void SingleObjectParam()
        {
            // Arrange
            var handler = new FakeHandler();
            var method  = handler.GetType().GetMethod("SingleObjectParam");
            var miw     = new MethodInfoWrapper <FakeHandler>(method);
            var input   = new FakeObject
            {
                Prop1 = "val1",
                Prop2 = 20,
                Prop3 = 20.5,
                Prop4 = true,
                Prop5 = DateTime.Now,
                Prop6 = new string[] { "va1", "val2", "val3" }
            };


            // Act
            miw.BindValues(JObject.FromObject(input));
            dynamic output = miw.Invoke(handler);

            // Assert
            Assert.AreEqual(1, miw.MatchedParameters());
            Assert.AreEqual(input, output);
        }
        public void ContainerQualifiedWildcardSelectItemIsNotImplemented()
        {
            FakeHandler handler = new FakeHandler();
            ContainerQualifiedWildcardSelectItem item = new ContainerQualifiedWildcardSelectItem(ModelBuildingHelpers.BuildValidEntityContainer());
            Action visitContainerQualifiedWildcard    = () => item.HandleWith(handler);

            visitContainerQualifiedWildcard.ShouldThrow <NotImplementedException>();
        }
        public void WildcardSelectItemIsNotImplemented()
        {
            FakeHandler        handler       = new FakeHandler();
            WildcardSelectItem item          = new WildcardSelectItem();
            Action             visitWildcard = () => item.HandleWith(handler);

            visitWildcard.ShouldThrow <NotImplementedException>();
        }
        public void Execute_AllHandlersAreCalled()
        {
            var handler = new FakeHandler();

            _handlers.Add(handler);

            _action.Execute(_args);

            Assert.That(handler.Called, Is.True);
        }
        public void DispatchEventWhenTheUserIsTheFacilitator()
        {
            MeetingService service = CreateService();
            Meeting        meeting = service.CreateMeeting(facilitatorId);


            service.EnableAnswersOfTheCurrentQuestion(meeting.Id, facilitatorId);


            Assert.True(FakeHandler.MeetingWasNotified(meeting.Id));
        }
        public void ExpandedNavigationPropertySelectItemIsNotImplemented()
        {
            FakeHandler handler = new FakeHandler();
            ExpandedNavigationSelectItem item = new ExpandedNavigationSelectItem(new ODataExpandPath()
            {
                new NavigationPropertySegment(ModelBuildingHelpers.BuildValidNavigationProperty(), ModelBuildingHelpers.BuildValidEntitySet())
            }, null, null);
            Action visitExpandedNavigationSelectItem = () => item.HandleWith(handler);

            visitExpandedNavigationSelectItem.ShouldThrow <NotImplementedException>();
        }
            public void MethodsMatchingCustomNameAreIncluded()
            {
                var attribute = new HandleByConventionAttribute { MethodName = "Custom" };
                var handleMethods = attribute.GetHandleMethods(typeof(FakeHandler), new Mock<IServiceProvider>().Object);
                var handleMethod = handleMethods.Single().Value;
                var handler = new FakeHandler();

                handleMethod(handler, new FakeEvent());

                Assert.True(handler.Handled);
            }
        public void PathSelectionItemIsNotImplemented()
        {
            FakeHandler    handler = new FakeHandler();
            PathSelectItem item    = new PathSelectItem(new ODataSelectPath()
            {
                new PropertySegment(ModelBuildingHelpers.BuildValidPrimitiveProperty())
            });
            Action visitPath = () => item.HandleWith(handler);

            visitPath.ShouldThrow <NotImplementedException>();
        }
Esempio n. 16
0
        public void RouteWithMessageHandler()
        {
            var fakeHandler = new FakeHandler();

            var root = new ApiRouter("").WithHandler(fakeHandler).To <FakeController>();

            var httpClient = new HttpClient(new FakeServer(root));

            var response = httpClient.GetAsync("http://localhost/").Result;

            Assert.True(fakeHandler.WasCalled);
        }
        public void NotDispatchEventWhenTheUserIsNotTheFacilitator()
        {
            Guid           userId  = Guid.NewGuid();
            MeetingService service = CreateService();
            Meeting        meeting = service.CreateMeeting(facilitatorId);


            service.EnableAnswersOfTheCurrentQuestion(meeting.Id, userId);


            Assert.False(FakeHandler.MeetingWasNotified(meeting.Id));
        }
Esempio n. 18
0
        public void When_I_receive_a_command_I_should_raise_created_event()
        {
            // Assign
            const string correlationId = "correlationidexample-123";
            const string testString    = "test";
            var          cmd           = new CreateFakeCommand(correlationId, testString);

            // Act
            var results = new FakeHandler().Handle(cmd);

            // Assert
            Assert.IsTrue(((FakeAggregateCreated)results.UncommitedEvents().First()).TestString.Equals(testString));
        }
            public void MethodsMatchingCustomNameAreIncluded()
            {
                var attribute = new HandleByConventionAttribute {
                    MethodName = "Custom"
                };
                var handleMethods = attribute.GetHandleMethods(typeof(FakeHandler), new Mock <IServiceProvider>().Object);
                var handleMethod  = handleMethods.Single().Value;
                var handler       = new FakeHandler();

                handleMethod(handler, new FakeEvent());

                Assert.True(handler.Handled);
            }
Esempio n. 20
0
        public async Task ShouldRoute()
        {
            var handler = new FakeHandler();
            var route   = new Route <Ping, Pong>("/Ping");
            var request = new FakeRequest();

            request.Services.Add(typeof(IRouteRequestHandler <Ping, Pong>), handler);
            var media = new FakeMedia();

            await route.Send(media, request);

            Assert.IsTrue(media.HasRead);
            Assert.IsTrue(media.HasWritten);
            Assert.IsTrue(handler.HasHandled);
        }
Esempio n. 21
0
        public void MapObjectToSingleStringParam_NoParameterShouldMatch()
        {
            // Arrange
            var handler = new FakeHandler();
            var method  = handler.GetType().GetMethod("OneStringParam");
            var miw     = new MethodInfoWrapper <FakeHandler>(method);
            var input   = new { test1 = "value1", test2 = "value2" };

            // Act
            miw.BindValues(JObject.FromObject(input));
            dynamic output = miw.Invoke(handler);

            // Assert
            Assert.AreEqual(0, miw.MatchedParameters());
        }
        public async Task Intercepts_NoQuotaProject(GoogleCredential credential)
        {
            HttpRequestHeaders headers;

            using (var interceptor = new FakeHandler())
                using (var httpClient = new ConfigurableHttpClient(new ConfigurableMessageHandler(interceptor)))
                {
                    ((IConfigurableHttpClientInitializer)credential).Initialize(httpClient);
                    await httpClient.GetAsync("http://will.be.ignored");

                    headers = interceptor.RequestHeaders;
                }

            Assert.DoesNotContain(headers, h => h.Key == QuotaProjectHeaderKey);
        }
Esempio n. 23
0
        public void OneStringParam()
        {
            // Arrange
            var handler = new FakeHandler();
            var method  = handler.GetType().GetMethod("OneStringParam");
            var miw     = new MethodInfoWrapper <FakeHandler>(method);
            var input   = new { param1 = "value1" };

            // Act
            miw.BindValues(JObject.FromObject(input));
            dynamic output = miw.Invoke(handler);

            // Assert
            Assert.AreEqual(1, miw.MatchedParameters());
            Assert.AreEqual(input.param1, output.param1);
        }
        public async Task Intercepts_WithQuotaProject(GoogleCredential credential)
        {
            credential = credential.CreateWithQuotaProject("my-billing-project");

            HttpRequestHeaders headers;

            using (var interceptor = new FakeHandler())
                using (var httpClient = new ConfigurableHttpClient(new ConfigurableMessageHandler(interceptor)))
                {
                    ((IConfigurableHttpClientInitializer)credential).Initialize(httpClient);
                    await httpClient.GetAsync("http://will.be.ignored");

                    headers = interceptor.RequestHeaders;
                }

            AssertContainsQuotaProject(headers, "my-billing-project");
        }
        public async Task AccessTokenCredential()
        {
            const string fakeAccessToken = "FakeAccessToken";
            // Create an access-token credential, and check the access token is correct.
            ICredential cred = GoogleCredential.FromAccessToken(fakeAccessToken);

            Assert.Equal(fakeAccessToken, await cred.GetAccessTokenForRequestAsync());
            // Check the auth header is added correctly to an HTTP request.
            var httpHandler = new FakeHandler();
            var httpClient  = new Http.ConfigurableHttpClient(new Http.ConfigurableMessageHandler(httpHandler));

            cred.Initialize(httpClient);
            await httpClient.GetAsync("http://localhost/TestRequest");

            Assert.Equal("Bearer", httpHandler.RequestHeaders.Authorization.Scheme);
            Assert.Equal(fakeAccessToken, httpHandler.RequestHeaders.Authorization.Parameter);
        }
        public void NotDispatchEventWhenAnyUsersNotAnswerTheQuestion()
        {
            Guid           firstUserId  = Guid.NewGuid();
            Guid           secondUserId = Guid.NewGuid();
            MeetingService service      = CreateService();
            Meeting        meeting      = service.CreateMeeting(facilitatorId);

            service.JoinTheMeeting(meeting.Id, firstUserId);
            service.JoinTheMeeting(meeting.Id, secondUserId);
            service.EnableAnswersOfTheCurrentQuestion(meeting.Id, facilitatorId);


            service.AnswerTheCurrentQuestion(meeting.Id, firstUserId, Answer.Green, annotation: null);


            Assert.False(FakeHandler.MeetingWasNotified(meeting.Id));
        }
Esempio n. 27
0
        public async Task Test1()
        {
            var requests = new List <HttpRequestMessage>();
            var handler  = new FakeHandler();

            handler.Sending += (s, e) =>
            {
                requests.Add(e.Request);
            };
            var clt      = new SoapClient(handler);
            var response = await clt.InvokeAsync("https://example.com", new SoapRequestParameters());

            Assert.Single(requests);
            var r = requests.First();

            Assert.Equal(HttpMethod.Post, r.Method);
            Assert.Equal(new Uri("https://example.com"), r.RequestUri);
        }
Esempio n. 28
0
        public async Task GetStatusInfoAsync_Test1()
        {
            var expected = new ConnectionStatusInfo
            {
                ConnectionStatus    = ConnectionStatus.Connected,
                LastConnectionError = ConnectionError.ERROR_NONE,
                Uptime = 1000,
            };
            var handler = new FakeHandler();

            handler.Sending += (s, e) => { e.Response.Content = new StringContent(expected.ToXmlContent()); };

            var clt    = new WANPPPConnectionClient("https://fritz.box", 5000, handler);
            var actual = await clt.GetStatusInfoAsync();

            Assert.Equal(expected.ConnectionStatus, actual.ConnectionStatus);
            Assert.Equal(expected.LastConnectionError, actual.LastConnectionError);
            Assert.Equal(expected.Uptime, actual.Uptime);
        }
Esempio n. 29
0
        public async void TestHttpClientWithoutIntercept()
        {
            var innerHandler = new FakeHandler();

            var retryHandler = new RetryDelegatingHandler
            {
                InnerHandler = innerHandler
            };

            var client = new HttpClient(retryHandler);

            var response = await client.GetAsync("http://hello.world/test");

            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);

            Assert.AreEqual(1, innerHandler.FailedCount);
            Assert.AreEqual(0, innerHandler.AuthorizationAttempts);
            Assert.AreEqual(0, innerHandler.OkCount);
        }
        public async Task TestHttpClientWithoutIntercept()
        {
            var innerHandler = new FakeHandler();

            var retryHandler = new RetryDelegatingHandler
            {
                InnerHandler = innerHandler
            };

            var client = new HttpClient(retryHandler);

            var response = await client.GetAsync("http://hello.world/test");

            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);

            Assert.AreEqual(1, innerHandler.FailedCount);
            Assert.AreEqual(0, innerHandler.AuthorizationAttempts);
            Assert.AreEqual(0, innerHandler.OkCount);
        }
Esempio n. 31
0
        public async Task GetConnectionTypeInfoAsync_Test1()
        {
            var expected = new ConnectionTypeInfo
            {
                ConnectionType          = ConnectionType.IP_Routed,
                PossibleConnectionTypes = PossibleConnectionTypes.IP_Routed | PossibleConnectionTypes.IP_Bridged,
            };

            {
                var s = expected.ToXmlContent();
            }

            var handler = new FakeHandler();

            handler.Sending += (s, e) => { e.Response.Content = new StringContent(expected.ToXmlContent()); };

            var clt    = new WANPPPConnectionClient("https://fritz.box:453", 5000, handler);
            var actual = await clt.GetConnectionTypeInfoAsync();
        }
Esempio n. 32
0
        public async Task ShouldMatchRoute()
        {
            var handler = new FakeHandler();
            var route   = new FakeRoute()
            {
                Path = "/Ping"
            };
            var request = new FakeRequest()
            {
                Path = "/Ping"
            };
            var media = new FakeMedia();

            var router = new Router(new[] { route }, new[] { media });

            await router.RouteRequest(request);

            Assert.IsTrue(request.IsHandled);
            Assert.IsTrue(route.HasSent);
        }
Esempio n. 33
0
        public void MultiTypeParam()
        {
            // Arrange
            var handler = new FakeHandler();
            var method  = handler.GetType().GetMethod("MultiTypeParam");
            var miw     = new MethodInfoWrapper <FakeHandler>(method);
            var input   = new {
                param1 = "value1",
                param2 = 10,
                param3 = 10.50,
                param4 = true,
                param5 = DateTime.Now,
                param6 = new List <string> {
                    "value1", "value2", "value3"
                },
                param7 = new FakeObject
                {
                    Prop1 = "val1",
                    Prop2 = 20,
                    Prop3 = 20.5,
                    Prop4 = true,
                    Prop5 = DateTime.Now,
                    Prop6 = new string[] { "va1", "val2", "val3" }
                }
            };

            // Act
            miw.BindValues(JObject.FromObject(input));
            dynamic output = miw.Invoke(handler);

            // Assert
            Assert.AreEqual(7, miw.MatchedParameters());
            Assert.AreEqual(input.param1, output.param1);
            Assert.AreEqual(input.param2, output.param2);
            Assert.AreEqual(input.param3, output.param3);
            Assert.AreEqual(input.param4, output.param4);
            Assert.AreEqual(input.param5, output.param5);
            Assert.AreEqual(input.param6, output.param6);
            Assert.AreEqual(input.param7, output.param7);
        }
Esempio n. 34
0
        public void TestHttpClientWithRetryIntercept()
        {
            var interceptCount = 0;

            var innerHandler = new FakeHandler();

            var provider = new HttpClientProvider
                           {
                               RetryIntercept = delegate
                                                      {
                                                          interceptCount++;
                                                          return Task.FromResult(false);
                                                      }
            };

            var client = provider.Create(innerHandler);

            client.GetAsync("http://hello.world/boo");

            Assert.AreEqual(1, interceptCount);
            Assert.AreEqual(1, innerHandler.RequestCount);
        }
        public void TestHttpClientWithRetryInterceptWhenShouldRetry()
        {
            var interceptCount = 0;

            var innerHandler = new FakeHandler();

            var provider = new HttpClientProvider
                           {
                               RetryIntercept = async delegate
                                   {
                                       interceptCount++;
                                       return true;
                                   }
                           };

            var client = provider.Create(innerHandler);

            client.GetAsync("http://hello.world/boo");

            Assert.AreEqual(1, interceptCount);
            Assert.AreEqual(2, innerHandler.RequestCount);
        }
Esempio n. 36
0
 public FakeDependencyResolver(FakeHandler fakeHandler)
 {
     _fakeHandler = fakeHandler;
 }