public void DeleteNetwork()
        {
            using (var httpTest = new HttpTest())
            {
                Identifier networkId = Guid.NewGuid();
                httpTest.RespondWith((int)HttpStatusCode.NoContent, "All gone!");

                _cloudNetworkService.DeleteNetwork(networkId);

                httpTest.ShouldHaveCalled("*/networks/" + networkId);
            }
        }
示例#2
0
        public async Task CodeUnderTestReturnsCorrectValue(HttpStatusCode statusCode, bool expectedResult)
        {
            //Arrange
            bool result;
            var  codeToTest = new ExternalApiCaller();

            using (var httpTest = new HttpTest())
            {
                httpTest.RespondWith(statusCode.ToString(), (int)statusCode);

                //Act
                result = await codeToTest.MakeTheCall();
            }

            //Assert
            Assert.That(result, Is.EqualTo(expectedResult));
        }
示例#3
0
        public async Task ShouldReturnTheExpectedCount()
        {
            using (var httpTest = new HttpTest())
            {
                httpTest.RespondWith("{ \"share_counter\": 209 }");

                var logger = new Mock <ILogger>().Object;
                var count  = await new Xing(logger).Get("http://www.dotnetgeek.de/test-url");


                httpTest.ShouldHaveCalled("https://www.xing-share.com/spi/shares/statistics")
                .WithVerb(HttpMethod.Post)
                .Times(1);

                Assert.Equal(209, Convert.ToInt32(count));
            }
        }
示例#4
0
        public async Task can_catch_parsing_error()
        {
            HttpTest.RespondWith("{ \"invalid JSON!");

            try {
                await "http://myapi.com".GetJsonAsync();
                Assert.Fail("should have failed to parse response.");
            }
            catch (FlurlParsingException ex) {
                Assert.AreEqual("Response could not be deserialized to JSON: GET http://myapi.com", ex.Message);
                // these are equivalent:
                Assert.AreEqual("{ \"invalid JSON!", await ex.GetResponseStringAsync());
                Assert.AreEqual("{ \"invalid JSON!", await ex.Call.Response.GetStringAsync());
                // will differ if you're using a different serializer (which you probably aren't):
                Assert.IsInstanceOf <Newtonsoft.Json.JsonReaderException>(ex.InnerException);
            }
        }
示例#5
0
        public void ResumeServer()
        {
            using (var httpTest = new HttpTest())
            {
                Identifier serverId = Guid.NewGuid();
                httpTest.RespondWithJson(new Server {
                    Id = serverId
                });
                httpTest.RespondWith((int)HttpStatusCode.Accepted, "Roger that, boss");

                var server = _compute.GetServer(serverId);
                server.Resume();

                httpTest.ShouldHaveCalled($"*/servers/{serverId}/action");
                Assert.Contains("resume", httpTest.CallLog.Last().RequestBody);
            }
        }
示例#6
0
文件: Tester.cs 项目: mrchief/Flurl
        public static async Task DoTestsAsync(Action <string> log)
        {
            var source = await "http://www.google.com".GetStringAsync();

            log(source.Substring(0, 40));
            log("^-- real response");
            using (var test = new HttpTest()) {
                test.RespondWith("totally fake google source");
                log(await "http://www.google.com".GetStringAsync());
                log("^-- fake response");
            }

            var path = await "http://www.google.com".DownloadFileAsync("c:\\flurl", "google.txt");

            log("dowloaded google source to " + path);
            log("done");
        }
示例#7
0
        public async Task can_disable_exception_behavior()
        {
            FlurlHttp.Configuration.OnError = call => {
                call.ExceptionHandled = true;
            };

            using (var test = new HttpTest()) {
                test.RespondWith(500, "server error");
                try {
                    var result = await "http://www.api.com".GetAsync();
                    Assert.IsFalse(result.IsSuccessStatusCode);
                }
                catch (Exception) {
                    Assert.Fail("Exception should not have been thrown.");
                }
            }
        }
