Пример #1
0
        public async Task CaptureAndFakeResponsesMatch()
        {
            // store the rest response in a subfolder of the solution directory for future use
            var captureFolder = Path.Combine(TestContext.TestRunDirectory, @"..\..\FakeResponses\");

            var capturingHandler = new CapturingHttpClientHandler(new FileSystemResponseStore(TestContext.DeploymentDirectory, captureFolder));
            var fakingHandler = new FakeHttpMessageHandler(new FileSystemResponseStore(captureFolder)); // point the fake to where the capture is stored

            using (var capturingClient = new HttpClient(capturingHandler, true))
            using (var fakingClient = new HttpClient(fakingHandler, true))
            {
                capturingClient.BaseAddress = new Uri("https://www.googleapis.com/");
                fakingClient.BaseAddress = new Uri("https://www.googleapis.com/");

                using (var capturedResponse = await capturingClient.GetAsync("storage/v1/b/uspto-pair"))
                using (var fakedResponse = await fakingClient.GetAsync("storage/v1/b/uspto-pair"))
                {
                    capturedResponse.EnsureSuccessStatusCode();
                    fakedResponse.EnsureSuccessStatusCode();

                    string captured = await capturedResponse.Content.Deserialize<string>();
                    string faked = await fakedResponse.Content.Deserialize<string>();

                    Assert.AreEqual(captured, faked);
                }
            }
        }
        public async Task GetCommentAsync_IsNotNull()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(AccountEndpointResponses.GetCommentResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/account/sarah/comment/yMgB7"),
                fakeResponse);

            var client = new ImgurClient("123", "1234");
            var endpoint = new AccountEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var comment = await endpoint.GetCommentAsync("yMgB7", "sarah");

            Assert.IsNotNull(comment);
            Assert.AreEqual(487008510, comment.Id);
            Assert.AreEqual("DMcOm2V", comment.ImageId);
            Assert.AreEqual(
                "Gyroscope detectors measure inertia.. the stabilization is done entirely by brushless motors. There are stabilizers which actually use 1/2",
                comment.CommentText);
            Assert.AreEqual("Scabab", comment.Author);
            Assert.AreEqual(4194299, comment.AuthorId);
            Assert.AreEqual(false, comment.OnAlbum);
            Assert.AreEqual(null, comment.AlbumCover);
            Assert.AreEqual(24, comment.Ups);
            Assert.AreEqual(0, comment.Downs);
            Assert.AreEqual(24, comment.Points);
            Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(1443969120), comment.DateTime);
            Assert.AreEqual(486983435, comment.ParentId);
            Assert.AreEqual(false, comment.Deleted);
            Assert.AreEqual(Vote.Down, comment.Vote);
            Assert.AreEqual(comment.Platform, "desktop");
        }
        public async Task GetAlbumAsync_IsNotNull()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(AccountEndpointResponses.GetAlbumResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/account/sarah/album/yMgB7"),
                fakeResponse);

            var client = new ImgurClient("123", "1234");
            var endpoint = new AccountEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var album = await endpoint.GetAlbumAsync("yMgB7", "sarah");

            Assert.IsNotNull(album);
            Assert.AreEqual("yMgB7", album.Id);
            Assert.AreEqual("Day 2 at Camp Imgur", album.Title);
            Assert.AreEqual(null, album.Description);
            Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(1439066984), album.DateTime);
            Assert.AreEqual("BOdd9Qd", album.Cover);
            Assert.AreEqual(5184, album.CoverWidth);
            Assert.AreEqual(3456, album.CoverHeight);
            Assert.AreEqual("sarah", album.AccountUrl);
            Assert.AreEqual(9571, album.AccountId);
            Assert.AreEqual(AlbumPrivacy.Public, album.Privacy);
            Assert.AreEqual(AlbumLayout.Blog, album.Layout);
            Assert.AreEqual(413310, album.Views);
            Assert.AreEqual("http://imgur.com/a/yMgB7", album.Link);
            Assert.AreEqual(false, album.Favorite);
            Assert.AreEqual(false, album.Nsfw);
            Assert.AreEqual("pics", album.Section);
            Assert.AreEqual(6, album.ImagesCount);
        }
Пример #4
0
 private void RespondWith(MandrillApi api, HttpStatusCode statusCode, string content)
 {
   var responseMessage = new HttpResponseMessage(statusCode);
   responseMessage.Content = new FakeHttpContent(content);
   var messageHandler = new FakeHttpMessageHandler(responseMessage);
   api.SetHttpClient(new HttpClient(messageHandler));
 }
