Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v3.18.1 #101

Merged
merged 1 commit into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

Represents the **NuGet** versions.

## v3.18.1
- *Fixed*: The `ITypedMappedHttpClient.MapResponse` was not validating the input HTTP response correctly before mapping; resulted in a `null` success value versus the originating error/exception.
- *Fixed*: The `HttpResult<T>.ThrowOnError` was not correctly throwing the internal exception.

## v3.18.0
- *Fixed*: Removed `Azure.Identity` dependency as no longer required; related to `https://github.com/advisories/GHSA-wvxc-855f-jvrv`.
- *Fixed*: Removed `AspNetCore.HealthChecks.SqlServer` dependency as no longer required.
Expand Down
2 changes: 1 addition & 1 deletion Common.targets
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<Version>3.18.0</Version>
<Version>3.18.1</Version>
<LangVersion>preview</LangVersion>
<Authors>Avanade</Authors>
<Company>Avanade</Company>
Expand Down
5 changes: 4 additions & 1 deletion src/CoreEx/Http/Extended/ITypedMappedHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ public interface ITypedMappedHttpClient
/// <typeparam name="TResponseHttp">The response HTTP <see cref="Type"/>.</typeparam>
/// <param name="httpResult">The <see cref="HttpResult{T}"/>.</param>
/// <returns>The mapped <see cref="HttpResult{T}"/>.</returns>
public HttpResult<TResponse> MapResponse<TResponse, TResponseHttp>(HttpResult<TResponseHttp> httpResult) => new(httpResult.Response, httpResult.BinaryContent, httpResult.IsSuccess && httpResult.Value is not null ? Mapper.Map<TResponse>(httpResult.Value, OperationTypes.Get) : default!);
public HttpResult<TResponse> MapResponse<TResponse, TResponseHttp>(HttpResult<TResponseHttp> httpResult)
=> httpResult.ThrowIfNull().IsSuccess
? new(httpResult.Response, httpResult.BinaryContent, Mapper.Map<TResponse>(httpResult.Value, OperationTypes.Get)!)
: new(httpResult.Response, httpResult.BinaryContent, httpResult.Exception);

/// <summary>
/// Maps the <typeparamref name="TRequest"/> <paramref name="value"/> to the <typeparamref name="TRequestHttp"/> <see cref="Type"/>.
Expand Down
4 changes: 2 additions & 2 deletions src/CoreEx/Http/HttpResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public static async Task<HttpResult<T>> CreateAsync<T>(HttpResponseMessage respo
}
catch (Exception ex)
{
return new HttpResult<T>(response, content, new InvalidOperationException($"Unable to convert the content '{content}' [{MediaTypeNames.Text.Plain}] to Type {typeof(T).Name}.", ex));
return new HttpResult<T>(response, content, new InvalidOperationException($"Unable to convert the content [{MediaTypeNames.Text.Plain}] content to Type {typeof(T).Name}.", ex));
}
}

Expand All @@ -84,7 +84,7 @@ public static async Task<HttpResult<T>> CreateAsync<T>(HttpResponseMessage respo
}
catch (Exception ex)
{
return new HttpResult<T>(response, content, new InvalidOperationException($"Unable to deserialize the JSON content '{content}' [{response.Content.Headers?.ContentType?.MediaType ?? "not specified"}] to Type {typeof(T).FullName}.", ex));
return new HttpResult<T>(response, content, new InvalidOperationException($"Unable to deserialize the JSON [{response.Content.Headers?.ContentType?.MediaType ?? "not specified"}] content to Type {typeof(T).FullName}.", ex));
}
}

Expand Down
10 changes: 9 additions & 1 deletion src/CoreEx/Http/HttpResultT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class HttpResult<T> : HttpResultBase, IToResult<T>
/// <param name="response">The <see cref="HttpResponseMessage"/>.</param>
/// <param name="content">The <see cref="HttpResponseMessage.Content"/> as <see cref="BinaryData"/> (see <see cref="HttpContent.ReadAsByteArrayAsync()"/>).</param>
/// <param name="internalException">The internal <see cref="Exception"/>.</param>
internal HttpResult(HttpResponseMessage response, BinaryData? content, Exception internalException) : this(response, content, default(T)!) => _internalException = internalException;
internal HttpResult(HttpResponseMessage response, BinaryData? content, Exception? internalException) : this(response, content, default(T)!) => _internalException = internalException;

