public async Task GetCurrencyRate_Always_ReturnsRate() { // arrange using var httpTest = new HttpTest(); var ondate = DateTime.Now; httpTest .ForCallsTo("https://www.nbrb.by/api/exrates/rates/USD") .WithVerb(HttpMethod.Get) .WithQueryParam("parammode", 2) .WithQueryParam("ondate", ondate.ToString()) .RespondWith( "{\"Cur_ID\":145,\"Date\":\"2021-06-15T00:00:00\"" + ",\"Cur_Abbreviation\":\"USD\",\"Cur_Scale\":1,\"Cur_Name\":" + "\"Доллар США\",\"Cur_OfficialRate\":2.4892}"); // act var api = new BynCurrenciesApi(); var result = await api.GetCurrencyRate("USD", ondate); // assert result.Should().BeEquivalentTo(new CurrencyRateModel { Date = ondate, Nominal = 1, Rate = 2.4892, Id = "145", Name = "Доллар США", CharCode = "USD" }); }
public async Task GetCurrenciesByDate_Always_ReturnsCurrenciesByDate() { // arrange using var httpTest = new HttpTest(); var ondate = new DateTime(2021, 01, 01); httpTest .ForCallsTo("https://www.nbrb.by/api/exrates/currencies/298") .WithVerb(HttpMethod.Get) .WithQueryParam("date", ondate.ToString()) .RespondWith( "{\"Cur_ID\":298,\"Date\":\"2021-01-01T00:00:00\",\"Cur_Abbreviation\":\"RUB\"," + "\"Cur_Scale\":100,\"Cur_Name\":\"Российских рублей\",\"Cur_OfficialRate\":3.4871}"); // act var api = new BynCurrenciesApi(); var result = await api.GetCurrencies(ondate); // assert var result1 = new CurrencyModel[1] { new CurrencyModel { Id = "298", Name = "Российских рублей", CharCode = "RUB" } }; result.Should().BeEquivalentTo(result1); }
public async Task GetCurrencies_Always_ReturnsCurrencies() { // arrange using var httpTest = new HttpTest(); var ondate = DateTime.Now; httpTest .ForCallsTo("https://www.nbrb.by/api/exrates/currencies") .WithVerb(HttpMethod.Get) .RespondWith( "[{ \"Cur_ID\":1,\"Cur_ParentID\":1,\"Cur_Code\":\"008\",\"Cur_Abbreviation\":\"ALL\",\"Cur_Name\":\"Албанский лек\"" + ",\"Cur_Name_Bel\":\"Албанскі лек\",\"Cur_Name_Eng\":\"Albanian Lek\",\"Cur_QuotName\":\"1 Албанский лек\"," + "\"Cur_QuotName_Bel\":\"1 Албанскі лек\",\"Cur_QuotName_Eng\":\"1 Albanian Lek\",\"Cur_NameMulti\":\"\",\"Cur_Name_BelMulti\":\"\"," + "\"Cur_Name_EngMulti\":\"\",\"Cur_Scale\":1,\"Cur_Periodicity\":1,\"Cur_DateStart\":\"1991-01-01T00:00:00\",\"Cur_DateEnd\":\"2007-11-30T00:00:00\"}," + "{ \"Cur_ID\":2,\"Cur_ParentID\":2,\"Cur_Code\":\"012\",\"Cur_Abbreviation\":\"DZD\",\"Cur_Name\":\"Алжирский динар\"," + "\"Cur_Name_Bel\":\"Алжырскі дынар\",\"Cur_Name_Eng\":\"Algerian Dinar\",\"Cur_QuotName\":\"1 Алжирский динар\"," + "\"Cur_QuotName_Bel\":\"1 Алжырскі дынар\",\"Cur_QuotName_Eng\":\"1 Algerian Dinar\",\"Cur_NameMulti\":\"\",\"Cur_Name_BelMulti\":\"\"," + "\"Cur_Name_EngMulti\":\"\",\"Cur_Scale\":1,\"Cur_Periodicity\":1,\"Cur_DateStart\":\"1991-01-01T00:00:00\",\"Cur_DateEnd\":\"2016-06-30T00:00:00\"}," + "{ \"Cur_ID\":5,\"Cur_ParentID\":5,\"Cur_Code\":\"032\",\"Cur_Abbreviation\":\"ARS\",\"Cur_Name\":\"Аргентинское песо\"," + "\"Cur_Name_Bel\":\"Аргенцінскае песа\",\"Cur_Name_Eng\":\"Argentine Peso\",\"Cur_QuotName\":\"1 Аргентинское песо\"," + "\"Cur_QuotName_Bel\":\"1 Аргенцінскае песа\",\"Cur_QuotName_Eng\":\"1 Argentine Peso\",\"Cur_NameMulti\":\"\",\"Cur_Name_BelMulti\":\"\"," + "\"Cur_Name_EngMulti\":\"\",\"Cur_Scale\":1,\"Cur_Periodicity\":1,\"Cur_DateStart\":\"1991-01-01T00:00:00\",\"Cur_DateEnd\":\"2016-06-30T00:00:00\"}]"); // act var api = new BynCurrenciesApi(); var result = await api.GetCurrencies(); // assert var result1 = new CurrencyModel[3] { new CurrencyModel { Id = "1", Name = "Албанский лек", CharCode = "ALL", }, new CurrencyModel { Id = "2", Name = "Алжирский динар", CharCode = "DZD", }, new CurrencyModel { Id = "5", Name = "Аргентинское песо", CharCode = "ARS", }, }; result.Should().BeEquivalentTo(result1); }
public async Task can_respond_based_on_any_call_condition() { HttpTest .ForCallsTo("*") .With(call => call.Request.Url.Fragment.StartsWith("abc")) .Without(call => call.Request.Url.Fragment.EndsWith("xyz")) .RespondWith("arbitrary conditions met!"); Assert.AreEqual("", await "http://api.com#abcxyz".GetStringAsync()); Assert.AreEqual("", await "http://api.com#xyz".GetStringAsync()); Assert.AreEqual("arbitrary conditions met!", await "http://api.com#abcxy".GetStringAsync()); }
public async Task can_respond_based_on_body() { HttpTest .ForCallsTo("*") .WithRequestBody("*something*") .WithRequestJson(new { a = "*", b = new { c = "*", d = "yes" } }) .RespondWith("body conditions met!"); Assert.AreEqual("", await "http://api.com".PostStringAsync("something").ReceiveString()); Assert.AreEqual("", await "http://api.com".PostJsonAsync( new { a = "hi", b = new { c = "bye", d = "yes" } }).ReceiveString()); Assert.AreEqual("body conditions met!", await "http://api.com".PostJsonAsync( new { a = "hi", b = new { c = "this is something!", d = "yes" } }).ReceiveString()); }
public async Task can_respond_based_on_headers() { HttpTest .ForCallsTo("*") .WithHeader("x") .WithHeader("y", "f*o") .WithoutHeader("y", "flo") .WithoutHeader("z") .RespondWith("header conditions met!"); Assert.AreEqual("", await "http://api.com".WithHeaders(new { y = "foo" }).GetStringAsync()); Assert.AreEqual("", await "http://api.com".WithHeaders(new { x = 1, y = "flo" }).GetStringAsync()); Assert.AreEqual("", await "http://api.com".WithHeaders(new { x = 1, y = "foo", z = 2 }).GetStringAsync()); Assert.AreEqual("header conditions met!", await "http://api.com".WithHeaders(new { x = 1, y = "foo" }).GetStringAsync()); }
public async Task can_respond_based_on_url() { HttpTest.RespondWith("never"); HttpTest.ForCallsTo("*/1").RespondWith("one"); HttpTest.ForCallsTo("*/2").RespondWith("two"); HttpTest.ForCallsTo("*/3").RespondWith("three"); HttpTest.ForCallsTo("http://www.api.com/*").RespondWith("foo!"); Assert.AreEqual("foo!", await "http://www.api.com/4".GetStringAsync()); Assert.AreEqual("three", await "http://www.api.com/3".GetStringAsync()); Assert.AreEqual("two", await "http://www.api.com/2".GetStringAsync()); Assert.AreEqual("one", await "http://www.api.com/1".GetStringAsync()); Assert.AreEqual(4, HttpTest.CallLog.Count); }
public async Task can_allow_real_http_in_test() { using (var test = new HttpTest()) { test.RespondWith("foo"); test.ForCallsTo("*httpbin*").AllowRealHttp(); Assert.AreEqual("foo", await "https://www.google.com".GetStringAsync()); Assert.AreNotEqual("foo", await "https://httpbin.org/get".GetStringAsync()); Assert.AreEqual("bar", (await "https://httpbin.org/get?x=bar".GetJsonAsync()).args.x); Assert.AreEqual("foo", await "https://www.microsoft.com".GetStringAsync()); // real calls still get logged Assert.AreEqual(4, test.CallLog.Count); test.ShouldHaveCalled("https://httpbin*").Times(2); } }
public static async Task TestProxyFallback() { using var x = await TestSetup.TextCtx(); var scraper = x.Scope.Resolve <YtWeb>(); using var httpTest = new HttpTest(); var rw = httpTest.ForCallsTo("*youtube.com*").RespondWith("mock too many requests failure", status: 429); var getExtra = scraper.GetExtra(x.Log, "Su1FQUkMojU", new[] { ExtraPart.EComment }); await 5.Seconds().Delay(); rw.AllowRealHttp(); var extra = await getExtra; // this should have fallen back to proxy and retried a once or twice in the 5 seconds. scraper.Client.UseProxy.Should().Be(true); }
public async Task can_respond_based_on_query_params() { HttpTest .ForCallsTo("*") .WithQueryParam("x", 1) .WithQueryParams(new { y = 2, z = 3 }) .WithAnyQueryParam("a", "b", "c") .WithoutQueryParam("d") .WithoutQueryParams(new { c = "n*" }) .RespondWith("query param conditions met!"); Assert.AreEqual("", await "http://api.com?x=1&y=2&a=yes".GetStringAsync()); Assert.AreEqual("", await "http://api.com?y=2&z=3&b=yes".GetStringAsync()); Assert.AreEqual("", await "http://api.com?x=1&y=2&z=3&c=yes&d=yes".GetStringAsync()); Assert.AreEqual("", await "http://api.com?x=1&y=2&z=3&c=no".GetStringAsync()); Assert.AreEqual("query param conditions met!", await "http://api.com?x=1&y=2&z=3&c=yes".GetStringAsync()); }
public async Task GetUrlListAsyncShouldReturnProperUrls(string endpoint) { var fakeURLResult = AutoFaker.Generate <ResourceResponse>(); var expectedResult = fakeURLResult.Results.Select(r => r.Url); using var httpTest = new HttpTest(); httpTest .ForCallsTo($"{Constants.BaseAddress}{endpoint}") .WithVerb(HttpMethod.Get) .WithQueryParam("limit", 100) .WithQueryParam("offset", 0) .RespondWithJson(fakeURLResult); var result = await _resourceService.GetUrlListAsync(endpoint, 100, 0); result.Should().NotBeNullOrEmpty(); result.Should().BeEquivalentTo(expectedResult); }
public static async Task GetBuyerOrganisationByOdsCode_CallsOdsApi_OnceForMultipleCalls() { var context = OdsRepositoryTestContext.Setup(); var url = $"{context.OdsSettings.ApiBaseUrl}/organisations/{OdsCode}"; using var httpTest = new HttpTest(); httpTest .ForCallsTo(url) .RespondWith(status: 200, body: ValidResponseBody); await context.OdsRepository.GetBuyerOrganisationByOdsCodeAsync(OdsCode); await context.OdsRepository.GetBuyerOrganisationByOdsCodeAsync(OdsCode); await context.OdsRepository.GetBuyerOrganisationByOdsCodeAsync(OdsCode); httpTest.ShouldHaveCalled(url) .WithVerb(HttpMethod.Get) .Times(1); }
public async Task can_respond_based_on_verb() { HttpTest.RespondWith("catch-all"); HttpTest .ForCallsTo("http://www.api.com*") .WithVerb(HttpMethod.Post) .RespondWith("I posted."); HttpTest .ForCallsTo("http://www.api.com*") .WithVerb("put", "PATCH") .RespondWith("I put or patched."); Assert.AreEqual("I put or patched.", await "http://www.api.com/1".PatchAsync(null).ReceiveString()); Assert.AreEqual("I posted.", await "http://www.api.com/2".PostAsync(null).ReceiveString()); Assert.AreEqual("I put or patched.", await "http://www.api.com/3".SendAsync(HttpMethod.Put, null).ReceiveString()); Assert.AreEqual("catch-all", await "http://www.api.com/4".DeleteAsync().ReceiveString()); Assert.AreEqual(4, HttpTest.CallLog.Count); }
[Test] // #596 public async Task url_patterns_ignore_query_when_not_specified() { HttpTest.ForCallsTo("http://api.com/1").RespondWith("one"); HttpTest.ForCallsTo("http://api.com/2").WithAnyQueryParam().RespondWith("two"); HttpTest.ForCallsTo("http://api.com/3").WithoutQueryParams().RespondWith("three"); Assert.AreEqual("one", await "http://api.com/1".GetStringAsync()); Assert.AreEqual("one", await "http://api.com/1?x=foo&y=bar".GetStringAsync()); Assert.AreEqual("", await "http://api.com/2".GetStringAsync()); Assert.AreEqual("two", await "http://api.com/2?x=foo&y=bar".GetStringAsync()); Assert.AreEqual("three", await "http://api.com/3".GetStringAsync()); Assert.AreEqual("", await "http://api.com/3?x=foo&y=bar".GetStringAsync()); HttpTest.ShouldHaveCalled("http://api.com/1").Times(2); HttpTest.ShouldHaveCalled("http://api.com/1").WithAnyQueryParam().Times(1); HttpTest.ShouldHaveCalled("http://api.com/1").WithoutQueryParams().Times(1); HttpTest.ShouldHaveCalled("http://api.com/1?x=foo").Times(1); HttpTest.ShouldHaveCalled("http://api.com/1?x=foo").WithQueryParam("y").Times(1); HttpTest.ShouldHaveCalled("http://api.com/1?x=foo").WithQueryParam("y", "bar").Times(1); }
public static async Task GetBuyerOrganisationByOdsCode_WithNotFoundResponseFromOdsApi_Returns_Null() { const string odsCode = "ods-code-839"; var context = OdsRepositoryTestContext.Setup(); var url = $"{context.OdsSettings.ApiBaseUrl}/organisations/{odsCode}"; var cachingService = new CachingService(); cachingService.CacheProvider.Remove(odsCode); var repository = new OdsRepository(context.OdsSettings, cachingService); using var httpTest = new HttpTest(); httpTest .ForCallsTo(url) .RespondWithJson(new { ErrorCode = 404, ErrorText = "Not Found." }, 404); var result = await repository.GetBuyerOrganisationByOdsCodeAsync(odsCode); httpTest.ShouldHaveCalled(url) .WithVerb(HttpMethod.Get) .Times(1); result.Should().BeNull(); }
public async Task GetDetailListUrlShouldReturnAnAbilityList() { var faker = new Faker(); var fakeUrl = faker.Internet.Url(); var fakeUrlList = new List <string>() { fakeUrl }; var fakeAbility = AutoFaker.Generate <Ability>(); var fakeAbilityList = new List <Ability>() { fakeAbility }; using var httpTest = new HttpTest(); httpTest.ForCallsTo(fakeUrl) .WithVerb(HttpMethod.Get) .RespondWithJson(fakeAbility); var result = await _resourceService.GetDetailListAsync <Ability>(fakeUrlList); result.Should().BeEquivalentTo(fakeAbilityList); }
public async Task GetDynamics_Always_ReturnDynamics() { // arrange using var httpTest = new HttpTest(); var ondate = DateTime.Now; string charCode = "USD"; DateTime start = new DateTime(2021, 01, 01); DateTime end = new DateTime(2021, 01, 03); //https://www.nbrb.by/API/ExRates/Rates/Dynamics/145?startDate=2021-1-1&endDate=2021-1-3 httpTest .ForCallsTo("https://www.nbrb.by/api/exrates/currencies") .WithVerb(HttpMethod.Get) .RespondWith("[{ \"Cur_ID\":145,\"Cur_ParentID\":145,\"Cur_Code\":" + "\"840\",\"Cur_Abbreviation\":\"USD\",\"Cur_Name\":\"Доллар США\"}]"); httpTest .ForCallsTo("https://www.nbrb.by/api/exrates/rates/dynamics/145") .WithVerb(HttpMethod.Get) .WithQueryParam("startdate", start.ToString()) .WithQueryParam("enddate", end.ToString()) .RespondWith( "[{ \"Cur_ID\":145,\"Date\":\"2021-01-01T00:00:00\",\"Cur_OfficialRate\":2.5789}," + "{ \"Cur_ID\":145,\"Date\":\"2021-01-02T00:00:00\",\"Cur_OfficialRate\":2.5789}," + "{ \"Cur_ID\":145,\"Date\":\"2021-01-03T00:00:00\",\"Cur_OfficialRate\":2.5789}]"); // act var api = new BynCurrenciesApi(); var result = await api.GetDynamics(charCode, start, end); // assert var result1 = new CurrencyRateModel[3] { new CurrencyRateModel { Date = new DateTime(2021, 01, 01), Id = "145", Name = "Доллар США", Nominal = 0, Rate = 2.5789, CharCode = "USD", }, new CurrencyRateModel { Date = new DateTime(2021, 01, 02), Id = "145", Name = "Доллар США", Nominal = 0, Rate = 2.5789, CharCode = "USD", }, new CurrencyRateModel { Date = new DateTime(2021, 01, 03), Id = "145", Name = "Доллар США", Nominal = 0, Rate = 2.5789, CharCode = "USD", }, }; result.Should().BeEquivalentTo(result1); }
public async Task POST_dockerhub_handler_should_get_services_from_swarmpit_filter_them_and_update_filtered_ones() { // Arrange const string secret = "my_secret"; const string baseUrl = "http://swarmpit/api/"; const string accessToken = "abc123"; const string helloRepositoryName = "dopplerdock/hello-microservice"; const string cdHelperRepositoryName = "dopplerdock/doppler-cd-helper"; const string intTag = "INT"; const string qaTag = "QA"; var hookData = new DockerHubHookData() { callback_url = "https://callback_url", push_data = new DockerHubHookDataPushData() { tag = intTag }, repository = new DockerHubHookDataRepository() { repo_name = helloRepositoryName } }; // should be redeployed var helloServiceInt = new SwarmServiceDescription() { id = "penpnhep0bsciofxzd542v62n", serviceName = "hello-int_hello-service", repository = new SwarmServiceDescriptionRepository() { name = helloRepositoryName, tag = intTag, imageDigest = "sha256:c7a459f13dbf082fe9b6631783f897d54978a32cc91aa8dee5fcb5630fa18a0b" } }; // should not be redeployed var cdHelperServiceInt = new SwarmServiceDescription() { id = "qn3jq891p77lyigwysj4fcww2", serviceName = "swarmpit_doppler-cd-helper", repository = new SwarmServiceDescriptionRepository() { name = cdHelperRepositoryName, tag = intTag, imageDigest = "sha256:a247c00ad3ae505bbcbcbc48eb58a50a16e0628339803da65c9081be365b3b9c" } }; // Exactly the same image with another configuration // should be redeployed var helloServiceIntWithAlternativeConfiguration = helloServiceInt with { id = "riq6gv8d0xr9rpagr9lg5xqrw", serviceName = "hello-int_hello-service_with_alternative_configuration", }; // The same image name with a different tag with another configuration // should not be redeployed var helloServiceQA = helloServiceInt with { id = "riq6gv8d0xr9rpagr9lg5xqrw", serviceName = "hello-int_hello-service_with_alternative_configuration", repository = helloServiceInt.repository with { tag = qaTag } }; using var customFactory = _factory.WithWebHostBuilder(c => { c.ConfigureServices(s => s.AddSingleton(Options.Create(new SwarmpitSwarmClientSettings() { BaseUrl = baseUrl, AccessToken = accessToken })) .AddSingleton(Options.Create(new DockerHubHookSettings() { Secret = secret }))); }); customFactory.Server.PreserveExecutionContext = true; using var httpTest = new HttpTest(); httpTest.ForCallsTo($"{baseUrl}services") .WithHeader("Authorization", $"Bearer {accessToken}") .WithVerb("GET") .RespondWithJson(new[] { helloServiceInt, cdHelperServiceInt, helloServiceIntWithAlternativeConfiguration, helloServiceQA }); var client = customFactory.CreateClient(new WebApplicationFactoryClientOptions() { AllowAutoRedirect = false }); // Act var response = await client.PostAsync( $"/hooks/{secret}/", JsonContent.Create(hookData)); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(3, httpTest.CallLog.Count()); httpTest.ShouldHaveCalled($"{baseUrl}services/{helloServiceInt.id}/redeploy") .WithOAuthBearerToken(accessToken) .WithVerb("POST"); httpTest.ShouldHaveCalled($"{baseUrl}services/{helloServiceIntWithAlternativeConfiguration.id}/redeploy") .WithOAuthBearerToken(accessToken) .WithVerb("POST"); }