Пример #5
0
        public void ShouldThrowExceptionWhenHttpClientFromGetResponseIsNull()
        {
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = null };
            var fakeHandler = new FakeHttpMessageHandler(fakeResponse);
            var httpClient = new HttpClient(fakeHandler) { BaseAddress = new Uri("http://localhost/") };

            var httpClientHelper = new HttpClientHelper { HttpClientObj = httpClient };
            Assert.Throws<BlogException>(() => httpClientHelper.Get("http://localhost/", "foo"));
        }
        public async Task HttpClient_GetAsync_ResponseContent_IsNull()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent("hello world")};

            fakeHttpMessageHandler.AddFakeResponse(new Uri("http://example.org/exists"), fakeResponse);

            var httpClient = new HttpClient(fakeHttpMessageHandler);
            var response = await httpClient.GetAsync("http://example.org/notfound");

            Assert.IsNull(response.Content);
        }
Пример #7
0
        public async Task ThrowWhenNoStaticResponseFound()
        {
            var handler = new FakeHttpMessageHandler(new FileSystemResponseStore(TestContext.DeploymentDirectory));

            using (var client = new HttpClient(handler, true))
            {
                client.BaseAddress = new Uri("http://openstates.org/api/v1/");

                var response = await client.GetAsync("metadata/NO_ENDPOINT_HERE");

                response.EnsureSuccessStatusCode();
            }
        }
Пример #8
0
        public async Task ThrowWhenNoStaticResponseFoundByParameterLookup()
        {
            var handler = new FakeHttpMessageHandler(new FileSystemResponseStore(TestContext.DeploymentDirectory));

            using (var fakingClient = new HttpClient(handler, true))
            {
                fakingClient.BaseAddress = new Uri("http://dev.virtualearth.net/");

                var fakedResponse = await fakingClient.GetAsync("REST/v1/Locations?c=en-us&countryregion=us&maxres=1&postalcode=NON_EXISTENT_POSTAL_CODE");

                fakedResponse.EnsureSuccessStatusCode();
            }
        }
        public async Task HttpClient_GetAsync_ResponseContentAreEqual()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent("get response")};

            fakeHttpMessageHandler.AddFakeResponse(new Uri("http://example.org/test"), fakeResponse);

            var httpClient = new HttpClient(fakeHttpMessageHandler);
            var response = await httpClient.GetAsync("http://example.org/test");
            var stringResponse = await response.Content.ReadAsStringAsync();

            Assert.AreEqual("get response", stringResponse);
        }
Пример #10
0
        public void ShouldReturnStringOnHttpGet()
        {
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.Accepted)
            {
                Content = new StringContent("{ Test: Message }")
            };
            var fakeHandler = new FakeHttpMessageHandler(fakeResponse);
            var httpClient = new HttpClient(fakeHandler) { BaseAddress = new Uri("http://localhost/") };

            var httpClientHelper = new HttpClientHelper { HttpClientObj = httpClient };
            var result = httpClientHelper.HttpGet("http://localhost/", "foo");

            Assert.AreEqual(fakeResponse, result);
        }
Пример #11
0
        public void ShouldHaveAuthenticationHeaderOnHttpGet()
        {
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.Accepted)
            {
                Content = new StringContent("{ Test: Message }")
            };
            var fakeHandler = new FakeHttpMessageHandler(fakeResponse);
            var httpClient = new HttpClient(fakeHandler) { BaseAddress = new Uri("http://localhost/") };

            var httpClientHelper = new HttpClientHelper { HttpClientObj = httpClient };
            httpClientHelper.HttpGet("http://localhost/", "foo", "bar");

            Assert.AreEqual(httpClientHelper.AuthenticationToken, "bar");
        }
Пример #12
0
        public async Task GetTokenByCodeAsync_ThrowsImgurException()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = new StringContent(OAuth2EndpointResponses.OAuth2TokenResponseError)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/oauth2/token"), fakeResponse);

            var client = new ImgurClient("123", "1234");
            var endpoint = new OAuth2Endpoint(client, new HttpClient(fakeHttpMessageHandler));
            await endpoint.GetTokenByCodeAsync("12345");
        }
Пример #13
0
        public async Task GivenPreActionForController_WhenProcessing_ThenActionIsPerformed()
        {
            int invocationCount       = 0;
            List <SampleModel> sample = new List <SampleModel>()
            {
                new SampleModel(), new SampleModel()
            };
            FakeHttpMessageHandler fake = new FakeHttpMessageHandler().WithPreRequest(() => invocationCount++)
                                          .WithExpectedContent(sample);
            HttpClient httpClient = new HttpClient(fake);
            ExampleControllerHandling exampleController = new ExampleControllerHandling(httpClient);
            IEnumerable <SampleModel> output            = await exampleController.GetAll();

            Assert.Equal(1, invocationCount);
        }
        private HttpClient CreateHttpClient(HttpStatusCode statusCode, object response)
        {
            var message = new FakeHttpMessageHandler(new HttpResponseMessage()
            {
                StatusCode = statusCode,
                Content    = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json")
            });

            var httpClient = new HttpClient(message)
            {
                BaseAddress = new Uri("http://test.com/")
            };

            return(httpClient);
        }