示例#8
0
        public async Task can_disable_exception_behavior()
        {
            using (var test = new HttpTest()) {
                GetSettings().OnError = call => {
                    call.ExceptionHandled = true;
                };
                test.RespondWith("server error", 500);
                try {
                    var result = await GetClient().GetAsync();

                    Assert.IsFalse(result.IsSuccessStatusCode);
                }
                catch (FlurlHttpException) {
                    Assert.Fail("Flurl should not have thrown exception.");
                }
            }
        }
示例#9
0
        public async Task HttpService_GetWithToken_ReturnsSerializedList()
        {
            //Arrange
            var    httpService = new HttpService("https://api.com/");
            string server_list = "[{\"name\":\"United States #3\",\"distance\":627},{\"name\":\"Japan #78\",\"distance\":1107}]";

            using (var httpTest = new HttpTest())
            {
                // arrange
                httpTest.RespondWith(server_list, 200);
                // act
                var result = await httpService.GetWithToken("123");

                // assert
                result.Result.Should().BeEquivalentTo(server_list);
            }
        }
示例#10
0
文件: GetTests.cs 项目: Marusyk/Flurl
        public async Task failure_throws_detailed_exception()
        {
            HttpTest.RespondWith("bad job", status: 500);

            try {
                await "http://api.com".GetStringAsync();
                Assert.Fail("FlurlHttpException was not thrown!");
            }
            catch (FlurlHttpException ex) {
                Assert.AreEqual("http://api.com/", ex.Call.HttpRequestMessage.RequestUri.AbsoluteUri);
                Assert.AreEqual(HttpMethod.Get, ex.Call.HttpRequestMessage.Method);
                Assert.AreEqual(500, ex.Call.Response.StatusCode);
                // these should be equivalent:
                Assert.AreEqual("bad job", await ex.Call.Response.GetStringAsync());
                Assert.AreEqual("bad job", await ex.GetResponseStringAsync());
            }
        }
示例#11
0
文件: Tester.cs 项目: codears/flurl
        public async Task DoTestsAsync()
        {
            _pass = 0;
            _fail = 0;

            await Test("Testing real request to google.com...", async() => {
                var real = await "http://www.google.com".GetStringAsync();
                Assert(real.Trim().StartsWith("<"), $"Response from google.com doesn't look right: {real}");
            });

            await Test("Testing fake request with HttpTest...", async() => {
                using (var test = new HttpTest()) {
                    test.RespondWith("fake response");
                    var fake = await "http://www.google.com".GetStringAsync();
                    Assert(fake == "fake response", $"Fake response doesn't look right: {fake}");
                }
            });

            await Test("Testing file download...", async() => {
                var path = "c:\\google.txt";
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                var result = await "http://www.google.com".DownloadFileAsync("c:\\", "google.txt");
                Assert(result == path, $"Download result {result} doesn't match {path}");
                Assert(File.Exists(path), $"File didn't appear to download to {path}");
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            });

            if (_fail > 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"{_pass} passed, {_fail} failed");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Everything looks good");
            }
            Console.ResetColor();
        }
示例#12
0
        public async Task WhenSuccessfullyCreated_ReturnsId(Guid id)
        {
            using (var httpTest = new HttpTest())
            {
                httpTest.RespondWith(
                    JsonConvert.SerializeObject(id),
                    (int)HttpStatusCode.Created);

                var result = await new CartHttpClient(this.configuration)
                             .CreateCart();

                httpTest
                .ShouldHaveCalled($"{BaseUrl}/v1/cart")
                .WithVerb(HttpMethod.Post)
                .Times(1);
                result.Should().Be(id);
            }
        }
        public void ChoosesCorrectUrlForGmxNetEmail()
        {
            // Put flurl into test mode
            using (HttpTest httpTest = new HttpTest())
            {
                httpTest.RespondWith("a");

                var credentials = new CloudStorageCredentials
                {
                    Username            = "******", // gmx.net domain
                    UnprotectedPassword = "******"
                };

                byte[] res = Task.Run(async() => await DownloadFileWorksAsync("a.txt", credentials)).Result;

                httpTest.ShouldHaveCalled("https://webdav.mc.gmx.net/*");
            }
        }
