Skip to content

Commit

Permalink
Merge branch 'main' into bt-4535-null-document
Browse files Browse the repository at this point in the history
  • Loading branch information
pnwpedro committed Jan 4, 2024
2 parents e76bb93 + 39dfcf6 commit e83aea8
Show file tree
Hide file tree
Showing 9 changed files with 180 additions and 146 deletions.
90 changes: 60 additions & 30 deletions Fauna.Test/Client.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,13 @@ private Client CreateClient(ClientConfig? config = null, IConnection? connection
: new Client(config ?? _defaultConfig ?? throw new InvalidOperationException("Default config is not set"));
}

private async Task<QueryResponse> MockQueryResponseAsync<T>(string responseBody, HttpStatusCode statusCode)
private HttpResponseMessage MockQueryResponse(string responseBody, HttpStatusCode statusCode)
{
var testMessage = new HttpResponseMessage(statusCode)
{
Content = new StringContent(responseBody)
};
return await QueryResponse.GetFromHttpResponseAsync<T>(testMessage);
return testMessage;
}

private void Write(string json)
Expand Down Expand Up @@ -102,34 +102,58 @@ public async Task CreateClientError()
}

[Test]
[TestCase("unauthorized", typeof(AuthenticationException), "Unauthorized: ")]
[TestCase("forbidden", typeof(AuthorizationException), "Forbidden: ")]
[TestCase("invalid_query", typeof(QueryCheckException), "Invalid Query: ")]
[TestCase("invalid_function_definition", typeof(QueryCheckException), "Invalid Query: ")]
[TestCase("invalid_identifier", typeof(QueryCheckException), "Invalid Query: ")]
[TestCase("invalid_syntax", typeof(QueryCheckException), "Invalid Query: ")]
[TestCase("invalid_type", typeof(QueryCheckException), "Invalid Query: ")]
[TestCase("invalid_argument", typeof(QueryRuntimeException), "Invalid Argument: ")]
[TestCase("abort", typeof(AbortException), "Abort: ")]
[TestCase("invalid_request", typeof(InvalidRequestException), "Invalid Request: ")]
[TestCase("contended_transaction", typeof(ContendedTransactionException), "Contended Transaction: ")]
[TestCase("limit_exceeded", typeof(ThrottlingException), "Limit Exceeded: ")]
[TestCase("time_limit_exceeded", typeof(QueryTimeoutException), "Time Limit Exceeded: ")]
[TestCase("internal_error", typeof(ServiceException), "Internal Error: ")]
[TestCase("timeout", typeof(QueryTimeoutException), "Timeout: ")]
[TestCase("time_out", typeof(QueryTimeoutException), "Timeout: ")]
[TestCase("bad_gateway", typeof(NetworkException), "Bad Gateway: ")]
[TestCase("gateway_timeout", typeof(NetworkException), "Gateway Timeout: ")]
[TestCase("unexpected_error", typeof(FaunaException), "Unexpected Error: ")] // Example for default case
public async Task QueryAsync_ShouldThrowCorrectException_ForErrorCode(string errorCode, Type expectedExceptionType, string expectedMessageStart)
[TestCase("unauthorized", 401, typeof(AuthenticationException), "Unauthorized: ")]
[TestCase("forbidden", 403, typeof(AuthorizationException), "Forbidden: ")]
[TestCase("invalid_query", 400, typeof(QueryCheckException), "Invalid Query: ")]
[TestCase("invalid_function_definition", 400, typeof(QueryCheckException), "Invalid Query: ")]
[TestCase("invalid_identifier", 400, typeof(QueryCheckException), "Invalid Query: ")]
[TestCase("invalid_syntax", 400, typeof(QueryCheckException), "Invalid Query: ")]
[TestCase("invalid_type", 400, typeof(QueryCheckException), "Invalid Query: ")]
[TestCase("invalid_argument", 400, typeof(QueryRuntimeException), "Invalid Argument: ")]
[TestCase("abort", 400, typeof(AbortException), "Abort: ")]
[TestCase("invalid_request", 400, typeof(InvalidRequestException), "Invalid Request: ")]
[TestCase("contended_transaction", 409, typeof(ContendedTransactionException), "Contended Transaction: ")]
[TestCase("limit_exceeded", 429, typeof(ThrottlingException), "Limit Exceeded: ")]
[TestCase("time_limit_exceeded", 440, typeof(QueryTimeoutException), "Time Limit Exceeded: ")]
[TestCase("internal_error", 500, typeof(ServiceException), "Internal Error: ")]
[TestCase("timeout", 503, typeof(QueryTimeoutException), "Timeout: ")]
[TestCase("time_out", 503, typeof(QueryTimeoutException), "Timeout: ")]
[TestCase("bad_gateway", 502, typeof(NetworkException), "Bad Gateway: ")]
[TestCase("gateway_timeout", 504, typeof(NetworkException), "Gateway Timeout: ")]
[TestCase("unexpected_error", 400, typeof(FaunaException), "Unexpected Error: ")] // Example for default case
public async Task QueryAsync_ShouldThrowCorrectException_ForErrorCode(string errorCode, int httpStatus, Type expectedExceptionType, string expectedMessageStart)
{
var client = CreateClientWithMockConnection();

Mock.Arrange(() => _mockConnection.DoPostAsync<object>(
HttpResponseMessage MockQR(string code, int status)
{
var body = $@"{{
""error"": {{
""code"": ""{code}"",
""message"": ""Mock message.""
}},
""summary"": ""error: Mock message."",
""txn_ts"": 1702346199930000,
""stats"": {{
""compute_ops"": 1,
""read_ops"": 0,
""write_ops"": 0,
""query_time_ms"": 105,
""contention_retries"": 0,
""storage_bytes_read"": 261,
""storage_bytes_write"": 0,
""rate_limits_hit"": []
}},
""schema_version"": 0
}}";
return MockQueryResponse(body, (HttpStatusCode)status);
}

Mock.Arrange(() => _mockConnection.DoPostAsync(
Arg.IsAny<string>(),
Arg.IsAny<Stream>(),
Arg.IsAny<Dictionary<string, string>>()))
.Returns(Task.FromResult<QueryResponse>(ExceptionTestHelper.CreateQueryFailure(errorCode)));
.Returns(Task.FromResult(MockQR(errorCode, httpStatus)));

async Task TestDelegate() => await client.QueryAsync<object>(new QueryExpr(new QueryLiteral("let x = 123; x")));

Expand Down Expand Up @@ -161,8 +185,8 @@ public async Task QueryAsync_ShouldThrowAbortExceptionWithCorrectObject_OnAbortE
}},
""schema_version"": 0
}}";
var qr = await MockQueryResponseAsync<string>(responseBody, HttpStatusCode.BadRequest);
Mock.Arrange(() => _mockConnection.DoPostAsync<string>(Arg.IsAny<string>(), Arg.IsAny<Stream>(), Arg.IsAny<Dictionary<string, string>>())).Returns(Task.FromResult(qr));
var qr = MockQueryResponse(responseBody, HttpStatusCode.BadRequest);
Mock.Arrange(() => _mockConnection.DoPostAsync(Arg.IsAny<string>(), Arg.IsAny<Stream>(), Arg.IsAny<Dictionary<string, string>>())).Returns(Task.FromResult(qr));
var c = CreateClientWithMockConnection();