Пример #15
0
        public void Save_TVShow_PosterUrl()
        {
            var fakePosterUrl      = "https://fake.tv.show/poster.png";
            var fakePosterContents = "fake tv show poster";

            FakeHttpMessageHandler.Mock(fakePosterUrl, fakePosterContents);

            string posterMetadataPath = Path.Combine(Folder, "folder.png");
            var    metadata           = new TVShow(title: "title", posterPathOrUrl: fakePosterUrl);

            LocalMetadata.Save(metadata, Folder);

            File.Exists(posterMetadataPath).ShouldBeTrue();
            File.ReadAllText(posterMetadataPath).ShouldBe(fakePosterContents);
        }
Пример #16
0
        public void Save_Movie_PosterUrl()
        {
            var fakePosterUrl      = "https://fake.com/poster.png";
            var fakePosterContents = "fake poster";

            FakeHttpMessageHandler.Mock(fakePosterUrl, fakePosterContents);

            var    metadata           = new Movie(title: "title", posterPathOrUrl: fakePosterUrl);
            string posterMetadataPath = Path.Combine(Folder, $"{metadata.Title}.png");

            LocalMetadata.Save(metadata, Folder, metadata.Title);

            File.Exists(posterMetadataPath).ShouldBeTrue();
            File.ReadAllText(posterMetadataPath).ShouldBe(fakePosterContents);
        }
Пример #17
0
        public async Task Should_get_a_Directory_object_from_the_default_endpoint()
        {
            var http      = new FakeHttpMessageHandler("http://baseaddress/");
            var directory = new Directory();

            var client =
                http.RequestTo("directory").Returns(directory).WithNonce("nonce")
                .GetHttpClient();

            var sut = new AcmeClient(client, new RSACryptoServiceProvider());

            var discoverResponse = await sut.GetDirectoryAsync();

            discoverResponse.Should().NotBeNull();
        }
Пример #18
0
        private static async Task <IEnumerable <string> > InvokeSut(string owner, string repo, string path, string pattern)
        {
            var messageResponse = FakeHttpMessageHandler.GetStringHttpResponseMessage(GetTestFileContent());

            var fakeMessageHandler = new FakeHttpMessageHandler(new HttpMessageOptions()
            {
                HttpResponseMessage = messageResponse, RequestUri = new Uri($"https://api.github.com/repos/{owner}/{repo}/contents/{path}")
            });

            var sut = new SloaderConfigLocator(fakeMessageHandler);

            var result = await sut.FromGitHub("Code-Inside", "KnowYourStack", "_data", pattern);

            return(result);
        }
Пример #19
0
 public void throws_without_saving_file_when_got_return_code_else_than_2XX()
 {
     if (!RunningOnWindows)
     {
         ReportSkip(nameof(throws_without_saving_file_when_got_return_code_else_than_2XX));
         return;
     }
     using (var messageHandler = new FakeHttpMessageHandler(_messages))
         using (var httpClient = new HttpClient(messageHandler))
         {
             var service = new DownloadService(httpClient, _fileSystem);
             Assert.ThrowsAsync <DownloadFailureException>(() => service.DownloadAsync(BadUrl, Destination)).Wait();
         }
     Assert.False(_fileSystem.FileExists(Destination), "saves file on disk");
 }
        public async void GetName_Returns_CharacterName()
        {
            // Given
            var          messageHandler = new FakeHttpMessageHandler(JsonConvert.SerializeObject(DefaultCharacterName));
            var          httpClient     = new HttpClient(messageHandler);
            INameService sut            = new RandomNameService(httpClient);

            // When
            var name = await sut.GetName();

            // Then
            Assert.Equal(DefaultUri, messageHandler.RequestMessage.RequestUri);
            Assert.Equal(DefaultCharacterName.Name, name.Name);
            Assert.Equal(DefaultCharacterName.Surname, name.Surname);
        }
        private HttpClient CreateClient(OAuthOptions options, params HttpMessageOptions[] httpOptions)
        {
            var handler = new FakeHttpMessageHandler(httpOptions);

            var wrapper = new OptionsWrapper <OAuthOptions>(options);

            var authenticator = new OAuthHubSpotAuthenticator(wrapper)
            {
                InnerHandler = handler
            };

            var client = new HttpClient(authenticator, false);

            return(client);
        }
Пример #22
0
        public async Task Loader_Should_Return_0_Without_Any_Shares()
        {
            const string responseData = "{'id':'http://...url...'}";

            var messageResponse = FakeHttpMessageHandler.GetStringHttpResponseMessage(responseData);

            var fakeMessageHandler = new FakeHttpMessageHandler(new HttpMessageOptions()
            {
                HttpResponseMessage = messageResponse
            });

            var sut = new FacebookShareCountLoader(fakeMessageHandler);

            Assert.Equal(0, await sut.GetAsync("http://blog.something.com"));
        }
