Skip to content
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Postgrest;
using Supabase.Postgrest.Attributes;
using Supabase.Postgrest.Exceptions;
using Supabase.Postgrest.Models;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;

namespace Postgrest.Tests.Requests;

/// <summary>
/// A 2xx body that isn't JSON throws a <see cref="PostgrestException" /> carrying the body and status.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class NonJsonResponseTests
{
private const string ProxyErrorPage = "<html><body>502 Bad Gateway</body></html>";

private WireMockServer server = null!;
private Client client = null!;

[Table("todos")]
private class Todo : BaseModel
{
[PrimaryKey("id")] public int Id { get; set; }
[Column("name")] public string? Name { get; set; }
}

[TestInitialize]
public void SetUp()
{
this.server = WireMockServer.Start();
this.client = new Client(this.server.Url!, new ClientOptions());
}

[TestCleanup]
public void TearDown() => this.server.Stop();

[TestMethod]
public async Task Get_ShouldThrowPostgrestException_GivenNonJsonBody()
{
this.MockProxyErrorPage("/todos");
var act = () => this.client.Table<Todo>().Get();
await act.Should().ThrowAsync<PostgrestException>()
.Where(exception => exception.Content == ProxyErrorPage && exception.StatusCode == 200,
"postgrest-js returns a non-JSON 2xx body as the error (#260)");
}

[TestMethod]
public async Task Rpc_ShouldThrowPostgrestException_GivenNonJsonBody()
{
this.MockProxyErrorPage("/rpc/echo");
var act = () => this.client.Rpc<int>("echo");
await act.Should().ThrowAsync<PostgrestException>()
.Where(exception => exception.Content == ProxyErrorPage && exception.StatusCode == 200,
"postgrest-js handles rpc responses the same way (#260)");
}

private void MockProxyErrorPage(string path) =>
this.server.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithStatusCode(200).WithBody(ProxyErrorPage));
}
2 changes: 1 addition & 1 deletion packages/Postgrest/Postgrest/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public T Attach<T>(T model) where T : BaseModel
{
var response = await this.Rpc(procedureName, parameters);

return string.IsNullOrEmpty(response.Content) ? default : JsonSerializer.Deserialize<TModeledResponse>(response.Content!, SerializerSettings(this.Options));
return string.IsNullOrEmpty(response.Content) ? default : Helpers.DeserializeBody<TModeledResponse>(response, SerializerSettings(this.Options));
}

/// <inheritdoc />
Expand Down
20 changes: 20 additions & 0 deletions packages/Postgrest/Postgrest/Helpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,26 @@ HttpRequestMessage CreateRequest()
}
}

/// <summary>
/// Deserializes a 2xx body and throws a PostgrestException when it can't be read, e.g. a proxy's HTML page.
/// </summary>
internal static T? DeserializeBody<T>(BaseResponse response, JsonSerializerOptions options)
{
try
{
return JsonSerializer.Deserialize<T>(response.Content!, options);
}
catch (JsonException e)
{
throw new PostgrestException(response.Content, e)
{
Content = response.Content,
Response = response.ResponseMessage,
StatusCode = (int) (response.ResponseMessage?.StatusCode ?? 0)
};
}
}

/// <summary>
/// Prepares the request with appropriate HTTP headers expected by Postgrest.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion packages/Postgrest/Postgrest/Responses/ModeledResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public ModeledResponse(BaseResponse baseResponse, JsonSerializerOptions serializ

if (!shouldParse || string.IsNullOrEmpty(this.Content)) return;

var token = JsonNode.Parse(this.Content!);
var token = Helpers.DeserializeBody<JsonNode>(this, serializerSettings);

switch (token)
{
Expand Down
Loading