示例#14
0
        public async void GetSchools_SiteIsAvailable_ReturnsSchools()
        {
            var timeout = TimeSpan.FromSeconds(5);
            var service = new SchoolsParser(timeout);

            using (var httpTest = new HttpTest())
            {
                httpTest.RespondWith(File.ReadAllText("TestData/Parsers/schools.html"));

                var result = await service.GetSchools();

                httpTest.ShouldHaveCalled(Constants.EndPoint)
                .WithVerb(HttpMethod.Get)
                .Times(1);

                Assert.NotEmpty(result);
            }
        }
示例#15
0
        public async Task TestGetGravatarProfileNotFound()
        {
            using (var httpTest = new HttpTest())
            {
                var fakeEmail = "*****@*****.**";
                httpTest.RespondWith("\"User not found\"", status: 404);
                try
                {
                    var profile = await TestFixture.Library.GetGravatarProfile(fakeEmail);

                    Assert.False(true, "GetGravatarProfile did not exception for non-existant gravatar");
                }
                catch (GravatarNotFoundException gnfe)
                {
                    Assert.Contains(fakeEmail, gnfe.Message);
                }
            }
        }
示例#16
0
        public void ShouldThrowServiceUnavailableExceptionOn503ResponseCode()
        {
            using (var http = new HttpTest())
            {
                http.RespondWith(HttpStatusCode.ServiceUnavailable, string.Empty);

                Func <Task> action = async() =>
                {
                    await Etcd.ClientFor(Fixtures.EtcdUrl.ToUri())
                    .Cluster
                    .GetLeader();
                };

                action.ShouldThrowExactly <ServiceUnavailableException>()
                .And
                .IsServiceUnavailable.Should().BeTrue();
            }
        }
示例#17
0
        public void WaitUntilDeleted_ThrowsException_WhenDeleteFails()
        {
            using (var httpTest = new HttpTest())
            {
                Identifier id = Guid.NewGuid();
                httpTest.RespondWithJson(new PublicIP {
                    Id = id, Status = PublicIPStatus.Active
                });
                httpTest.RespondWithJson(new PublicIP {
                    Id = id, Status = PublicIPStatus.Active
                });
                httpTest.RespondWith(JObject.Parse(@"{'status':'REMOVE_FAILED'}").ToString());

                var ip = _rackConnectService.GetPublicIP(id);
                ip.Delete();
                Assert.Throws <ServiceOperationFailedException>(() => ip.WaitUntilDeleted());
            }
        }
示例#18
0
        public async Task DeveConverterTesouroDiretoCorretamente()
        {
            IEnumerable <Investimento> result = null;

            using (var httpTest = new HttpTest())
            {
                httpTest.RespondWith(TwoTesouroDiretoJson, 200);
                result = await _tesouroDiretoService.GetInvestimentosByIdCliente("CLIENT_123");
            }

            var tesouroDireto = (TesouroDireto)result.ElementAt(1);

            result.Should().NotBeNull();
            result.Should().HaveCount(2);
            result.Should().AllBeOfType <TesouroDireto>();
            tesouroDireto.Iof.Should().BeApproximately(0f, 2);
            tesouroDireto.Indice.Should().Be("IPCA");
        }
示例#19
0
        public async Task NotExists()
        {
            using var httpTest = new HttpTest();
            httpTest.RespondWith(string.Empty, 404);
            // Logout
            httpTest.RespondWithJson(new { ok = true });

            var db = "rebel";

            await using var client = new CouchClient("http://localhost");
            var result = await client.ExistsAsync(db);

            Assert.False(result);

            httpTest
            .ShouldHaveCalled($"http://localhost/{db}")
            .WithVerb(HttpMethod.Head);
        }
示例#20
0
        public async Task GetSchools_SiteIsNotAvailable_ThrowsException()
        {
            var timeout = TimeSpan.FromSeconds(5);
            var service = new SchoolsParser(timeout);

            using (var httpTest = new HttpTest())
            {
                httpTest.RespondWith(string.Empty, 404);

                Func <Task> func = async() => await service.GetSchools();

                await func.Should().ThrowAsync <FlurlHttpException>();

                httpTest.ShouldHaveCalled(Constants.EndPoint)
                .WithVerb(HttpMethod.Get)
                .Times(1);
            }
        }