Пример #23
0
        public void UpsertUser_Returns_True_When_Response_Is_Success(HttpStatusCode responseHttpCode)
        {
            var handler          = FakeHttpMessageHandler.Create(request => new HttpResponseMessage(responseHttpCode));
            var client           = new HttpClient(handler);
            var clientConfig     = new ClientConfiguration();
            var serverConfigMock = new Mock <IServerConfig>();
            var dataMapper       = new JsonDataMapper(clientConfig);

            var manager = new ClusterManager(clientConfig, serverConfigMock.Object, dataMapper, client, "username", "password");
            var result  = manager.UpsertUser("alice", "secure123", "Alice Liddell", new Role {
                Name = "Admin"
            });

            Assert.AreEqual(responseHttpCode == HttpStatusCode.OK, result.Success);
        }
        private HttpClient CreateClient(ApiKeyOptions options, HttpMessageOptions httpOptions)
        {
            var handler = new FakeHttpMessageHandler(httpOptions);

            var wrapper = new OptionsWrapper <ApiKeyOptions>(options);

            var authenticator = new ApiKeyHubSpotAuthenticator(wrapper)
            {
                InnerHandler = handler
            };

            var client = new HttpClient(authenticator);

            return(client);
        }
Пример #25
0
        public void PostAsync_Ok_Form_xWwwHeader()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var httpClient             = new HttpClient(fakeHttpMessageHandler);
            var httpProvider           = new HttpProvider(httpClient);

            var request = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >());
            var result  = httpProvider.PostAsync("http://test", request);

            Assert.AreEqual(HttpStatusCode.OK, result.Result.StatusCode);
            var contentTypeHeader = request.Headers
                                    .FirstOrDefault(p => p.Key == "Content-Type").Value.FirstOrDefault();

            Assert.AreEqual("application/x-www-form-urlencoded", contentTypeHeader);
        }