try
Expand Down Expand Up @@ -199,16 +223,22 @@ public async Task LastSeenTxnPropagatesToSubsequentQueries()
},
""schema_version"": 0
}";
var qr = await MockQueryResponseAsync<string>(responseBody, HttpStatusCode.OK);
Mock.Arrange(() => _mockConnection.DoPostAsync<string>(Arg.IsAny<string>(), Arg.IsAny<Stream>(), Arg.IsAny<Dictionary<string, string>>())).Returns(Task.FromResult(qr));
var qr = MockQueryResponse(responseBody, HttpStatusCode.OK);
Mock.Arrange(() =>
_mockConnection.DoPostAsync(
Arg.IsAny<string>(),
Arg.IsAny<Stream>(),
Arg.IsAny<Dictionary<string, string>>())
).Returns(Task.FromResult(qr));

var c = CreateClientWithMockConnection();
var r = await c.QueryAsync<string>(new QueryExpr(new QueryLiteral("let x = 123; x")));

bool check = false;

var qr2 = MockQueryResponse(responseBody, HttpStatusCode.OK);
Mock.Arrange(() =>
_mockConnection.DoPostAsync<string>(
_mockConnection.DoPostAsync(
Arg.IsAny<string>(),
Arg.IsAny<Stream>(),
Arg.IsAny<Dictionary<string, string>>()
Expand All @@ -217,7 +247,7 @@ public async Task LastSeenTxnPropagatesToSubsequentQueries()
{
Assert.AreEqual(1702346199930000.ToString(), headers[Headers.LastTxnTs]);
check = true;
}).Returns(Task.FromResult(qr));
}).Returns(Task.FromResult(qr2));

var r2 = await c.QueryAsync<string>(new QueryExpr(new QueryLiteral("let x = 123; x")));

Expand Down
22 changes: 12 additions & 10 deletions Fauna.Test/Exceptions/AbortException.Tests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Fauna.Exceptions;
using Fauna.Serialization;
using Fauna.Test.Helpers;
using NUnit.Framework;

