From ba60208e7a9556711d1e048987ecec41d80e5b4e Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Tue, 9 Aug 2022 21:29:41 +0530 Subject: [PATCH 01/30] Initial progress on the setup --- .../SqlTests/RestApiTests/RestApiTestBase.cs | 2 +- src/Service.Tests/SqlTests/SqlTestBase.cs | 193 +++++++++++++++++- src/Service.Tests/SqlTests/SqlTestHelper.cs | 3 +- src/Service.Tests/TestHelper.cs | 8 +- .../RestRequestContexts/RestRequestContext.cs | 4 +- src/Service/Parsers/ODataASTVisitor.cs | 1 + src/Service/Parsers/RequestParser.cs | 6 +- .../Sql Query Structures/SqlQueryStructure.cs | 2 + 8 files changed, 207 insertions(+), 12 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs index 54f3e82626..9773f5dcac 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs @@ -33,7 +33,7 @@ public abstract class RestApiTestBase : SqlTestBase protected static readonly string _integrationBrokenMappingEntity = "Fungus"; protected static readonly string _integrationUniqueCharactersEntity = "ArtOfWar"; protected static readonly string _integrationUniqueCharactersTable = "aow"; - protected static readonly string _nonExistentEntityName = "!@#$%^&*()_+definitely_nonexistent_entity!@#$%^&*()_+"; + protected static readonly string _nonExistentEntityName = "!@definitely_nonexistent_entity!@"; protected static readonly string _emptyTableEntityName = "Empty"; protected static readonly string _emptyTableTableName = "empty_table"; protected static readonly string _simple_all_books = "books_view_all"; diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index fe9bdea1a4..46a1cb1c26 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -1,12 +1,16 @@ +using System; using System.Collections.Generic; using System.Data.Common; using System.IO; +using System.Linq; using System.Net; using System.Net.Http; +using System.Net.Http.Json; using System.Security.Claims; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; +using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web; using Azure.DataApiBuilder.Auth; @@ -14,18 +18,18 @@ using Azure.DataApiBuilder.Service.Authorization; using Azure.DataApiBuilder.Service.Configurations; using Azure.DataApiBuilder.Service.Controllers; +using Azure.DataApiBuilder.Service.Exceptions; using Azure.DataApiBuilder.Service.Resolvers; using Azure.DataApiBuilder.Service.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Http.Features; -using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Microsoft.Data.SqlClient; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Primitives; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using MySqlConnector; @@ -149,7 +153,17 @@ protected static async Task InitializeTestFixture(TestContext context, List(implementationFactory: (serviceProvider) => + { + return new SqlQueryEngine( + _queryExecutor, + _queryBuilder, + _sqlMetadataProvider, + ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider), + _authorizationResolver, + _queryEngineLogger + ); + }); services.AddSingleton(implementationFactory: (serviceProvider) => { return new SqlMutationEngine( @@ -395,7 +409,7 @@ protected static async Task GetDatabaseResultAsync( /// enum represents the returned sub status code /// The expected location header in the response (if any) /// - protected static async Task SetupAndRunRestApiTest( + /*protected static async Task SetupAndRunRestApiTest( string primaryKeyRoute, string queryString, string entity, @@ -421,6 +435,7 @@ protected static async Task SetupAndRunRestApiTest( headers, requestBody ); + string baseUrl = UriHelper.GetEncodedUrl(controller.HttpContext.Request); if (expectedLocationHeader != null) { @@ -482,6 +497,176 @@ operationType is Operation.Update || expectedLocationHeader, !exception, verifyNumRecords); + }*/ + + protected static async Task SetupAndRunRestApiTest( + string primaryKeyRoute, + string queryString, + string entity, + string sqlQuery, + RestController controller, + Operation operationType = Operation.Read, + string path = "api", + IHeaderDictionary headers = null, + string requestBody = null, + bool exception = false, + string expectedErrorMessage = "", + HttpStatusCode expectedStatusCode = HttpStatusCode.OK, + string expectedSubStatusCode = "BadRequest", + string expectedLocationHeader = null, + string expectedAfterQueryString = "", + bool paginated = false, + int verifyNumRecords = -1) + { + string restEndPoint = path + "/" + entity; + + if (!string.IsNullOrEmpty(primaryKeyRoute)) + { + restEndPoint = restEndPoint + "/" + primaryKeyRoute; + } + + if (!string.IsNullOrEmpty(queryString)) + { + restEndPoint = restEndPoint + queryString; + } + + HttpMethod httpMethod = GetHttpMethodFromOperation(operationType); + + //JsonContent payload = requestBody is null ? null : JsonContent.Create(requestBody); + HttpRequestMessage request = new(httpMethod, restEndPoint) + { + Content = JsonContent.Create(requestBody) + }; + + if (headers is not null) + { + foreach ((string key,StringValues value) in headers) + { + request.Headers.Add(key, value.ToString()); + } + } + + HttpResponseMessage response = await HttpClient.SendAsync(request); + + string responseBody = await response.Content.ReadAsStringAsync(); + + /*ConfigureRestController( + controller, + queryString, + operationType, + headers, + requestBody + );*/ + + //string baseUrl = UriHelper.GetEncodedUrl(controller.HttpContext.Request); + /*if (expectedLocationHeader != null) + { + expectedLocationHeader = + baseUrl + + @"/" + expectedLocationHeader; + }*/ + + /*IActionResult actionResult = await SqlTestHelper.PerformApiTest( + controller, + path, + entity, + primaryKeyRoute, + operationType);*/ + + // if an exception is expected we generate the correct error + // The expected result should be a Query that confirms the result state + // of the Operation performed for the test. However: + // Initial DELETE request results in 204 no content, no exception thrown. + // Subsequent DELETE requests result in 404, which result in an exception. + string expected; + if ((operationType is Operation.Delete || + operationType is Operation.Upsert || + operationType is Operation.UpsertIncremental || + operationType is Operation.Update || + operationType is Operation.UpdateIncremental) + && response.StatusCode.Equals(HttpStatusCode.NoContent) + ) + { + expected = string.Empty; + } + else + { + JsonSerializerOptions options = new() + { + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }; + + if (exception) + { + expected = JsonSerializer.Serialize(RestController.ErrorResponse( + expectedSubStatusCode.ToString(), + expectedErrorMessage, + expectedStatusCode).Value, + options); + } + else + { + string baseUrl = HttpClient.BaseAddress.ToString() + path + "/" + entity; + if (!string.IsNullOrEmpty(queryString)) + { + baseUrl = baseUrl + "?" + HttpUtility.ParseQueryString(queryString).ToString(); + } + + string dbResult = await GetDatabaseResultAsync(sqlQuery); + // For FIND requests, null result signifies an empty result set + dbResult = (operationType is Operation.Read && dbResult is null) ? "[]" : dbResult; + expected = $"{{\"value\":{FormatExpectedValue(dbResult)}{ExpectedNextLinkIfAny(paginated, baseUrl, $"{expectedAfterQueryString}")}}}"; + } + } + + if (!exception) + { + Assert.IsTrue(SqlTestHelper.JsonStringsDeepEqual(expected, responseBody)); + Assert.AreEqual(expectedStatusCode, response.StatusCode); + if (operationType == Operation.Insert) + { + string responseUri = (response.Headers.GetValues("Location").ToList())[0]; + string requestUri = request.RequestUri.OriginalString; + string actualLocation = responseUri.Substring( + responseUri.IndexOf(requestUri + "/") + requestUri.Length + 1); + Assert.AreEqual(expectedLocationHeader, actualLocation); + } + } + else + { + responseBody = Regex.Replace(responseBody, @"\\u0022", @"\"""); + responseBody = Regex.Unescape(responseBody); + Assert.AreEqual(expected, responseBody, ignoreCase: true); + } + /*SqlTestHelper.VerifyResult( + actionResult, + expected, + expectedStatusCode, + expectedLocationHeader, + !exception, + verifyNumRecords);*/ + } + + private static HttpMethod GetHttpMethodFromOperation(Operation operationType) + { + switch (operationType) + { + case Operation.Read: + return HttpMethod.Get; + case Operation.Insert: + return HttpMethod.Post; + case Operation.Delete: + return HttpMethod.Delete; + case Operation.Upsert: + return HttpMethod.Put; + case Operation.UpsertIncremental: + return HttpMethod.Patch; + default: + throw new DataApiBuilderException( + message: "Operation not supported for the request.", + statusCode: HttpStatusCode.NotImplemented, + subStatusCode: DataApiBuilderException.SubStatusCodes.NotSupported); + } } /// diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index 558993fa37..fa26a708e7 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -45,7 +45,8 @@ public static void RemoveAllRelationshipBetweenEntities(RuntimeConfig runtimeCon /// True if JSON objects are the same public static bool JsonStringsDeepEqual(string jsonString1, string jsonString2) { - return JToken.DeepEquals(JToken.Parse(jsonString1), JToken.Parse(jsonString2)); + return string.IsNullOrEmpty(jsonString1) && string.IsNullOrEmpty(jsonString2) || + JToken.DeepEquals(JToken.Parse(jsonString1), JToken.Parse(jsonString2)); } /// diff --git a/src/Service.Tests/TestHelper.cs b/src/Service.Tests/TestHelper.cs index 79a4548a92..1a90d94b71 100644 --- a/src/Service.Tests/TestHelper.cs +++ b/src/Service.Tests/TestHelper.cs @@ -127,8 +127,12 @@ public static void AddMissingEntitiesToConfig(RuntimeConfig config, string entit ""permissions"": [ { ""role"": ""anonymous"", - ""actions"": [ ""read"" ] - }, + ""actions"": [" + + $" \"{Operation.Create.ToString().ToLower()}\"," + + $" \"{Operation.Read.ToString().ToLower()}\"," + + $" \"{Operation.Delete.ToString().ToLower()}\"," + + $" \"{Operation.Update.ToString().ToLower()}\" ]" + + @"}, { ""role"": ""authenticated"", ""actions"": [" + diff --git a/src/Service/Models/RestRequestContexts/RestRequestContext.cs b/src/Service/Models/RestRequestContexts/RestRequestContext.cs index 98c3dd2674..70292cb21f 100644 --- a/src/Service/Models/RestRequestContexts/RestRequestContext.cs +++ b/src/Service/Models/RestRequestContexts/RestRequestContext.cs @@ -150,9 +150,9 @@ public void CalculateCumulativeColumns() Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); throw new DataApiBuilderException( - message: "Request content invalid.", + message: "$filter query parameter is not well formed.", statusCode: HttpStatusCode.BadRequest, - subStatusCode: DataApiBuilderException.SubStatusCodes.AuthorizationCumulativeColumnCheckFailed); + subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); } } diff --git a/src/Service/Parsers/ODataASTVisitor.cs b/src/Service/Parsers/ODataASTVisitor.cs index c7011c77ba..484746996b 100644 --- a/src/Service/Parsers/ODataASTVisitor.cs +++ b/src/Service/Parsers/ODataASTVisitor.cs @@ -57,6 +57,7 @@ public override string Visit(UnaryOperatorNode nodeIn) /// String representing the Field name public override string Visit(SingleValuePropertyAccessNode nodeIn) { + // For filter clause. _metadataProvider.TryGetBackingColumn(_struct.EntityName, nodeIn.Property.Name, out string? backingColumnName); return _metadataProvider.GetQueryBuilder().QuoteIdentifier(backingColumnName!); } diff --git a/src/Service/Parsers/RequestParser.cs b/src/Service/Parsers/RequestParser.cs index 9f53899b7d..beaf5a68b4 100644 --- a/src/Service/Parsers/RequestParser.cs +++ b/src/Service/Parsers/RequestParser.cs @@ -162,12 +162,13 @@ public static void ParseQueryString(RestRequestContext context, ISqlMetadataProv throw new DataApiBuilderException(message: "OrderBy property is not supported.", HttpStatusCode.BadRequest, DataApiBuilderException.SubStatusCodes.BadRequest); - + string columnName; string backingColumnName; if (expression.Kind is QueryNodeKind.SingleValuePropertyAccess) { // if name is in SingleValuePropertyAccess node it matches our model and we will // always be able to get backing column successfully + columnName = ((SingleValuePropertyAccessNode)expression).Property.Name; sqlMetadataProvider.TryGetBackingColumn(context.EntityName, ((SingleValuePropertyAccessNode)expression).Property.Name, out backingColumnName!); } else if (expression.Kind is QueryNodeKind.Constant && @@ -175,6 +176,7 @@ public static void ParseQueryString(RestRequestContext context, ISqlMetadataProv { // since this comes from constant node, it was not checked against our model // so this may return false in which case we throw for a bad request + columnName = ((ConstantNode)expression).Value.ToString()!; if (!sqlMetadataProvider.TryGetBackingColumn(context.EntityName, ((ConstantNode)expression).Value.ToString()!, out backingColumnName!)) { throw new DataApiBuilderException( @@ -194,7 +196,7 @@ public static void ParseQueryString(RestRequestContext context, ISqlMetadataProv // We convert to an Enum of our own that matches the SQL text we want OrderBy direction = GetDirection(node.Direction); // Add OrderByColumn and remove any matching columns from our primary key set - orderByList.Add(new OrderByColumn(schemaName, tableName, backingColumnName, direction: direction)); + orderByList.Add(new OrderByColumn(schemaName, tableName, columnName, direction: direction)); remainingKeys.Remove(backingColumnName); node = node.ThenBy; } diff --git a/src/Service/Resolvers/Sql Query Structures/SqlQueryStructure.cs b/src/Service/Resolvers/Sql Query Structures/SqlQueryStructure.cs index 604601d56d..fef1803baa 100644 --- a/src/Service/Resolvers/Sql Query Structures/SqlQueryStructure.cs +++ b/src/Service/Resolvers/Sql Query Structures/SqlQueryStructure.cs @@ -179,6 +179,8 @@ public SqlQueryStructure( if (string.IsNullOrEmpty(column.TableAlias)) { column.TableAlias = TableAlias; + sqlMetadataProvider.TryGetBackingColumn(EntityName, column.ColumnName!, out string? backingColumnName); + column.ColumnName = backingColumnName!; } } From fcb9e4118a5753467e4f65d9020e192590333b94 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Wed, 10 Aug 2022 13:45:40 +0530 Subject: [PATCH 02/30] Find tests working for all 3 dbs --- src/Service/hawaii-config.MsSql.json | 4 ++++ src/Service/hawaii-config.MySql.json | 4 ++++ src/Service/hawaii-config.PostgreSql.json | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/src/Service/hawaii-config.MsSql.json b/src/Service/hawaii-config.MsSql.json index 9bd791c30e..e56016bd34 100644 --- a/src/Service/hawaii-config.MsSql.json +++ b/src/Service/hawaii-config.MsSql.json @@ -629,6 +629,10 @@ "source": "empty_table", "rest": true, "permissions": [ + { + "role": "anonymous", + "actions": [ "read" ] + }, { "role": "authenticated", "actions": [ "create", "read", "update", "delete" ] diff --git a/src/Service/hawaii-config.MySql.json b/src/Service/hawaii-config.MySql.json index 778c2c9380..645c3ee7e0 100644 --- a/src/Service/hawaii-config.MySql.json +++ b/src/Service/hawaii-config.MySql.json @@ -656,6 +656,10 @@ "source": "empty_table", "rest": true, "permissions": [ + { + "role": "anonymous", + "actions": [ "read" ] + }, { "role": "authenticated", "actions": [ "create", "read", "update", "delete" ] diff --git a/src/Service/hawaii-config.PostgreSql.json b/src/Service/hawaii-config.PostgreSql.json index 5a525e0af7..681749388c 100644 --- a/src/Service/hawaii-config.PostgreSql.json +++ b/src/Service/hawaii-config.PostgreSql.json @@ -656,6 +656,10 @@ "source": "empty_table", "rest": true, "permissions": [ + { + "role": "anonymous", + "actions": [ "read" ] + }, { "role": "authenticated", "actions": [ "create", "read", "update", "delete" ] From 200ef9242f4d3bdd2b27467af56b44f609c22584 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Wed, 10 Aug 2022 14:38:27 +0530 Subject: [PATCH 03/30] Put tests working --- src/Service.Tests/SqlTests/SqlTestBase.cs | 2 +- src/Service/hawaii-config.MsSql.json | 6 +++--- src/Service/hawaii-config.MySql.json | 6 +++--- src/Service/hawaii-config.PostgreSql.json | 6 +++--- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 46a1cb1c26..6328fa85e5 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -634,7 +634,7 @@ operationType is Operation.Update || } else { - responseBody = Regex.Replace(responseBody, @"\\u0022", @"\"""); + responseBody = Regex.Replace(responseBody, @"\\u0022", @"\\"""); responseBody = Regex.Unescape(responseBody); Assert.AreEqual(expected, responseBody, ignoreCase: true); } diff --git a/src/Service/hawaii-config.MsSql.json b/src/Service/hawaii-config.MsSql.json index e56016bd34..4588695505 100644 --- a/src/Service/hawaii-config.MsSql.json +++ b/src/Service/hawaii-config.MsSql.json @@ -188,7 +188,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "read" ] + "actions": [ "create", "read", "update"] }, { "role": "authenticated", @@ -474,7 +474,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "read" ] + "actions": [ "create", "read", "update" ] }, { "role": "authenticated", @@ -495,7 +495,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "read" ] + "actions": [ "create", "read", "update" ] }, { "role": "authenticated", diff --git a/src/Service/hawaii-config.MySql.json b/src/Service/hawaii-config.MySql.json index 645c3ee7e0..e3995669fd 100644 --- a/src/Service/hawaii-config.MySql.json +++ b/src/Service/hawaii-config.MySql.json @@ -185,7 +185,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "read" ] + "actions": [ "create", "read", "update" ] }, { "role": "authenticated", @@ -501,7 +501,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "read" ] + "actions": [ "create", "read", "update" ] }, { "role": "authenticated", @@ -522,7 +522,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "read" ] + "actions": [ "create", "read", "update" ] }, { "role": "authenticated", diff --git a/src/Service/hawaii-config.PostgreSql.json b/src/Service/hawaii-config.PostgreSql.json index 681749388c..b1f6adde61 100644 --- a/src/Service/hawaii-config.PostgreSql.json +++ b/src/Service/hawaii-config.PostgreSql.json @@ -185,7 +185,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "read" ] + "actions": [ "create", "read", "update" ] }, { "role": "authenticated", @@ -501,7 +501,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "read" ] + "actions": [ "create", "read", "update" ] }, { "role": "authenticated", @@ -522,7 +522,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "read" ] + "actions": [ "create", "read", "update" ] }, { "role": "authenticated", From bb42bf4fe26c344bc3d71d9123fa4502b9dee5f6 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Wed, 10 Aug 2022 14:49:17 +0530 Subject: [PATCH 04/30] Patch,delete tests working --- src/Service/hawaii-config.MsSql.json | 2 +- src/Service/hawaii-config.MySql.json | 2 +- src/Service/hawaii-config.PostgreSql.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Service/hawaii-config.MsSql.json b/src/Service/hawaii-config.MsSql.json index 4588695505..48cce98aed 100644 --- a/src/Service/hawaii-config.MsSql.json +++ b/src/Service/hawaii-config.MsSql.json @@ -188,7 +188,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "create", "read", "update"] + "actions": [ "create", "read", "update", "delete" ] }, { "role": "authenticated", diff --git a/src/Service/hawaii-config.MySql.json b/src/Service/hawaii-config.MySql.json index e3995669fd..157282e941 100644 --- a/src/Service/hawaii-config.MySql.json +++ b/src/Service/hawaii-config.MySql.json @@ -185,7 +185,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "create", "read", "update" ] + "actions": [ "create", "read", "update", "delete" ] }, { "role": "authenticated", diff --git a/src/Service/hawaii-config.PostgreSql.json b/src/Service/hawaii-config.PostgreSql.json index b1f6adde61..b3ef1b034a 100644 --- a/src/Service/hawaii-config.PostgreSql.json +++ b/src/Service/hawaii-config.PostgreSql.json @@ -185,7 +185,7 @@ "permissions": [ { "role": "anonymous", - "actions": [ "create", "read", "update" ] + "actions": [ "create", "read", "update", "delete" ] }, { "role": "authenticated", From b9f8255fd62fe54f837f48d88d5d7c0f0989fcda Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Fri, 12 Aug 2022 11:37:01 +0530 Subject: [PATCH 05/30] Fixing unique character InsertRestApiTest --- src/Service.Tests/SqlTests/SqlTestBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 6328fa85e5..bd7df01349 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -625,7 +625,7 @@ operationType is Operation.Update || Assert.AreEqual(expectedStatusCode, response.StatusCode); if (operationType == Operation.Insert) { - string responseUri = (response.Headers.GetValues("Location").ToList())[0]; + string responseUri = (response.Headers.Location.OriginalString); string requestUri = request.RequestUri.OriginalString; string actualLocation = responseUri.Substring( responseUri.IndexOf(requestUri + "/") + requestUri.Length + 1); From ed41fd52ee506e9d80a9bf391988871d4a55c28d Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Tue, 16 Aug 2022 21:39:40 +0530 Subject: [PATCH 06/30] Using unsaferelaxedjsonescaping --- src/Service.Tests/SqlTests/SqlTestBase.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index bee01249f9..b014ea66b7 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -530,6 +530,11 @@ protected static async Task SetupAndRunRestApiTest( restEndPoint = restEndPoint + queryString; } + JsonSerializerOptions options = new() + { + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }; + HttpMethod httpMethod = GetHttpMethodFromOperation(operationType); //JsonContent payload = requestBody is null ? null : JsonContent.Create(requestBody); @@ -591,11 +596,6 @@ operationType is Operation.Update || } else { - JsonSerializerOptions options = new() - { - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping - }; - if (exception) { expected = JsonSerializer.Serialize(RestController.ErrorResponse( From 8144a756984c5913dec1a4fc4564352e8384cb7d Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Wed, 17 Aug 2022 14:46:17 +0530 Subject: [PATCH 07/30] Fixed INSERT test cases --- src/Service.Tests/SqlTests/SqlTestBase.cs | 34 +------------------ .../InsertRequestContext.cs | 19 ++++++++--- src/Service/Services/RequestValidator.cs | 15 ++------ 3 files changed, 18 insertions(+), 50 deletions(-) diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index b014ea66b7..6cfcf5f1ca 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -536,11 +536,9 @@ protected static async Task SetupAndRunRestApiTest( }; HttpMethod httpMethod = GetHttpMethodFromOperation(operationType); - - //JsonContent payload = requestBody is null ? null : JsonContent.Create(requestBody); HttpRequestMessage request = new(httpMethod, restEndPoint) { - Content = JsonContent.Create(requestBody) + Content = JsonContent.Create(requestBody, options: options) }; if (headers is not null) @@ -555,29 +553,6 @@ protected static async Task SetupAndRunRestApiTest( string responseBody = await response.Content.ReadAsStringAsync(); - /*ConfigureRestController( - controller, - queryString, - operationType, - headers, - requestBody - );*/ - - //string baseUrl = UriHelper.GetEncodedUrl(controller.HttpContext.Request); - /*if (expectedLocationHeader != null) - { - expectedLocationHeader = - baseUrl - + @"/" + expectedLocationHeader; - }*/ - - /*IActionResult actionResult = await SqlTestHelper.PerformApiTest( - controller, - path, - entity, - primaryKeyRoute, - operationType);*/ - // if an exception is expected we generate the correct error // The expected result should be a Query that confirms the result state // of the Operation performed for the test. However: @@ -638,13 +613,6 @@ operationType is Operation.Update || responseBody = Regex.Unescape(responseBody); Assert.AreEqual(expected, responseBody, ignoreCase: true); } - /*SqlTestHelper.VerifyResult( - actionResult, - expected, - expectedStatusCode, - expectedLocationHeader, - !exception, - verifyNumRecords);*/ } private static HttpMethod GetHttpMethodFromOperation(Operation operationType) diff --git a/src/Service/Models/RestRequestContexts/InsertRequestContext.cs b/src/Service/Models/RestRequestContexts/InsertRequestContext.cs index 074c4af564..8e57233df6 100644 --- a/src/Service/Models/RestRequestContexts/InsertRequestContext.cs +++ b/src/Service/Models/RestRequestContexts/InsertRequestContext.cs @@ -43,10 +43,21 @@ public InsertRequestContext( } catch (JsonException) { - throw new DataApiBuilderException( - message: "The request body is not in a valid JSON format.", - statusCode: HttpStatusCode.BadRequest, - subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); + try + { + Dictionary[]? fieldValuePairs = JsonSerializer.Deserialize[]>(payload); + throw new DataApiBuilderException( + statusCode: HttpStatusCode.BadRequest, + message: "Mutation operation on many instances of an entity in a single request are not yet supported.", + subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); + } + catch (JsonException) + { + throw new DataApiBuilderException( + message: "The request body is not in a valid JSON format.", + statusCode: HttpStatusCode.BadRequest, + subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); + } } } else diff --git a/src/Service/Services/RequestValidator.cs b/src/Service/Services/RequestValidator.cs index 2dfb8bc6c1..94bf32720f 100644 --- a/src/Service/Services/RequestValidator.cs +++ b/src/Service/Services/RequestValidator.cs @@ -382,19 +382,8 @@ private static TableDefinition TryGetTableDefinition(string entityName, ISqlMeta /// private static JsonElement GetInsertPayload(string requestBody) { - using JsonDocument insertPayload = JsonDocument.Parse(requestBody); - - if (insertPayload.RootElement.ValueKind == JsonValueKind.Array) - { - throw new DataApiBuilderException( - statusCode: HttpStatusCode.BadRequest, - message: "Mutation operation on many instances of an entity in a single request are not yet supported.", - subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); - } - else - { - return insertPayload.RootElement.Clone(); - } + //requestBody = requestBody.Substring(1, requestBody.Length - 2); + return JsonDocument.Parse(requestBody).RootElement.Clone(); } /// From e106f9ba665e1a9b54e4e85d505b2d2341865c70 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Wed, 17 Aug 2022 16:59:59 +0530 Subject: [PATCH 08/30] Removing restcontroller's use --- .../RestApiTests/Delete/DeleteApiTestBase.cs | 7 - .../RestApiTests/Delete/MsSqlDeleteApiTest.cs | 10 - .../RestApiTests/Delete/MySqlDeleteApiTest.cs | 9 - .../Delete/PostgreSqlDeleteApiTests.cs | 9 - .../RestApiTests/Find/FindApiTestBase.cs | 190 ++++++------------ .../RestApiTests/Find/MsSqlFindApiTests.cs | 10 - .../RestApiTests/Find/MySqlFindApiTests.cs | 9 - .../Find/PostgreSqlFindApiTests.cs | 9 - .../RestApiTests/Insert/InsertApiTestBase.cs | 19 -- .../Insert/MsSqlInsertApiTests.cs | 10 - .../Insert/MySqlInsertApiTests.cs | 9 - .../Insert/PostgreSqlInsertApiTests.cs | 9 - .../RestApiTests/OtherRestApiTests.cs | 1 - .../RestApiTests/Patch/MsSqlPatchApiTests.cs | 10 - .../RestApiTests/Patch/MySqlPatchApiTests.cs | 9 - .../RestApiTests/Patch/PatchApiTestBase.cs | 19 -- .../Patch/PostgreSqlPatchApiTests.cs | 9 - .../RestApiTests/Put/MsSqlPutApiTests.cs | 10 - .../RestApiTests/Put/MySqlPutApiTests.cs | 9 - .../RestApiTests/Put/PostgreSqlPutApiTests.cs | 9 - .../RestApiTests/Put/PutApiTestBase.cs | 28 --- .../PrimaryKeyTestsForCompositeViews.cs | 3 +- src/Service.Tests/SqlTests/SqlTestBase.cs | 107 ---------- 23 files changed, 61 insertions(+), 453 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/Delete/DeleteApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Delete/DeleteApiTestBase.cs index eb5d8c2f59..81f0be7f2c 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Delete/DeleteApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Delete/DeleteApiTestBase.cs @@ -31,7 +31,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationEntityName, sqlQuery: null, - controller: _restController, operationType: Operation.Delete, requestBody: null, expectedStatusCode: HttpStatusCode.NoContent @@ -55,7 +54,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationMappingEntity, sqlQuery: null, - controller: _restController, operationType: Operation.Delete, requestBody: null, expectedStatusCode: HttpStatusCode.NoContent @@ -80,7 +78,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationUniqueCharactersEntity, sqlQuery: null, - controller: _restController, operationType: Operation.Delete, requestBody: null, expectedStatusCode: HttpStatusCode.NoContent @@ -105,7 +102,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Delete, requestBody: string.Empty, exception: true, @@ -130,7 +126,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Delete, requestBody: string.Empty, exception: true, @@ -154,7 +149,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Delete, requestBody: string.Empty, exception: true, @@ -186,7 +180,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Delete, requestBody: string.Empty, exception: true, diff --git a/src/Service.Tests/SqlTests/RestApiTests/Delete/MsSqlDeleteApiTest.cs b/src/Service.Tests/SqlTests/RestApiTests/Delete/MsSqlDeleteApiTest.cs index 87f5455d54..9a36087a2d 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Delete/MsSqlDeleteApiTest.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Delete/MsSqlDeleteApiTest.cs @@ -34,16 +34,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MSSQL; await InitializeTestFixture(context); - // Setup REST Components - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/Delete/MySqlDeleteApiTest.cs b/src/Service.Tests/SqlTests/RestApiTests/Delete/MySqlDeleteApiTest.cs index 166872b71a..56c2ecd841 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Delete/MySqlDeleteApiTest.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Delete/MySqlDeleteApiTest.cs @@ -36,15 +36,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MYSQL; await InitializeTestFixture(context); - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/Delete/PostgreSqlDeleteApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Delete/PostgreSqlDeleteApiTests.cs index c944732376..90ec8914cb 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Delete/PostgreSqlDeleteApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Delete/PostgreSqlDeleteApiTests.cs @@ -36,15 +36,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.POSTGRESQL; await InitializeTestFixture(context); - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } #endregion diff --git a/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs index a61a0b77b5..fd941c1dd2 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs @@ -30,8 +30,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: "id/2", queryString: string.Empty, entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindByIdTest)), - controller: _restController + sqlQuery: GetQuery(nameof(FindByIdTest)) ); } @@ -48,16 +47,14 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: string.Empty, entity: _emptyTableEntityName, - sqlQuery: GetQuery("FindEmptyTable"), - controller: _restController + sqlQuery: GetQuery("FindEmptyTable") ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=1 ne 1", entity: _integrationEntityName, - sqlQuery: GetQuery("FindEmptyResultSetWithQueryFilter"), - controller: _restController + sqlQuery: GetQuery("FindEmptyResultSetWithQueryFilter") ); } @@ -73,8 +70,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: string.Empty, entity: _integrationUniqueCharactersEntity, - sqlQuery: GetQuery("FindOnTableWithUniqueCharacters"), - controller: _restController); + sqlQuery: GetQuery("FindOnTableWithUniqueCharacters")); } /// @@ -88,24 +84,21 @@ await SetupAndRunRestApiTest( primaryKeyRoute: "id/2", queryString: string.Empty, entity: _simple_all_books, - sqlQuery: GetQuery("FindViewAll"), - controller: _restController + sqlQuery: GetQuery("FindViewAll") ); await SetupAndRunRestApiTest( primaryKeyRoute: "categoryid/2/pieceid/1", queryString: string.Empty, entity: _simple_subset_stocks, - sqlQuery: GetQuery("FindViewSelected"), - controller: _restController + sqlQuery: GetQuery("FindViewSelected") ); await SetupAndRunRestApiTest( primaryKeyRoute: "id/2", queryString: string.Empty, entity: _composite_subset_bookPub, - sqlQuery: GetQuery("FindViewComposite"), - controller: _restController + sqlQuery: GetQuery("FindViewComposite") ); } @@ -120,37 +113,36 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id ge 4", entity: _simple_all_books, - sqlQuery: GetQuery("FindTestWithFilterQueryOneGeFilterOnView"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryOneGeFilterOnView") + ); await SetupAndRunRestApiTest( primaryKeyRoute: "id/1", queryString: "?$select=id,title", entity: _simple_all_books, - sqlQuery: GetQuery("FindByIdTestWithQueryStringFieldsOnView"), - controller: _restController + sqlQuery: GetQuery("FindByIdTestWithQueryStringFieldsOnView") ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=pieceid eq 1", entity: _simple_subset_stocks, - sqlQuery: GetQuery("FindTestWithFilterQueryStringOneEqFilterOnView"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryStringOneEqFilterOnView") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=not (categoryid gt 1)", entity: _simple_subset_stocks, - sqlQuery: GetQuery("FindTestWithFilterQueryOneNotFilterOnView"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryOneNotFilterOnView") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter= id lt 5", entity: _composite_subset_bookPub, - sqlQuery: GetQuery("FindTestWithFilterQueryOneLtFilterOnView"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryOneLtFilterOnView") + ); } /// @@ -164,8 +156,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: "id/1", queryString: "?$select=id,title", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindByIdTestWithQueryStringFields)), - controller: _restController + sqlQuery: GetQuery(nameof(FindByIdTestWithQueryStringFields)) ); } @@ -180,8 +171,8 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$select=id", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithQueryStringOneField)), - controller: _restController); + sqlQuery: GetQuery(nameof(FindTestWithQueryStringOneField)) + ); } @@ -196,8 +187,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: string.Empty, entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithQueryStringAllFields)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithQueryStringAllFields)) ); } @@ -212,62 +202,61 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id eq 1", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestWithFilterQueryStringOneEqFilter"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryStringOneEqFilter") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=2 eq id", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestWithFilterQueryStringValueFirstOneEqFilter"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryStringValueFirstOneEqFilter") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id gt 3", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestWithFilterQueryOneGtFilter"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryOneGtFilter") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id ge 4", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestWithFilterQueryOneGeFilter"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryOneGeFilter") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id lt 5", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestWithFilterQueryOneLtFilter"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryOneLtFilter") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id le 4", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestWithFilterQueryOneLeFilter"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryOneLeFilter") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id ne 3", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestWithFilterQueryOneNeFilter"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryOneNeFilter") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=not (id lt 2)", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestWithFilterQueryOneNotFilter"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryOneNotFilter") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=not (title eq null)", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestWithFilterQueryOneRightNullEqFilter"), - controller: _restController); + sqlQuery: GetQuery("FindTestWithFilterQueryOneRightNullEqFilter") + ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=null ne title", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestWithFilterQueryOneLeftNullNeFilter"), - controller: _restController + sqlQuery: GetQuery("FindTestWithFilterQueryOneLeftNullNeFilter") ); } @@ -282,8 +271,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id lt 3 and id gt 1", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringSingleAndFilter)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringSingleAndFilter)) ); } @@ -298,8 +286,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id lt 3 or id gt 4", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringSingleOrFilter)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringSingleOrFilter)) ); } @@ -314,8 +301,8 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id lt 4 and id gt 1 and title ne 'Awesome book'", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringMultipleAndFilters)), - controller: _restController); + sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringMultipleAndFilters)) + ); } @@ -330,8 +317,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=id eq 1 or id eq 2 or id eq 3", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringMultipleOrFilters)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringMultipleOrFilters)) ); } @@ -346,8 +332,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=(id gt 2 and id lt 4) or (title eq 'Awesome book')", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringMultipleAndOrFilters)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringMultipleAndOrFilters)) ); } @@ -362,8 +347,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=(not (id lt 3) or id lt 4) or not (title eq 'Awesome book')", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringMultipleNotAndOrFilters)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringMultipleNotAndOrFilters)) ); } @@ -379,7 +363,6 @@ await SetupAndRunRestApiTest( queryString: "?$filter=id eq (publisher_id gt 1)", entity: _integrationEntityName, sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringSingleAndFilter)), - controller: _restController, exception: true, expectedErrorMessage: "A binary operator with incompatible types was detected. " + "Found operand types 'Edm.Int32' and 'Edm.Boolean' for operator kind 'Equal'.", @@ -394,8 +377,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: "id/567/book_id/1", queryString: "?$select=id,content", entity: _entityWithCompositePrimaryKey, - sqlQuery: GetQuery(nameof(FindTestWithPrimaryKeyContainingForeignKey)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithPrimaryKeyContainingForeignKey)) ); } @@ -413,7 +395,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1", entity: _integrationEntityName, sqlQuery: GetQuery(nameof(FindTestWithFirstSingleKeyPagination)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(after)}", paginated: true ); @@ -434,7 +415,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1", entity: _entityWithCompositePrimaryKey, sqlQuery: GetQuery(nameof(FindTestWithFirstMultiKeyPagination)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", paginated: true ); @@ -452,8 +432,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: $"?$after={HttpUtility.UrlEncode(after)}", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithAfterSingleKeyPagination)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithAfterSingleKeyPagination)) ); } @@ -471,8 +450,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: $"?$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", entity: _entityWithCompositePrimaryKey, - sqlQuery: GetQuery(nameof(FindTestWithAfterMultiKeyPagination)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithAfterMultiKeyPagination)) ); } @@ -490,7 +468,6 @@ await SetupAndRunRestApiTest( queryString: $"?$first=1", entity: _integrationEntityName, sqlQuery: GetQuery(nameof(FindTestWithPaginationVerifSinglePrimaryKeyInAfter)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(after)}", paginated: true ); @@ -511,7 +488,6 @@ await SetupAndRunRestApiTest( queryString: $"?$first=1", entity: _entityWithCompositePrimaryKey, sqlQuery: GetQuery(nameof(FindTestWithPaginationVerifMultiplePrimaryKeysInAfter)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", paginated: true ); @@ -528,8 +504,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$orderby=title", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithQueryStringAllFieldsOrderByAsc)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithQueryStringAllFieldsOrderByAsc)) ); } @@ -545,8 +520,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$orderby='ID Number'", entity: _integrationEntityHasColumnWithSpace, - sqlQuery: GetQuery(nameof(FindTestWithQueryStringSpaceInNamesOrderByAsc)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithQueryStringSpaceInNamesOrderByAsc)) ); } @@ -566,7 +540,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1&$orderby='Last Name'", entity: _integrationEntityHasColumnWithSpace, sqlQuery: GetQuery(nameof(FindTestWithFirstAndSpacedColumnOrderBy)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", paginated: true @@ -584,8 +557,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$orderby=publisher_id desc", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestWithQueryStringAllFieldsOrderByDesc)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithQueryStringAllFieldsOrderByDesc)) ); } @@ -604,7 +576,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1&$orderby=title", entity: _integrationEntityName, sqlQuery: GetQuery(nameof(FindTestWithFirstSingleKeyPaginationAndOrderBy)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", paginated: true ); @@ -624,7 +595,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1&$orderby=id", entity: _integrationEntityName, sqlQuery: GetQuery(nameof(FindTestWithFirstSingleKeyIncludedInOrderByAndPagination)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(after)}", paginated: true ); @@ -644,7 +614,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=2&$orderby=id", entity: _integrationEntityName, sqlQuery: GetQuery(nameof(FindTestWithFirstTwoOrderByAndPagination)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(after)}", paginated: true ); @@ -667,7 +636,6 @@ await SetupAndRunRestApiTest( queryString: $"?$first=2&$orderby=birthdate, name, id desc", entity: _integrationTieBreakEntity, sqlQuery: GetQuery(nameof(FindTestWithFirstTwoVerifyAfterFormedCorrectlyWithOrderBy)), - controller: _restController, expectedAfterQueryString: after, paginated: true ); @@ -691,7 +659,6 @@ await SetupAndRunRestApiTest( queryString: $"?$first=2&$orderby=birthdate, name, id{after}", entity: _integrationTieBreakEntity, sqlQuery: GetQuery(nameof(FindTestWithFirstTwoVerifyAfterBreaksTieCorrectlyWithOrderBy)), - controller: _restController, verifyNumRecords: _numRecordsReturnedFromTieBreakTable ); } @@ -712,7 +679,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1&$orderby=id desc, book_id", entity: _entityWithCompositePrimaryKey, sqlQuery: GetQuery(nameof(FindTestWithFirstMultiKeyIncludeAllInOrderByAndPagination)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", paginated: true ); @@ -734,7 +700,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1&$orderby=book_id", entity: _entityWithCompositePrimaryKey, sqlQuery: GetQuery(nameof(FindTestWithFirstMultiKeyIncludeOneInOrderByAndPagination)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", paginated: true ); @@ -758,7 +723,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1&$orderby=publisher_id desc, title desc", entity: _integrationEntityName, sqlQuery: GetQuery(nameof(FindTestWithFirstAndMultiColumnOrderBy)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", paginated: true ); @@ -780,7 +744,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1&$orderby=publisher_id desc", entity: _integrationEntityName, sqlQuery: GetQuery(nameof(FindTestWithFirstAndTiedColumnOrderBy)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", paginated: true ); @@ -798,15 +761,13 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$orderby=id desc, publisher_id", entity: _integrationEntityName, - sqlQuery: GetQuery(nameof(FindTestVerifyMaintainColumnOrderForOrderBy)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestVerifyMaintainColumnOrderForOrderBy)) ); await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$orderby=publisher_id, id desc", entity: _integrationEntityName, - sqlQuery: GetQuery("FindTestVerifyMaintainColumnOrderForOrderByInReverse"), - controller: _restController + sqlQuery: GetQuery("FindTestVerifyMaintainColumnOrderForOrderByInReverse") ); } @@ -827,7 +788,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1&$orderby=content desc", entity: _entityWithCompositePrimaryKey, sqlQuery: GetQuery(nameof(FindTestWithFirstMultiKeyPaginationAndOrderBy)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", paginated: true ); @@ -847,8 +807,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: string.Empty, entity: _integrationMappingEntity, - sqlQuery: GetQuery(nameof(FindTestWithMappedFieldsToBeReturned)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithMappedFieldsToBeReturned)) ); } @@ -866,8 +825,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$select=Scientific Name", entity: _integrationMappingEntity, - sqlQuery: GetQuery(nameof(FindTestWithSingleMappedFieldsToBeReturned)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithSingleMappedFieldsToBeReturned)) ); } @@ -885,8 +843,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$select=treeId", entity: _integrationMappingEntity, - sqlQuery: GetQuery(nameof(FindTestWithUnMappedFieldsToBeReturned)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithUnMappedFieldsToBeReturned)) ); } @@ -903,8 +860,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$filter=fancyName eq 'Tsuga terophylla'", entity: _integrationMappingDifferentEntity, - sqlQuery: GetQuery(nameof(FindTestWithDifferentMappedFieldsAndFilter)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithDifferentMappedFieldsAndFilter)) ); } @@ -922,8 +878,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: "?$orderby=fancyName", entity: _integrationMappingDifferentEntity, - sqlQuery: GetQuery(nameof(FindTestWithDifferentMappedFieldsAndOrderBy)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithDifferentMappedFieldsAndOrderBy)) ); } @@ -944,7 +899,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=1&$orderby=fancyName", entity: _integrationMappingDifferentEntity, sqlQuery: GetQuery(nameof(FindTestWithDifferentMappingFirstSingleKeyPaginationAndOrderBy)), - controller: _restController, expectedAfterQueryString: $"&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", paginated: true ); @@ -966,8 +920,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: string.Empty, queryString: $"?$orderby=fancyName,treeId&$after={HttpUtility.UrlEncode(SqlPaginationUtil.Base64Encode(after))}", entity: _integrationMappingDifferentEntity, - sqlQuery: GetQuery(nameof(FindTestWithDifferentMappingAfterSingleKeyPaginationAndOrderBy)), - controller: _restController + sqlQuery: GetQuery(nameof(FindTestWithDifferentMappingAfterSingleKeyPaginationAndOrderBy)) ); } #endregion @@ -987,7 +940,6 @@ await SetupAndRunRestApiTest( queryString: "?$first=0", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "Invalid number of items requested, $first must be an integer greater than 0. Actual value: 0", expectedStatusCode: HttpStatusCode.BadRequest @@ -1012,7 +964,6 @@ await SetupAndRunRestApiTest( queryString: $"?$filter={keyword}{value} {compareTo}", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "$filter query parameter is not well formed.", expectedStatusCode: HttpStatusCode.BadRequest, @@ -1028,7 +979,6 @@ await SetupAndRunRestApiTest( queryString: "?$filter=pq ge 4", entity: _simple_all_books, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: $"Could not find a property named 'pq' on type 'default_namespace.{_simple_all_books}.{GetDefaultSchemaForEdmModel()}books_view_all'.", expectedStatusCode: HttpStatusCode.BadRequest @@ -1039,7 +989,6 @@ await SetupAndRunRestApiTest( queryString: "?$filter=pq le 4", entity: _simple_subset_stocks, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: $"Could not find a property named 'pq' on type 'default_namespace.{_simple_subset_stocks}.{GetDefaultSchemaForEdmModel()}stocks_view_selected'.", expectedStatusCode: HttpStatusCode.BadRequest @@ -1051,7 +1000,6 @@ await SetupAndRunRestApiTest( queryString: "?$filter=not (title gt 1)", entity: _composite_subset_bookPub, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: $"Could not find a property named 'title' on type 'default_namespace.{_composite_subset_bookPub}.{GetDefaultSchemaForEdmModel()}books_publishers_view_composite'.", expectedStatusCode: HttpStatusCode.BadRequest @@ -1069,7 +1017,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "The request is invalid since it contains a primary key with no value specified.", expectedStatusCode: HttpStatusCode.BadRequest @@ -1090,7 +1037,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "Support for url template with implicit primary key field names is not yet added.", expectedStatusCode: HttpStatusCode.BadRequest @@ -1109,7 +1055,6 @@ await SetupAndRunRestApiTest( queryString: "?$select=id,content", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "Invalid field to be returned requested: content", expectedStatusCode: HttpStatusCode.BadRequest @@ -1133,7 +1078,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _nonExistentEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: $"{_nonExistentEntityName} is not a valid entity.", expectedStatusCode: HttpStatusCode.NotFound, @@ -1149,7 +1093,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: integrationEntityNameIncorrectCase, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: $"{integrationEntityNameIncorrectCase} is not a valid entity.", expectedStatusCode: HttpStatusCode.NotFound, @@ -1170,7 +1113,6 @@ await SetupAndRunRestApiTest( queryString: "?$select=id,null", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "Invalid Field name: null or white space", expectedStatusCode: HttpStatusCode.BadRequest, @@ -1190,7 +1132,6 @@ await SetupAndRunRestApiTest( queryString: "?$select=", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "Invalid Field name: null or white space", expectedStatusCode: HttpStatusCode.BadRequest, @@ -1209,7 +1150,6 @@ await SetupAndRunRestApiTest( queryString: "?$orderby=id random", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: HttpUtility.UrlDecode("Syntax error at position 9 in \u0027id random\u0027."), expectedStatusCode: HttpStatusCode.BadRequest @@ -1227,7 +1167,6 @@ await SetupAndRunRestApiTest( queryString: "?$orderby=Pinecone", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: $"Could not find a property named 'Pinecone' on type 'default_namespace.{_integrationEntityName}.{GetDefaultSchemaForEdmModel()}books'.", expectedStatusCode: HttpStatusCode.BadRequest @@ -1246,7 +1185,6 @@ await SetupAndRunRestApiTest( queryString: "?$orderby='Large Pinecone'", entity: _integrationEntityHasColumnWithSpace, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: $"Invalid orderby column requested: Large Pinecone.", expectedStatusCode: HttpStatusCode.BadRequest @@ -1265,7 +1203,6 @@ await SetupAndRunRestApiTest( queryString: "?orderby=id", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: $"Invalid Query Parameter: orderby", expectedStatusCode: HttpStatusCode.BadRequest @@ -1283,7 +1220,6 @@ await SetupAndRunRestApiTest( queryString: "?$orderby=null", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "OrderBy property is not supported.", expectedStatusCode: HttpStatusCode.BadRequest @@ -1305,7 +1241,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationBrokenMappingEntity, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "The request is invalid since the primary keys: spores requested were not found in the entity definition.", expectedStatusCode: HttpStatusCode.NotFound, @@ -1328,7 +1263,6 @@ await SetupAndRunRestApiTest( queryString: "?$select=hazards", entity: _integrationBrokenMappingEntity, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "Invalid field to be returned requested: hazards", expectedStatusCode: HttpStatusCode.BadRequest, @@ -1350,7 +1284,6 @@ await SetupAndRunRestApiTest( queryString: "?$select=species", entity: _integrationMappingEntity, sqlQuery: GetQuery(nameof(FindTestWithUnMappedFieldsToBeReturned)), - controller: _restController, exception: true, expectedErrorMessage: "Invalid field to be returned requested: species", expectedStatusCode: HttpStatusCode.BadRequest @@ -1389,7 +1322,6 @@ await SetupAndRunRestApiTest( queryString: $"?$select=id", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: message, expectedStatusCode: HttpStatusCode.BadRequest @@ -1425,7 +1357,6 @@ await SetupAndRunRestApiTest( queryString: $"?$select={sqlInjection}", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: $"Invalid field to be returned requested: {sqlInjection}", expectedStatusCode: HttpStatusCode.BadRequest @@ -1461,7 +1392,6 @@ await SetupAndRunRestApiTest( queryString: $"?$select={sqlInjection}", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: $"Invalid field to be returned requested: {sqlInjection}", expectedStatusCode: HttpStatusCode.BadRequest diff --git a/src/Service.Tests/SqlTests/RestApiTests/Find/MsSqlFindApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Find/MsSqlFindApiTests.cs index a1b59097d4..53ff2a47cf 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Find/MsSqlFindApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Find/MsSqlFindApiTests.cs @@ -400,16 +400,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MSSQL; await InitializeTestFixture(context); - // Setup REST Components - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/Find/MySqlFindApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Find/MySqlFindApiTests.cs index d13c095189..9674b712e1 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Find/MySqlFindApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Find/MySqlFindApiTests.cs @@ -741,15 +741,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MYSQL; await InitializeTestFixture(context); - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/Find/PostgreSqlFindApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Find/PostgreSqlFindApiTests.cs index eef36b17ae..1e74ce3095 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Find/PostgreSqlFindApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Find/PostgreSqlFindApiTests.cs @@ -649,15 +649,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.POSTGRESQL; await InitializeTestFixture(context); - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } #endregion diff --git a/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs index a329a0b6b4..84465a6d52 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs @@ -30,7 +30,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationEntityName, sqlQuery: GetQuery(nameof(InsertOneTest)), - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -50,7 +49,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("InsertOneInCompositeNonAutoGenPKTest"), - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -79,7 +77,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationUniqueCharactersEntity, sqlQuery: GetQuery(nameof(InsertOneUniqueCharactersTest)), - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -107,7 +104,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationMappingEntity, sqlQuery: GetQuery(nameof(InsertOneWithMappingTest)), - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -134,7 +130,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _entityWithCompositePrimaryKey, sqlQuery: GetQuery(nameof(InsertOneInCompositeKeyTableTest)), - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -152,7 +147,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _entityWithCompositePrimaryKey, sqlQuery: GetQuery("InsertOneInDefaultTestTable"), - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -178,7 +172,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("InsertOneWithNullFieldValue"), - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -210,7 +203,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: GetQuery(query), - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -236,7 +228,6 @@ await SetupAndRunRestApiTest( queryString: "?/id/5001", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, exception: true, @@ -262,7 +253,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, exception: true, @@ -289,7 +279,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, exception: true, @@ -313,7 +302,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, exception: true, @@ -339,7 +327,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, exception: true, @@ -365,7 +352,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integration_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, exception: true, @@ -393,7 +379,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integration_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, exception: true, @@ -413,7 +398,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, exception: true, @@ -440,7 +424,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, exception: true, @@ -462,7 +445,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, requestBody: requestBody, exception: true, @@ -494,7 +476,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationBrokenMappingEntity, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Insert, exception: true, requestBody: requestBody, diff --git a/src/Service.Tests/SqlTests/RestApiTests/Insert/MsSqlInsertApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Insert/MsSqlInsertApiTests.cs index 794c18cc24..a94bb67412 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Insert/MsSqlInsertApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Insert/MsSqlInsertApiTests.cs @@ -146,16 +146,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MSSQL; await InitializeTestFixture(context); - // Setup REST Components - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/Insert/MySqlInsertApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Insert/MySqlInsertApiTests.cs index cf41f0606e..49019134ee 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Insert/MySqlInsertApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Insert/MySqlInsertApiTests.cs @@ -171,15 +171,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MYSQL; await InitializeTestFixture(context); - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/Insert/PostgreSqlInsertApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Insert/PostgreSqlInsertApiTests.cs index a8b806723f..d69cfb92ab 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Insert/PostgreSqlInsertApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Insert/PostgreSqlInsertApiTests.cs @@ -168,15 +168,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.POSTGRESQL; await InitializeTestFixture(context); - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } #endregion diff --git a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs index 0d8337b102..bcd7da95a6 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs @@ -74,7 +74,6 @@ await SetupAndRunRestApiTest( queryString: "?$select=id,content", entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, exception: true, expectedErrorMessage: "Invalid field to be returned requested: content", expectedStatusCode: HttpStatusCode.BadRequest diff --git a/src/Service.Tests/SqlTests/RestApiTests/Patch/MsSqlPatchApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Patch/MsSqlPatchApiTests.cs index df4a86926c..639ff77581 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Patch/MsSqlPatchApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Patch/MsSqlPatchApiTests.cs @@ -130,16 +130,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MSSQL; await InitializeTestFixture(context); - // Setup REST Components - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/Patch/MySqlPatchApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Patch/MySqlPatchApiTests.cs index 7901393ce0..ec048ba962 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Patch/MySqlPatchApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Patch/MySqlPatchApiTests.cs @@ -199,15 +199,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MYSQL; await InitializeTestFixture(context); - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/Patch/PatchApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Patch/PatchApiTestBase.cs index 7983dc70f8..a2ccac65e3 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Patch/PatchApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Patch/PatchApiTestBase.cs @@ -40,7 +40,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PatchOne_Insert_Nulled_Test"), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -59,7 +58,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PatchOne_Update_Nulled_Test"), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK @@ -90,7 +88,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationUniqueCharactersEntity, sqlQuery: GetQuery(nameof(PatchOne_Insert_UniqueCharacters_Test)), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -120,7 +117,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integration_NonAutoGenPK_EntityName, sqlQuery: GetQuery(nameof(PatchOne_Insert_NonAutoGenPK_Test)), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -140,7 +136,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PatchOne_Insert_CompositeNonAutoGenPK_Test"), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -160,7 +155,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PatchOne_Insert_Empty_Test"), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -178,7 +172,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PatchOne_Insert_Default_Test"), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -198,7 +191,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationMappingEntity, sqlQuery: GetQuery("PatchOne_Insert_Mapping_Test"), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -225,7 +217,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationEntityName, sqlQuery: GetQuery(nameof(PatchOne_Update_Test)), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK @@ -241,7 +232,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _entityWithCompositePrimaryKey, sqlQuery: GetQuery("PatchOne_Update_Default_Test"), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK @@ -257,7 +247,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PatchOne_Update_CompositeNonAutoGenPK_Test"), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK @@ -274,7 +263,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PatchOne_Update_Empty_Test"), - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK @@ -302,7 +290,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationEntityName, sqlQuery: GetQuery(nameof(PatchOne_Update_IfMatchHeaders_Test)), - controller: _restController, operationType: Operation.UpsertIncremental, headers: new HeaderDictionary(headerDictionary), requestBody: requestBody, @@ -334,7 +321,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationEntityName, sqlQuery: null, - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, exception: true, @@ -364,7 +350,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integration_NonAutoGenPK_EntityName, sqlQuery: null, - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, exception: true, @@ -396,7 +381,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.UpsertIncremental, headers: new HeaderDictionary(headerDictionary), requestBody: requestBody, @@ -429,7 +413,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationBrokenMappingEntity, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.UpsertIncremental, exception: true, requestBody: requestBody, @@ -461,7 +444,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, exception: true, @@ -482,7 +464,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.UpsertIncremental, requestBody: requestBody, exception: true, diff --git a/src/Service.Tests/SqlTests/RestApiTests/Patch/PostgreSqlPatchApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Patch/PostgreSqlPatchApiTests.cs index 4868d8a995..0f516ace9e 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Patch/PostgreSqlPatchApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Patch/PostgreSqlPatchApiTests.cs @@ -183,15 +183,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.POSTGRESQL; await InitializeTestFixture(context); - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } #endregion diff --git a/src/Service.Tests/SqlTests/RestApiTests/Put/MsSqlPutApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Put/MsSqlPutApiTests.cs index 8cc989f8a1..a71b62d287 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Put/MsSqlPutApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Put/MsSqlPutApiTests.cs @@ -173,16 +173,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MSSQL; await InitializeTestFixture(context); - // Setup REST Components - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/Put/MySqlPutApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Put/MySqlPutApiTests.cs index 9265280687..222ee494b0 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Put/MySqlPutApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Put/MySqlPutApiTests.cs @@ -258,15 +258,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MYSQL; await InitializeTestFixture(context); - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/Put/PostgreSqlPutApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Put/PostgreSqlPutApiTests.cs index 8376bc4533..57cf7445a3 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Put/PostgreSqlPutApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Put/PostgreSqlPutApiTests.cs @@ -258,15 +258,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.POSTGRESQL; await InitializeTestFixture(context); - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } #endregion diff --git a/src/Service.Tests/SqlTests/RestApiTests/Put/PutApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Put/PutApiTestBase.cs index 3f0c6a939d..023fd3eb4b 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Put/PutApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Put/PutApiTestBase.cs @@ -37,7 +37,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationEntityName, sqlQuery: GetQuery(nameof(PutOne_Update_Test)), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK @@ -54,7 +53,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _entityWithCompositePrimaryKey, sqlQuery: GetQuery("PutOne_Update_Default_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK, @@ -74,7 +72,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PutOne_Update_CompositeNonAutoGenPK_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK, @@ -95,7 +92,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PutOne_Update_NullOutMissingField_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK, @@ -115,7 +111,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PutOne_Update_Empty_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK, @@ -144,7 +139,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationEntityName, sqlQuery: GetQuery(nameof(PutOne_Update_IfMatchHeaders_Test)), - controller: _restController, operationType: Operation.Upsert, headers: new HeaderDictionary(headerDictionary), requestBody: requestBody, @@ -173,7 +167,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integration_NonAutoGenPK_EntityName, sqlQuery: GetQuery(nameof(PutOne_Insert_Test)), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -195,7 +188,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integration_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PutOne_Insert_Nullable_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -218,7 +210,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integration_AutoGenNonPK_EntityName, sqlQuery: GetQuery("PutOne_Insert_AutoGenNonPK_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -238,7 +229,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PutOne_Insert_CompositeNonAutoGenPK_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -256,7 +246,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PutOne_Insert_Default_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -276,7 +265,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PutOne_Insert_Empty_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -307,7 +295,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PutOne_Insert_Nulled_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.Created, @@ -329,7 +316,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: GetQuery("PutOne_Update_Nulled_Test"), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK, @@ -358,7 +344,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationMappingEntity, sqlQuery: GetQuery(nameof(PutOne_Update_With_Mapping_Test)), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK @@ -388,7 +373,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integrationEntityName, sqlQuery: GetQuery(query), - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedStatusCode: HttpStatusCode.OK @@ -414,7 +398,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, exception: true, @@ -440,7 +423,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, exception: true, @@ -469,7 +451,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, exception: true, @@ -500,7 +481,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, exception: true, @@ -523,7 +503,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _entityWithCompositePrimaryKey, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, exception: true, @@ -552,7 +531,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, exception: true, @@ -571,7 +549,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, exception: true, @@ -599,7 +576,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integration_AutoGenNonPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, expectedErrorMessage: @"Invalid request body. Either insufficient or extra fields supplied.", @@ -629,7 +605,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, headers: new HeaderDictionary(headerDictionary), requestBody: requestBody, @@ -661,7 +636,6 @@ await SetupAndRunRestApiTest( queryString: null, entity: _integration_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, exception: true, @@ -692,7 +666,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, exception: true, @@ -713,7 +686,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _Composite_NonAutoGenPK_EntityName, sqlQuery: string.Empty, - controller: _restController, operationType: Operation.Upsert, requestBody: requestBody, exception: true, diff --git a/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs b/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs index 68c4223cb0..d2cfa1e0bb 100644 --- a/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs +++ b/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs @@ -133,8 +133,7 @@ await SetupAndRunRestApiTest( primaryKeyRoute: "book_id/1/author_id/123", queryString: string.Empty, entity: _compositeViewName, - sqlQuery: query, - controller: _restController + sqlQuery: query ); } } diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 6cfcf5f1ca..b2b468eeb7 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -1,8 +1,6 @@ -using System; using System.Collections.Generic; using System.Data.Common; using System.IO; -using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Json; @@ -400,7 +398,6 @@ protected static async Task GetDatabaseResultAsync( /// string represents the query string provided in URL /// string represents the name of the entity /// string represents the query to be executed - /// string represents the rest controller /// The operation type to be tested. /// string represents JSON data used in mutation operations /// bool represents if we expect an exception @@ -409,102 +406,11 @@ protected static async Task GetDatabaseResultAsync( /// enum represents the returned sub status code /// The expected location header in the response (if any) /// - /*protected static async Task SetupAndRunRestApiTest( - string primaryKeyRoute, - string queryString, - string entity, - string sqlQuery, - RestController controller, - Operation operationType = Operation.Read, - string path = "api", - IHeaderDictionary headers = null, - string requestBody = null, - bool exception = false, - string expectedErrorMessage = "", - HttpStatusCode expectedStatusCode = HttpStatusCode.OK, - string expectedSubStatusCode = "BadRequest", - string expectedLocationHeader = null, - string expectedAfterQueryString = "", - bool paginated = false, - int verifyNumRecords = -1) - { - ConfigureRestController( - controller, - queryString, - operationType, - headers, - requestBody - ); - - string baseUrl = UriHelper.GetEncodedUrl(controller.HttpContext.Request); - if (expectedLocationHeader != null) - { - expectedLocationHeader = - baseUrl - + @"/" + expectedLocationHeader; - } - - IActionResult actionResult = await SqlTestHelper.PerformApiTest( - controller, - path, - entity, - primaryKeyRoute, - operationType); - - // if an exception is expected we generate the correct error - // The expected result should be a Query that confirms the result state - // of the Operation performed for the test. However: - // Initial DELETE request results in 204 no content, no exception thrown. - // Subsequent DELETE requests result in 404, which result in an exception. - string expected; - if ((operationType is Operation.Delete || - operationType is Operation.Upsert || - operationType is Operation.UpsertIncremental || - operationType is Operation.Update || - operationType is Operation.UpdateIncremental) - && actionResult is NoContentResult) - { - expected = null; - } - else - { - JsonSerializerOptions options = new() - { - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping - }; - - if (exception) - { - expected = JsonSerializer.Serialize(RestController.ErrorResponse( - expectedSubStatusCode.ToString(), - expectedErrorMessage, - expectedStatusCode).Value, - options); - } - else - { - string dbResult = await GetDatabaseResultAsync(sqlQuery); - // For FIND requests, null result signifies an empty result set - dbResult = (operationType is Operation.Read && dbResult is null) ? "[]" : dbResult; - expected = $"{{\"value\":{FormatExpectedValue(dbResult)}{ExpectedNextLinkIfAny(paginated, EncodeQueryString(baseUrl), $"{expectedAfterQueryString}")}}}"; - } - } - - SqlTestHelper.VerifyResult( - actionResult, - expected, - expectedStatusCode, - expectedLocationHeader, - !exception, - verifyNumRecords); - }*/ - protected static async Task SetupAndRunRestApiTest( string primaryKeyRoute, string queryString, string entity, string sqlQuery, - RestController controller, Operation operationType = Operation.Read, string path = "api", IHeaderDictionary headers = null, @@ -637,19 +543,6 @@ private static HttpMethod GetHttpMethodFromOperation(Operation operationType) } } - /// - /// Helper function encodes the url with query string into the correct - /// format. We utilize the toString() of the HttpValueCollection - /// which is used by the NameValueCollection returned from - /// ParseQueryString to avoid writing this ourselves. - /// - /// Url to be encoded as query string. - /// query string encoded url. - private static string EncodeQueryString(string fullUrl) - { - return HttpUtility.ParseQueryString(fullUrl).ToString(); - } - /// /// Helper function formats the expected value to match actual response format. /// From 0b74a8c4427d45ce0fe7143314d730bf8ec98431 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Wed, 17 Aug 2022 17:04:49 +0530 Subject: [PATCH 09/30] Fixing insertrequestcontext unit test --- .../RestRequestContexts/InsertRequestContext.cs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Service/Models/RestRequestContexts/InsertRequestContext.cs b/src/Service/Models/RestRequestContexts/InsertRequestContext.cs index 8e57233df6..c6fda81305 100644 --- a/src/Service/Models/RestRequestContexts/InsertRequestContext.cs +++ b/src/Service/Models/RestRequestContexts/InsertRequestContext.cs @@ -46,10 +46,17 @@ public InsertRequestContext( try { Dictionary[]? fieldValuePairs = JsonSerializer.Deserialize[]>(payload); - throw new DataApiBuilderException( - statusCode: HttpStatusCode.BadRequest, - message: "Mutation operation on many instances of an entity in a single request are not yet supported.", - subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); + if (fieldValuePairs is null) + { + throw new JsonException("Failed to deserialize the insert payload"); + } + else + { + throw new DataApiBuilderException( + statusCode: HttpStatusCode.BadRequest, + message: "Mutation operation on many instances of an entity in a single request are not yet supported.", + subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); + } } catch (JsonException) { From 5f41fbfb55b327144d719510c513de920091acc6 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Wed, 17 Aug 2022 17:14:57 +0530 Subject: [PATCH 10/30] Formatting fixes --- .../SqlTests/RestApiTests/Delete/MsSqlDeleteApiTest.cs | 2 -- .../SqlTests/RestApiTests/Delete/MySqlDeleteApiTest.cs | 2 -- .../SqlTests/RestApiTests/Delete/PostgreSqlDeleteApiTests.cs | 2 -- .../SqlTests/RestApiTests/Find/MsSqlFindApiTests.cs | 2 -- .../SqlTests/RestApiTests/Find/MySqlFindApiTests.cs | 2 -- .../SqlTests/RestApiTests/Find/PostgreSqlFindApiTests.cs | 2 -- .../SqlTests/RestApiTests/Insert/MsSqlInsertApiTests.cs | 2 -- .../SqlTests/RestApiTests/Insert/MySqlInsertApiTests.cs | 2 -- .../SqlTests/RestApiTests/Insert/PostgreSqlInsertApiTests.cs | 2 -- .../SqlTests/RestApiTests/Patch/MsSqlPatchApiTests.cs | 2 -- .../SqlTests/RestApiTests/Patch/MySqlPatchApiTests.cs | 2 -- .../SqlTests/RestApiTests/Patch/PostgreSqlPatchApiTests.cs | 2 -- src/Service.Tests/SqlTests/RestApiTests/Put/MsSqlPutApiTests.cs | 2 -- src/Service.Tests/SqlTests/RestApiTests/Put/MySqlPutApiTests.cs | 2 -- .../SqlTests/RestApiTests/Put/PostgreSqlPutApiTests.cs | 2 -- src/Service.Tests/SqlTests/SqlTestBase.cs | 2 +- 16 files changed, 1 insertion(+), 31 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/Delete/MsSqlDeleteApiTest.cs b/src/Service.Tests/SqlTests/RestApiTests/Delete/MsSqlDeleteApiTest.cs index 9a36087a2d..9f0467e7b9 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Delete/MsSqlDeleteApiTest.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Delete/MsSqlDeleteApiTest.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Delete diff --git a/src/Service.Tests/SqlTests/RestApiTests/Delete/MySqlDeleteApiTest.cs b/src/Service.Tests/SqlTests/RestApiTests/Delete/MySqlDeleteApiTest.cs index 56c2ecd841..7ddc824455 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Delete/MySqlDeleteApiTest.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Delete/MySqlDeleteApiTest.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Delete diff --git a/src/Service.Tests/SqlTests/RestApiTests/Delete/PostgreSqlDeleteApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Delete/PostgreSqlDeleteApiTests.cs index 90ec8914cb..848558b5b3 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Delete/PostgreSqlDeleteApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Delete/PostgreSqlDeleteApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Delete diff --git a/src/Service.Tests/SqlTests/RestApiTests/Find/MsSqlFindApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Find/MsSqlFindApiTests.cs index 53ff2a47cf..19bb7ebcad 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Find/MsSqlFindApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Find/MsSqlFindApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Find diff --git a/src/Service.Tests/SqlTests/RestApiTests/Find/MySqlFindApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Find/MySqlFindApiTests.cs index 9674b712e1..0b4a97e858 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Find/MySqlFindApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Find/MySqlFindApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Find diff --git a/src/Service.Tests/SqlTests/RestApiTests/Find/PostgreSqlFindApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Find/PostgreSqlFindApiTests.cs index 1e74ce3095..4385bf3f6d 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Find/PostgreSqlFindApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Find/PostgreSqlFindApiTests.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Find diff --git a/src/Service.Tests/SqlTests/RestApiTests/Insert/MsSqlInsertApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Insert/MsSqlInsertApiTests.cs index a94bb67412..da6d97537a 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Insert/MsSqlInsertApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Insert/MsSqlInsertApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Insert diff --git a/src/Service.Tests/SqlTests/RestApiTests/Insert/MySqlInsertApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Insert/MySqlInsertApiTests.cs index 49019134ee..593322ecd9 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Insert/MySqlInsertApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Insert/MySqlInsertApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Insert diff --git a/src/Service.Tests/SqlTests/RestApiTests/Insert/PostgreSqlInsertApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Insert/PostgreSqlInsertApiTests.cs index d69cfb92ab..563f9b842f 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Insert/PostgreSqlInsertApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Insert/PostgreSqlInsertApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Insert diff --git a/src/Service.Tests/SqlTests/RestApiTests/Patch/MsSqlPatchApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Patch/MsSqlPatchApiTests.cs index 639ff77581..eb65ead650 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Patch/MsSqlPatchApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Patch/MsSqlPatchApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Patch diff --git a/src/Service.Tests/SqlTests/RestApiTests/Patch/MySqlPatchApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Patch/MySqlPatchApiTests.cs index ec048ba962..93b4b06b06 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Patch/MySqlPatchApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Patch/MySqlPatchApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Patch diff --git a/src/Service.Tests/SqlTests/RestApiTests/Patch/PostgreSqlPatchApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Patch/PostgreSqlPatchApiTests.cs index 0f516ace9e..8d75a30e1d 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Patch/PostgreSqlPatchApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Patch/PostgreSqlPatchApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Patch diff --git a/src/Service.Tests/SqlTests/RestApiTests/Put/MsSqlPutApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Put/MsSqlPutApiTests.cs index a71b62d287..fbc42bb887 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Put/MsSqlPutApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Put/MsSqlPutApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Put diff --git a/src/Service.Tests/SqlTests/RestApiTests/Put/MySqlPutApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Put/MySqlPutApiTests.cs index 222ee494b0..5e7610c1ad 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Put/MySqlPutApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Put/MySqlPutApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Put diff --git a/src/Service.Tests/SqlTests/RestApiTests/Put/PostgreSqlPutApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/Put/PostgreSqlPutApiTests.cs index 57cf7445a3..5bc5f1da3b 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Put/PostgreSqlPutApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Put/PostgreSqlPutApiTests.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests.Put diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index b2b468eeb7..19a611ce34 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -449,7 +449,7 @@ protected static async Task SetupAndRunRestApiTest( if (headers is not null) { - foreach ((string key,StringValues value) in headers) + foreach ((string key, StringValues value) in headers) { request.Headers.Add(key, value.ToString()); } From 022582635f4fdec0dd90d3c2b939178855ca04dc Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Wed, 17 Aug 2022 18:11:37 +0530 Subject: [PATCH 11/30] Code refactoring, clean up and comments/summary --- src/Service.Tests/SqlTests/SqlTestBase.cs | 47 ++++----- src/Service.Tests/SqlTests/SqlTestHelper.cs | 100 +++++++++++--------- 2 files changed, 80 insertions(+), 67 deletions(-) diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 19a611ce34..8257c3bfe7 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -8,7 +8,6 @@ using System.Text; using System.Text.Encodings.Web; using System.Text.Json; -using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web; using Azure.DataApiBuilder.Auth; @@ -424,29 +423,39 @@ protected static async Task SetupAndRunRestApiTest( bool paginated = false, int verifyNumRecords = -1) { + // Create the rest endpoint using the path and entity name. string restEndPoint = path + "/" + entity; + // Append primaryKeyRoute to the endpoint if it is not empty. if (!string.IsNullOrEmpty(primaryKeyRoute)) { restEndPoint = restEndPoint + "/" + primaryKeyRoute; } + // Append queryString to the endpoint if it is not empty. if (!string.IsNullOrEmpty(queryString)) { restEndPoint = restEndPoint + queryString; } + // Use UnsafeRelaxedJsonEscaping to be less strict about what is encoded. + // More details can be found here: + // https://docs.microsoft.com/en-us/dotnet/api/system.text.encodings.web.javascriptencoder.unsaferelaxedjsonescaping?view=net-6.0 JsonSerializerOptions options = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + // Get the httpMethod based on the operation to be executed. HttpMethod httpMethod = GetHttpMethodFromOperation(operationType); + + // Create the request to be sent to the engine. HttpRequestMessage request = new(httpMethod, restEndPoint) { Content = JsonContent.Create(requestBody, options: options) }; + // Add headers to the request if any. if (headers is not null) { foreach ((string key, StringValues value) in headers) @@ -455,10 +464,9 @@ protected static async Task SetupAndRunRestApiTest( } } + // Send request to the engine. HttpResponseMessage response = await HttpClient.SendAsync(request); - string responseBody = await response.Content.ReadAsStringAsync(); - // if an exception is expected we generate the correct error // The expected result should be a Query that confirms the result state // of the Operation performed for the test. However: @@ -500,27 +508,22 @@ operationType is Operation.Update || } } - if (!exception) - { - Assert.IsTrue(SqlTestHelper.JsonStringsDeepEqual(expected, responseBody)); - Assert.AreEqual(expectedStatusCode, response.StatusCode); - if (operationType == Operation.Insert) - { - string responseUri = (response.Headers.Location.OriginalString); - string requestUri = request.RequestUri.OriginalString; - string actualLocation = responseUri.Substring( - responseUri.IndexOf(requestUri + "/") + requestUri.Length + 1); - Assert.AreEqual(expectedLocationHeader, actualLocation); - } - } - else - { - responseBody = Regex.Replace(responseBody, @"\\u0022", @"\\"""); - responseBody = Regex.Unescape(responseBody); - Assert.AreEqual(expected, responseBody, ignoreCase: true); - } + await SqlTestHelper.VerifyResultAsync( + expected: expected, + request: request, + response: response, + exception: exception, + httpMethod: httpMethod, + expectedLocationHeader: expectedLocationHeader, + verifyNumRecords: verifyNumRecords); } + /// + /// Helper method to get the HttpMethod based on the operation type. + /// + /// The operation to be executed on the entity. + /// + /// private static HttpMethod GetHttpMethodFromOperation(Operation operationType) { switch (operationType) diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index 1927702410..bca17cea85 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -2,11 +2,12 @@ using System.Collections.Generic; using System.Linq; using System.Net; +using System.Net.Http; using System.Text.Encodings.Web; using System.Text.Json; +using System.Text.RegularExpressions; using System.Threading.Tasks; using Azure.DataApiBuilder.Config; -using Azure.DataApiBuilder.Service.Controllers; using Azure.DataApiBuilder.Service.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -83,50 +84,6 @@ public static void TestForErrorInGraphQLResponse(string response, string message } } - /// - /// Performs test on the given entity name by calling the correct Api based on the - /// operation type passed for the given primaryKeyRoute (if any). - /// - /// The REST controller with the request context. - /// The entity name. - /// The primary key portion of the route. - /// The operation type to be tested. - public static async Task PerformApiTest( - RestController controller, - string path, - string entityName, - string primaryKeyRoute, - Operation operationType = Operation.Read) - - { - IActionResult actionResult; - string pathAndEntityName = $"{path}/{entityName}"; - switch (operationType) - { - case Operation.Read: - actionResult = await controller.Find($"{pathAndEntityName}/{primaryKeyRoute}"); - break; - case Operation.Insert: - actionResult = await controller.Insert($"{pathAndEntityName}"); - break; - case Operation.Delete: - actionResult = await controller.Delete($"{pathAndEntityName}/{primaryKeyRoute}"); - break; - case Operation.Update: - case Operation.Upsert: - actionResult = await controller.Upsert($"{pathAndEntityName}/{primaryKeyRoute}"); - break; - case Operation.UpdateIncremental: - case Operation.UpsertIncremental: - actionResult = await controller.UpsertIncremental($"{pathAndEntityName}/{primaryKeyRoute}"); - break; - default: - throw new NotSupportedException("This operation is not yet supported."); - } - - return actionResult; - } - /// /// Verifies the ActionResult is as expected with the expected status code. /// @@ -195,6 +152,59 @@ public static void VerifyResult( } } + /// + /// Verifies the ActionResult is as expected with the expected status code. + /// + /// Expected result of the query execution. + /// The HttpRequestMessage sent to the engine via HttpClient. + /// The HttpResponseMessage returned by the engine. + /// Boolean value indicating whether an exception is expected as + /// a result of executing the request on the engine. + /// The http method specified in the request. + /// The expected location header in the response(if any). + /// + /// + public static async Task VerifyResultAsync( + string expected, + HttpRequestMessage request, + HttpResponseMessage response, + bool exception, + HttpMethod httpMethod, + string expectedLocationHeader, + int verifyNumRecords) + { + string responseBody = await response.Content.ReadAsStringAsync(); + if (!exception) + { + Assert.IsTrue(JsonStringsDeepEqual(expected, responseBody)); + + // Assert that the expectedLocation and actualLocation are equal in case of + // POST operation. + if (httpMethod == HttpMethod.Post ) + { + string responseUri = (response.Headers.Location.OriginalString); + string requestUri = request.RequestUri.OriginalString; + string actualLocation = responseUri.Substring(requestUri.Length + 1); + Assert.AreEqual(expectedLocationHeader, actualLocation); + } + + if (response.StatusCode == HttpStatusCode.OK && verifyNumRecords >= 0) + { + // Assert the number of records received is equal to expected number of records. + Dictionary actualAsDict = JsonSerializer.Deserialize>(responseBody); + Assert.AreEqual(actualAsDict["value"].Length, verifyNumRecords); + } + } + else + { + responseBody = Regex.Replace(responseBody, @"\\u0022", @"\\"""); + + // Convert the escaped characters into their unescaped form. + responseBody = Regex.Unescape(responseBody); + Assert.AreEqual(expected, responseBody, ignoreCase: true); + } + } + /// /// Returns the HTTP verb for a provided Operation. /// From 6ebe23c17a6fc538ba2eafeee4184defce8a4d99 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Wed, 17 Aug 2022 18:31:18 +0530 Subject: [PATCH 12/30] Comment for clarity --- src/Service.Tests/SqlTests/SqlTestHelper.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index bca17cea85..8d21dc40e4 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -180,7 +180,7 @@ public static async Task VerifyResultAsync( // Assert that the expectedLocation and actualLocation are equal in case of // POST operation. - if (httpMethod == HttpMethod.Post ) + if (httpMethod == HttpMethod.Post) { string responseUri = (response.Headers.Location.OriginalString); string requestUri = request.RequestUri.OriginalString; @@ -197,6 +197,8 @@ public static async Task VerifyResultAsync( } else { + // Quote(") has to be treated differently than other unicode characters + // as it has to be added with a preceding backslash. responseBody = Regex.Replace(responseBody, @"\\u0022", @"\\"""); // Convert the escaped characters into their unescaped form. From c0f530ca44b91d64549cd6fb1951b7f880524468 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Thu, 18 Aug 2022 16:42:31 +0530 Subject: [PATCH 13/30] One insert test still to fix --- .../RestApiTests/Insert/InsertApiTestBase.cs | 4 ++-- src/Service.Tests/SqlTests/SqlTestBase.cs | 15 +++++++++++--- .../InsertRequestContext.cs | 20 +------------------ src/Service/Services/RequestValidator.cs | 15 ++++++++++++-- 4 files changed, 28 insertions(+), 26 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs index 84465a6d52..c4b0073e46 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs @@ -265,7 +265,7 @@ await SetupAndRunRestApiTest( /// /// Tests the InsertOne functionality with a request body containing values that do not match the value type defined in the schema. /// - [TestMethod] + /*[TestMethod] public virtual async Task InsertOneWithInvalidTypeInJsonBodyTest() { string requestBody = @" @@ -286,7 +286,7 @@ await SetupAndRunRestApiTest( expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: "BadRequest" ); - } + }*/ /// /// Tests the InsertOne functionality with no valid fields in the request body. diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 8257c3bfe7..1fd9e92381 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -450,10 +450,19 @@ protected static async Task SetupAndRunRestApiTest( HttpMethod httpMethod = GetHttpMethodFromOperation(operationType); // Create the request to be sent to the engine. - HttpRequestMessage request = new(httpMethod, restEndPoint) + HttpRequestMessage request; + if (!string.IsNullOrEmpty(requestBody)) { - Content = JsonContent.Create(requestBody, options: options) - }; + using JsonDocument requestBodyJsonDoc = JsonDocument.Parse(requestBody); + request = new(httpMethod, restEndPoint) + { + Content = JsonContent.Create(JsonSerializer.SerializeToElement(requestBodyJsonDoc), options: options) + }; + } + else + { + request = new(httpMethod, restEndPoint); + } // Add headers to the request if any. if (headers is not null) diff --git a/src/Service/Models/RestRequestContexts/InsertRequestContext.cs b/src/Service/Models/RestRequestContexts/InsertRequestContext.cs index c6fda81305..68d1353d4f 100644 --- a/src/Service/Models/RestRequestContexts/InsertRequestContext.cs +++ b/src/Service/Models/RestRequestContexts/InsertRequestContext.cs @@ -43,28 +43,10 @@ public InsertRequestContext( } catch (JsonException) { - try - { - Dictionary[]? fieldValuePairs = JsonSerializer.Deserialize[]>(payload); - if (fieldValuePairs is null) - { - throw new JsonException("Failed to deserialize the insert payload"); - } - else - { - throw new DataApiBuilderException( - statusCode: HttpStatusCode.BadRequest, - message: "Mutation operation on many instances of an entity in a single request are not yet supported.", - subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); - } - } - catch (JsonException) - { - throw new DataApiBuilderException( + throw new DataApiBuilderException( message: "The request body is not in a valid JSON format.", statusCode: HttpStatusCode.BadRequest, subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); - } } } else diff --git a/src/Service/Services/RequestValidator.cs b/src/Service/Services/RequestValidator.cs index 94bf32720f..2dfb8bc6c1 100644 --- a/src/Service/Services/RequestValidator.cs +++ b/src/Service/Services/RequestValidator.cs @@ -382,8 +382,19 @@ private static TableDefinition TryGetTableDefinition(string entityName, ISqlMeta /// private static JsonElement GetInsertPayload(string requestBody) { - //requestBody = requestBody.Substring(1, requestBody.Length - 2); - return JsonDocument.Parse(requestBody).RootElement.Clone(); + using JsonDocument insertPayload = JsonDocument.Parse(requestBody); + + if (insertPayload.RootElement.ValueKind == JsonValueKind.Array) + { + throw new DataApiBuilderException( + statusCode: HttpStatusCode.BadRequest, + message: "Mutation operation on many instances of an entity in a single request are not yet supported.", + subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); + } + else + { + return insertPayload.RootElement.Clone(); + } } /// From 5c372043b7a5b4af4c89ad293b9d86834ef42d27 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Thu, 18 Aug 2022 18:56:26 +0530 Subject: [PATCH 14/30] Correcting indentation --- .../Models/RestRequestContexts/InsertRequestContext.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Service/Models/RestRequestContexts/InsertRequestContext.cs b/src/Service/Models/RestRequestContexts/InsertRequestContext.cs index 68d1353d4f..074c4af564 100644 --- a/src/Service/Models/RestRequestContexts/InsertRequestContext.cs +++ b/src/Service/Models/RestRequestContexts/InsertRequestContext.cs @@ -44,9 +44,9 @@ public InsertRequestContext( catch (JsonException) { throw new DataApiBuilderException( - message: "The request body is not in a valid JSON format.", - statusCode: HttpStatusCode.BadRequest, - subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); + message: "The request body is not in a valid JSON format.", + statusCode: HttpStatusCode.BadRequest, + subStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest); } } else From 4c924f5143eb6658050d20b3eb9df611ca50453a Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Thu, 18 Aug 2022 21:54:53 +0530 Subject: [PATCH 15/30] All tests fixed --- .../SqlTests/RestApiTests/Insert/InsertApiTestBase.cs | 8 ++++---- src/Service.Tests/SqlTests/SqlTestBase.cs | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs index c4b0073e46..3a9eee88f6 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs @@ -265,13 +265,13 @@ await SetupAndRunRestApiTest( /// /// Tests the InsertOne functionality with a request body containing values that do not match the value type defined in the schema. /// - /*[TestMethod] + [TestMethod] public virtual async Task InsertOneWithInvalidTypeInJsonBodyTest() { string requestBody = @" { ""title"": [""My New Book"", ""Another new Book"", {""author"": ""unknown""}], - ""publisher_id"": [1234, 4321] + ""publisher_id"": [1234,4321] }"; await SetupAndRunRestApiTest( @@ -282,11 +282,11 @@ await SetupAndRunRestApiTest( operationType: Operation.Insert, requestBody: requestBody, exception: true, - expectedErrorMessage: "Parameter \"[1234, 4321]\" cannot be resolved as column \"publisher_id\" with type \"Int32\".", + expectedErrorMessage: "Parameter \"[1234,4321]\" cannot be resolved as column \"publisher_id\" with type \"Int32\".", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: "BadRequest" ); - }*/ + } /// /// Tests the InsertOne functionality with no valid fields in the request body. diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 1fd9e92381..100fb30e67 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -453,10 +453,10 @@ protected static async Task SetupAndRunRestApiTest( HttpRequestMessage request; if (!string.IsNullOrEmpty(requestBody)) { - using JsonDocument requestBodyJsonDoc = JsonDocument.Parse(requestBody); + JsonElement requestBodyElement = JsonDocument.Parse(requestBody).RootElement.Clone(); request = new(httpMethod, restEndPoint) { - Content = JsonContent.Create(JsonSerializer.SerializeToElement(requestBodyJsonDoc), options: options) + Content = JsonContent.Create(requestBodyElement, options: options) }; } else From c27280acb8aa1c69bcb3d2a2e01f654880c311bd Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Fri, 19 Aug 2022 13:16:13 +0530 Subject: [PATCH 16/30] Removing unused code --- .../RestApiTests/OtherRestApiTests.cs | 34 ++++---- src/Service.Tests/SqlTests/SqlTestBase.cs | 87 ------------------- src/Service.Tests/SqlTests/SqlTestHelper.cs | 74 +--------------- 3 files changed, 22 insertions(+), 173 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs index bcd7da95a6..6b473335e3 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs @@ -1,12 +1,11 @@ using System; using System.Net; +using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; -using Azure.DataApiBuilder.Config; using Azure.DataApiBuilder.Service.Controllers; using Azure.DataApiBuilder.Service.Services; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -89,24 +88,29 @@ await SetupAndRunRestApiTest( [TestMethod] public async Task HandleAndExecuteUnsupportedOperationUnitTestAsync() { - string expected = "{\"error\":{\"code\":\"BadRequest\",\"message\":\"This operation is not supported.\",\"status\":400}}"; - // need header to instantiate identity in controller - HeaderDictionary headers = new(); - headers.Add("x-ms-client-principal", Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"hello\":\"world\"}"))); - - ConfigureRestController(_restController, string.Empty, Operation.None); - + string expectedBody = string.Empty; // Setup params to invoke function with // Must use valid entity name string path = "api"; string entityName = "Book"; - Operation operationType = Operation.None; - string primaryKeyRoute = string.Empty; + HttpMethod method = HttpMethod.Head; + + // Since primarykey route and querystring are empty for this test, end point would only comprise + // of path and entity name. + string restEndPoint = path + "/" + entityName; + + HttpRequestMessage request = new(method, restEndPoint); + // need header to instantiate identity in controller + request.Headers.Add("x-ms-client-principal", Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"hello\":\"world\"}"))); + + // Send request to the engine. + HttpResponseMessage response = await HttpClient.SendAsync(request); + + // Read response as string. + string responseBody = await response.Content.ReadAsStringAsync(); - // Reflection to invoke a private method to unit test all code paths - PrivateObject testObject = new(_restController); - IActionResult actionResult = await testObject.Invoke("HandleOperation", new object[] { $"{path}/{entityName}/{primaryKeyRoute}", operationType }); - SqlTestHelper.VerifyResult(actionResult, expected, System.Net.HttpStatusCode.BadRequest, string.Empty); + // Assert that expectedBody and responseBody are the same. + Assert.AreEqual(expectedBody, responseBody); } #region Private helpers diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 100fb30e67..4ad61c6fe8 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -5,7 +5,6 @@ using System.Net.Http; using System.Net.Http.Json; using System.Security.Claims; -using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Threading.Tasks; @@ -20,7 +19,6 @@ using Azure.DataApiBuilder.Service.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Microsoft.Data.SqlClient; @@ -302,63 +300,6 @@ protected static async Task ResetDbStateAsync() using DbDataReader _ = await _queryExecutor.ExecuteQueryAsync(File.ReadAllText($"{DatabaseEngine}Books.sql"), parameters: null); } - /// - /// Constructs an http context with request consisting of the given query string and/or body data. - /// - /// query - /// The data to be put in the request body e.g. GraphQLQuery - /// The operation used to define the HttpContext HTTP Method - /// The http context with request consisting of the given query string (if any) - /// and request body (if any) as a stream of utf-8 bytes. - protected static DefaultHttpContext GetRequestHttpContext( - string queryStringUrl = null, - IHeaderDictionary headers = null, - string bodyData = null, - Operation operation = Operation.Read) - { - DefaultHttpContext httpContext; - IFeatureCollection features = new FeatureCollection(); - //Add response features - features.Set(new HttpResponseFeature()); - features.Set(new StreamResponseBodyFeature(new MemoryStream())); - - if (headers is not null) - { - features.Set(new HttpRequestFeature { Headers = headers, Method = SqlTestHelper.OperationTypeToHTTPVerb(operation) }); - httpContext = new(features); - } - else - { - features.Set(new HttpRequestFeature { Method = SqlTestHelper.OperationTypeToHTTPVerb(operation) }); - httpContext = new(features); - } - - if (!string.IsNullOrEmpty(queryStringUrl)) - { - httpContext.Request.QueryString = new(queryStringUrl); - } - - if (!string.IsNullOrEmpty(bodyData)) - { - MemoryStream stream = new(Encoding.UTF8.GetBytes(bodyData)); - httpContext.Request.Body = stream; - httpContext.Request.ContentLength = stream.Length; - } - - // Add identity object to the Mock context object. - ClaimsIdentity identity = new(authenticationType: "Bearer"); - identity.AddClaim(new Claim(ClaimTypes.Role, "anonymous")); - identity.AddClaim(new Claim(ClaimTypes.Role, "authenticated")); - - ClaimsPrincipal user = new(identity); - httpContext.User = user; - - // Set the user role as authenticated to allow tests to execute with all privileges. - httpContext.Request.Headers[AuthorizationResolver.CLIENT_ROLE_HEADER] = "authenticated"; - - return httpContext; - } - /// /// Sends raw SQL query to database engine to retrieve expected result in JSON format. /// @@ -578,34 +519,6 @@ private static string ExpectedNextLinkIfAny(bool paginated, string baseUrl, stri return paginated ? $",\"nextLink\":\"{baseUrl}{queryString}\"" : string.Empty; } - /// - /// Add HttpContext with query and body(if any) to the RestController - /// - /// The controller to configure. - /// The query string in the url. - /// The data to be put in the request body. - protected static void ConfigureRestController( - RestController restController, - string queryString, - Operation operation, - IHeaderDictionary headers = null, - string requestBody = null - ) - { - restController.ControllerContext.HttpContext = - GetRequestHttpContext( - queryString, - headers, - bodyData: requestBody, - operation); - - // Set the mock context accessor's request same as the controller's request. - _httpContextAccessor.Setup(x => x.HttpContext.Request).Returns(restController.ControllerContext.HttpContext.Request); - - //Set the mock context accessor's Items same as the controller's Items - _httpContextAccessor.Setup(x => x.HttpContext.Items).Returns(restController.ControllerContext.HttpContext.Items); - } - /// /// Read the data property of the GraphQLController result /// diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index 8d21dc40e4..f569fd2902 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -3,13 +3,11 @@ using System.Linq; using System.Net; using System.Net.Http; -using System.Text.Encodings.Web; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; using Azure.DataApiBuilder.Config; using Azure.DataApiBuilder.Service.Models; -using Microsoft.AspNetCore.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; @@ -84,74 +82,6 @@ public static void TestForErrorInGraphQLResponse(string response, string message } } - /// - /// Verifies the ActionResult is as expected with the expected status code. - /// - /// The action result of the operation to verify. - /// string represents the expected result. This value can be null for NoContent or NotFound - /// results of operations like GET and DELETE - /// int represents the returned http status code - /// The expected location header in the response(if any). - public static void VerifyResult( - IActionResult actionResult, - string expected, - HttpStatusCode expectedStatusCode, - string expectedLocationHeader, - bool isJson = false, - int verifyNumRecords = -1) - { - JsonSerializerOptions options = new() - { - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping - }; - string actual; - switch (actionResult) - { - case OkObjectResult okResult: - Assert.AreEqual((int)expectedStatusCode, okResult.StatusCode); - actual = JsonSerializer.Serialize(okResult.Value, options); - // if verifyNumRecords is positive we want to compare its value to - // the number of elements associated with "value" in the actual result. - // because the okResult.Value is an annonymous type we use the serialized - // json string, actual, to easily get the inner array and get its length. - if (verifyNumRecords >= 0) - { - Dictionary actualAsDict = JsonSerializer.Deserialize>(actual); - Assert.AreEqual(actualAsDict["value"].Length, verifyNumRecords); - } - - break; - case CreatedResult createdResult: - Assert.AreEqual((int)expectedStatusCode, createdResult.StatusCode); - Assert.AreEqual(expectedLocationHeader, createdResult.Location); - actual = JsonSerializer.Serialize(createdResult.Value); - break; - // NoContentResult does not have value property for messages - case NoContentResult noContentResult: - Assert.AreEqual((int)expectedStatusCode, noContentResult.StatusCode); - actual = null; - break; - case NotFoundResult notFoundResult: - Assert.AreEqual((int)expectedStatusCode, notFoundResult.StatusCode); - actual = null; - break; - default: - JsonResult actualResult = (JsonResult)actionResult; - actual = JsonSerializer.Serialize(actualResult.Value, options); - break; - } - - Console.WriteLine($"Expected: {expected}\nActual: {actual}"); - if (isJson && !string.IsNullOrEmpty(expected)) - { - Assert.IsTrue(JsonStringsDeepEqual(expected, actual)); - } - else - { - Assert.AreEqual(expected, actual, ignoreCase: true); - } - } - /// /// Verifies the ActionResult is as expected with the expected status code. /// @@ -176,6 +106,7 @@ public static async Task VerifyResultAsync( string responseBody = await response.Content.ReadAsStringAsync(); if (!exception) { + Console.WriteLine($"Expected: {expected}\nActual: {responseBody}"); Assert.IsTrue(JsonStringsDeepEqual(expected, responseBody)); // Assert that the expectedLocation and actualLocation are equal in case of @@ -203,7 +134,8 @@ public static async Task VerifyResultAsync( // Convert the escaped characters into their unescaped form. responseBody = Regex.Unescape(responseBody); - Assert.AreEqual(expected, responseBody, ignoreCase: true); + Console.WriteLine($"Expected: {expected}\nActual: {responseBody}"); + Assert.AreEqual(expected, responseBody); } } From 6ba3d6d325a31786b58a584eb30c564d42c321c9 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Fri, 19 Aug 2022 13:35:41 +0530 Subject: [PATCH 17/30] Removing unused class members --- .../SqlTests/RestApiTests/OtherRestApiTests.cs | 10 ---------- .../SqlTests/RestApiTests/RestApiTestBase.cs | 2 -- 2 files changed, 12 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs index 6b473335e3..5ae3ef478c 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs @@ -38,16 +38,6 @@ public static async Task SetupAsync(TestContext context) { DatabaseEngine = TestCategory.MSSQL; await InitializeTestFixture(context); - // Setup REST Components - _restService = new RestService(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - _restController = new RestController(_restService, - _restControllerLogger); } /// diff --git a/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs index 7da5930cf8..ae4f0c41eb 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs @@ -10,8 +10,6 @@ namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests [TestClass] public abstract class RestApiTestBase : SqlTestBase { - protected static RestService _restService; - protected static RestController _restController; protected static readonly string _integrationEntityName = "Book"; protected static readonly string _integrationTableName = "books"; protected static readonly string _entityWithCompositePrimaryKey = "Review"; From 744a838ae48b25d65ded4dd951aa2e77c72b5f7b Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Fri, 19 Aug 2022 13:39:53 +0530 Subject: [PATCH 18/30] Formatting fix --- src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs | 2 -- src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs | 2 -- 2 files changed, 4 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs index 5ae3ef478c..c4c991a7ed 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs @@ -4,8 +4,6 @@ using System.Reflection; using System.Text; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs index ae4f0c41eb..1881667096 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs @@ -1,5 +1,3 @@ -using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests From 57f446870f4aae0381d48387a8a97e5636b38ee1 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Mon, 22 Aug 2022 09:07:10 +0530 Subject: [PATCH 19/30] Code clean up --- .../RestApiTests/OtherRestApiTests.cs | 29 ------------------- src/Service.Tests/SqlTests/SqlTestBase.cs | 2 +- src/Service.Tests/SqlTests/SqlTestHelper.cs | 3 +- 3 files changed, 2 insertions(+), 32 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs index c4c991a7ed..33d5776f8c 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs @@ -100,34 +100,5 @@ public async Task HandleAndExecuteUnsupportedOperationUnitTestAsync() // Assert that expectedBody and responseBody are the same. Assert.AreEqual(expectedBody, responseBody); } - - #region Private helpers - - /// - /// Helper function uses reflection to invoke - /// private methods from outside class. - /// Expects async method returning Task. - /// - class PrivateObject - { - private readonly object _classToInvoke; - public PrivateObject(object classToInvoke) - { - _classToInvoke = classToInvoke; - } - - public Task Invoke(string privateMethodName, params object[] privateMethodArgs) - { - MethodInfo methodInfo = _classToInvoke.GetType().GetMethod(privateMethodName, BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); - if (methodInfo is null) - { - throw new System.Exception($"{privateMethodName} not found in class '{_classToInvoke.GetType()}'"); - } - - return (Task)methodInfo.Invoke(_classToInvoke, privateMethodArgs); - } - } - - #endregion } } diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 4ad61c6fe8..43b97ee4cf 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -428,7 +428,7 @@ operationType is Operation.Upsert || operationType is Operation.UpsertIncremental || operationType is Operation.Update || operationType is Operation.UpdateIncremental) - && response.StatusCode.Equals(HttpStatusCode.NoContent) + && response.StatusCode == HttpStatusCode.NoContent ) { expected = string.Empty; diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index f569fd2902..8b5cc5e771 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -44,8 +44,7 @@ public static void RemoveAllRelationshipBetweenEntities(RuntimeConfig runtimeCon /// True if JSON objects are the same public static bool JsonStringsDeepEqual(string jsonString1, string jsonString2) { - return string.IsNullOrEmpty(jsonString1) && string.IsNullOrEmpty(jsonString2) || - JToken.DeepEquals(JToken.Parse(jsonString1), JToken.Parse(jsonString2)); + return JToken.DeepEquals(JToken.Parse(jsonString1), JToken.Parse(jsonString2)); } /// From 6e87e8bd295310406a263c14d742b4154e7a6f86 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Mon, 22 Aug 2022 09:18:50 +0530 Subject: [PATCH 20/30] Fixing assertions --- src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs | 2 -- src/Service.Tests/SqlTests/SqlTestBase.cs | 1 + src/Service.Tests/SqlTests/SqlTestHelper.cs | 3 ++- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs index 33d5776f8c..2040913bba 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs @@ -1,10 +1,8 @@ using System; using System.Net; using System.Net.Http; -using System.Reflection; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestApiTests diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 43b97ee4cf..a1c195920c 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -458,6 +458,7 @@ operationType is Operation.Update || } } + // Verify the expected and actual response are identical. await SqlTestHelper.VerifyResultAsync( expected: expected, request: request, diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index 8b5cc5e771..f569fd2902 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -44,7 +44,8 @@ public static void RemoveAllRelationshipBetweenEntities(RuntimeConfig runtimeCon /// True if JSON objects are the same public static bool JsonStringsDeepEqual(string jsonString1, string jsonString2) { - return JToken.DeepEquals(JToken.Parse(jsonString1), JToken.Parse(jsonString2)); + return string.IsNullOrEmpty(jsonString1) && string.IsNullOrEmpty(jsonString2) || + JToken.DeepEquals(JToken.Parse(jsonString1), JToken.Parse(jsonString2)); } /// From baf3e9e5a1823b6b1e990ddc5067cd1cd3a2fd13 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Mon, 22 Aug 2022 09:28:45 +0530 Subject: [PATCH 21/30] Removing unused method --- src/Service.Tests/SqlTests/SqlTestBase.cs | 31 +------------------- src/Service.Tests/SqlTests/SqlTestHelper.cs | 32 ++++++++++----------- 2 files changed, 17 insertions(+), 46 deletions(-) diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index a1c195920c..ca40348b15 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -14,7 +14,6 @@ using Azure.DataApiBuilder.Service.Authorization; using Azure.DataApiBuilder.Service.Configurations; using Azure.DataApiBuilder.Service.Controllers; -using Azure.DataApiBuilder.Service.Exceptions; using Azure.DataApiBuilder.Service.Resolvers; using Azure.DataApiBuilder.Service.Services; using Microsoft.AspNetCore.Authorization; @@ -388,7 +387,7 @@ protected static async Task SetupAndRunRestApiTest( }; // Get the httpMethod based on the operation to be executed. - HttpMethod httpMethod = GetHttpMethodFromOperation(operationType); + HttpMethod httpMethod = SqlTestHelper.GetHttpMethodFromOperation(operationType); // Create the request to be sent to the engine. HttpRequestMessage request; @@ -469,34 +468,6 @@ await SqlTestHelper.VerifyResultAsync( verifyNumRecords: verifyNumRecords); } - /// - /// Helper method to get the HttpMethod based on the operation type. - /// - /// The operation to be executed on the entity. - /// - /// - private static HttpMethod GetHttpMethodFromOperation(Operation operationType) - { - switch (operationType) - { - case Operation.Read: - return HttpMethod.Get; - case Operation.Insert: - return HttpMethod.Post; - case Operation.Delete: - return HttpMethod.Delete; - case Operation.Upsert: - return HttpMethod.Put; - case Operation.UpsertIncremental: - return HttpMethod.Patch; - default: - throw new DataApiBuilderException( - message: "Operation not supported for the request.", - statusCode: HttpStatusCode.NotImplemented, - subStatusCode: DataApiBuilderException.SubStatusCodes.NotSupported); - } - } - /// /// Helper function formats the expected value to match actual response format. /// diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index f569fd2902..b4816efc6c 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -7,7 +7,7 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using Azure.DataApiBuilder.Config; -using Azure.DataApiBuilder.Service.Models; +using Azure.DataApiBuilder.Service.Exceptions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; @@ -140,30 +140,30 @@ public static async Task VerifyResultAsync( } /// - /// Returns the HTTP verb for a provided Operation. + /// Helper method to get the HttpMethod based on the operation type. /// - /// Operation such as Find, Upsert, Delete, etc. - /// When Operation.None is provided from some tests, return empty string. - /// Matching HttpConstants value - /// - public static string OperationTypeToHTTPVerb(Operation operationType) + /// The operation to be executed on the entity. + /// + /// + public static HttpMethod GetHttpMethodFromOperation(Operation operationType) { switch (operationType) { case Operation.Read: - return HttpConstants.GET; + return HttpMethod.Get; case Operation.Insert: - return HttpConstants.POST; + return HttpMethod.Post; + case Operation.Delete: + return HttpMethod.Delete; case Operation.Upsert: - return HttpConstants.PUT; + return HttpMethod.Put; case Operation.UpsertIncremental: - return HttpConstants.PATCH; - case Operation.Delete: - return HttpConstants.DELETE; - case Operation.None: - return string.Empty; + return HttpMethod.Patch; default: - throw new ArgumentException(message: $"Invalid operationType {operationType} provided"); + throw new DataApiBuilderException( + message: "Operation not supported for the request.", + statusCode: HttpStatusCode.NotImplemented, + subStatusCode: DataApiBuilderException.SubStatusCodes.NotSupported); } } From c7d958006a934d46fc46cd370660224010387efd Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Mon, 22 Aug 2022 09:41:08 +0530 Subject: [PATCH 22/30] Renaming variables --- .../RestApiTests/Delete/DeleteApiTestBase.cs | 8 ++-- .../RestApiTests/Find/FindApiTestBase.cs | 48 +++++++++---------- .../RestApiTests/Insert/InsertApiTestBase.cs | 22 ++++----- .../RestApiTests/OtherRestApiTests.cs | 2 +- .../RestApiTests/Patch/PatchApiTestBase.cs | 12 ++--- .../RestApiTests/Put/PutApiTestBase.cs | 22 ++++----- src/Service.Tests/SqlTests/SqlTestBase.cs | 8 ++-- src/Service.Tests/SqlTests/SqlTestHelper.cs | 16 +++---- 8 files changed, 69 insertions(+), 69 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/Delete/DeleteApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Delete/DeleteApiTestBase.cs index 81f0be7f2c..5d19ab8435 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Delete/DeleteApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Delete/DeleteApiTestBase.cs @@ -104,7 +104,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Delete, requestBody: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Not Found", expectedStatusCode: HttpStatusCode.NotFound, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound.ToString() @@ -128,7 +128,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Delete, requestBody: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "The request is invalid since the primary keys: title requested were not found in the entity definition.", expectedStatusCode: HttpStatusCode.NotFound, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound.ToString() @@ -151,7 +151,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Delete, requestBody: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Primary Key for DELETE requests is required.", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest.ToString() @@ -182,7 +182,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Delete, requestBody: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: message, expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest.ToString() diff --git a/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs index fd941c1dd2..dfb9d472bb 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs @@ -363,7 +363,7 @@ await SetupAndRunRestApiTest( queryString: "?$filter=id eq (publisher_id gt 1)", entity: _integrationEntityName, sqlQuery: GetQuery(nameof(FindTestWithFilterQueryStringSingleAndFilter)), - exception: true, + exceptionExpected: true, expectedErrorMessage: "A binary operator with incompatible types was detected. " + "Found operand types 'Edm.Int32' and 'Edm.Boolean' for operator kind 'Equal'.", expectedStatusCode: HttpStatusCode.BadRequest @@ -940,7 +940,7 @@ await SetupAndRunRestApiTest( queryString: "?$first=0", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid number of items requested, $first must be an integer greater than 0. Actual value: 0", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -964,7 +964,7 @@ await SetupAndRunRestApiTest( queryString: $"?$filter={keyword}{value} {compareTo}", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "$filter query parameter is not well formed.", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: "BadRequest" @@ -979,7 +979,7 @@ await SetupAndRunRestApiTest( queryString: "?$filter=pq ge 4", entity: _simple_all_books, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Could not find a property named 'pq' on type 'default_namespace.{_simple_all_books}.{GetDefaultSchemaForEdmModel()}books_view_all'.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -989,7 +989,7 @@ await SetupAndRunRestApiTest( queryString: "?$filter=pq le 4", entity: _simple_subset_stocks, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Could not find a property named 'pq' on type 'default_namespace.{_simple_subset_stocks}.{GetDefaultSchemaForEdmModel()}stocks_view_selected'.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1000,7 +1000,7 @@ await SetupAndRunRestApiTest( queryString: "?$filter=not (title gt 1)", entity: _composite_subset_bookPub, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Could not find a property named 'title' on type 'default_namespace.{_composite_subset_bookPub}.{GetDefaultSchemaForEdmModel()}books_publishers_view_composite'.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1017,7 +1017,7 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "The request is invalid since it contains a primary key with no value specified.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1037,7 +1037,7 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Support for url template with implicit primary key field names is not yet added.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1055,7 +1055,7 @@ await SetupAndRunRestApiTest( queryString: "?$select=id,content", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid field to be returned requested: content", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1078,7 +1078,7 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _nonExistentEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"{_nonExistentEntityName} is not a valid entity.", expectedStatusCode: HttpStatusCode.NotFound, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound.ToString() @@ -1093,7 +1093,7 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: integrationEntityNameIncorrectCase, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"{integrationEntityNameIncorrectCase} is not a valid entity.", expectedStatusCode: HttpStatusCode.NotFound, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound.ToString() @@ -1113,7 +1113,7 @@ await SetupAndRunRestApiTest( queryString: "?$select=id,null", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid Field name: null or white space", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest.ToString() @@ -1132,7 +1132,7 @@ await SetupAndRunRestApiTest( queryString: "?$select=", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid Field name: null or white space", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest.ToString() @@ -1150,7 +1150,7 @@ await SetupAndRunRestApiTest( queryString: "?$orderby=id random", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: HttpUtility.UrlDecode("Syntax error at position 9 in \u0027id random\u0027."), expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1167,7 +1167,7 @@ await SetupAndRunRestApiTest( queryString: "?$orderby=Pinecone", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Could not find a property named 'Pinecone' on type 'default_namespace.{_integrationEntityName}.{GetDefaultSchemaForEdmModel()}books'.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1185,7 +1185,7 @@ await SetupAndRunRestApiTest( queryString: "?$orderby='Large Pinecone'", entity: _integrationEntityHasColumnWithSpace, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Invalid orderby column requested: Large Pinecone.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1203,7 +1203,7 @@ await SetupAndRunRestApiTest( queryString: "?orderby=id", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Invalid Query Parameter: orderby", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1220,7 +1220,7 @@ await SetupAndRunRestApiTest( queryString: "?$orderby=null", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "OrderBy property is not supported.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1241,7 +1241,7 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationBrokenMappingEntity, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "The request is invalid since the primary keys: spores requested were not found in the entity definition.", expectedStatusCode: HttpStatusCode.NotFound, expectedSubStatusCode: "EntityNotFound" @@ -1263,7 +1263,7 @@ await SetupAndRunRestApiTest( queryString: "?$select=hazards", entity: _integrationBrokenMappingEntity, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid field to be returned requested: hazards", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: "BadRequest" @@ -1284,7 +1284,7 @@ await SetupAndRunRestApiTest( queryString: "?$select=species", entity: _integrationMappingEntity, sqlQuery: GetQuery(nameof(FindTestWithUnMappedFieldsToBeReturned)), - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid field to be returned requested: species", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1322,7 +1322,7 @@ await SetupAndRunRestApiTest( queryString: $"?$select=id", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: message, expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1357,7 +1357,7 @@ await SetupAndRunRestApiTest( queryString: $"?$select={sqlInjection}", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Invalid field to be returned requested: {sqlInjection}", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1392,7 +1392,7 @@ await SetupAndRunRestApiTest( queryString: $"?$select={sqlInjection}", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Invalid field to be returned requested: {sqlInjection}", expectedStatusCode: HttpStatusCode.BadRequest ); diff --git a/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs index 3a9eee88f6..4f6cfd006e 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Insert/InsertApiTestBase.cs @@ -230,7 +230,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Insert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Query string for POST requests is an invalid url.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -255,7 +255,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Insert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Mutation operation on many instances of an entity in a single request are not yet supported.", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: "BadRequest" @@ -281,7 +281,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Insert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Parameter \"[1234,4321]\" cannot be resolved as column \"publisher_id\" with type \"Int32\".", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: "BadRequest" @@ -304,7 +304,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Insert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid request body. Missing field in body: title.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -329,7 +329,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Insert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid request body. Field not allowed in body: id.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -354,7 +354,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Insert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid request body. Missing field in body: id.", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: "BadRequest" @@ -381,7 +381,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Insert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid request body. Missing field in body: title.", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: "BadRequest" @@ -400,7 +400,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Insert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid request body. Missing field in body: categoryName.", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: "BadRequest" @@ -426,7 +426,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Insert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid value for field piecesRequired in request body.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -447,7 +447,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Insert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid value for field categoryName in request body.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -477,7 +477,7 @@ await SetupAndRunRestApiTest( entity: _integrationBrokenMappingEntity, sqlQuery: string.Empty, operationType: Operation.Insert, - exception: true, + exceptionExpected: true, requestBody: requestBody, expectedErrorMessage: "Invalid request body. Contained unexpected fields in body: hazards", expectedStatusCode: HttpStatusCode.BadRequest, diff --git a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs index 2040913bba..15bde0afd2 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/OtherRestApiTests.cs @@ -59,7 +59,7 @@ await SetupAndRunRestApiTest( queryString: "?$select=id,content", entity: _integrationEntityName, sqlQuery: string.Empty, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid field to be returned requested: content", expectedStatusCode: HttpStatusCode.BadRequest ); diff --git a/src/Service.Tests/SqlTests/RestApiTests/Patch/PatchApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Patch/PatchApiTestBase.cs index a2ccac65e3..7bd61c46a8 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Patch/PatchApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Patch/PatchApiTestBase.cs @@ -323,7 +323,7 @@ await SetupAndRunRestApiTest( sqlQuery: null, operationType: Operation.UpsertIncremental, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Cannot perform INSERT and could not find {_integrationEntityName} with primary key to perform UPDATE on.", expectedStatusCode: HttpStatusCode.NotFound, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound.ToString() @@ -352,7 +352,7 @@ await SetupAndRunRestApiTest( sqlQuery: null, operationType: Operation.UpsertIncremental, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Cannot perform INSERT and could not find {_integration_NonAutoGenPK_EntityName} with primary key to perform UPDATE on.", expectedStatusCode: HttpStatusCode.NotFound, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound.ToString() @@ -384,7 +384,7 @@ await SetupAndRunRestApiTest( operationType: Operation.UpsertIncremental, headers: new HeaderDictionary(headerDictionary), requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "No Update could be performed, record not found", expectedStatusCode: HttpStatusCode.PreconditionFailed, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.DatabaseOperationFailed.ToString() @@ -414,7 +414,7 @@ await SetupAndRunRestApiTest( entity: _integrationBrokenMappingEntity, sqlQuery: string.Empty, operationType: Operation.UpsertIncremental, - exception: true, + exceptionExpected: true, requestBody: requestBody, expectedErrorMessage: "Invalid request body. Either insufficient or extra fields supplied.", expectedStatusCode: HttpStatusCode.BadRequest, @@ -446,7 +446,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.UpsertIncremental, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid value for field categoryName in request body.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -466,7 +466,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.UpsertIncremental, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid value for field categoryName in request body.", expectedStatusCode: HttpStatusCode.BadRequest ); diff --git a/src/Service.Tests/SqlTests/RestApiTests/Put/PutApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Put/PutApiTestBase.cs index 023fd3eb4b..7a8229b162 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Put/PutApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Put/PutApiTestBase.cs @@ -400,7 +400,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Upsert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid request body. Missing field in body: categoryName.", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: "BadRequest" @@ -425,7 +425,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Upsert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: expectedErrorMessage, expectedStatusCode: HttpStatusCode.InternalServerError, expectedSubStatusCode: $"{DataApiBuilderException.SubStatusCodes.DatabaseOperationFailed}" @@ -453,7 +453,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Upsert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid request body. Missing field in body: publisher_id.", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest.ToString() @@ -483,7 +483,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Upsert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Cannot perform INSERT and could not find {_integrationEntityName} with primary key to perform UPDATE on.", expectedStatusCode: HttpStatusCode.NotFound, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound.ToString() @@ -505,7 +505,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Upsert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Cannot perform INSERT and could not find {_entityWithCompositePrimaryKey} with primary key to perform UPDATE on.", expectedStatusCode: HttpStatusCode.NotFound, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.EntityNotFound.ToString() @@ -533,7 +533,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Upsert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Invalid request body. Missing field in body: publisher_id.", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest.ToString() @@ -551,7 +551,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Upsert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: $"Invalid request body. Missing field in body: categoryName.", expectedStatusCode: HttpStatusCode.BadRequest, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.BadRequest.ToString() @@ -608,7 +608,7 @@ await SetupAndRunRestApiTest( operationType: Operation.Upsert, headers: new HeaderDictionary(headerDictionary), requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "No Update could be performed, record not found", expectedStatusCode: HttpStatusCode.PreconditionFailed, expectedSubStatusCode: DataApiBuilderException.SubStatusCodes.DatabaseOperationFailed.ToString() @@ -638,7 +638,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Upsert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Primary Key for UPSERT requests is required.", expectedStatusCode: HttpStatusCode.BadRequest, expectedLocationHeader: expectedLocationHeader @@ -668,7 +668,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Upsert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid value for field categoryName in request body.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -688,7 +688,7 @@ await SetupAndRunRestApiTest( sqlQuery: string.Empty, operationType: Operation.Upsert, requestBody: requestBody, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid value for field categoryName in request body.", expectedStatusCode: HttpStatusCode.BadRequest ); diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index ca40348b15..18d29ebf76 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -339,7 +339,7 @@ protected static async Task GetDatabaseResultAsync( /// string represents the query to be executed /// The operation type to be tested. /// string represents JSON data used in mutation operations - /// bool represents if we expect an exception + /// bool represents if we expect an exception /// string represents the error message in the JsonResponse /// int represents the returned http status code /// enum represents the returned sub status code @@ -354,7 +354,7 @@ protected static async Task SetupAndRunRestApiTest( string path = "api", IHeaderDictionary headers = null, string requestBody = null, - bool exception = false, + bool exceptionExpected = false, string expectedErrorMessage = "", HttpStatusCode expectedStatusCode = HttpStatusCode.OK, string expectedSubStatusCode = "BadRequest", @@ -434,7 +434,7 @@ operationType is Operation.Update || } else { - if (exception) + if (exceptionExpected) { expected = JsonSerializer.Serialize(RestController.ErrorResponse( expectedSubStatusCode.ToString(), @@ -462,7 +462,7 @@ await SqlTestHelper.VerifyResultAsync( expected: expected, request: request, response: response, - exception: exception, + exceptionExpected: exceptionExpected, httpMethod: httpMethod, expectedLocationHeader: expectedLocationHeader, verifyNumRecords: verifyNumRecords); diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index b4816efc6c..8bf94cc2a4 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -88,7 +88,7 @@ public static void TestForErrorInGraphQLResponse(string response, string message /// Expected result of the query execution. /// The HttpRequestMessage sent to the engine via HttpClient. /// The HttpResponseMessage returned by the engine. - /// Boolean value indicating whether an exception is expected as + /// Boolean value indicating whether an exception is expected as /// a result of executing the request on the engine. /// The http method specified in the request. /// The expected location header in the response(if any). @@ -98,17 +98,14 @@ public static async Task VerifyResultAsync( string expected, HttpRequestMessage request, HttpResponseMessage response, - bool exception, + bool exceptionExpected, HttpMethod httpMethod, string expectedLocationHeader, int verifyNumRecords) { string responseBody = await response.Content.ReadAsStringAsync(); - if (!exception) + if (!exceptionExpected) { - Console.WriteLine($"Expected: {expected}\nActual: {responseBody}"); - Assert.IsTrue(JsonStringsDeepEqual(expected, responseBody)); - // Assert that the expectedLocation and actualLocation are equal in case of // POST operation. if (httpMethod == HttpMethod.Post) @@ -119,12 +116,15 @@ public static async Task VerifyResultAsync( Assert.AreEqual(expectedLocationHeader, actualLocation); } - if (response.StatusCode == HttpStatusCode.OK && verifyNumRecords >= 0) + // Assert the number of records received is equal to expected number of records. + if (response.StatusCode is HttpStatusCode.OK && verifyNumRecords >= 0) { - // Assert the number of records received is equal to expected number of records. Dictionary actualAsDict = JsonSerializer.Deserialize>(responseBody); Assert.AreEqual(actualAsDict["value"].Length, verifyNumRecords); } + + Console.WriteLine($"Expected: {expected}\nActual: {responseBody}"); + Assert.IsTrue(JsonStringsDeepEqual(expected, responseBody)); } else { From ef2de17a73f4998f86e3b7f5360a1ec9ecd91f5a Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Mon, 22 Aug 2022 12:27:31 +0530 Subject: [PATCH 23/30] Removing redundant code --- .../PrimaryKeyTestsForCompositeViews.cs | 11 ---------- src/Service.Tests/SqlTests/SqlTestBase.cs | 21 +------------------ src/Service.Tests/SqlTests/SqlTestHelper.cs | 2 -- 3 files changed, 1 insertion(+), 33 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs b/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs index d2cfa1e0bb..9f767dc78c 100644 --- a/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs +++ b/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs @@ -106,17 +106,6 @@ await InitializeTestFixture( context: null, new List { compositeDbViewquery }, new List { customEntity }); - // Perform a GET operation on the view to confirm that it is functional. - // Set up rest controller. - RestService _restService = new(_queryEngine, - _mutationEngine, - _sqlMetadataProvider, - _httpContextAccessor.Object, - _authorizationService.Object, - _authorizationResolver, - _runtimeConfigProvider); - RestController _restController = new(_restService, - _restControllerLogger); // Query to validate the GET operation result. string query = @" diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 18d29ebf76..c1034e5832 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -39,8 +39,6 @@ public abstract class SqlTestBase { protected static IQueryExecutor _queryExecutor; protected static IQueryBuilder _queryBuilder; - protected static IQueryEngine _queryEngine; - protected static IMutationEngine _mutationEngine; protected static Mock _authorizationService; protected static Mock _httpContextAccessor; protected static DbExceptionParser _dbExceptionParser; @@ -123,23 +121,6 @@ protected static async Task InitializeTestFixture(TestContext context, List() .WithWebHostBuilder(builder => { @@ -161,7 +142,7 @@ protected static async Task InitializeTestFixture(TestContext context, List(implementationFactory: (serviceProvider) => { return new SqlMutationEngine( - _queryEngine, + ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider), _queryExecutor, _queryBuilder, _sqlMetadataProvider, diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index 8bf94cc2a4..360153831c 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -123,7 +123,6 @@ public static async Task VerifyResultAsync( Assert.AreEqual(actualAsDict["value"].Length, verifyNumRecords); } - Console.WriteLine($"Expected: {expected}\nActual: {responseBody}"); Assert.IsTrue(JsonStringsDeepEqual(expected, responseBody)); } else @@ -134,7 +133,6 @@ public static async Task VerifyResultAsync( // Convert the escaped characters into their unescaped form. responseBody = Regex.Unescape(responseBody); - Console.WriteLine($"Expected: {expected}\nActual: {responseBody}"); Assert.AreEqual(expected, responseBody); } } From 2f96bf04c38fa51a6c846ec5c8fffc9c063000c7 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Mon, 22 Aug 2022 12:35:20 +0530 Subject: [PATCH 24/30] Comment for actualLocation evaluation --- .../RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs | 2 -- src/Service.Tests/SqlTests/SqlTestHelper.cs | 5 +++++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs b/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs index 9f767dc78c..c9c9adbc91 100644 --- a/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs +++ b/src/Service.Tests/SqlTests/RestBootstrapTests/PrimaryKeyTestsForCompositeViews.cs @@ -1,9 +1,7 @@ using System.Collections.Generic; using System.Net; using System.Threading.Tasks; -using Azure.DataApiBuilder.Service.Controllers; using Azure.DataApiBuilder.Service.Exceptions; -using Azure.DataApiBuilder.Service.Services; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Azure.DataApiBuilder.Service.Tests.SqlTests.RestBootstrapTests diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index 360153831c..5e967b9dbd 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -110,6 +110,11 @@ public static async Task VerifyResultAsync( // POST operation. if (httpMethod == HttpMethod.Post) { + // Find the actual location using the response and request uri. + // Response uri = Request uri + "/" + actualLocation + // For eg. Request URI: http://localhost/api/Review + // Response URI: http://localhost/api/Review/book_id/1/id/5001 + // therefore, actualLocation = book_id/1/id/5001 string responseUri = (response.Headers.Location.OriginalString); string requestUri = request.RequestUri.OriginalString; string actualLocation = responseUri.Substring(requestUri.Length + 1); From 9b3f0bf16c0faf5b6f08c18ca46eb3da6ab8e3de Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Mon, 22 Aug 2022 13:39:43 +0530 Subject: [PATCH 25/30] Fixing procedure tests --- .../SqlTests/RestApiTests/Find/FindApiTestBase.cs | 14 ++++---------- src/Service.Tests/SqlTests/SqlTestBase.cs | 2 +- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs index 2a5584f712..8581fbdbe7 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/Find/FindApiTestBase.cs @@ -46,7 +46,6 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationProcedureFindMany_EntityName, sqlQuery: GetQuery("FindManyStoredProcedureTest"), - controller: _restController, expectJson: false ); } @@ -63,7 +62,6 @@ await SetupAndRunRestApiTest( queryString: "?id=1", entity: _integrationProcedureFindOne_EntityName, sqlQuery: GetQuery("FindOneStoredProcedureTestUsingParameter"), - controller: _restController, expectJson: false ); } @@ -974,8 +972,7 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationProcedureFindMany_EntityName, sqlQuery: string.Empty, - controller: _restController, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Primary key route not supported for this entity.", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -993,8 +990,7 @@ await SetupAndRunRestApiTest( queryString: string.Empty, entity: _integrationProcedureFindOne_EntityName, sqlQuery: string.Empty, - controller: _restController, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid request. Missing required procedure parameters: id", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1013,8 +1009,7 @@ await SetupAndRunRestApiTest( queryString: "?param=value", entity: _integrationProcedureFindMany_EntityName, sqlQuery: string.Empty, - controller: _restController, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid request. Contained unexpected fields: param", expectedStatusCode: HttpStatusCode.BadRequest ); @@ -1025,8 +1020,7 @@ await SetupAndRunRestApiTest( queryString: "?id=1¶m=value", entity: _integrationProcedureFindOne_EntityName, sqlQuery: string.Empty, - controller: _restController, - exception: true, + exceptionExpected: true, expectedErrorMessage: "Invalid request. Contained unexpected fields: param", expectedStatusCode: HttpStatusCode.BadRequest ); diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 1493615cfe..458e456425 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -452,7 +452,7 @@ operationType is Operation.Update || baseUrl = baseUrl + "?" + HttpUtility.ParseQueryString(queryString).ToString(); } - string dbResult = await GetDatabaseResultAsync(sqlQuery); + string dbResult = await GetDatabaseResultAsync(sqlQuery, expectJson); // For FIND requests, null result signifies an empty result set dbResult = (operationType is Operation.Read && dbResult is null) ? "[]" : dbResult; expected = $"{{\"value\":{FormatExpectedValue(dbResult)}{ExpectedNextLinkIfAny(paginated, baseUrl, $"{expectedAfterQueryString}")}}}"; From 2156aa3a9b443a4f94a6ec75f082c4590716ba5a Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Mon, 22 Aug 2022 13:46:57 +0530 Subject: [PATCH 26/30] Adding permission for anonymous role --- src/Service/dab-config.MsSql.json | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Service/dab-config.MsSql.json b/src/Service/dab-config.MsSql.json index 56a92b6c55..abb6d3c789 100644 --- a/src/Service/dab-config.MsSql.json +++ b/src/Service/dab-config.MsSql.json @@ -821,6 +821,10 @@ "rest": true, "graphql": false, "permissions": [ + { + "role": "anonymous", + "actions": [ "read" ] + }, { "role": "authenticated", "actions": [ "*" ] @@ -835,6 +839,10 @@ "rest": true, "graphql": false, "permissions": [ + { + "role": "anonymous", + "actions": [ "read" ] + }, { "role": "authenticated", "actions": [ "*" ] From 3517df6cce970534d2994abd62aef917e33fb48b Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Mon, 22 Aug 2022 15:04:27 +0530 Subject: [PATCH 27/30] Adding comment for escaping --- src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs | 2 +- src/Service.Tests/SqlTests/SqlTestBase.cs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs b/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs index 9c30d25f98..c9cc96725f 100644 --- a/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs +++ b/src/Service.Tests/SqlTests/RestApiTests/RestApiTestBase.cs @@ -29,7 +29,7 @@ public abstract class RestApiTestBase : SqlTestBase protected static readonly string _integrationBrokenMappingEntity = "Fungus"; protected static readonly string _integrationUniqueCharactersEntity = "ArtOfWar"; protected static readonly string _integrationUniqueCharactersTable = "aow"; - protected static readonly string _nonExistentEntityName = "!@definitely_nonexistent_entity!@"; + protected static readonly string _nonExistentEntityName = "!@$%^&*()_+definitely_nonexistent_entity!@$%^&*()_+"; protected static readonly string _emptyTableEntityName = "Empty"; protected static readonly string _emptyTableTableName = "empty_table"; protected static readonly string _simple_all_books = "books_view_all"; diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 458e456425..477aa64a07 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -381,6 +381,9 @@ protected static async Task SetupAndRunRestApiTest( } // Use UnsafeRelaxedJsonEscaping to be less strict about what is encoded. + // For eg. Without using this encoder, quotation mark (") will be encoded as + // \" rather than \u0022. And single quote(') will be encoded as \u0027 rather + // than being left unescaped. // More details can be found here: // https://docs.microsoft.com/en-us/dotnet/api/system.text.encodings.web.javascriptencoder.unsaferelaxedjsonescaping?view=net-6.0 JsonSerializerOptions options = new() From 131c08835251bb5548e21d86b6af4093a47822a6 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Tue, 23 Aug 2022 10:57:45 +0530 Subject: [PATCH 28/30] Correcting comment --- src/Service.Tests/SqlTests/SqlTestBase.cs | 5 +++-- src/Service.Tests/SqlTests/SqlTestHelper.cs | 11 +++++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 477aa64a07..22de8e0f96 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -382,7 +382,7 @@ protected static async Task SetupAndRunRestApiTest( // Use UnsafeRelaxedJsonEscaping to be less strict about what is encoded. // For eg. Without using this encoder, quotation mark (") will be encoded as - // \" rather than \u0022. And single quote(') will be encoded as \u0027 rather + // \u0022 rather than \". And single quote(') will be encoded as \u0027 rather // than being left unescaped. // More details can be found here: // https://docs.microsoft.com/en-us/dotnet/api/system.text.encodings.web.javascriptencoder.unsaferelaxedjsonescaping?view=net-6.0 @@ -458,7 +458,8 @@ operationType is Operation.Update || string dbResult = await GetDatabaseResultAsync(sqlQuery, expectJson); // For FIND requests, null result signifies an empty result set dbResult = (operationType is Operation.Read && dbResult is null) ? "[]" : dbResult; - expected = $"{{\"value\":{FormatExpectedValue(dbResult)}{ExpectedNextLinkIfAny(paginated, baseUrl, $"{expectedAfterQueryString}")}}}"; + expected = $"{{\"{SqlTestHelper.jsonKeyInRestResponse}\":" + + $"{FormatExpectedValue(dbResult)}{ExpectedNextLinkIfAny(paginated, baseUrl, $"{expectedAfterQueryString}")}}}"; } } diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index 5e967b9dbd..9b43dd2410 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -15,6 +15,9 @@ namespace Azure.DataApiBuilder.Service.Tests.SqlTests { public class SqlTestHelper : TestHelper { + // This is is the key which holds all the rows in the response + // for REST requests. + public static readonly string jsonKeyInRestResponse = "value"; public static void RemoveAllRelationshipBetweenEntities(RuntimeConfig runtimeConfig) { foreach ((string entityName, Entity entity) in runtimeConfig.Entities.ToList()) @@ -112,8 +115,8 @@ public static async Task VerifyResultAsync( { // Find the actual location using the response and request uri. // Response uri = Request uri + "/" + actualLocation - // For eg. Request URI: http://localhost/api/Review - // Response URI: http://localhost/api/Review/book_id/1/id/5001 + // For eg. POST Request URI: http://localhost/api/Review + // 201 Created Response URI: http://localhost/api/Review/book_id/1/id/5001 // therefore, actualLocation = book_id/1/id/5001 string responseUri = (response.Headers.Location.OriginalString); string requestUri = request.RequestUri.OriginalString; @@ -125,7 +128,7 @@ public static async Task VerifyResultAsync( if (response.StatusCode is HttpStatusCode.OK && verifyNumRecords >= 0) { Dictionary actualAsDict = JsonSerializer.Deserialize>(responseBody); - Assert.AreEqual(actualAsDict["value"].Length, verifyNumRecords); + Assert.AreEqual(actualAsDict[jsonKeyInRestResponse].Length, verifyNumRecords); } Assert.IsTrue(JsonStringsDeepEqual(expected, responseBody)); @@ -165,7 +168,7 @@ public static HttpMethod GetHttpMethodFromOperation(Operation operationType) default: throw new DataApiBuilderException( message: "Operation not supported for the request.", - statusCode: HttpStatusCode.NotImplemented, + statusCode: HttpStatusCode.BadRequest, subStatusCode: DataApiBuilderException.SubStatusCodes.NotSupported); } } From deb3444e41c1b73a1aa24355df5d6474843a39a9 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Tue, 23 Aug 2022 11:27:52 +0530 Subject: [PATCH 29/30] Changing variable name --- src/Service.Tests/SqlTests/SqlTestBase.cs | 2 +- src/Service.Tests/SqlTests/SqlTestHelper.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Service.Tests/SqlTests/SqlTestBase.cs b/src/Service.Tests/SqlTests/SqlTestBase.cs index 22de8e0f96..3704375709 100644 --- a/src/Service.Tests/SqlTests/SqlTestBase.cs +++ b/src/Service.Tests/SqlTests/SqlTestBase.cs @@ -458,7 +458,7 @@ operationType is Operation.Update || string dbResult = await GetDatabaseResultAsync(sqlQuery, expectJson); // For FIND requests, null result signifies an empty result set dbResult = (operationType is Operation.Read && dbResult is null) ? "[]" : dbResult; - expected = $"{{\"{SqlTestHelper.jsonKeyInRestResponse}\":" + + expected = $"{{\"{SqlTestHelper.jsonResultTopLevelKey}\":" + $"{FormatExpectedValue(dbResult)}{ExpectedNextLinkIfAny(paginated, baseUrl, $"{expectedAfterQueryString}")}}}"; } } diff --git a/src/Service.Tests/SqlTests/SqlTestHelper.cs b/src/Service.Tests/SqlTests/SqlTestHelper.cs index 9b43dd2410..fca6ea42fa 100644 --- a/src/Service.Tests/SqlTests/SqlTestHelper.cs +++ b/src/Service.Tests/SqlTests/SqlTestHelper.cs @@ -17,7 +17,7 @@ public class SqlTestHelper : TestHelper { // This is is the key which holds all the rows in the response // for REST requests. - public static readonly string jsonKeyInRestResponse = "value"; + public static readonly string jsonResultTopLevelKey = "value"; public static void RemoveAllRelationshipBetweenEntities(RuntimeConfig runtimeConfig) { foreach ((string entityName, Entity entity) in runtimeConfig.Entities.ToList()) @@ -128,7 +128,7 @@ public static async Task VerifyResultAsync( if (response.StatusCode is HttpStatusCode.OK && verifyNumRecords >= 0) { Dictionary actualAsDict = JsonSerializer.Deserialize>(responseBody); - Assert.AreEqual(actualAsDict[jsonKeyInRestResponse].Length, verifyNumRecords); + Assert.AreEqual(actualAsDict[jsonResultTopLevelKey].Length, verifyNumRecords); } Assert.IsTrue(JsonStringsDeepEqual(expected, responseBody)); From e1c20f975bb0fe13f73b30ef68785ddfa3929e24 Mon Sep 17 00:00:00 2001 From: Ayush Agarwal Date: Tue, 23 Aug 2022 11:37:05 +0530 Subject: [PATCH 30/30] Reverting temporary changes --- src/Service/Parsers/ODataASTVisitor.cs | 1 - src/Service/Parsers/RequestParser.cs | 5 +---- .../Resolvers/Sql Query Structures/SqlQueryStructure.cs | 2 -- 3 files changed, 1 insertion(+), 7 deletions(-) diff --git a/src/Service/Parsers/ODataASTVisitor.cs b/src/Service/Parsers/ODataASTVisitor.cs index 484746996b..c7011c77ba 100644 --- a/src/Service/Parsers/ODataASTVisitor.cs +++ b/src/Service/Parsers/ODataASTVisitor.cs @@ -57,7 +57,6 @@ public override string Visit(UnaryOperatorNode nodeIn) /// String representing the Field name public override string Visit(SingleValuePropertyAccessNode nodeIn) { - // For filter clause. _metadataProvider.TryGetBackingColumn(_struct.EntityName, nodeIn.Property.Name, out string? backingColumnName); return _metadataProvider.GetQueryBuilder().QuoteIdentifier(backingColumnName!); } diff --git a/src/Service/Parsers/RequestParser.cs b/src/Service/Parsers/RequestParser.cs index beaf5a68b4..bdb8b3ad98 100644 --- a/src/Service/Parsers/RequestParser.cs +++ b/src/Service/Parsers/RequestParser.cs @@ -162,13 +162,11 @@ public static void ParseQueryString(RestRequestContext context, ISqlMetadataProv throw new DataApiBuilderException(message: "OrderBy property is not supported.", HttpStatusCode.BadRequest, DataApiBuilderException.SubStatusCodes.BadRequest); - string columnName; string backingColumnName; if (expression.Kind is QueryNodeKind.SingleValuePropertyAccess) { // if name is in SingleValuePropertyAccess node it matches our model and we will // always be able to get backing column successfully - columnName = ((SingleValuePropertyAccessNode)expression).Property.Name; sqlMetadataProvider.TryGetBackingColumn(context.EntityName, ((SingleValuePropertyAccessNode)expression).Property.Name, out backingColumnName!); } else if (expression.Kind is QueryNodeKind.Constant && @@ -176,7 +174,6 @@ public static void ParseQueryString(RestRequestContext context, ISqlMetadataProv { // since this comes from constant node, it was not checked against our model // so this may return false in which case we throw for a bad request - columnName = ((ConstantNode)expression).Value.ToString()!; if (!sqlMetadataProvider.TryGetBackingColumn(context.EntityName, ((ConstantNode)expression).Value.ToString()!, out backingColumnName!)) { throw new DataApiBuilderException( @@ -196,7 +193,7 @@ public static void ParseQueryString(RestRequestContext context, ISqlMetadataProv // We convert to an Enum of our own that matches the SQL text we want OrderBy direction = GetDirection(node.Direction); // Add OrderByColumn and remove any matching columns from our primary key set - orderByList.Add(new OrderByColumn(schemaName, tableName, columnName, direction: direction)); + orderByList.Add(new OrderByColumn(schemaName, tableName, backingColumnName, direction: direction)); remainingKeys.Remove(backingColumnName); node = node.ThenBy; } diff --git a/src/Service/Resolvers/Sql Query Structures/SqlQueryStructure.cs b/src/Service/Resolvers/Sql Query Structures/SqlQueryStructure.cs index 07256e553e..d57cd9c0e4 100644 --- a/src/Service/Resolvers/Sql Query Structures/SqlQueryStructure.cs +++ b/src/Service/Resolvers/Sql Query Structures/SqlQueryStructure.cs @@ -180,8 +180,6 @@ public SqlQueryStructure( if (string.IsNullOrEmpty(column.TableAlias)) { column.TableAlias = TableAlias; - sqlMetadataProvider.TryGetBackingColumn(EntityName, column.ColumnName!, out string? backingColumnName); - column.ColumnName = backingColumnName!; } }