Пример #26
0
        public async Task FakeResponseHadRequestMessageSet()
        {
            var captureFolder = Path.Combine(TestContext.TestRunDirectory, @"..\..\FakeResponses\");
            var handler       = new FakeHttpMessageHandler(new FileSystemResources(TestContext.DeploymentDirectory));

            using (var client = new HttpClient(handler, true))
            {
                client.BaseAddress = new Uri("https://www.googleapis.com/");
                using (var response = await client.GetAsync("storage/v1/b/uspto-pair"))
                {
                    response.EnsureSuccessStatusCode();
                    Assert.IsNotNull(response.RequestMessage);
                }
            }
        }
Пример #27
0
        public KinlyPlatformServiceTest()
        {
            _fakeHttpHandler = new FakeHttpMessageHandler();
            _kinlySelfTestScoreEndpointUrl = "https://someUrl.com";

            _kinlyPlatformService = new KinlyPlatformService
                                    (
                new HttpClient(_fakeHttpHandler)
            {
                Timeout = TimeSpan.FromSeconds(1)
            },
                new Mock <ICustomJwtTokenProvider>().Object,
                _kinlySelfTestScoreEndpointUrl
                                    );
        }
Пример #28
0
        public async Task Loader_Should_Return_0_On_HttpError()
        {
            const string responseData = "Bad Request";

            var messageResponse = FakeHttpMessageHandler.GetStringHttpResponseMessage(responseData, HttpStatusCode.BadRequest);

            var fakeMessageHandler = new FakeHttpMessageHandler(new HttpMessageOptions()
            {
                HttpResponseMessage = messageResponse
            });

            var sut = new FacebookShareCountLoader(fakeMessageHandler);

            Assert.Equal(0, await sut.GetAsync("http://blog.something.com"));
        }
        public void Import_throws_exception_when_json_is_invalid(string handleUri)
        {
            var configuration = new ClusterOptions().WithServers("http://localhost");

            var httpClient = new HttpClient(
                FakeHttpMessageHandler.Create(request => new HttpResponseMessage(HttpStatusCode.OK))
                );

            var client = new AnalyticsClient(httpClient,
                                             new JsonDataMapper(new DefaultSerializer()),
                                             configuration);

            var json = JsonConvert.SerializeObject(new { v = 1, uri = handleUri });

            Assert.Throws <ArgumentException>(() => client.ImportDeferredQueryHandle <dynamic>(json));
        }
        public CommitmentsRestClientTestsFixture()
        {
            LoggerFactoryMock = new Mock <ILoggerFactory>();
            FakeLogger        = new FakeLogger();
            LoggerFactoryMock
            .Setup(lfm => lfm.CreateLogger(It.Is <string>(s => s.EndsWith(nameof(CommitmentsRestHttpClient)))))
            .Returns(FakeLogger);

            ModelErrors        = new List <ErrorDetail>();
            HttpMessageHandler = new FakeHttpMessageHandler();
            HttpClient         = new HttpClient(HttpMessageHandler)
            {
                BaseAddress = new Uri("https://example.com")
            };
            RestHttpClient = new CommitmentsRestHttpClient(HttpClient, LoggerFactoryMock.Object);
        }
Пример #31
0
        public async Task UpdateImageAsync_AreEqual()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse           = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(ImageEndpointResponses.Imgur.UpdateImageResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/image/123xyj"), fakeResponse);

            var client   = new ImgurClient("123", "1234");
            var endpoint = new ImageEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var updated  = await endpoint.UpdateImageAsync("123xyj");

            Assert.AreEqual(true, updated);
        }
Пример #32
0
        public async Task QueryAsync_Sets_LastActivity()
        {
            var httpClient = new HttpClient(
                FakeHttpMessageHandler.Create(request => new HttpResponseMessage(HttpStatusCode.OK))
                );

            var config = new ClientConfiguration();
            var client = new AnalyticsClient(httpClient, new JsonDataMapper(config), config);

            Assert.IsNull(client.LastActivity);

            var queryRequest = new AnalyticsRequest("SELECT * FROM `default`;");
            await client.QueryAsync <dynamic>(queryRequest, CancellationToken.None);

            Assert.IsNotNull(client.LastActivity);
        }
    public HttpClient CreateHttpClientWithBaseUri(Uri baseUri, string relativeUri, string response, string responseContentType = "application/json", HttpStatusCode responseCode = HttpStatusCode.OK)
    {
        var httpResponseMessage = CreateFakeResponse(response, responseContentType, responseCode);

        var uri = new Uri(baseUri, relativeUri);
        var fakeMessageHandler = new FakeHttpMessageHandler();

        fakeMessageHandler.AddFakeResponse(uri, httpResponseMessage);

        var httpClient = new HttpClient(fakeMessageHandler)
        {
            BaseAddress = baseUri
        };

        return(httpClient);
    }
Пример #34
0
        private IMockProviderService GetSubject(int port = 1234, bool enableSsl = false)
        {
            _mockHttpHost                 = Substitute.For <IHttpHost>();
            _fakeHttpMessageHandler       = new FakeHttpMessageHandler();
            _mockHttpHostFactoryCallCount = 0;

            return(new MockProviderService(
                       baseUri =>
            {
                _mockHttpHostFactoryCallCount++;
                return _mockHttpHost;
            },
                       port,
                       enableSsl,
                       baseUri => new AdminHttpClient(baseUri, _fakeHttpMessageHandler)));
        }
Пример #35
0
        public void LoadSwaggerResourceShouldReturnSerialisedObject()
        {
            string testData        = "{\"swaggerVersion\":\"1.2\",\"apiVersion\":\"1.0\",\"apis\":[{\"path\":\"/SomeEndpoint\"}]}";
            var    responseMessage = new HttpResponseMessage();

            responseMessage.Content = new FakeHttpContent(testData);
            var messageHandler = new FakeHttpMessageHandler(responseMessage);
            var client         = new HttpClient(messageHandler);
            var classUnderTest = new SpecReader(client);

            var response = classUnderTest.LoadSwaggerResource("http://someUrl/");

            Assert.That(response.ApiVersion, Is.EqualTo("1.0"));
            Assert.That(response.SwaggerVersion, Is.EqualTo("1.2"));
            Assert.That(response.Apis.First().Path, Is.EqualTo("/SomeEndpoint"));
        }
        public async Task UpdateRouteAsync_ReturnsNothing()
        {
            // arrange
            var fakeResponse = new HttpResponseMessage
            {
                StatusCode = System.Net.HttpStatusCode.OK
            };

            var fakeHandler = new FakeHttpMessageHandler(fakeResponse);
            var httpClient  = new HttpClient(fakeHandler);

            _routeService = new RouteService(httpClient);

            // act
            await _routeService.UpdateRouteAsync("102T", 22, new UpdateRouteWithStops { });
        }
        public async Task GetByRouteIdAsync_InvalidRouteId_Returns404()
        {
            // arrange
            var fakeResponse = new HttpResponseMessage
            {
                StatusCode = System.Net.HttpStatusCode.NotFound
            };

            var fakeHandler = new FakeHttpMessageHandler(fakeResponse);
            var httpClient  = new HttpClient(fakeHandler);

            _routeService = new RouteService(httpClient);

            // act
            var result = await _routeService.GetByRouteIdAsync(999999);
        }
Пример #38
0
        public async Task GivenHeader_WhenCallingExecuteGetRequest_HeaderIsSetInRequestMessage()
        {
            string timestamp = DateTime.UtcNow.ToString();
            FakeHttpMessageHandler fakeHttpMessageHandler = new FakeHttpMessageHandler();
            RequestHeaders         requestHeaders         = new RequestHeaders();

            requestHeaders.Add("timestamp", timestamp);
            HttpClient httpClient = new HttpClient(fakeHttpMessageHandler);
            GetRequest getRequest = new GetRequest(httpClient)
            {
                RequestHeaders = requestHeaders
            };
            HttpResponseMessage response = await getRequest.Execute("http://www.google.com");

            Assert.Equal(timestamp, response.RequestMessage.Headers.GetValues("timestamp").First());
        }
        public async Task MoveStopAsync_ReturnsNothing()
        {
            // arrange
            var fakeResponse = new HttpResponseMessage
            {
                StatusCode = System.Net.HttpStatusCode.OK
            };

            var fakeHandler = new FakeHttpMessageHandler(fakeResponse);
            var httpClient  = new HttpClient(fakeHandler);

            _routeService = new RouteService(httpClient);

            // act
            await _routeService.MoveStopAsync(new MoveStopTestModel { });
        }
Пример #40
0
        public void Arrange()
        {
            _fixture = new Fixture();

            _httpClientHandlerFake = new FakeHttpMessageHandler();

            _hashingServiceMock = new Mock <IHashingService>();
            _hashingServiceMock.Setup(x => x.DecodeValue(It.IsAny <string>())).Returns((string s) => Convert.ToInt64(s));

            _httpClient = new HttpClient(_httpClientHandlerFake)
            {
                BaseAddress = new Uri(_baseUrl)
            };

            _sut = new ApplicationService(_httpClient, _hashingServiceMock.Object);
        }
        public async Task GetAlbumImagesAsync_ImageCountIsTrue()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse           = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(AlbumEndpointResponses.Imgur.GetAlbumImagesResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/album/5F5Cy/images"), fakeResponse);

            var client   = new ImgurClient("123", "1234");
            var endpoint = new AlbumEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var images   = await endpoint.GetAlbumImagesAsync("5F5Cy");

            Assert.IsTrue(images.Count() == 3);
        }
        public async Task DeleteAlbumAsync_IsTrue()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse           = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(AlbumEndpointResponses.Imgur.DeleteAlbumResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/album/12x5454"), fakeResponse);

            var client   = new ImgurClient("123", "1234");
            var endpoint = new AlbumEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var deleted  = await endpoint.DeleteAlbumAsync("12x5454");

            Assert.IsTrue(deleted);
        }
        public async Task GetAccountFavoritesAsync_Any()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(AccountEndpointResponses.GetAccountFavoritesResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/account/me/favorites"), fakeResponse);

            var fakeOAuth2Handler = new FakeOAuth2TokenHandler();
            var client = new ImgurClient("123", "1234", fakeOAuth2Handler.GetOAuth2TokenCodeResponse());
            var endpoint = new AccountEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var favorites = await endpoint.GetAccountFavoritesAsync();

            Assert.IsTrue(favorites.Any());
        }
        public async Task HttpClient_PostAsync_ResponseContentAreEqual()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent("post response")};

            fakeHttpMessageHandler.AddFakeResponse(new Uri("http://example.org/test"), fakeResponse);

            var httpClient = new HttpClient(fakeHttpMessageHandler);
            var parameters = new Dictionary<string, string> {{"Name", "bob"}};

            var content = new FormUrlEncodedContent(parameters.ToArray());

            var response = await httpClient.PostAsync("http://example.org/test", content);
            var stringResponse = await response.Content.ReadAsStringAsync();

            Assert.AreEqual("post response", stringResponse);
        }
        public async Task DeleteAlbumAsync_IsNotNull()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(AccountEndpointResponses.DeleteAlbumResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/account/sarah/album/yMgB7"),
                fakeResponse);

            var fakeOAuth2TokenHandler = new FakeOAuth2TokenHandler();
            var client = new ImgurClient("123", "1234", fakeOAuth2TokenHandler.GetOAuth2TokenCodeResponse());
            var endpoint = new AccountEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var deleted = await endpoint.DeleteAlbumAsync("yMgB7", "sarah");

            Assert.IsTrue(deleted);
        }
        public async Task GetNotificationsAsync_IsNotNull()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(AccountEndpointResponses.GetNotifications)
            };

            fakeHttpMessageHandler.AddFakeResponse(
                new Uri("https://api.imgur.com/3/account/me/notifications?new=false"), fakeResponse);

            var fakeOAuth2Handler = new FakeOAuth2TokenHandler();
            var client = new ImgurClient("123", "1234", fakeOAuth2Handler.GetOAuth2TokenCodeResponse());
            var endpoint = new AccountEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var notifications = await endpoint.GetNotificationsAsync(false);

            Assert.IsNotNull(notifications);
            Assert.IsNotNull(notifications.Messages);
            Assert.IsNotNull(notifications.Replies);
        }