Expand All @@ -11,18 +12,19 @@ private class TestClass
{
public string Name { get; set; }
public int Age { get; set; }

}

private static SerializationContext ctx = new();

[Test]
public void Ctor_InitializesPropertiesCorrectly()
{
var expectedQueryFailure = ExceptionTestHelper.CreateQueryFailure("abort", "Query aborted.", $"{{\"@int\":\"123\"}}");
var expectedMessage = "Test message";
var expectedInnerException = new Exception("Inner exception");

var actual1 = new AbortException(expectedQueryFailure, expectedMessage);
var actual2 = new AbortException(expectedQueryFailure, expectedMessage, expectedInnerException);
var actual1 = new AbortException(ctx, expectedQueryFailure, expectedMessage);
var actual2 = new AbortException(ctx, expectedQueryFailure, expectedMessage, expectedInnerException);

Assert.AreEqual(expectedQueryFailure.ErrorInfo.Abort, actual1.QueryFailure.ErrorInfo.Abort);
Assert.AreEqual(expectedMessage, actual1.Message);
Expand All @@ -37,7 +39,7 @@ public void GetData_WithIntData_ReturnsDeserializedObject()
{
var expected = 123;
var queryFailure = ExceptionTestHelper.CreateQueryFailure("abort", "Query aborted.", $"{{\"@int\":\"{expected}\"}}");
var exception = new AbortException(queryFailure, "Test message");
var exception = new AbortException(ctx, queryFailure, "Test message");

var actual = exception.GetData();

Expand All @@ -52,7 +54,7 @@ public void GetDataT_WithIntData_ReturnsDeserializedTypedObject()
{
var expected = 123;
var queryFailure = ExceptionTestHelper.CreateQueryFailure("abort", "Query aborted.", $"{{\"@int\":\"{expected}\"}}");
var exception = new AbortException(queryFailure, "Test message");
var exception = new AbortException(ctx, queryFailure, "Test message");

var actual = exception.GetData<int>();

Expand All @@ -65,7 +67,7 @@ public void GetData_WithPocoData_ReturnsDeserializedObject()
{
var expected = new TestClass { Name = "John", Age = 105 };
var queryFailure = ExceptionTestHelper.CreateQueryFailure("abort", "Query aborted.", $"{{\"@object\":{{\"Name\":\"{expected.Name}\",\"Age\":{{\"@int\":\"{expected.Age}\"}}}}}}");
var exception = new AbortException(queryFailure, "Test message");
var exception = new AbortException(ctx, queryFailure, "Test message");

var actual = exception.GetData() as IDictionary<string, object>;

Expand All @@ -79,7 +81,7 @@ public void GetDataT_WithPocoData_ReturnsDeserializedTypedObject()
{
var expected = new TestClass { Name = "John", Age = 105 };
var queryFailure = ExceptionTestHelper.CreateQueryFailure("abort", "Query aborted.", $"{{\"@object\":{{\"Name\":\"{expected.Name}\",\"Age\":{{\"@int\":\"{expected.Age}\"}}}}}}");
var exception = new AbortException(queryFailure, "Test message");
var exception = new AbortException(ctx, queryFailure, "Test message");

var actual = exception.GetData<TestClass>();

Expand All @@ -92,7 +94,7 @@ public void GetDataT_WithPocoData_ReturnsDeserializedTypedObject()
public void GetData_WithNullAbortData_ReturnsNull()
{
var queryFailure = ExceptionTestHelper.CreateQueryFailure("abort", "Query aborted.", null);
var exception = new AbortException(queryFailure, "Test message");
var exception = new AbortException(ctx, queryFailure, "Test message");

var result = exception.GetData();

Expand All @@ -104,7 +106,7 @@ public void GetData_CachesDataCorrectly()
{
var mockData = new TestClass { Name = "John", Age = 105 };
var queryFailure = ExceptionTestHelper.CreateQueryFailure("abort", "Query aborted.", $"{{\"@object\":{{\"Name\":\"{mockData.Name}\",\"Age\":{{\"@int\":\"{mockData.Age}\"}}}}}}");
var exception = new AbortException(queryFailure, "Test message");
var exception = new AbortException(ctx, queryFailure, "Test message");

var callResult1 = exception.GetData();
var typedCallResult1 = exception.GetData<TestClass>();
Expand All @@ -116,4 +118,4 @@ public void GetData_CachesDataCorrectly()
Assert.AreNotSame(callResult1, typedCallResult1);
Assert.AreNotSame(callResult2, typedCallResult2);
}
}
}
Loading

0 comments on commit e83aea8

Please sign in to comment.