示例#21
0
        public void WaitUntilDeleted()
        {
            using (var httpTest = new HttpTest())
            {
                Identifier id = Guid.NewGuid();
                httpTest.RespondWithJson(new PublicIP {
                    Id = id, Status = PublicIPStatus.Active
                });
                httpTest.RespondWith((int)HttpStatusCode.NoContent, "All gone!");
                httpTest.RespondWithJson(new PublicIP {
                    Id = id, Status = PublicIPStatus.Deleted
                });

                var ip = _rackConnectService.GetPublicIP(id);
                ip.Delete();
                ip.WaitUntilDeleted();
            }
        }
示例#22
0
        public async Task WhenDoesNotExist_ReturnsCart(Guid id)
        {
            using (var httpTest = new HttpTest())
            {
                httpTest.RespondWith(
                    JsonConvert.SerializeObject(default(Cart)),
                    (int)HttpStatusCode.NotFound);

                var result = await new CartHttpClient(this.configuration)
                             .GetCart(id);

                httpTest
                .ShouldHaveCalled($"{BaseUrl}/v1/carts/{id}")
                .WithVerb(HttpMethod.Get)
                .Times(1);
                result.Should().BeNull();
            }
        }
示例#23
0
        public async Task GetOrCreateDatabase_402_ReturnDatabase()
        {
            using var httpTest = new HttpTest();
            // Operation result
            httpTest.RespondWith(string.Empty, 412);
            // Logout
            httpTest.RespondWithJson(new { ok = true });

            await using var client = new CouchClient("http://localhost");
            var rebels = await client.GetOrCreateDatabaseAsync <Rebel>();

            Assert.NotNull(rebels);

            httpTest
            .ShouldHaveCalled("http://localhost/rebels")
            .WithVerb(HttpMethod.Put);
            Assert.Equal("rebels", rebels.Database);
        }
示例#24
0
        public async Task Test1()
        {
            var jsonText = @"{ ""msg"": ""Hello world!"" }";

            using var httpTest = new HttpTest();
            httpTest.RespondWith(jsonText, 200);

            var json = await "https://api.com"
                       .AppendPathSegment("foo")
                       .SetQueryParams(new { fail = "false" })
                       .GetStringAsync();

            httpTest.ShouldHaveCalled("https://api.com/foo")
            .WithVerb(HttpMethod.Get)
            .WithQueryParam("fail");

            json.Should().Be(jsonText);
        }
        public async void GetSchedule_IncorrectId_ReturnsLessons()
        {
            const int teacherId = 1;
            var       timeout   = TimeSpan.FromSeconds(5);
            var       service   = new TeachersSchedule(timeout);

            using (var httpTest = new HttpTest())
            {
                httpTest.RespondWith("", 404);

                await Assert.ThrowsAsync <FlurlHttpException>(async() => await service.GetLessons(teacherId));

                httpTest.ShouldHaveCalled(Constants.EndPoint)
                .WithVerb(HttpMethod.Get)
                .WithQueryParamValue("lecturer", teacherId)
                .Times(1);
            }
        }
示例#26
0
        public async Task IsNotUp()
        {
            using (var httpTest = new HttpTest())
            {
                // Operation result
                httpTest.RespondWithJson(new { ok = true });
                // Logout
                httpTest.RespondWithJson(new { ok = true });

                using (var client = new CouchClient("http://localhost"))
                {
                    httpTest.RespondWith("Not found", 404);
                    var result = await client.IsUpAsync();

                    Assert.False(result);
                }
            }
        }