Пример #47
0
        public async Task ThrowWhenStaticallySimulateFailure()
        {
            var handler = new FakeHttpMessageHandler(new FileSystemResponseStore(TestContext.DeploymentDirectory));

            using (var client = new HttpClient(handler, true))
            {
                client.BaseAddress = new Uri("http://openstates.org/api/v1/");

                var response = await client.PostAsync("metadata/mn", new StringContent("payload"));

                try
                {
                    response.EnsureSuccessStatusCode();
                }
                catch (HttpRequestException e)
                {
                    Assert.IsTrue(e.Message.Contains("401"));
                }
            }
        }
        public async Task ShouldNotValidateSchema()
        {
            var content = new StringContent("{ name: 'foo' }",
                Encoding.UTF8,
                "application/json");

            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            response.Content = content;

            var handler = new FakeHttpMessageHandler(response);
            var client = new HttpClient(handler);
            client.BaseAddress = new Uri("http://localhost");

            var proxy = new Movies.MoviesApi(client);
            proxy.SchemaValidation.RaiseExceptions = false;

            var movies = await proxy.Movies.Get();

            Assert.IsFalse(movies.SchemaValidation.Value.IsValid);
                        
        }
        public async Task ShouldValidateNulls()
        {
            var content = new StringContent("[{ id : 1, name: 'Big Fish', director: 'Tim Burton', genre: null, cast: 'Ewan McGregor, Albert Finney, Billy Crudup', duration: null, storyline: 'none', language: 'English', rented: false }]",
                Encoding.UTF8,
                "application/json");

            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            response.Content = content;

            var handler = new FakeHttpMessageHandler(response);
            var client = new HttpClient(handler);
            client.BaseAddress = new Uri("http://localhost");

            var proxy = new Movies.MoviesApi(client);
            proxy.SchemaValidation.RaiseExceptions = false;

            var movies = await proxy.Movies.Get();

            Assert.IsTrue(movies.SchemaValidation.Value.IsValid);

        }