/// <summary>
/// Gets the response value.
Expand All @@ -45,6 +45,11 @@ public T Value
}
}

/// <summary>
/// Gets the internal exception where the request/response handling was not successful; i.e. JSON deserialization error.
/// </summary>
public Exception? Exception => _internalException;

/// <inheritdoc/>
public override bool IsSuccess => _internalException is null && base.IsSuccess;

Expand All @@ -62,6 +67,9 @@ public HttpResult<T> ThrowOnError(bool throwKnownException = true, bool useConte
if (IsSuccess)
return this;

if (_internalException is not null)
throw _internalException;

if (throwKnownException)
{
var eex = CreateExtendedException(Response, Content, useContentAsErrorMessage);
Expand Down
9 changes: 8 additions & 1 deletion src/CoreEx/Results/Result.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,14 @@ public Result() { }
public Result(Exception error) => _error = error.ThrowIfNull(nameof(error));

/// <inheritdoc/>
object? IResult.Value => null;
object? IResult.Value
{
get
{
ThrowOnError();
return null;
}
}

/// <inheritdoc/>
public Exception Error { get => _error ?? throw new InvalidOperationException($"The {nameof(Error)} cannot be accessed as the {nameof(Result)} is in a successful state."); }
Expand Down
30 changes: 30 additions & 0 deletions tests/CoreEx.Test/Framework/Http/HttpResultTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using CoreEx.Http;
using NUnit.Framework;
using System;
using System.Net;
using System.Threading.Tasks;

namespace CoreEx.Test.Framework.Http
{
[TestFixture]
public class HttpResultTest
{
[Test]
public async Task Create_InternalException()
{
var r = new System.Net.Http.HttpResponseMessage(HttpStatusCode.OK) { Content = new System.Net.Http.StringContent("[]") };
var hr = await HttpResult.CreateAsync<int>(r);

Assert.That(hr.IsSuccess, Is.False);
Assert.Throws<InvalidOperationException>(() => hr.ThrowOnError());
Assert.Throws<InvalidOperationException>(() => _ = hr.Value);

var rr = hr.ToResult();
Assert.Multiple(() =>
{
Assert.That(rr.IsSuccess, Is.False);
Assert.That(rr.Error, Is.TypeOf<InvalidOperationException>());
});
}
}
}
135 changes: 135 additions & 0 deletions tests/CoreEx.Test/Framework/Http/TypedMapperHttpClientBaseTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
using CoreEx.Http.Extended;
using CoreEx.Mapping;
using Moq;
using NUnit.Framework;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using UnitTestEx.Mocking;

namespace CoreEx.Test.Framework.Http
{
[TestFixture]
public class TypedMapperHttpClientBaseTest
{
[Test]
public async Task MapSuccess()
{
var m = new Mapper();
m.Register(new CustomerMapper());
m.Register(new BackendMapper());

var mcf = UnitTestEx.NUnit.MockHttpClientFactory.Create();
mcf.CreateDefaultClient().Request(HttpMethod.Post, "test").WithJsonBody(new Backend { First = "John", Last = "Doe" }).Respond.WithJson(new Backend { First = "John", Last = "Doe" });

var mc = new TypedMappedHttpClient(mcf.GetHttpClient()!, m);
var hr = await mc.PostMappedAsync<Customer, Backend, Customer, Backend>("test", new Customer { FirstName = "John", LastName = "Doe" });

Assert.Multiple(() =>
{
Assert.That(hr.IsSuccess, Is.True);
Assert.That(hr.Value, Is.Not.Null);
});
Assert.Multiple(() =>
{
Assert.That(hr.Value.FirstName, Is.EqualTo("John"));
Assert.That(hr.Value.LastName, Is.EqualTo("Doe"));
});

var r = hr.ToResult();
Assert.That(r.IsSuccess, Is.True);
}

[Test]
public async Task MapServerError()
{
var m = new Mapper();
m.Register(new CustomerMapper());
m.Register(new BackendMapper());

var mcf = UnitTestEx.NUnit.MockHttpClientFactory.Create();
mcf.CreateDefaultClient().Request(HttpMethod.Post, "test").WithJsonBody(new Backend { First = "John", Last = "Doe" }).Respond.With(HttpStatusCode.InternalServerError);

var mc = new TypedMappedHttpClient(mcf.GetHttpClient()!, m);
var hr = await mc.PostMappedAsync<Customer, Backend, Customer, Backend>("test", new Customer { FirstName = "John", LastName = "Doe" });

Assert.Multiple(() =>
{
Assert.That(hr.IsSuccess, Is.False);
Assert.That(hr.StatusCode, Is.EqualTo(HttpStatusCode.InternalServerError));
});

var r = hr.ToResult();
Assert.Multiple(() =>
{
Assert.That(r.IsSuccess, Is.False);
Assert.That(r.Error, Is.TypeOf<HttpRequestException>());
});
}

[Test]
public async Task MapJsonError()
{
var m = new Mapper();
m.Register(new CustomerMapper());
m.Register(new BackendMapper());

var mcf = UnitTestEx.NUnit.MockHttpClientFactory.Create();
mcf.CreateDefaultClient().Request(HttpMethod.Post, "test").WithJsonBody(new Backend { First = "John", Last = "Doe" }).Respond.WithJson("{\"first\":\"Dave\",\"age\":\"ten\"}");

var mc = new TypedMappedHttpClient(mcf.GetHttpClient()!, m);
var hr = await mc.PostMappedAsync<Customer, Backend, Customer, Backend>("test", new Customer { FirstName = "John", LastName = "Doe" });

Assert.Multiple(() =>
{
Assert.That(hr.IsSuccess, Is.False);
Assert.That(hr.StatusCode, Is.EqualTo(HttpStatusCode.InternalServerError));
Assert.That(hr.Exception, Is.TypeOf<InvalidOperationException>());
});

var r = hr.ToResult();
Assert.Multiple(() =>
{
Assert.That(r.IsSuccess, Is.False);
Assert.That(r.Error, Is.TypeOf<InvalidOperationException>());
});
}
}

public class Customer
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
}

public class Backend
{
public string? First { get; set; }
public string? Last { get; set; }
public int? Age { get; set; }
}

public class CustomerMapper : CoreEx.Mapping.Mapper<Customer, Backend>
{
protected override Backend? OnMap(Customer? source, Backend? destination, OperationTypes operationType)
{
destination ??= new Backend();
destination.First = source?.FirstName;
destination.Last = source?.LastName;
return destination;
}
}

public class BackendMapper : Mapper<Backend, Customer>
{
protected override Customer? OnMap(Backend? source, Customer? destination, OperationTypes operationType)
{
destination ??= new Customer();
destination.FirstName = source?.First;
destination.LastName = source?.Last;
return destination;
}
}
}
7 changes: 7 additions & 0 deletions tests/CoreEx.Test/Framework/Results/ResultTTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,5 +219,12 @@ public async Task AsTask()
Assert.That(r.Value, Is.EqualTo(1));
});
}

[Test]
public void Failure_Value()
{
var ir = (IResult)Result<int>.Fail("On no!");
Assert.Throws<BusinessException>(() => _ = ir.Value);
}
}
}
14 changes: 14 additions & 0 deletions tests/CoreEx.Test/Framework/Results/ResultTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,5 +141,19 @@ public async Task AsTask()
var r = await Result.Go().AsTask();
Assert.That(r, Is.EqualTo(Result.Success));
}

[Test]
public void Success_Value()
{
var ir = (IResult)Result.Success;
Assert.That(ir.Value, Is.Null);
}

[Test]
public void Failure_Value()
{
var ir = (IResult)Result.Fail("On no!");
Assert.Throws<BusinessException>(() => _ = ir.Value);
}
}
}
Loading