public async Task StubIntegration_Proxy_Post_ProxiesCorrectly()
    {
        // Arrange
        var          url         = $"{TestServer.BaseAddress}todoitems/todos";
        const string postContent = "this is the content";
        var          request     = new HttpRequestMessage
        {
            RequestUri = new Uri(url),
            Method     = HttpMethod.Post,
            Content    = new StringContent(postContent, Encoding.UTF8, Constants.TextMime)
        };

        MockHttp
        .When(HttpMethod.Post, "https://jsonplaceholder.typicode.com/todos")
        .WithContent(postContent)
        .Respond(Constants.TextMime, "OK from Proxy");

        // Act / Assert
        using var response = await Client.SendAsync(request);

        var content = await response.Content.ReadAsStringAsync();

        Assert.AreEqual("OK from Proxy", content);
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }
Example #2
0
        public async Task Should_RequestWithHeaderAndParams_When_ConfigureServeralOptions()
        {
            // Given
            var content = new { A = "b" };
            var request = MockHttp.When(HttpMethod.Post, "http://localhost:8080/api/index")
                          .WithHeaders(HttpRequestHeader.Authorization.ToString(), "Bearer AccessToken")
                          .WithQueryString("a", "b")
                          .WithQueryString("c", "d")
                          .WithContent(JsonConvert.SerializeObject(content))
                          .Respond(HttpStatusCode.OK, new StringContent("Hello"));

            // When
            var message = await Client.WithUri("http://localhost:8080/api/index")
                          .WithHeader(HttpRequestHeader.Authorization, "Bearer AccessToken")
                          .WithQuery("a", "b")
                          .WithQuery("c", "d")
                          .WithJsonContent(content)
                          .PostAsync();

            // Then
            message.StatusCode.Should().Be(HttpStatusCode.OK);
            var response = await message.Content.ReadAsStringAsync();

            response.Should().Be("Hello");
            MockHttp.GetMatchCount(request).Should().Be(1);
        }
Example #3
0
        public void Arrange()
        {
            Setup();

            var certificateResponses = Builder <CertificateResponse> .CreateListOfSize(10).Build();

            MockHttp.When("http://localhost:59022/api/v1/certificates/tobeprinted")
            .Respond("application/json", JsonConvert.SerializeObject(certificateResponses));     // Respond with JSON

            _result = AssessorServiceApi.GetCertificatesToBePrinted().Result;
        }
        public async Task ThenItShouldUpdateCertificatesInChunksOf100(int batchSize, int chunksSent)
        {
            Setup();

            var request = MockHttp.When(HttpMethod.Put, "http://localhost:59022/api/v1/certificates/*")
                          .Respond(System.Net.HttpStatusCode.OK, "application/json", "{'status' : 'Boo'}");

            var certificateResponses = Builder <CertificateResponse> .CreateListOfSize(batchSize).Build();

            await AssessorServiceApi.ChangeStatusToPrinted(1, certificateResponses);

            Assert.AreEqual(chunksSent, MockHttp.GetMatchCount(request));
        }