Пример #50
0
        public async Task GetTokenByCodeAsync_AreEqual()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(OAuth2EndpointResponses.OAuth2TokenCodeResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/oauth2/token"), fakeResponse);

            var client = new ImgurClient("123", "1234");
            var endpoint = new OAuth2Endpoint(client, new HttpClient(fakeHttpMessageHandler));
            var token = await endpoint.GetTokenByCodeAsync("12345");

            Assert.AreEqual("CodeResponse", token.AccessToken);
            Assert.AreEqual("2132d34234jkljj84ce0c16fjkljfsdfdc70", token.RefreshToken);
            Assert.AreEqual("bearer", token.TokenType);
            Assert.AreEqual(2419200, token.ExpiresIn);
            Assert.AreEqual("Bob", token.AccountUsername);
            Assert.AreEqual("45344", token.AccountId);
        }
Пример #51
0
        public async Task GetRateLimitAsync_AreEqual()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(RateLimitEndpointResponses.RateLimitResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/credits"), fakeResponse);

            var httpClient = new HttpClient(fakeHttpMessageHandler);

            var client = new ImgurClient("123", "1234");
            var endpoint = new RateLimitEndpoint(client, httpClient);

            var rateLimit = await endpoint.GetRateLimitAsync();

            Assert.IsNotNull(rateLimit);
            Assert.AreEqual(412, rateLimit.UserLimit);
            Assert.AreEqual(382, rateLimit.UserRemaining);
            Assert.AreEqual(10500, rateLimit.ClientLimit);
            Assert.AreEqual(9500, rateLimit.ClientRemaining);
        }
        public async Task GetGalleryProfileAsync_IsNotNull()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(AccountEndpointResponses.GetGalleryProfileResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/account/me/gallery_profile"),
                fakeResponse);

            var fakeOAuth2Handler = new FakeOAuth2TokenHandler();
            var client = new ImgurClient("123", "1234", fakeOAuth2Handler.GetOAuth2TokenCodeResponse());
            var endpoint = new AccountEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var profile = await endpoint.GetGalleryProfileAsync();

            Assert.IsNotNull(profile);
        }
        public async Task GetAlbumsAsync_AreEqual()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(AccountEndpointResponses.GetAlbumsResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/account/bob/albums/2"), fakeResponse);

            var client = new ImgurClient("123", "1234");
            var endpoint = new AccountEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var albums = await endpoint.GetAlbumsAsync("bob", 2);

            Assert.AreEqual(50, albums.Count());
        }
Пример #54
0
        public void ShouldThrowExceptionWhenHttpClientFromHttpGetResponseIsNull()
        {
            var fakeHandler = new FakeHttpMessageHandler(null);
            var httpClient = new HttpClient(fakeHandler) { BaseAddress = new Uri("http://localhost/") };

            var httpClientHelper = new HttpClientHelper { HttpClientObj = httpClient };
            Assert.Throws<BlogException>(() => httpClientHelper.HttpGet("http://localhost/", "foo"));
        }
