Skip to content

Commit

Permalink
Merge pull request #4 from Zuntara/Issue-3
Browse files Browse the repository at this point in the history
Use response content as ErrorReason + unit test
  • Loading branch information
Zuntara authored Aug 3, 2017
2 parents 05bef2a + d8811a1 commit e281462
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 12 deletions.
63 changes: 59 additions & 4 deletions RestApiBuilder.Core.Tests/RestApiClientBuilderTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
Expand All @@ -23,9 +25,9 @@ private Mock<IRestConnectionProvider<HttpClient>> GetFaultedConnection()
return connectionProviderMock;
}

private Mock<IRestConnectionProvider<HttpClient>> GetSuccessConnection()
private Mock<HttpClientConnectionProvider> GetSuccessConnection()
{
Mock<IRestConnectionProvider<HttpClient>> connectionProviderMock = new Mock<IRestConnectionProvider<HttpClient>>();
Mock<HttpClientConnectionProvider> connectionProviderMock = new Mock<HttpClientConnectionProvider>();
connectionProviderMock.Setup(c => c.ProcessRequestAsync(It.IsAny<ConnectionRequest>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new ConnectionRequestResponse { IsSuccess = true, StatusCode = 200 });
return connectionProviderMock;
Expand Down Expand Up @@ -65,7 +67,7 @@ public void RestApiClientBuilder_GET_No_Arguments_HasCustomHeaders()
.Callback<ConnectionRequest, CancellationToken>((conn, ct) =>
{
connectionProviderMock.Object.ConfigureHeaders(conn, null);
}).ReturnsAsync(new ConnectionRequestResponse {IsSuccess = false, StatusCode = 400});
}).ReturnsAsync(new ConnectionRequestResponse { IsSuccess = false, StatusCode = 400 });

connectionProviderMock.Setup(p => p.CreateRequest(It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<Uri>(), It.IsAny<string>()))
.Returns(new ConnectionRequest());
Expand Down Expand Up @@ -383,7 +385,7 @@ public void RestApiClientBuilder_DELETE_With_UriArguments_HandlesError()
[TestMethod]
public void RestApiClientBuilder_GET_With_OwnCancellationToken_NotDisposed()
{
Mock<IRestConnectionProvider<HttpClient>> connectionProviderMock = GetSuccessConnection();
Mock<HttpClientConnectionProvider> connectionProviderMock = GetSuccessConnection();

var definition = EndpointDefinition.Build(_baseUri, "Routes", "Search");

Expand All @@ -409,6 +411,59 @@ public void RestApiClientBuilder_GET_With_OwnCancellationToken_NotDisposed()
Assert.IsNotNull(result.Errors);
Assert.AreEqual(0, result.Errors.Count);
Assert.AreEqual(new Uri(_baseUri, "/api/I/Routes/Search"), result.Uri);
}