Example #5
0
        public void Arrange()
        {
            Setup();

            _emailTemplate = Builder <EMailTemplate> .CreateNew().Build();

            var templateName = EMailTemplateNames.PrintAssessorCoverLetters;

            MockHttp.When($"http://localhost:59022/api/v1/emailTemplates/{templateName}")
            .Respond("application/json", JsonConvert.SerializeObject(_emailTemplate));     // Respond with JSON

            _result = AssessorServiceApi.GetEmailTemplate(templateName).Result;
        }
        public void Arrange()
        {
            Setup();

            _expected = Builder <BatchLogResponse> .CreateNew()
                        .With(q => q.BatchNumber = 12)
                        .Build();

            MockHttp.When("http://localhost:59022/api/v1/batches/latest")
            .Respond("application/json", JsonConvert.SerializeObject(_expected));     // Respond with JSON

            _result = AssessorServiceApi.GetCurrentBatchLog().Result;
        }
        public async Task Given_job_is_queued_outside_correlationContext_should_put_correlationId_in_http_header()
        {
            string jobId = _client.Enqueue <BackgroundTestExecutor>(job => job.RunAsync(TimeoutInMillis, null));

            MockHttp
            .When(matching => matching.Header(CorrelationHttpHeaders.CorrelationId, jobId))
            .Callback(r => _testOutputHelper.WriteLine("Request sent with correlation id: {0}", jobId))
            .Respond(HttpStatusCode.OK)
            .Verifiable();

            // Act
            await WaitUntilJobCompletedAsync(jobId);

            // Assert
            MockHttp.Verify();
        }
        public async Task DoNotRequestNewTokenWhenRefreshedTokenIsNotExpired()
        {
            MockHttp.Clear();

            var getToken = MockHttp.When(AuthUrl)
                           .WithFormData("grant_type", "password")
                           .Respond(HttpStatusCode.OK, "application/json",
                                    @"{
                        'access_token': 'old_token',
                        'token_type': 'token_type',
                        'refresh_token': 'refresh_token',
                        'expires_in': 0,
                        'scope': 'scope',
                        'jti': '00000000-0000-0000-0000-000000000000'
                    }");

            var refreshToken = MockHttp.When(AuthUrl)
                               .WithFormData("grant_type", "refresh_token")
                               .Respond(HttpStatusCode.OK, "application/json",
                                        @"{
                        'access_token': 'new_token',
                        'token_type': 'token_type',
                        'refresh_token': 'refresh_token',
                        'expires_in': 1000,
                        'scope': 'scope',
                        'jti': '00000000-0000-0000-0000-000000000000'
                    }");

            var provider = CreateTokenProvider();

            await provider.GetAuthorizationHeader(false);

            await provider.GetAuthorizationHeader(false);

            var header = await provider.GetAuthorizationHeader(false);

            Assert.Equal("Authorization", header.Key);
            Assert.Equal("token_type new_token", header.Value);

            Assert.Equal(1, MockHttp.GetMatchCount(getToken));
            Assert.Equal(1, MockHttp.GetMatchCount(refreshToken));
        }
        public async Task ProvideAccessToken()
        {
            MockHttp.Clear();

            MockHttp
            .When(AuthUrl)
            .Respond(HttpStatusCode.OK, "application/json",
                     @"{
                    'access_token': 'access_token_value',
                    'token_type': 'token_type_value',
                    'refresh_token': 'refresh_token_value',
                    'expires_in': 1000,
                    'scope': 'scim.me openid password.write approvals.me oauth.approvals',
                    'jti': '11111111-1111-1111-1111-111111111111'
                }");

            var header = await CreateTokenProvider().GetAuthorizationHeader(false);

            Assert.Equal("Authorization", header.Key);
            Assert.Equal("token_type_value access_token_value", header.Value);
        }
    public async Task StubIntegration_Proxy_GetWithQueryString_ProxiesCorrectly()
    {
        // Arrange
        var url     = $"{TestServer.BaseAddress}todoitems/todos/1?key=val&key2=val2";
        var request = new HttpRequestMessage
        {
            RequestUri = new Uri(url)
        };

        MockHttp
        .When(HttpMethod.Get, "https://jsonplaceholder.typicode.com/todos/1?key=val&key2=val2")
        .Respond(Constants.TextMime, "OK from Proxy");

        // Act / Assert
        using var response = await Client.SendAsync(request);

        var content = await response.Content.ReadAsStringAsync();

        Assert.AreEqual("OK from Proxy", content);
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }
Example #11
0
 public async Task WithBaseUri()
 {
     Client
     .WithBaseUri("http://test.com/api/auth")
     .Match(MockHttp.When("http://test.com/api/auth"));
 }
 public UpdateDownloaderFileTests()
 {
     MockHttp.When("*download").Respond(HttpHandler);
 }
        public async Task SendAdditionalRequestIfTokenExpired()
        {
            var json = @"[
                    'name1',
                    'name2',
                    'name3'
                ]".QuotesToDoubleQuotes();

            var expectedList = new List <string>()
            {
                "name1",
                "name2",
                "name3"
            };

            var url = BaseUrl + $"/v1/o/{OrgName}/apiproducts?count={EntitiesLimit}";

            MockHttp.Clear();

            var getProductsUnauthorized = MockHttp.When(url)
                                          .WithHeaders("Authorization", "token_type access_token")
                                          .Respond(HttpStatusCode.Unauthorized);

            var getToken = MockHttp.When(AuthUrl)
                           .WithFormData("grant_type", "password")
                           .Respond(HttpStatusCode.OK, "application/json",
                                    @"{
                        'access_token': 'access_token',
                        'token_type': 'token_type',
                        'refresh_token': 'refresh_token',
                        'expires_in': 1000,
                        'scope': 'scope',
                        'jti': '00000000-0000-0000-0000-000000000000'
                    }");

            var refreshToken = MockHttp.When(AuthUrl)
                               .WithFormData("grant_type", "refresh_token")
                               .Respond(HttpStatusCode.OK, "application/json",
                                        @"{
                        'access_token': 'new_token',
                        'token_type': 'token_type',
                        'refresh_token': 'refresh_token',
                        'expires_in': 1000,
                        'scope': 'scope',
                        'jti': '00000000-0000-0000-0000-000000000000'
                    }");

            var getProductsSuccessful = MockHttp.When(url)
                                        .WithHeaders(@"Authorization: token_type new_token")
                                        .Respond("application/json", json);

            var apiProductNames = await GetApigeeClient().GetApiProductNames();

            Assert.Equal(expectedList.Count, apiProductNames.Count);
            Assert.Equal(expectedList[0], apiProductNames[0]);
            Assert.Equal(expectedList[1], apiProductNames[1]);
            Assert.Equal(expectedList[2], apiProductNames[2]);

            Assert.Equal(1, MockHttp.GetMatchCount(getProductsUnauthorized));
            Assert.Equal(1, MockHttp.GetMatchCount(getProductsSuccessful));
            Assert.Equal(1, MockHttp.GetMatchCount(getToken));
            Assert.Equal(1, MockHttp.GetMatchCount(refreshToken));
        }