示例#27
0
        public async Task EvacuateServer()
        {
            using (var httpTest = new HttpTest())
            {
                Identifier serverId = Guid.NewGuid();
                httpTest.RespondWithJson(new Server {
                    Id = serverId
                });
                httpTest.RespondWith((int)HttpStatusCode.Accepted, "Roger that, boss");

                var server = _compute.GetServer(serverId);
                await server.EvacuateAsync(new EvacuateServerRequest(false));

                httpTest.ShouldHaveCalled($"*/servers/{serverId}/action");
                string lastRequest = httpTest.CallLog.Last().RequestBody;
                Assert.True(lastRequest.Contains("evacuate"));
            }
        }
        public void AssignPublicIP_RetriesWhenTheServerIsNotFound()
        {
            using (var httpTest = new HttpTest())
            {
                Identifier serverId = Guid.NewGuid();
                Identifier id = Guid.NewGuid();
                httpTest.RespondWithJson(new PublicIP { Id = id });
                httpTest.RespondWith((int)HttpStatusCode.Conflict, $"Cloud Server {serverId} does not exist");
                httpTest.RespondWithJson(new PublicIP { Id = id, Server = new PublicIPServerAssociation { ServerId = serverId } });

                var ip = _rackConnectService.GetPublicIP(id);
                ip.Assign(serverId);

                httpTest.ShouldHaveCalled($"*/public_ips/{id}");
                Assert.NotNull(ip.Server);
                Assert.Equal(serverId, ip.Server.ServerId);
            }
        }
        public async Task StudySubjectsRequest_correctly_parses_response()
        {
            var httpTest = new HttpTest();

            httpTest.RespondWith(
                @"<ODM FileType=""Snapshot"" FileOID=""767a1f8b-7b72-4d12-adbe-37d4d62ba75e""
                         CreationDateTime=""2013-04-08T10:02:17.781-00:00""
                         ODMVersion=""1.3""
                         xmlns:mdsol=""http://www.mdsol.com/ns/odm/metadata""
                         xmlns:xlink=""http://www.w3.org/1999/xlink""
                         xmlns=""http://www.cdisc.org/ns/odm/v1.3"">
                 <ClinicalData StudyOID=""FakeItTillYaMakeIt(Dev)"" MetaDataVersionOID=""1111"">
                    <SubjectData SubjectKey=""000002"">
                       <SiteRef LocationOID=""101""/>
                    </SubjectData>
                 </ClinicalData>
                 <ClinicalData StudyOID=""FakeItTillYaMakeIt(Dev)"" MetaDataVersionOID=""1111"">
                     <SubjectData SubjectKey=""000003"">
                        <SiteRef LocationOID=""6""/>
                     </SubjectData>
                 </ClinicalData>
                 <ClinicalData StudyOID=""FakeItTillYaMakeIt(Dev)"" MetaDataVersionOID=""1111"">
                     <SubjectData SubjectKey=""EC82F1AB-D463-4930-841D-36FC865E63B2"" mdsol:SubjectName=""1"" mdsol:SubjectKeyType=""SubjectUUID"">
                        <SiteRef LocationOID=""6""/>
                     </SubjectData>
                 </ClinicalData>
            </ODM>");

            var connection = new RwsConnection("innovate", "test", "pw");
            var request    = new StudySubjectsRequest(ProjectName, Environment);
            var response   = await connection.SendRequestAsync(request) as RwsSubjects;

            Assert.IsInstanceOfType(response, typeof(RwsSubjects));

            var subjectNames = new string[] { "000002", "000003", "1" };

            foreach (var subject in response)
            {
                Assert.IsInstanceOfType(subject, typeof(RwsSubjectListItem));
                Assert.IsTrue(subjectNames.Contains(subject.SubjectName));
            }

            httpTest.Dispose();
        }
        public async Task CanLoginOn170(string token, string user, string password)
        {
            _http.ResponseQueue.Clear();
            _http.RespondWithJson(new SystemInfo {
                Version = "v1.7.0-rc.0"
            });
            _http.RespondWith("", cookies: new { sid = token });

            await client.Login(user, password);

            Assert.Equal(token, client.SessionToken);
            _http.ShouldHaveCalled("*/c/login").WithVerb(HttpMethod.Post).WithRequestBody($"principal={user}&password={password}").Times(1);
        }
示例#31
0
        public async Task GenericExceptionWithMessage()
        {
            using (var httpTest = new HttpTest())
            {
                string message = "message text";
                string reason  = "reason text";
                httpTest.RespondWith($"{{error: \"{message}\", reason: \"{reason}\"}}", (int)HttpStatusCode.InternalServerError);

                using (var client = new CouchClient("http://localhost"))
                {
                    var db             = client.GetDatabase <Rebel>();
                    var couchException = await Assert.ThrowsAsync <CouchException>(() => db.FindAsync("aoeu"));

                    Assert.Equal(message, couchException.Message);
                    Assert.Equal(reason, couchException.Reason);
                    Assert.IsType <Flurl.Http.FlurlHttpException>(couchException.InnerException);
                }
            }
        }
示例#32
0
        public async void GetLocationsAsync_ReturnsWithCorrectResults()
        {
            using (var httpTest = new HttpTest())
            {
                // Arrange
                httpTest.RespondWith("[{\"distance\":1836,\"title\":\"Santa Cruz\",\"location_type\":\"City\",\"woeid\":2488853,\"latt_long\":\"36.974018, -122.030952\"}]");

                // Act
                var results = await weatherService.GetLocationsAsync(10, 10);

                // Asert
                Assert.NotNull(results);
                Assert.True(results.Count == 1);
                var result = results.First();
                Assert.Equal("Santa Cruz", result.Title);
                Assert.Equal(2488853, result.WoeId);
                Assert.Equal("36.974018, -122.030952", result.Latt_Long);
            }
        }
示例#33
0
        public void WhenDeleteNetwork_Returns404NotFound_ShouldConsiderRequestSuccessful()
        {
            using (var httpTest = new HttpTest())
            {
                Identifier networkId = Guid.NewGuid();
                httpTest.RespondWith((int)HttpStatusCode.NotFound, "Not here, boss...");

                _cloudNetworkService.DeleteNetwork(networkId);

                httpTest.ShouldHaveCalled("*/networks/" + networkId);
            }
        }
        public void WaitUntilDeleted_AcceptsNotFoundExceptionAsSuccess()
        {
            using (var httpTest = new HttpTest())
            {
                Identifier id = Guid.NewGuid();
                httpTest.RespondWithJson(new PublicIP { Id = id, Status = PublicIPStatus.Active });
                httpTest.RespondWith((int) HttpStatusCode.NoContent, "All gone!");
                httpTest.RespondWith((int) HttpStatusCode.NotFound, "Not here, boss!");

                var ip = _rackConnectService.GetPublicIP(id);
                ip.Delete();
                ip.WaitUntilDeleted();
            }
        }
        public void CreatePublicIP_RetriesWhenTheServerIsNotFound()
        {
            using (var httpTest = new HttpTest())
            {
                string serverId = Guid.NewGuid().ToString();
                Identifier id = Guid.NewGuid();
                httpTest.RespondWith((int)HttpStatusCode.Conflict, $"Cloud Server {serverId} does not exist");
                httpTest.RespondWithJson(new PublicIP { Id = id });

                var ipRequest = new PublicIPCreateDefinition { ServerId = serverId };
                var result = _rackConnectService.CreatePublicIP(ipRequest);

                httpTest.ShouldHaveCalled($"*/public_ips");
                Assert.NotNull(result);
                Assert.Equal(id, result.Id);
                Assert.NotNull(((IServiceResource<RackConnectService>)result).Owner);
            }
        }
        public void WaitUntilDeleted_ThrowsException_WhenDeleteFails()
        {
            using (var httpTest = new HttpTest())
            {
                Identifier id = Guid.NewGuid();
                httpTest.RespondWithJson(new PublicIP { Id = id, Status = PublicIPStatus.Active });
                httpTest.RespondWithJson(new PublicIP { Id = id, Status = PublicIPStatus.Active });
                httpTest.RespondWith(JObject.Parse(@"{'status':'REMOVE_FAILED'}").ToString());

                var ip = _rackConnectService.GetPublicIP(id);
                ip.Delete();
                Assert.Throws<ServiceOperationFailedException>(() =>ip.WaitUntilDeleted());
            }
        }