[TestMethod]
public void RestApiClientBuilder_GET_With_ReturnsErrorCode()
{
Mock<HttpClientConnectionProvider> connectionProviderMock = GetSuccessConnection();
connectionProviderMock
.Setup(p => p.ProcessRequestAsync(It.IsAny<ConnectionRequest>(), It.IsAny<CancellationToken>()))
.CallBase();

connectionProviderMock
.Setup(p => p.CreateRequest(It.IsAny<HttpMethod>(), It.IsAny<Uri>(), It.IsAny<Uri>(),
It.IsAny<string>())).Returns(new ConnectionRequest
{
Method = HttpMethod.Get,
BaseAddress = new Uri("http://localhost"),
RelativeUri = new Uri("/api", UriKind.Relative)
});

connectionProviderMock.Setup(p => p.ExecuteHttpCallAsync(It.IsAny<CancellationToken>(), It.IsAny<HttpCompletionOption>(), It.IsAny<HttpRequestMessage>()))
.ReturnsAsync(new HttpResponseMessage(HttpStatusCode.NotFound) {Content = new StringContent("Test Message")});

var mocked = connectionProviderMock.Object;

var definition = EndpointDefinition.Build(_baseUri, "Routes", "Search");

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(5000);

bool errorHandlerCalled = false;
bool successHandlerCalled = false;

var result = RestApiClientBuilder.Build()
.UseConnectionProvider(mocked)
.From(definition)
.Get()
.OnError(httpCode => { errorHandlerCalled = true; })
.OnSuccess(httpCode => { successHandlerCalled = true; })
.ExecuteAsync(cancellationTokenSource).Result;

cancellationTokenSource.Cancel();

Assert.AreEqual(true, errorHandlerCalled);
Assert.AreEqual(false, successHandlerCalled);
Assert.IsNotNull(result);
Assert.AreEqual(false, result.IsSucceeded);
Assert.IsNotNull(result.Errors);
Assert.AreEqual(1, result.Errors.Count);
Assert.AreEqual("Test Message", result.Errors.First());
Assert.AreEqual(new Uri(_baseUri, "/api/I/Routes/Search"), result.Uri);




}
}
}
33 changes: 25 additions & 8 deletions RestApiBuilder.Core/Providers/HttpClientConnectionProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,14 +108,14 @@ public override async Task<ConnectionRequestResponse> ProcessRequestAsync(Connec

ConfigureHeaders(connectionRequest, request.Content);

HttpResponseMessage response = await _httpClient.SendAsync(request, token);
HttpResponseMessage response = await ExecuteHttpCallAsync(token, request);

return new ConnectionRequestResponse
{
IsSuccess = response.IsSuccessStatusCode,
ResponseString = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : null,
StatusCode = (int)response.StatusCode,
ErrorReason = !response.IsSuccessStatusCode ? response.ReasonPhrase : null
ErrorReason = await ResolveErrorReasonAsync(response)
};
}
if (connectionRequest.Method == HttpMethod.Put)
Expand All @@ -127,45 +127,62 @@ public override async Task<ConnectionRequestResponse> ProcessRequestAsync(Connec

ConfigureHeaders(connectionRequest, request.Content);

HttpResponseMessage response = await _httpClient.SendAsync(request, token);
HttpResponseMessage response = await ExecuteHttpCallAsync(token, request);

return new ConnectionRequestResponse
{
IsSuccess = response.IsSuccessStatusCode,
ResponseString = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : null,
StatusCode = (int)response.StatusCode,
ErrorReason = !response.IsSuccessStatusCode ? response.ReasonPhrase : null
ErrorReason = await ResolveErrorReasonAsync(response)
};
}
if (connectionRequest.Method == HttpMethod.Get)
{
HttpRequestMessage request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, connectionRequest.RelativeUri);

HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, token);
HttpResponseMessage response = await ExecuteHttpCallAsync(token, HttpCompletionOption.ResponseContentRead, request);

return new ConnectionRequestResponse
{
IsSuccess = response.IsSuccessStatusCode,
ResponseString = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : null,
StatusCode = (int)response.StatusCode,
ErrorReason = !response.IsSuccessStatusCode ? response.ReasonPhrase : null
ErrorReason = await ResolveErrorReasonAsync(response)
};
}
if (connectionRequest.Method == HttpMethod.Delete)
{
HttpRequestMessage request = new HttpRequestMessage(System.Net.Http.HttpMethod.Delete, connectionRequest.RelativeUri);

HttpResponseMessage response = await _httpClient.SendAsync(request, token);
HttpResponseMessage response = await ExecuteHttpCallAsync(token, request);

return new ConnectionRequestResponse
{
IsSuccess = response.IsSuccessStatusCode,
ResponseString = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : null,
StatusCode = (int)response.StatusCode,
ErrorReason = !response.IsSuccessStatusCode ? response.ReasonPhrase : null
ErrorReason = await ResolveErrorReasonAsync(response)
};
}
return null;
}

public virtual async Task<HttpResponseMessage> ExecuteHttpCallAsync(CancellationToken token, HttpRequestMessage request)
{
HttpResponseMessage response = await _httpClient.SendAsync(request, token);
return response;
}

public virtual async Task<HttpResponseMessage> ExecuteHttpCallAsync(CancellationToken token, HttpCompletionOption httpCompletionOption, HttpRequestMessage request)
{
HttpResponseMessage response = await _httpClient.SendAsync(request, httpCompletionOption, token);
return response;
}

private async Task<string> ResolveErrorReasonAsync(HttpResponseMessage response)
{
return !response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : null;
}
}
}

0 comments on commit e281462

Please sign in to comment.