Пример #55
0
 public void CreateHttpTest()
 {
   var responseMessage = new HttpResponseMessage();
   var messageHandler = new FakeHttpMessageHandler(responseMessage);
   httpClient = new HttpClient(messageHandler);
 }
        public async Task ShouldNotThrowExceptionForNonJSONSchema()
        {
            var content = new StringContent("data",
                Encoding.UTF8,
                "text/plain");

            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            response.Content = content;

            var handler = new FakeHttpMessageHandler(response);
            var client = new HttpClient(handler);
            client.BaseAddress = new Uri("http://localhost");

            var proxy = new Movies.MoviesApi(client);
            proxy.SchemaValidation.RaiseExceptions = true;

            var movies = await proxy.Movies.Get();

            Assert.IsNotNull(movies);
        }
        public async Task ShouldIgnoreNonJsonSchemas()
        {
            var content = new StringContent("content",
                Encoding.UTF8,
                "text/plain");

            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            response.Content = content;

            var handler = new FakeHttpMessageHandler(response);
            var client = new HttpClient(handler);
            client.BaseAddress = new Uri("http://localhost");

            var proxy = new Movies.MoviesApi(client);
            proxy.SchemaValidation.RaiseExceptions = false;

            var movies = await proxy.Movies.Get();

            Assert.IsTrue(movies.SchemaValidation.Value.IsValid);

        }
Пример #58
0
        public async Task FilteredQueryParametrIsIgnoredDuringFaking()
        {
            string key = CredentialStore.RetrieveObject("bing.key.json").Key;
            // store the rest response in a subfolder of the solution directory for future use
            var captureFolder = Path.Combine(TestContext.TestRunDirectory, @"..\..\FakeResponses\");

            // when capturing the real response, we do not want to serialize things like api keys
            // both because that is a possible infomration leak and also because it would
            // bind the serialized resposne to the key, making successful faking dependent on
            // the key used when capturing the response. The fake response lookup will try to find
            // a serialized response that matches a hash of all the query paramerters. The lambda in
            // the response store constructor below allows us to ignore certain paramters for that lookup
            // when capturing and faking responses
            //
            // this test ensures that our mechansim to filter out those paramters we want to ignore works
            //
            var capturingHandler = new CapturingHttpClientHandler(new FileSystemResponseStore(TestContext.DeploymentDirectory, captureFolder, (name, value) => name == "key"));
            var fakingHandler = new FakeHttpMessageHandler(new FileSystemResponseStore(captureFolder, (name, value) => name == "key")); // point the fake to where the capture is stored

            using (var capturingClient = new HttpClient(capturingHandler, true))
            using (var fakingClient = new HttpClient(fakingHandler, true))
            {
                capturingClient.BaseAddress = new Uri("http://dev.virtualearth.net/");
                fakingClient.BaseAddress = new Uri("http://dev.virtualearth.net/");

                using (var capturedResponse = await capturingClient.GetAsync("REST/v1/Locations?c=en-us&countryregion=us&maxres=1&postalcode=55116&key=" + key))
                using (var fakedResponse = await fakingClient.GetAsync("REST/v1/Locations?c=en-us&countryregion=us&maxres=1&postalcode=55116&key=THIS_SHOULD_NOT_MATTER"))
                {
                    capturedResponse.EnsureSuccessStatusCode();
                    fakedResponse.EnsureSuccessStatusCode();

                    string captured = await capturedResponse.Content.Deserialize<string>();
                    string faked = await fakedResponse.Content.Deserialize<string>();

                    Assert.AreEqual(captured, faked);
                }
            }
        }
        public async Task GetAlbumCountAsync_IsNotNull()
        {
            var fakeHttpMessageHandler = new FakeHttpMessageHandler();
            var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(AccountEndpointResponses.GetAlbumCountResponse)
            };

            fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/account/sarah/albums/count"),
                fakeResponse);

            var client = new ImgurClient("123", "1234");
            var endpoint = new AccountEndpoint(client, new HttpClient(fakeHttpMessageHandler));
            var count = await endpoint.GetAlbumCountAsync("sarah");

            Assert.AreEqual(count, 105);
        }
        public async Task ShouldValidateV4Schema()
        {
            var content = new StringContent("{ Component: 'component', Version: 'version' }",
                Encoding.UTF8,
                "application/json");

            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            response.Content = content;

            var handler = new FakeHttpMessageHandler(response);
            var client = new HttpClient(handler);
            client.BaseAddress = new Uri("http://localhost");

            var proxy = new EPiServerServiceAPI.EpiApi(client);
            proxy.SchemaValidation.RaiseExceptions = false;
            proxy.OAuthAccessToken = "token";

            var version = await proxy.Version.Get();

            Assert.IsTrue(version.SchemaValidation.Value.IsValid);

        }