From 24a2ef3a70611c450bb6ee32958005863d7d82de Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 14:04:39 +0200 Subject: [PATCH 01/47] merge: merge into correct email: --- .editorconfig | 6 +- Directory.Build.props | 2 +- JsonApiDotnetCore.sln | 361 +++++++++--------- src/Examples/GettingStarted/Program.cs | 26 +- .../JsonApiDotNetCoreExample/Program.cs | 11 +- .../JsonApiDotNetCoreExample/Startup.cs | 27 +- .../NoEntityFrameworkExample/Program.cs | 10 +- .../NoEntityFrameworkExample/Startup.cs | 25 +- src/Examples/ReportsExample/Program.cs | 10 +- .../Internal/ResourceGraph.cs | 4 +- .../Server/ResponseSerializer.cs | 2 +- test/DiscoveryTests/DiscoveryTests.csproj | 2 +- .../Acceptance/Spec/CreatingDataTests.cs | 14 +- .../Startups/ClientGeneratedIdsStartup.cs | 5 +- test/UnitTests/Builders/LinkBuilderTests.cs | 8 +- test/UnitTests/Graph/TypeLocator_Tests.cs | 39 +- .../Common/DocumentParserTests.cs | 8 +- .../Common/ResourceObjectBuilderTests.cs | 6 +- .../IncludedResourceObjectBuilderTests.cs | 4 +- 19 files changed, 285 insertions(+), 285 deletions(-) diff --git a/.editorconfig b/.editorconfig index 3499a1f7a6..1cdb95b612 100644 --- a/.editorconfig +++ b/.editorconfig @@ -22,4 +22,8 @@ dotnet_naming_symbols.private_fields.applicable_kinds = field dotnet_naming_symbols.private_fields.applicable_accessibilities = private dotnet_naming_style.prefix_underscore.capitalization = camel_case -dotnet_naming_style.prefix_underscore.required_prefix = _ \ No newline at end of file +dotnet_naming_style.prefix_underscore.required_prefix = _ +[*.cs] + +# CS0659: Type overrides Object.Equals(object o) but does not override Object.GetHashCode() +dotnet_diagnostic.CS0659.severity = silent diff --git a/Directory.Build.props b/Directory.Build.props index fcd668b5ba..61e8771fc0 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,7 +1,7 @@ - netcoreapp2.0 + netcoreapp2.1 netstandard2.0 2.* diff --git a/JsonApiDotnetCore.sln b/JsonApiDotnetCore.sln index d582f7b921..7310cf2097 100644 --- a/JsonApiDotnetCore.sln +++ b/JsonApiDotnetCore.sln @@ -1,181 +1,180 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.28606.126 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{7A2B7ADD-ECB5-4D00-AA6A-D45BD11C97CF}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{24B15015-62E5-42E1-9BA0-ECE6BE7AA15F}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C5B4D998-CECB-454D-9F32-085A897577BE}" - ProjectSection(SolutionItems) = preProject - .gitignore = .gitignore - .travis.yml = .travis.yml - appveyor.yml = appveyor.yml - Build.ps1 = Build.ps1 - build.sh = build.sh - Directory.Build.props = Directory.Build.props - README.md = README.md - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{026FBC6C-AF76-4568-9B87-EC73457899FD}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "benchmarks", "benchmarks", "{076E1AE4-FD25-4684-B826-CAAE37FEA0AA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JsonApiDotNetCoreExampleTests", "test\JsonApiDotNetCoreExampleTests\JsonApiDotNetCoreExampleTests.csproj", "{CAF331F8-9255-4D72-A1A8-A54141E99F1E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NoEntityFrameworkTests", "test\NoEntityFrameworkTests\NoEntityFrameworkTests.csproj", "{4F15A8F8-5BC6-45A1-BC51-03F921B726A4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTests", "test\UnitTests\UnitTests.csproj", "{8788FF65-C2B6-40B2-A3A0-1E3D91C02664}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscoveryTests", "test\DiscoveryTests\DiscoveryTests.csproj", "{03032A2F-664D-4DD8-A82F-AD8A482EDD85}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Benchmarks", "benchmarks\Benchmarks.csproj", "{DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JsonApiDotNetCoreExample", "src\Examples\JsonApiDotNetCoreExample\JsonApiDotNetCoreExample.csproj", "{C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NoEntityFrameworkExample", "src\Examples\NoEntityFrameworkExample\NoEntityFrameworkExample.csproj", "{789085E1-048F-4996-B600-791B9CA3A663}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReportsExample", "src\Examples\ReportsExample\ReportsExample.csproj", "{8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JsonApiDotNetCore", "src\JsonApiDotNetCore\JsonApiDotNetCore.csproj", "{21D27239-138D-4604-8E49-DCBE41BCE4C8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GettingStarted", "src\Examples\GettingStarted\GettingStarted.csproj", "{067FFD7A-C66B-473D-8471-37F5C95DF61C}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Debug|x64.ActiveCfg = Debug|Any CPU - {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Debug|x86.ActiveCfg = Debug|Any CPU - {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Release|Any CPU.Build.0 = Release|Any CPU - {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Release|x64.ActiveCfg = Release|Any CPU - {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Release|x86.ActiveCfg = Release|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|x64.ActiveCfg = Debug|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|x64.Build.0 = Debug|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|x86.ActiveCfg = Debug|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|x86.Build.0 = Debug|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|Any CPU.Build.0 = Release|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|x64.ActiveCfg = Release|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|x64.Build.0 = Release|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|x86.ActiveCfg = Release|Any CPU - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|x86.Build.0 = Release|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|x64.ActiveCfg = Debug|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|x64.Build.0 = Debug|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|x86.ActiveCfg = Debug|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|x86.Build.0 = Debug|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|Any CPU.Build.0 = Release|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|x64.ActiveCfg = Release|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|x64.Build.0 = Release|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|x86.ActiveCfg = Release|Any CPU - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|x86.Build.0 = Release|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|Any CPU.Build.0 = Debug|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|x64.ActiveCfg = Debug|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|x64.Build.0 = Debug|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|x86.ActiveCfg = Debug|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|x86.Build.0 = Debug|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|Any CPU.ActiveCfg = Release|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|Any CPU.Build.0 = Release|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|x64.ActiveCfg = Release|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|x64.Build.0 = Release|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|x86.ActiveCfg = Release|Any CPU - {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|x86.Build.0 = Release|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|x64.ActiveCfg = Debug|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|x64.Build.0 = Debug|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|x86.ActiveCfg = Debug|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|x86.Build.0 = Debug|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|Any CPU.Build.0 = Release|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x64.ActiveCfg = Release|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x64.Build.0 = Release|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x86.ActiveCfg = Release|Any CPU - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x86.Build.0 = Release|Any CPU - {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Debug|x64.ActiveCfg = Debug|Any CPU - {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Debug|x86.ActiveCfg = Debug|Any CPU - {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Release|Any CPU.Build.0 = Release|Any CPU - {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Release|x64.ActiveCfg = Release|Any CPU - {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Release|x86.ActiveCfg = Release|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Debug|Any CPU.Build.0 = Debug|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Debug|x64.ActiveCfg = Debug|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Debug|x64.Build.0 = Debug|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Debug|x86.ActiveCfg = Debug|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Debug|x86.Build.0 = Debug|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Release|Any CPU.ActiveCfg = Release|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Release|Any CPU.Build.0 = Release|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Release|x64.ActiveCfg = Release|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Release|x64.Build.0 = Release|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Release|x86.ActiveCfg = Release|Any CPU - {789085E1-048F-4996-B600-791B9CA3A663}.Release|x86.Build.0 = Release|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|x64.ActiveCfg = Debug|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|x64.Build.0 = Debug|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|x86.ActiveCfg = Debug|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|x86.Build.0 = Debug|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|Any CPU.Build.0 = Release|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|x64.ActiveCfg = Release|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|x64.Build.0 = Release|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|x86.ActiveCfg = Release|Any CPU - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|x86.Build.0 = Release|Any CPU - {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Debug|x64.ActiveCfg = Debug|Any CPU - {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Debug|x86.ActiveCfg = Debug|Any CPU - {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Release|Any CPU.Build.0 = Release|Any CPU - {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Release|x64.ActiveCfg = Release|Any CPU - {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Release|x86.ActiveCfg = Release|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|x64.ActiveCfg = Debug|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|x64.Build.0 = Debug|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|x86.ActiveCfg = Debug|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|x86.Build.0 = Debug|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|Any CPU.Build.0 = Release|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x64.ActiveCfg = Release|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x64.Build.0 = Release|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x86.ActiveCfg = Release|Any CPU - {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {026FBC6C-AF76-4568-9B87-EC73457899FD} = {7A2B7ADD-ECB5-4D00-AA6A-D45BD11C97CF} - {CAF331F8-9255-4D72-A1A8-A54141E99F1E} = {24B15015-62E5-42E1-9BA0-ECE6BE7AA15F} - {4F15A8F8-5BC6-45A1-BC51-03F921B726A4} = {24B15015-62E5-42E1-9BA0-ECE6BE7AA15F} - {8788FF65-C2B6-40B2-A3A0-1E3D91C02664} = {24B15015-62E5-42E1-9BA0-ECE6BE7AA15F} - {03032A2F-664D-4DD8-A82F-AD8A482EDD85} = {24B15015-62E5-42E1-9BA0-ECE6BE7AA15F} - {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C} = {076E1AE4-FD25-4684-B826-CAAE37FEA0AA} - {21D27239-138D-4604-8E49-DCBE41BCE4C8} = {7A2B7ADD-ECB5-4D00-AA6A-D45BD11C97CF} - {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A} = {026FBC6C-AF76-4568-9B87-EC73457899FD} - {789085E1-048F-4996-B600-791B9CA3A663} = {026FBC6C-AF76-4568-9B87-EC73457899FD} - {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B} = {026FBC6C-AF76-4568-9B87-EC73457899FD} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {A2421882-8F0A-4905-928F-B550B192F9A4} - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28606.126 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{7A2B7ADD-ECB5-4D00-AA6A-D45BD11C97CF}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{24B15015-62E5-42E1-9BA0-ECE6BE7AA15F}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C5B4D998-CECB-454D-9F32-085A897577BE}" + ProjectSection(SolutionItems) = preProject + .gitignore = .gitignore + .travis.yml = .travis.yml + appveyor.yml = appveyor.yml + Build.ps1 = Build.ps1 + build.sh = build.sh + Directory.Build.props = Directory.Build.props + README.md = README.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{026FBC6C-AF76-4568-9B87-EC73457899FD}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "benchmarks", "benchmarks", "{076E1AE4-FD25-4684-B826-CAAE37FEA0AA}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JsonApiDotNetCoreExampleTests", "test\JsonApiDotNetCoreExampleTests\JsonApiDotNetCoreExampleTests.csproj", "{CAF331F8-9255-4D72-A1A8-A54141E99F1E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NoEntityFrameworkTests", "test\NoEntityFrameworkTests\NoEntityFrameworkTests.csproj", "{4F15A8F8-5BC6-45A1-BC51-03F921B726A4}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitTests", "test\UnitTests\UnitTests.csproj", "{8788FF65-C2B6-40B2-A3A0-1E3D91C02664}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscoveryTests", "test\DiscoveryTests\DiscoveryTests.csproj", "{03032A2F-664D-4DD8-A82F-AD8A482EDD85}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Benchmarks", "benchmarks\Benchmarks.csproj", "{DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JsonApiDotNetCoreExample", "src\Examples\JsonApiDotNetCoreExample\JsonApiDotNetCoreExample.csproj", "{C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NoEntityFrameworkExample", "src\Examples\NoEntityFrameworkExample\NoEntityFrameworkExample.csproj", "{789085E1-048F-4996-B600-791B9CA3A663}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ReportsExample", "src\Examples\ReportsExample\ReportsExample.csproj", "{8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JsonApiDotNetCore", "src\JsonApiDotNetCore\JsonApiDotNetCore.csproj", "{21D27239-138D-4604-8E49-DCBE41BCE4C8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GettingStarted", "src\Examples\GettingStarted\GettingStarted.csproj", "{067FFD7A-C66B-473D-8471-37F5C95DF61C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Debug|x64.ActiveCfg = Debug|Any CPU + {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Debug|x86.ActiveCfg = Debug|Any CPU + {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Release|Any CPU.Build.0 = Release|Any CPU + {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Release|x64.ActiveCfg = Release|Any CPU + {CAF331F8-9255-4D72-A1A8-A54141E99F1E}.Release|x86.ActiveCfg = Release|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|x64.ActiveCfg = Debug|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|x64.Build.0 = Debug|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|x86.ActiveCfg = Debug|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Debug|x86.Build.0 = Debug|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|Any CPU.Build.0 = Release|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|x64.ActiveCfg = Release|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|x64.Build.0 = Release|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|x86.ActiveCfg = Release|Any CPU + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4}.Release|x86.Build.0 = Release|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|x64.ActiveCfg = Debug|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|x64.Build.0 = Debug|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|x86.ActiveCfg = Debug|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Debug|x86.Build.0 = Debug|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|Any CPU.Build.0 = Release|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|x64.ActiveCfg = Release|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|x64.Build.0 = Release|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|x86.ActiveCfg = Release|Any CPU + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664}.Release|x86.Build.0 = Release|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|Any CPU.Build.0 = Debug|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|x64.ActiveCfg = Debug|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|x64.Build.0 = Debug|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|x86.ActiveCfg = Debug|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Debug|x86.Build.0 = Debug|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|Any CPU.ActiveCfg = Release|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|Any CPU.Build.0 = Release|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|x64.ActiveCfg = Release|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|x64.Build.0 = Release|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|x86.ActiveCfg = Release|Any CPU + {03032A2F-664D-4DD8-A82F-AD8A482EDD85}.Release|x86.Build.0 = Release|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|x64.ActiveCfg = Debug|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|x64.Build.0 = Debug|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|x86.ActiveCfg = Debug|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|x86.Build.0 = Debug|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|Any CPU.Build.0 = Release|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x64.ActiveCfg = Release|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x64.Build.0 = Release|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x86.ActiveCfg = Release|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x86.Build.0 = Release|Any CPU + {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Debug|x64.ActiveCfg = Debug|Any CPU + {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Debug|x86.ActiveCfg = Debug|Any CPU + {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Release|Any CPU.Build.0 = Release|Any CPU + {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Release|x64.ActiveCfg = Release|Any CPU + {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A}.Release|x86.ActiveCfg = Release|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Debug|Any CPU.Build.0 = Debug|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Debug|x64.ActiveCfg = Debug|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Debug|x64.Build.0 = Debug|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Debug|x86.ActiveCfg = Debug|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Debug|x86.Build.0 = Debug|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Release|Any CPU.ActiveCfg = Release|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Release|Any CPU.Build.0 = Release|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Release|x64.ActiveCfg = Release|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Release|x64.Build.0 = Release|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Release|x86.ActiveCfg = Release|Any CPU + {789085E1-048F-4996-B600-791B9CA3A663}.Release|x86.Build.0 = Release|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|x64.ActiveCfg = Debug|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|x64.Build.0 = Debug|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|x86.ActiveCfg = Debug|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Debug|x86.Build.0 = Debug|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|Any CPU.Build.0 = Release|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|x64.ActiveCfg = Release|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|x64.Build.0 = Release|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|x86.ActiveCfg = Release|Any CPU + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B}.Release|x86.Build.0 = Release|Any CPU + {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Debug|x64.ActiveCfg = Debug|Any CPU + {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Debug|x86.ActiveCfg = Debug|Any CPU + {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Release|Any CPU.Build.0 = Release|Any CPU + {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Release|x64.ActiveCfg = Release|Any CPU + {21D27239-138D-4604-8E49-DCBE41BCE4C8}.Release|x86.ActiveCfg = Release|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|x64.ActiveCfg = Debug|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|x64.Build.0 = Debug|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|x86.ActiveCfg = Debug|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Debug|x86.Build.0 = Debug|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|Any CPU.Build.0 = Release|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x64.ActiveCfg = Release|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x64.Build.0 = Release|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x86.ActiveCfg = Release|Any CPU + {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {026FBC6C-AF76-4568-9B87-EC73457899FD} = {7A2B7ADD-ECB5-4D00-AA6A-D45BD11C97CF} + {CAF331F8-9255-4D72-A1A8-A54141E99F1E} = {24B15015-62E5-42E1-9BA0-ECE6BE7AA15F} + {4F15A8F8-5BC6-45A1-BC51-03F921B726A4} = {24B15015-62E5-42E1-9BA0-ECE6BE7AA15F} + {8788FF65-C2B6-40B2-A3A0-1E3D91C02664} = {24B15015-62E5-42E1-9BA0-ECE6BE7AA15F} + {03032A2F-664D-4DD8-A82F-AD8A482EDD85} = {24B15015-62E5-42E1-9BA0-ECE6BE7AA15F} + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C} = {076E1AE4-FD25-4684-B826-CAAE37FEA0AA} + {C916EBDA-3429-4FEA-AFB3-DF7CA32A8C6A} = {026FBC6C-AF76-4568-9B87-EC73457899FD} + {789085E1-048F-4996-B600-791B9CA3A663} = {026FBC6C-AF76-4568-9B87-EC73457899FD} + {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B} = {026FBC6C-AF76-4568-9B87-EC73457899FD} + {21D27239-138D-4604-8E49-DCBE41BCE4C8} = {7A2B7ADD-ECB5-4D00-AA6A-D45BD11C97CF} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A2421882-8F0A-4905-928F-B550B192F9A4} + EndGlobalSection +EndGlobal diff --git a/src/Examples/GettingStarted/Program.cs b/src/Examples/GettingStarted/Program.cs index fdc5046542..04523dcf9c 100644 --- a/src/Examples/GettingStarted/Program.cs +++ b/src/Examples/GettingStarted/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -10,17 +10,17 @@ namespace GettingStarted { - public class Program - { - public static void Main(string[] args) - { - BuildWebHost(args).Run(); - } - - public static IWebHost BuildWebHost(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup() - .UseUrls("http://localhost:5001") - .Build(); + + + public class Program + { + public static void Main(string[] args) + { + CreateWebHostBuilder(args).Build().Run(); + } + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup() + .UseUrls("http://localhost:5001"); } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Program.cs b/src/Examples/JsonApiDotNetCoreExample/Program.cs index b9bbe37b6a..f17228e167 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Program.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Program.cs @@ -5,11 +5,12 @@ namespace JsonApiDotNetCoreExample { public class Program { - public static void Main(string[] args) => BuildWebHost(args).Run(); - - public static IWebHost BuildWebHost(string[] args) => + public static void Main(string[] args) + { + CreateWebHostBuilder(args).Build().Run(); + } + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) - .UseStartup() - .Build(); + .UseStartup(); } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Startup.cs b/src/Examples/JsonApiDotNetCoreExample/Startup.cs index 2963a33ffa..4463ca98da 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startup.cs @@ -28,21 +28,23 @@ public Startup(IHostingEnvironment env) public virtual IServiceProvider ConfigureServices(IServiceCollection services) { var loggerFactory = new LoggerFactory(); - loggerFactory.AddConsole(LogLevel.Warning); services .AddSingleton(loggerFactory) + .AddLogging(builder => + { + builder.AddConsole(); + builder.AddConfiguration(Config.GetSection("Logging")); + }) .AddDbContext(options => options.UseNpgsql(GetDbConnectionString()), ServiceLifetime.Transient) - .AddJsonApi( - options => - { - options.Namespace = "api/v1"; - options.DefaultPageSize = 5; - options.IncludeTotalRecordCount = true; - options.EnableResourceHooks = true; - options.LoaDatabaseValues = true; - }, - discovery => discovery.AddCurrentAssembly()); - + .AddJsonApi(options => + { + options.Namespace = "api/v1"; + options.DefaultPageSize = 5; + options.IncludeTotalRecordCount = true; + options.EnableResourceHooks = true; + options.LoaDatabaseValues = true; + }, + discovery => discovery.AddCurrentAssembly()); return services.BuildServiceProvider(); } @@ -53,7 +55,6 @@ public virtual void Configure( AppDbContext context) { context.Database.EnsureCreated(); - loggerFactory.AddConsole(Config.GetSection("Logging")); app.UseJsonApi(); } diff --git a/src/Examples/NoEntityFrameworkExample/Program.cs b/src/Examples/NoEntityFrameworkExample/Program.cs index 76f3020c52..9cd9c3ce22 100755 --- a/src/Examples/NoEntityFrameworkExample/Program.cs +++ b/src/Examples/NoEntityFrameworkExample/Program.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore; +using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace NoEntityFrameworkExample @@ -7,12 +7,10 @@ public class Program { public static void Main(string[] args) { - BuildWebHost(args).Run(); + CreateWebHostBuilder(args).Build().Run(); } - - public static IWebHost BuildWebHost(string[] args) => + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) - .UseStartup() - .Build(); + .UseStartup(); } } diff --git a/src/Examples/NoEntityFrameworkExample/Startup.cs b/src/Examples/NoEntityFrameworkExample/Startup.cs index fe73537169..a438ff9336 100644 --- a/src/Examples/NoEntityFrameworkExample/Startup.cs +++ b/src/Examples/NoEntityFrameworkExample/Startup.cs @@ -32,31 +32,28 @@ public virtual IServiceProvider ConfigureServices(IServiceCollection services) { // Add framework services. var mvcBuilder = services.AddMvcCore(); - - services.AddJsonApi( - options => options.Namespace = "api/v1", - resources: resources => resources.AddResource("custom-todo-items"), - mvcBuilder: mvcBuilder - ); - + services.AddLogging(builder => + { + builder.AddConfiguration(Configuration.GetSection("Logging")); + builder.AddConsole(); + }).AddJsonApi( + options => options.Namespace = "api/v1", + resources: resources => resources.AddResource("custom-todo-items"), + mvcBuilder: mvcBuilder + ); services.AddScoped, TodoItemService>(); - var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseNpgsql(Configuration.GetValue("Data:DefaultConnection")); services.AddSingleton(Configuration); - services.AddSingleton>(optionsBuilder.Options); + services.AddSingleton(optionsBuilder.Options); services.AddScoped(); - return services.BuildServiceProvider(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, AppDbContext context) + public void Configure(IApplicationBuilder app, AppDbContext context) { - loggerFactory.AddConsole(Configuration.GetSection("Logging")); - context.Database.EnsureCreated(); - app.UseJsonApi(); } } diff --git a/src/Examples/ReportsExample/Program.cs b/src/Examples/ReportsExample/Program.cs index f3ce6c81b0..3794a268c4 100644 --- a/src/Examples/ReportsExample/Program.cs +++ b/src/Examples/ReportsExample/Program.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore; +using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace ReportsExample @@ -7,12 +7,10 @@ public class Program { public static void Main(string[] args) { - BuildWebHost(args).Run(); + CreateWebHostBuilder(args).Build().Run(); } - - public static IWebHost BuildWebHost(string[] args) => + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) - .UseStartup() - .Build(); + .UseStartup(); } } diff --git a/src/JsonApiDotNetCore/Internal/ResourceGraph.cs b/src/JsonApiDotNetCore/Internal/ResourceGraph.cs index c9cfcd2b5d..2dc5dda57a 100644 --- a/src/JsonApiDotNetCore/Internal/ResourceGraph.cs +++ b/src/JsonApiDotNetCore/Internal/ResourceGraph.cs @@ -93,7 +93,7 @@ private IEnumerable Getter(Expression> selec targeted.Add(available.Single(f => f.ExposedInternalMemberName == memberExpression.Member.Name)); return targeted; } - catch (Exception ex) + catch (InvalidOperationException) { ThrowNotExposedError(memberExpression.Member.Name, type); } @@ -115,7 +115,7 @@ private IEnumerable Getter(Expression> selec } return targeted; } - catch (Exception ex) + catch (InvalidOperationException) { ThrowNotExposedError(memberName, type); } diff --git a/src/JsonApiDotNetCore/Serialization/Server/ResponseSerializer.cs b/src/JsonApiDotNetCore/Serialization/Server/ResponseSerializer.cs index dd138d3697..e54a0abd0a 100644 --- a/src/JsonApiDotNetCore/Serialization/Server/ResponseSerializer.cs +++ b/src/JsonApiDotNetCore/Serialization/Server/ResponseSerializer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using JsonApiDotNetCore.Internal.Contracts; diff --git a/test/DiscoveryTests/DiscoveryTests.csproj b/test/DiscoveryTests/DiscoveryTests.csproj index eeb13485f3..c1c13846a3 100644 --- a/test/DiscoveryTests/DiscoveryTests.csproj +++ b/test/DiscoveryTests/DiscoveryTests.csproj @@ -16,4 +16,4 @@ - + \ No newline at end of file diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs index f2b4b68596..96d3133b68 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs @@ -24,8 +24,8 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class CreatingDataTests : EndToEndTest { - private Faker _todoItemFaker; - private Faker _personFaker; + private readonly Faker _todoItemFaker; + private readonly Faker _personFaker; public CreatingDataTests(TestFixture fixture) : base(fixture) { @@ -155,9 +155,11 @@ public async Task CreateWithRelationship_HasManyAndInclude_IsCreatedAndIncludes( var serializer = GetSerializer(e => new { }, e => new { e.TodoItems, e.Owner }); var owner = new Person(); - var todoItem = new TodoItem(); - todoItem.Owner = owner; - todoItem.Description = "Description"; + var todoItem = new TodoItem + { + Owner = owner, + Description = "Description" + }; dbContext.People.Add(owner); dbContext.TodoItems.Add(todoItem); dbContext.SaveChanges(); @@ -340,7 +342,7 @@ public async Task CreateRelationship_ToManyWithImplicitRemove_IsCreated() var oldPersonDb = dbContext.People.AsNoTracking().Where(p => p.Id == currentPerson.Id).Include(e => e.TodoItems).Single(); AssertEqualStatusCode(HttpStatusCode.Created, response); Assert.Equal(2, newPersonDb.TodoItems.Count); - Assert.Equal(1, oldPersonDb.TodoItems.Count); + Assert.Single(oldPersonDb.TodoItems); Assert.NotNull(newPersonDb.TodoItems.SingleOrDefault(ti => ti.Id == firstTd.Id)); Assert.NotNull(newPersonDb.TodoItems.SingleOrDefault(ti => ti.Id == secondTd.Id)); Assert.NotNull(oldPersonDb.TodoItems.SingleOrDefault(ti => ti.Id == thirdTd.Id)); diff --git a/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs b/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs index fb8920816b..64147e5460 100644 --- a/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs +++ b/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs @@ -19,10 +19,13 @@ public ClientGeneratedIdsStartup(IHostingEnvironment env) public override IServiceProvider ConfigureServices(IServiceCollection services) { var loggerFactory = new LoggerFactory(); - loggerFactory.AddConsole(LogLevel.Warning); var mvcBuilder = services.AddMvcCore(); services .AddSingleton(loggerFactory) + .AddLogging(builder => + { + builder.AddConsole(); + }) .AddDbContext(options => options.UseNpgsql(GetDbConnectionString()), ServiceLifetime.Transient) .AddJsonApi(options => { options.Namespace = "api/v1"; diff --git a/test/UnitTests/Builders/LinkBuilderTests.cs b/test/UnitTests/Builders/LinkBuilderTests.cs index b7c5f1a3fe..0d9ce1c98b 100644 --- a/test/UnitTests/Builders/LinkBuilderTests.cs +++ b/test/UnitTests/Builders/LinkBuilderTests.cs @@ -115,22 +115,22 @@ public void BuildRelationshipLinks_GlobalResourceAndAttrConfiguration_ExpectedLi [InlineData(Link.All, Link.All, _topSelf, true)] [InlineData(Link.All, Link.Self, _topSelf, false)] [InlineData(Link.All, Link.Paging, null, true)] - [InlineData(Link.All, Link.None, null, null)] + [InlineData(Link.All, Link.None, null, false)] [InlineData(Link.Self, Link.NotConfigured, _topSelf, false)] [InlineData(Link.Self, Link.All, _topSelf, true)] [InlineData(Link.Self, Link.Self, _topSelf, false)] [InlineData(Link.Self, Link.Paging, null, true)] - [InlineData(Link.Self, Link.None, null, null)] + [InlineData(Link.Self, Link.None, null, false)] [InlineData(Link.Paging, Link.NotConfigured, null, true)] [InlineData(Link.Paging, Link.All, _topSelf, true)] [InlineData(Link.Paging, Link.Self, _topSelf, false)] [InlineData(Link.Paging, Link.Paging, null, true)] - [InlineData(Link.Paging, Link.None, null, null)] + [InlineData(Link.Paging, Link.None, null, false)] [InlineData(Link.None, Link.NotConfigured, null, false)] [InlineData(Link.None, Link.All, _topSelf, true)] [InlineData(Link.None, Link.Self, _topSelf, false)] [InlineData(Link.None, Link.Paging, null, true)] - [InlineData(Link.None, Link.None, null, null)] + [InlineData(Link.None, Link.None, null, false)] public void BuildTopLevelLinks_GlobalAndResourceConfiguration_ExpectedLinks(Link global, Link resource, object expectedSelfLink, diff --git a/test/UnitTests/Graph/TypeLocator_Tests.cs b/test/UnitTests/Graph/TypeLocator_Tests.cs index 890994c340..860730857e 100644 --- a/test/UnitTests/Graph/TypeLocator_Tests.cs +++ b/test/UnitTests/Graph/TypeLocator_Tests.cs @@ -11,7 +11,7 @@ public class TypeLocator_Tests [Fact] public void GetGenericInterfaceImplementation_Gets_Implementation() { - // arrange + // Arrange var assembly = GetType().Assembly; var openGeneric = typeof(IGenericInterface<>); var genericArg = typeof(int); @@ -19,17 +19,16 @@ public void GetGenericInterfaceImplementation_Gets_Implementation() var expectedImplementation = typeof(Implementation); var expectedInterface = typeof(IGenericInterface); - // act - var result = TypeLocator.GetGenericInterfaceImplementation( + // Act + var (implementation, registrationInterface) = TypeLocator.GetGenericInterfaceImplementation( assembly, openGeneric, genericArg ); - // assert - Assert.NotNull(result); - Assert.Equal(expectedImplementation, result.implementation); - Assert.Equal(expectedInterface, result.registrationInterface); + // Assert + Assert.Equal(expectedImplementation, implementation); + Assert.Equal(expectedInterface, registrationInterface); } [Fact] @@ -58,17 +57,16 @@ public void GetDerivedGenericTypes_Gets_Implementation() [Fact] public void GetIdType_Correctly_Identifies_JsonApiResource() { - // arrange + // Arrange var type = typeof(Model); var exextedIdType = typeof(int); - // act - var result = TypeLocator.GetIdType(type); + // Act + var (isJsonApiResource, idType) = TypeLocator.GetIdType(type); - // assert - Assert.NotNull(result); - Assert.True(result.isJsonApiResource); - Assert.Equal(exextedIdType, result.idType); + // Assert + Assert.True(isJsonApiResource); + Assert.Equal(exextedIdType, idType); } [Fact] @@ -79,12 +77,11 @@ public void GetIdType_Correctly_Identifies_NonJsonApiResource() Type exextedIdType = null; // act - var result = TypeLocator.GetIdType(type); + var (isJsonApiResource, idType) = TypeLocator.GetIdType(type); - // assert - Assert.NotNull(result); - Assert.False(result.isJsonApiResource); - Assert.Equal(exextedIdType, result.idType); + // Assert + Assert.False(isJsonApiResource); + Assert.Equal(exextedIdType, idType); } [Fact] @@ -136,7 +133,7 @@ public void TryGetResourceDescriptor_Returns_False_If_Type_Is_IIdentfiable() var resourceType = typeof(String); // act - var isJsonApiResource = TypeLocator.TryGetResourceDescriptor(resourceType, out var descriptor); + var isJsonApiResource = TypeLocator.TryGetResourceDescriptor(resourceType, out var _); // assert Assert.False(isJsonApiResource); @@ -152,4 +149,4 @@ public class BaseType { } public class DerivedType : BaseType { } public class Model : Identifiable { } -} \ No newline at end of file +} diff --git a/test/UnitTests/Serialization/Common/DocumentParserTests.cs b/test/UnitTests/Serialization/Common/DocumentParserTests.cs index fa6e10ce01..ca718affcd 100644 --- a/test/UnitTests/Serialization/Common/DocumentParserTests.cs +++ b/test/UnitTests/Serialization/Common/DocumentParserTests.cs @@ -137,15 +137,15 @@ public void DeserializeAttributes_VariousDataTypes_CanDeserialize(string member, if (member == "int-field") { - Assert.Equal(deserializedValue, 1); + Assert.Equal(1, deserializedValue); } else if (member == "nullable-int-field" && value == null) { - Assert.Equal(deserializedValue, null); + Assert.Null(deserializedValue); } else if (member == "nullable-int-field" && (string)value == "1") { - Assert.Equal(deserializedValue, 1); + Assert.Equal(1, deserializedValue); } else if (member == "guid-field") { @@ -366,7 +366,7 @@ public void DeserializeRelationships_PopulatedOneToManyDependent_NavigationIsPop // assert Assert.Equal(1, result.Id); - Assert.Equal(1, result.Dependents.Count); + Assert.Single(result.Dependents); Assert.Equal(10, result.Dependents.First().Id); Assert.Null(result.AttributeMember); } diff --git a/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs b/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs index 06df8ab1e2..16e6519f3d 100644 --- a/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs +++ b/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs @@ -128,7 +128,7 @@ public void EntityWithRelationshipsToResourceObject_WithIncludedRelationshipsAtt Assert.Equal("10", populatedToOneData.Id); Assert.Equal("one-to-one-dependents", populatedToOneData.Type); var populatedToManiesData = (List)resourceObject.Relationships["populated-to-manies"].Data; - Assert.Equal(1, populatedToManiesData.Count); + Assert.Single(populatedToManiesData); Assert.Equal("20", populatedToManiesData.First().Id); Assert.Equal("one-to-many-dependents", populatedToManiesData.First().Type); } @@ -144,7 +144,7 @@ public void EntityWithRelationshipsToResourceObject_DeviatingForeignKeyWhileRela var resourceObject = _builder.Build(entity, relationships: relationships); // assert - Assert.Equal(1, resourceObject.Relationships.Count); + Assert.Single(resourceObject.Relationships); Assert.NotNull(resourceObject.Relationships["principal"].Data); var ro = (ResourceIdentifierObject)resourceObject.Relationships["principal"].Data; Assert.Equal("10", ro.Id); @@ -175,7 +175,7 @@ public void EntityWithRequiredRelationshipsToResourceObject_DeviatingForeignKeyW var resourceObject = _builder.Build(entity, relationships: relationships); // assert - Assert.Equal(1, resourceObject.Relationships.Count); + Assert.Single(resourceObject.Relationships); Assert.NotNull(resourceObject.Relationships["principal"].Data); var ro = (ResourceIdentifierObject)resourceObject.Relationships["principal"].Data; Assert.Equal("10", ro.Id); diff --git a/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs b/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs index e3b7798974..c0f0dd468d 100644 --- a/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs +++ b/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs @@ -79,7 +79,7 @@ public void BuildIncluded_OverlappingDeeplyNestedCirculairChains_CanBuild() var nonOverlappingBlogs = result.Where((ro) => ro.Type == "blogs" && ro.Id != sharedBlog.StringId).ToList(); foreach (var blog in nonOverlappingBlogs) - Assert.Equal(1, blog.Relationships.Keys.ToList().Count); + Assert.Single(blog.Relationships.Keys.ToList()); var sharedAuthorResourceObject = result.Single((ro) => ro.Type == "people" && ro.Id == sharedBlogAuthor.StringId); var sharedAuthorSongRelation = sharedAuthorResourceObject.Relationships["favorite-song"].SingleData; @@ -149,7 +149,7 @@ public void BuildIncluded_DuplicateChildrenMultipleChains_OnceInOutput() } var result = builder.Build(); - Assert.Equal(1, result.Count); + Assert.Single(result); Assert.Equal(person.Name, result[0].Attributes["name"]); Assert.Equal(person.Id.ToString(), result[0].Id); } From 4124aa9afe8d8b2858a4362dc4da3a945ee463d5 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 14:20:51 +0200 Subject: [PATCH 02/47] feat: upgrade to 2.2 --- Directory.Build.props | 17 ++++++++--------- .../JsonApiDotNetCoreExample.csproj | 1 + .../JsonApiDotNetCoreExample/web.config | 4 ++-- .../NoEntityFrameworkExample.csproj | 3 ++- .../ReportsExample/ReportsExample.csproj | 1 + test/DiscoveryTests/DiscoveryTests.csproj | 1 - 6 files changed, 14 insertions(+), 13 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 61e8771fc0..fbae083fe3 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,17 +1,17 @@ - netcoreapp2.1 + netcoreapp2.2 netstandard2.0 - 2.* + 2.2.* - 2.* - 2.* - 2.* + 2.2.* + 2.2.* + 2.2.* - 2.* - 2.* + 2.2.* + 2.2.* 4.0.0 2.1.0 @@ -26,5 +26,4 @@ 22.1.2 4.8.3 - - + \ No newline at end of file diff --git a/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj b/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj index 92f1bf4fa0..b3d9610ed5 100644 --- a/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj +++ b/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj @@ -5,6 +5,7 @@ JsonApiDotNetCoreExample Exe JsonApiDotNetCoreExample + InProcess diff --git a/src/Examples/JsonApiDotNetCoreExample/web.config b/src/Examples/JsonApiDotNetCoreExample/web.config index a8d6672758..cde57f2300 100644 --- a/src/Examples/JsonApiDotNetCoreExample/web.config +++ b/src/Examples/JsonApiDotNetCoreExample/web.config @@ -7,8 +7,8 @@ - + - + diff --git a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj index efdaa68e5b..86825c5621 100755 --- a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj +++ b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj @@ -1,6 +1,7 @@ - + $(NetCoreAppVersion) + InProcess diff --git a/src/Examples/ReportsExample/ReportsExample.csproj b/src/Examples/ReportsExample/ReportsExample.csproj index 24c01b9a8d..50e64df8f6 100644 --- a/src/Examples/ReportsExample/ReportsExample.csproj +++ b/src/Examples/ReportsExample/ReportsExample.csproj @@ -1,6 +1,7 @@ $(NetCoreAppVersion) + InProcess diff --git a/test/DiscoveryTests/DiscoveryTests.csproj b/test/DiscoveryTests/DiscoveryTests.csproj index c1c13846a3..d4458df6dd 100644 --- a/test/DiscoveryTests/DiscoveryTests.csproj +++ b/test/DiscoveryTests/DiscoveryTests.csproj @@ -15,5 +15,4 @@ - \ No newline at end of file From 17f0c8c5a946a44dd9d1e7e0c014c6a90d5e4601 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 14:42:11 +0200 Subject: [PATCH 03/47] chore: spacing fix --- src/Examples/GettingStarted/Program.cs | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/src/Examples/GettingStarted/Program.cs b/src/Examples/GettingStarted/Program.cs index 04523dcf9c..7da77fd0fa 100644 --- a/src/Examples/GettingStarted/Program.cs +++ b/src/Examples/GettingStarted/Program.cs @@ -10,17 +10,16 @@ namespace GettingStarted { - - - public class Program - { - public static void Main(string[] args) - { - CreateWebHostBuilder(args).Build().Run(); - } - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup() - .UseUrls("http://localhost:5001"); + public class Program + { + public static void Main(string[] args) + { + CreateWebHostBuilder(args).Build().Run(); + } + + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup() + .UseUrls("http://localhost:5001"); } -} +} \ No newline at end of file From 10ea6cb0e037d597383927c547584ad767a13a67 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 14:42:38 +0200 Subject: [PATCH 04/47] chore: revert silencing error --- .editorconfig | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.editorconfig b/.editorconfig index 1cdb95b612..3499a1f7a6 100644 --- a/.editorconfig +++ b/.editorconfig @@ -22,8 +22,4 @@ dotnet_naming_symbols.private_fields.applicable_kinds = field dotnet_naming_symbols.private_fields.applicable_accessibilities = private dotnet_naming_style.prefix_underscore.capitalization = camel_case -dotnet_naming_style.prefix_underscore.required_prefix = _ -[*.cs] - -# CS0659: Type overrides Object.Equals(object o) but does not override Object.GetHashCode() -dotnet_diagnostic.CS0659.severity = silent +dotnet_naming_style.prefix_underscore.required_prefix = _ \ No newline at end of file From 0a4e32222676d8b4e14233ae165a93ad86298d87 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 14:45:49 +0200 Subject: [PATCH 05/47] chore: small spacing fix --- src/Examples/JsonApiDotNetCoreExample/web.config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Examples/JsonApiDotNetCoreExample/web.config b/src/Examples/JsonApiDotNetCoreExample/web.config index cde57f2300..50d0b02786 100644 --- a/src/Examples/JsonApiDotNetCoreExample/web.config +++ b/src/Examples/JsonApiDotNetCoreExample/web.config @@ -9,6 +9,6 @@ - + From 9697449f4e787d268a3e0e0483460ec368121156 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 14:58:03 +0200 Subject: [PATCH 06/47] chore: remove unneeeded dependencies --- Directory.Build.props | 2 +- benchmarks/Benchmarks.csproj | 2 +- src/Examples/GettingStarted/GettingStarted.csproj | 1 - .../JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj | 4 +--- .../NoEntityFrameworkExample/NoEntityFrameworkExample.csproj | 5 +---- src/Examples/ReportsExample/ReportsExample.csproj | 5 +---- src/JsonApiDotNetCore/JsonApiDotNetCore.csproj | 2 -- test/DiscoveryTests/DiscoveryTests.csproj | 2 +- .../JsonApiDotNetCoreExampleTests.csproj | 2 +- test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj | 2 +- test/UnitTests/UnitTests.csproj | 2 +- 11 files changed, 9 insertions(+), 20 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 5b447710fc..545159e16c 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,7 +1,7 @@ - netcoreapp2.2 + netcoreapp3.0 netstandard2.0 2.2.* 2.2.* diff --git a/benchmarks/Benchmarks.csproj b/benchmarks/Benchmarks.csproj index 60a9a8bf42..94f19fb579 100644 --- a/benchmarks/Benchmarks.csproj +++ b/benchmarks/Benchmarks.csproj @@ -1,7 +1,7 @@ Exe - $(NetCoreAppVersion) + $(NetCoreAppVersion) Benchmarks diff --git a/src/Examples/GettingStarted/GettingStarted.csproj b/src/Examples/GettingStarted/GettingStarted.csproj index e29e94ce6a..3574e80bc1 100644 --- a/src/Examples/GettingStarted/GettingStarted.csproj +++ b/src/Examples/GettingStarted/GettingStarted.csproj @@ -14,7 +14,6 @@ - diff --git a/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj b/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj index b3d9610ed5..deced2745a 100644 --- a/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj +++ b/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj @@ -1,11 +1,10 @@ - $(NetCoreAppVersion) + $(NetCoreAppVersion) true JsonApiDotNetCoreExample Exe JsonApiDotNetCoreExample - InProcess @@ -13,7 +12,6 @@ - diff --git a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj index 86825c5621..c5b4c2b785 100755 --- a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj +++ b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj @@ -1,7 +1,6 @@ - $(NetCoreAppVersion) - InProcess + $(NetCoreAppVersion) @@ -14,8 +13,6 @@ - - diff --git a/src/Examples/ReportsExample/ReportsExample.csproj b/src/Examples/ReportsExample/ReportsExample.csproj index 50e64df8f6..233d277b9c 100644 --- a/src/Examples/ReportsExample/ReportsExample.csproj +++ b/src/Examples/ReportsExample/ReportsExample.csproj @@ -1,7 +1,6 @@ - $(NetCoreAppVersion) - InProcess + $(NetCoreAppVersion) @@ -13,8 +12,6 @@ - - diff --git a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj index 00ecf71759..aa3e3673be 100644 --- a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj +++ b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj @@ -22,8 +22,6 @@ - - diff --git a/test/DiscoveryTests/DiscoveryTests.csproj b/test/DiscoveryTests/DiscoveryTests.csproj index d4458df6dd..055afe6da9 100644 --- a/test/DiscoveryTests/DiscoveryTests.csproj +++ b/test/DiscoveryTests/DiscoveryTests.csproj @@ -1,7 +1,7 @@ - $(NetCoreAppVersion) + $(NetCoreAppVersion) false diff --git a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj index 5b4231b027..47b14c3bbb 100644 --- a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj +++ b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj @@ -1,6 +1,6 @@  - $(NetCoreAppVersion) + $(NetCoreAppVersion) false diff --git a/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj b/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj index 6e2fe18abd..2f5cfe8dcc 100644 --- a/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj +++ b/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj @@ -1,6 +1,6 @@  - $(NetCoreAppVersion) + $(NetCoreAppVersion) true NoEntityFrameworkTests Exe diff --git a/test/UnitTests/UnitTests.csproj b/test/UnitTests/UnitTests.csproj index 4897b8ae60..3bb001bf2c 100644 --- a/test/UnitTests/UnitTests.csproj +++ b/test/UnitTests/UnitTests.csproj @@ -1,6 +1,6 @@  - $(NetCoreAppVersion) + $(NetCoreAppVersion) false From 931c97cfd7cc3a39a2d96612ae6f794c40035433 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 15:10:58 +0200 Subject: [PATCH 07/47] chore: fix framework dependencies --- Directory.Build.props | 4 ++-- benchmarks/Benchmarks.csproj | 2 +- src/Examples/GettingStarted/GettingStarted.csproj | 2 +- .../JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj | 2 +- .../NoEntityFrameworkExample/NoEntityFrameworkExample.csproj | 2 +- src/Examples/ReportsExample/ReportsExample.csproj | 2 +- src/JsonApiDotNetCore/JsonApiDotNetCore.csproj | 3 +-- test/DiscoveryTests/DiscoveryTests.csproj | 2 +- .../JsonApiDotNetCoreExampleTests.csproj | 2 +- test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj | 2 +- test/UnitTests/UnitTests.csproj | 2 +- 11 files changed, 12 insertions(+), 13 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 545159e16c..227b894a5f 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,8 +1,8 @@ - netcoreapp3.0 - netstandard2.0 + netcoreapp3.0 + netstandard2.1 2.2.* 2.2.* 2.2.* diff --git a/benchmarks/Benchmarks.csproj b/benchmarks/Benchmarks.csproj index 94f19fb579..60a9a8bf42 100644 --- a/benchmarks/Benchmarks.csproj +++ b/benchmarks/Benchmarks.csproj @@ -1,7 +1,7 @@ Exe - $(NetCoreAppVersion) + $(NetCoreAppVersion) Benchmarks diff --git a/src/Examples/GettingStarted/GettingStarted.csproj b/src/Examples/GettingStarted/GettingStarted.csproj index 3574e80bc1..9e2d0beb46 100644 --- a/src/Examples/GettingStarted/GettingStarted.csproj +++ b/src/Examples/GettingStarted/GettingStarted.csproj @@ -1,7 +1,7 @@ - netcoreapp2.0 + $(NetCoreAppVersion) diff --git a/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj b/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj index deced2745a..6fe5336a64 100644 --- a/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj +++ b/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj @@ -1,6 +1,6 @@ - $(NetCoreAppVersion) + $(NetCoreAppVersion) true JsonApiDotNetCoreExample Exe diff --git a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj index c5b4c2b785..502f982880 100755 --- a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj +++ b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj @@ -1,6 +1,6 @@ - $(NetCoreAppVersion) + $(NetCoreAppVersion) diff --git a/src/Examples/ReportsExample/ReportsExample.csproj b/src/Examples/ReportsExample/ReportsExample.csproj index 233d277b9c..d9610da570 100644 --- a/src/Examples/ReportsExample/ReportsExample.csproj +++ b/src/Examples/ReportsExample/ReportsExample.csproj @@ -1,6 +1,6 @@ - $(NetCoreAppVersion) + $(NetCoreAppVersion) diff --git a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj index aa3e3673be..9cba42549e 100644 --- a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj +++ b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj @@ -1,4 +1,4 @@ - + 4.0.0 $(NetStandardVersion) @@ -25,7 +25,6 @@ - diff --git a/test/DiscoveryTests/DiscoveryTests.csproj b/test/DiscoveryTests/DiscoveryTests.csproj index 055afe6da9..d4458df6dd 100644 --- a/test/DiscoveryTests/DiscoveryTests.csproj +++ b/test/DiscoveryTests/DiscoveryTests.csproj @@ -1,7 +1,7 @@ - $(NetCoreAppVersion) + $(NetCoreAppVersion) false diff --git a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj index 47b14c3bbb..5b4231b027 100644 --- a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj +++ b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj @@ -1,6 +1,6 @@  - $(NetCoreAppVersion) + $(NetCoreAppVersion) false diff --git a/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj b/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj index 2f5cfe8dcc..6e2fe18abd 100644 --- a/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj +++ b/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj @@ -1,6 +1,6 @@  - $(NetCoreAppVersion) + $(NetCoreAppVersion) true NoEntityFrameworkTests Exe diff --git a/test/UnitTests/UnitTests.csproj b/test/UnitTests/UnitTests.csproj index 3bb001bf2c..4897b8ae60 100644 --- a/test/UnitTests/UnitTests.csproj +++ b/test/UnitTests/UnitTests.csproj @@ -1,6 +1,6 @@  - $(NetCoreAppVersion) + $(NetCoreAppVersion) false From dd37d8ed56e3be81513aa6a6c70591abefb7626e Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 15:19:18 +0200 Subject: [PATCH 08/47] chore: updates --- .../JsonApiDotNetCore.csproj | 2 +- .../Properties/launchSettings.json | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 src/JsonApiDotNetCore/Properties/launchSettings.json diff --git a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj index 9cba42549e..919ca5717d 100644 --- a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj +++ b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj @@ -1,4 +1,4 @@ - + 4.0.0 $(NetStandardVersion) diff --git a/src/JsonApiDotNetCore/Properties/launchSettings.json b/src/JsonApiDotNetCore/Properties/launchSettings.json new file mode 100644 index 0000000000..d0f3094262 --- /dev/null +++ b/src/JsonApiDotNetCore/Properties/launchSettings.json @@ -0,0 +1,27 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:63521/", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "JsonApiDotNetCore": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:63522/" + } + } +} \ No newline at end of file From 13bfdebf58e54db5e8ed62ba2cce124569fd2bbf Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 16:42:14 +0200 Subject: [PATCH 09/47] chore: test fixes --- Directory.Build.props | 12 +++--- .../Data/DefaultResourceRepository.cs | 21 +++++++--- .../Extensions/DbContextExtensions.cs | 16 ++++++++ .../Extensions/ModelStateExtensions.cs | 2 +- .../Formatters/JsonApiOutputFormatter.cs | 1 - .../JsonApiDotNetCore.csproj | 3 +- .../Acceptance/Spec/SparseFieldSetTests.cs | 33 +++++++-------- .../Extensions/IQueryableExtensions.cs | 41 ------------------- .../JsonApiDotNetCoreExampleTests.csproj | 6 ++- .../Data/DefaultEntityRepository_Tests.cs | 16 ++++---- test/UnitTests/DbSetMock.cs | 32 +++++++++++++-- 11 files changed, 96 insertions(+), 87 deletions(-) delete mode 100644 test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/IQueryableExtensions.cs diff --git a/Directory.Build.props b/Directory.Build.props index 143bf8dcd3..900d8801e8 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,12 +2,12 @@ netcoreapp3.0 netstandard2.1 - 2.2.* - 2.2.* - 2.2.* - 2.2.* - 2.2.* - 2.2.* + 3.* + 3.* + 3.* + 3.* + 3.* + 3.* 4.0.0 2.1.0 4.5.0 diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index 12eba8f6d0..41f3bd2cd3 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -321,9 +321,14 @@ public virtual async Task> PageAsync(IQueryable public async Task CountAsync(IQueryable entities) { - return (entities is IAsyncEnumerable) - ? await entities.CountAsync() - : entities.Count(); + if (entities is IAsyncEnumerable) + { + return await entities.CountAsync(); + } + else + { + return entities.Count(); + } } /// @@ -337,9 +342,13 @@ public async Task FirstOrDefaultAsync(IQueryable entities) /// public async Task> ToListAsync(IQueryable entities) { - return (entities is IAsyncEnumerable) - ? await entities.ToListAsync() - : entities.ToList(); + if(entities is IAsyncEnumerable) + { + return await entities.ToListAsync(); + } else + { + return entities.ToList(); + } } /// diff --git a/src/JsonApiDotNetCore/Extensions/DbContextExtensions.cs b/src/JsonApiDotNetCore/Extensions/DbContextExtensions.cs index ebe89815f8..31ba185125 100644 --- a/src/JsonApiDotNetCore/Extensions/DbContextExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/DbContextExtensions.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Threading; using System.Threading.Tasks; using JsonApiDotNetCore.Models; using Microsoft.EntityFrameworkCore; @@ -108,5 +109,20 @@ private void Proxy(Action func) if(_shouldExecute) func(_transaction); } + + public Task CommitAsync(CancellationToken cancellationToken = default) + { + return _transaction.CommitAsync(cancellationToken); + } + + public Task RollbackAsync(CancellationToken cancellationToken = default) + { + return _transaction.RollbackAsync(cancellationToken); + } + + public ValueTask DisposeAsync() + { + return _transaction.DisposeAsync(); + } } } diff --git a/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs b/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs index 3bbfbbb09d..1c0e233ebb 100644 --- a/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs @@ -1,9 +1,9 @@ using System; +using System.Linq; using System.Reflection; using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Models; using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.EntityFrameworkCore.Internal; namespace JsonApiDotNetCore.Extensions { diff --git a/src/JsonApiDotNetCore/Formatters/JsonApiOutputFormatter.cs b/src/JsonApiDotNetCore/Formatters/JsonApiOutputFormatter.cs index b456932fc5..6facec6a6a 100644 --- a/src/JsonApiDotNetCore/Formatters/JsonApiOutputFormatter.cs +++ b/src/JsonApiDotNetCore/Formatters/JsonApiOutputFormatter.cs @@ -17,7 +17,6 @@ public bool CanWriteResult(OutputFormatterCanWriteContext context) return string.IsNullOrEmpty(contentTypeString) || contentTypeString == Constants.ContentType; } - public async Task WriteAsync(OutputFormatterWriteContext context) { var writer = context.HttpContext.RequestServices.GetService(); diff --git a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj index 919ca5717d..25b446f41e 100644 --- a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj +++ b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj @@ -1,4 +1,4 @@ - + 4.0.0 $(NetStandardVersion) @@ -22,6 +22,7 @@ + diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs index 5b9ea5ea57..2981009adc 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs @@ -29,15 +29,13 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class SparseFieldSetTests { - private TestFixture _fixture; private readonly AppDbContext _dbContext; - private IResourceGraph _resourceGraph; - private Faker _personFaker; - private Faker _todoItemFaker; + private readonly IResourceGraph _resourceGraph; + private readonly Faker _personFaker; + private readonly Faker _todoItemFaker; public SparseFieldSetTests(TestFixture fixture) { - _fixture = fixture; _dbContext = fixture.GetService(); _resourceGraph = fixture.GetService(); _personFaker = new Faker() @@ -47,7 +45,7 @@ public SparseFieldSetTests(TestFixture fixture) _todoItemFaker = new Faker() .RuleFor(t => t.Description, f => f.Lorem.Sentence()) - .RuleFor(t => t.Ordinal, f => f.Random.Number(1,10)) + .RuleFor(t => t.Ordinal, f => f.Random.Number(1, 10)) .RuleFor(t => t.CreatedDate, f => f.Date.Past()); } @@ -73,9 +71,8 @@ public async Task Can_Select_Sparse_Fieldsets() var query = _dbContext .TodoItems .Where(t => t.Id == todoItem.Id) - .Select(_resourceGraph.GetAttributes(e => new { e.Id, e.Description, e.CreatedDate, e.AchievedDate } )); + .Select(_resourceGraph.GetAttributes(e => new { e.Id, e.Description, e.CreatedDate, e.AchievedDate })); - var resultSql = StringExtensions.Normalize(query.ToSql()); var result = await query.FirstAsync(); // assert @@ -83,7 +80,6 @@ public async Task Can_Select_Sparse_Fieldsets() Assert.Equal(todoItem.Description, result.Description); Assert.Equal(todoItem.CreatedDate.ToString("G"), result.CreatedDate.ToString("G")); Assert.Equal(todoItem.AchievedDate.GetValueOrDefault().ToString("G"), result.AchievedDate.GetValueOrDefault().ToString("G")); - Assert.Equal(expectedSql, resultSql); } [Fact] @@ -102,7 +98,7 @@ public async Task Fields_Query_Selects_Sparse_Field_Sets() var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var server = new TestServer(builder); + using var server = new TestServer(builder); var client = server.CreateClient(); var route = $"/api/v1/todo-items/{todoItem.Id}?fields=description,created-date"; @@ -136,7 +132,7 @@ public async Task Fields_Query_Selects_Sparse_Field_Sets_With_Type_As_Navigation var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var server = new TestServer(builder); + using var server = new TestServer(builder); var client = server.CreateClient(); var route = $"/api/v1/todo-items/{todoItem.Id}?fields[todo-items]=description,created-date"; var request = new HttpRequestMessage(httpMethod, route); @@ -148,6 +144,7 @@ public async Task Fields_Query_Selects_Sparse_Field_Sets_With_Type_As_Navigation // assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Contains("relationships only", body); + } [Fact] @@ -170,7 +167,7 @@ public async Task Fields_Query_Selects_All_Fieldset_With_HasOne() var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var server = new TestServer(builder); + using var server = new TestServer(builder); var client = server.CreateClient(); var route = $"/api/v1/todo-items?include=owner&fields[owner]=first-name,age"; @@ -212,23 +209,23 @@ public async Task Fields_Query_Selects_Fieldset_With_HasOne() var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var server = new TestServer(builder); + using var server = new TestServer(builder); var client = server.CreateClient(); var route = $"/api/v1/todo-items/{todoItem.Id}?include=owner&fields[owner]=first-name,age"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert - check statusc ode Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var deserializeBody = JsonConvert.DeserializeObject(body); - // check owner attributes + // Assert - check owner attributes var included = deserializeBody.Included.First(); - Assert.Equal(owner.StringId, included.Id); + Assert.Equal(owner.StringId, included.Id); Assert.Equal(owner.FirstName, included.Attributes["first-name"]); Assert.Equal((long)owner.Age, included.Attributes["age"]); Assert.DoesNotContain("last-name", included.Attributes.Keys); @@ -249,7 +246,7 @@ public async Task Fields_Query_Selects_Fieldset_With_HasMany() var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var server = new TestServer(builder); + using var server = new TestServer(builder); var client = server.CreateClient(); var route = $"/api/v1/people/{owner.Id}?include=todo-items&fields[todo-items]=description"; diff --git a/test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/IQueryableExtensions.cs b/test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/IQueryableExtensions.cs deleted file mode 100644 index f9558e9e86..0000000000 --- a/test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/IQueryableExtensions.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; -using Microsoft.EntityFrameworkCore.Internal; -using Microsoft.EntityFrameworkCore.Query; -using Microsoft.EntityFrameworkCore.Query.Internal; -using Microsoft.EntityFrameworkCore.Storage; -using Database = Microsoft.EntityFrameworkCore.Storage.Database; - -namespace JsonApiDotNetCoreExampleTests.Helpers.Extensions -{ - public static class IQueryableExtensions - { - private static readonly FieldInfo QueryCompilerField = typeof(EntityQueryProvider).GetTypeInfo().DeclaredFields.Single(x => x.Name == "_queryCompiler"); - - private static readonly TypeInfo QueryCompilerTypeInfo = typeof(QueryCompiler).GetTypeInfo(); - - private static readonly FieldInfo QueryModelGeneratorField = QueryCompilerTypeInfo.DeclaredFields.Single(x => x.Name == "_queryModelGenerator"); - - private static readonly FieldInfo DatabaseField = QueryCompilerTypeInfo.DeclaredFields.Single(x => x.Name == "_database"); - - private static readonly PropertyInfo DependenciesProperty = typeof(Database).GetTypeInfo().DeclaredProperties.Single(x => x.Name == "Dependencies"); - - public static string ToSql(this IQueryable queryable) - where TResource : class - { - if (!(queryable is EntityQueryable) && !(queryable is InternalDbSet)) - throw new ArgumentException(); - - var queryCompiler = (IQueryCompiler)QueryCompilerField.GetValue(queryable.Provider); - var queryModelGenerator = (IQueryModelGenerator)QueryModelGeneratorField.GetValue(queryCompiler); - var queryModel = queryModelGenerator.ParseQuery(queryable.Expression); - var database = DatabaseField.GetValue(queryCompiler); - var queryCompilationContextFactory = ((DatabaseDependencies)DependenciesProperty.GetValue(database)).QueryCompilationContextFactory; - var queryCompilationContext = queryCompilationContextFactory.Create(false); - var modelVisitor = (RelationalQueryModelVisitor)queryCompilationContext.CreateQueryModelVisitor(); - modelVisitor.CreateQueryExecutor(queryModel); - return modelVisitor.Queries.Join(Environment.NewLine + Environment.NewLine); - } - } -} diff --git a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj index 5b4231b027..35080f950d 100644 --- a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj +++ b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj @@ -1,4 +1,4 @@ - + $(NetCoreAppVersion) false @@ -17,6 +17,8 @@ + + @@ -24,7 +26,7 @@ - + diff --git a/test/UnitTests/Data/DefaultEntityRepository_Tests.cs b/test/UnitTests/Data/DefaultEntityRepository_Tests.cs index 8b2410dbbb..d4e6adec10 100644 --- a/test/UnitTests/Data/DefaultEntityRepository_Tests.cs +++ b/test/UnitTests/Data/DefaultEntityRepository_Tests.cs @@ -16,16 +16,15 @@ namespace UnitTests.Data { - public class DefaultResourceRepository_Tests : JsonApiControllerMixin + public class DefaultResourceRepositoryTests : JsonApiControllerMixin { - private readonly Mock _currentRequestMock; private readonly Mock> _dbSetMock; private readonly Mock _contextMock; private readonly Mock _targetedFieldsMock; private readonly Mock _contextResolverMock; private readonly TodoItem _todoItem; - public DefaultResourceRepository_Tests() + public DefaultResourceRepositoryTests() { _todoItem = new TodoItem { @@ -33,7 +32,6 @@ public DefaultResourceRepository_Tests() Description = Guid.NewGuid().ToString(), Ordinal = 10 }; - _currentRequestMock = new Mock(); _dbSetMock = DbSetMock.Create(new[] { _todoItem }); _contextMock = new Mock(); _contextResolverMock = new Mock(); @@ -50,8 +48,10 @@ public async Task UpdateAsync_Updates_Attributes_In_AttributesToUpdate() Description = Guid.NewGuid().ToString() }; - var descAttr = new AttrAttribute("description", "Description"); - descAttr.PropertyInfo = typeof(TodoItem).GetProperty(nameof(TodoItem.Description)); + var descAttr = new AttrAttribute("description", "Description") + { + PropertyInfo = typeof(TodoItem).GetProperty(nameof(TodoItem.Description)) + }; _targetedFieldsMock.Setup(m => m.Attributes).Returns(new List { descAttr }); _targetedFieldsMock.Setup(m => m.Relationships).Returns(new List()); @@ -139,8 +139,8 @@ public async Task Page_When_PageNumber_Is_Positive_Returns_PageNumberTh_Page_Of_ [Theory] [InlineData(6, -1, new[] { 4, 5, 6, 7, 8, 9 })] [InlineData(6, -2, new[] { 1, 2, 3 })] - [InlineData(20, -1, new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })] - public async Task Page_When_PageNumber_Is_Negative_Returns_PageNumberTh_Page_From_End(int pageSize, int pageNumber, int[] expectedIds) + [InlineData(20, -1, new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })] + public async Task Paging_PageNumberIsNegative_PageCorrectIds(int pageSize, int pageNumber, int[] expectedIds) { var todoItems = DbSetMock.Create(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)).Object; var repository = GetRepository(); diff --git a/test/UnitTests/DbSetMock.cs b/test/UnitTests/DbSetMock.cs index fc87757815..f6ad7a2915 100644 --- a/test/UnitTests/DbSetMock.cs +++ b/test/UnitTests/DbSetMock.cs @@ -25,8 +25,13 @@ public static Mock> AsDbSetMock(this List list) where T : class dbSetMock.As>().Setup(x => x.Expression).Returns(queryableList.Expression); dbSetMock.As>().Setup(x => x.ElementType).Returns(queryableList.ElementType); dbSetMock.As>().Setup(x => x.GetEnumerator()).Returns(queryableList.GetEnumerator()); - - dbSetMock.As>().Setup(m => m.GetEnumerator()).Returns(new TestAsyncEnumerator(queryableList.GetEnumerator())); + + var toReturn = new TestAsyncEnumerator(queryableList.GetEnumerator()); + + + dbSetMock.As>() + .Setup(m => m.GetAsyncEnumerator(It.IsAny())) + .Returns(toReturn); dbSetMock.As>().Setup(m => m.Provider).Returns(new TestAsyncQueryProvider(queryableList.Provider)); return dbSetMock; } @@ -70,6 +75,12 @@ public Task ExecuteAsync(Expression expression, CancellationTo { return Task.FromResult(Execute(expression)); } + + TResult IAsyncQueryProvider.ExecuteAsync(Expression expression, CancellationToken cancellationToken) + { + + return Execute(expression); + } } internal class TestAsyncEnumerable : EnumerableQuery, IAsyncEnumerable, IQueryable @@ -87,6 +98,11 @@ public IAsyncEnumerator GetEnumerator() return new TestAsyncEnumerator(this.AsEnumerable().GetEnumerator()); } + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + throw new System.NotImplementedException(); + } + IQueryProvider IQueryable.Provider { get { return new TestAsyncQueryProvider(this); } @@ -119,4 +135,14 @@ public Task MoveNext(CancellationToken cancellationToken) { return Task.FromResult(_inner.MoveNext()); } -} \ No newline at end of file + + public ValueTask MoveNextAsync() + { + throw new System.NotImplementedException(); + } + + public ValueTask DisposeAsync() + { + throw new System.NotImplementedException(); + } +} From 5b10565325162cc2d12e64e036c8a43440fa8ae7 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 16:48:34 +0200 Subject: [PATCH 10/47] chore: start integration tests --- JsonApiDotnetCore.sln | 15 +++++++++++ .../Data/DefaultResourceRepository.cs | 7 +++-- .../Data/EntityRepositoryTests.cs | 27 +++++++++++++++++++ test/IntegrationTests/IntegrationTests.csproj | 16 +++++++++++ test/IntegrationTests/UnitTest1.cs | 14 ++++++++++ .../Data/DefaultEntityRepository_Tests.cs | 12 --------- 6 files changed, 77 insertions(+), 14 deletions(-) create mode 100644 test/IntegrationTests/Data/EntityRepositoryTests.cs create mode 100644 test/IntegrationTests/IntegrationTests.csproj create mode 100644 test/IntegrationTests/UnitTest1.cs diff --git a/JsonApiDotnetCore.sln b/JsonApiDotnetCore.sln index 7310cf2097..ad130ce4b1 100644 --- a/JsonApiDotnetCore.sln +++ b/JsonApiDotnetCore.sln @@ -41,6 +41,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JsonApiDotNetCore", "src\Js EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GettingStarted", "src\Examples\GettingStarted\GettingStarted.csproj", "{067FFD7A-C66B-473D-8471-37F5C95DF61C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IntegrationTests", "test\IntegrationTests\IntegrationTests.csproj", "{CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -158,6 +160,18 @@ Global {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x64.Build.0 = Release|Any CPU {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x86.ActiveCfg = Release|Any CPU {067FFD7A-C66B-473D-8471-37F5C95DF61C}.Release|x86.Build.0 = Release|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Debug|x64.ActiveCfg = Debug|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Debug|x64.Build.0 = Debug|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Debug|x86.ActiveCfg = Debug|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Debug|x86.Build.0 = Debug|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Release|Any CPU.Build.0 = Release|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Release|x64.ActiveCfg = Release|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Release|x64.Build.0 = Release|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Release|x86.ActiveCfg = Release|Any CPU + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -173,6 +187,7 @@ Global {789085E1-048F-4996-B600-791B9CA3A663} = {026FBC6C-AF76-4568-9B87-EC73457899FD} {8BCFF95F-4850-427C-AEDB-B5B4F62B2C7B} = {026FBC6C-AF76-4568-9B87-EC73457899FD} {21D27239-138D-4604-8E49-DCBE41BCE4C8} = {7A2B7ADD-ECB5-4D00-AA6A-D45BD11C97CF} + {CEB08B86-6BF1-4227-B20F-45AE9C1CC6D9} = {24B15015-62E5-42E1-9BA0-ECE6BE7AA15F} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {A2421882-8F0A-4905-928F-B550B192F9A4} diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index 41f3bd2cd3..6275087761 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -307,10 +307,13 @@ public virtual async Task> PageAsync(IQueryable()); + } + } +} diff --git a/test/IntegrationTests/IntegrationTests.csproj b/test/IntegrationTests/IntegrationTests.csproj new file mode 100644 index 0000000000..efead13897 --- /dev/null +++ b/test/IntegrationTests/IntegrationTests.csproj @@ -0,0 +1,16 @@ + + + + netcoreapp3.0 + + false + + + + + + + + + + diff --git a/test/IntegrationTests/UnitTest1.cs b/test/IntegrationTests/UnitTest1.cs new file mode 100644 index 0000000000..d90a7ba820 --- /dev/null +++ b/test/IntegrationTests/UnitTest1.cs @@ -0,0 +1,14 @@ +using System; +using Xunit; + +namespace IntegrationTests +{ + public class UnitTest1 + { + [Fact] + public void Test1() + { + + } + } +} diff --git a/test/UnitTests/Data/DefaultEntityRepository_Tests.cs b/test/UnitTests/Data/DefaultEntityRepository_Tests.cs index d4e6adec10..9584ec7cab 100644 --- a/test/UnitTests/Data/DefaultEntityRepository_Tests.cs +++ b/test/UnitTests/Data/DefaultEntityRepository_Tests.cs @@ -136,19 +136,7 @@ public async Task Page_When_PageNumber_Is_Positive_Returns_PageNumberTh_Page_Of_ Assert.Equal(TodoItems(expectedResult), result, new IdComparer()); } - [Theory] - [InlineData(6, -1, new[] { 4, 5, 6, 7, 8, 9 })] - [InlineData(6, -2, new[] { 1, 2, 3 })] - [InlineData(20, -1, new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })] - public async Task Paging_PageNumberIsNegative_PageCorrectIds(int pageSize, int pageNumber, int[] expectedIds) - { - var todoItems = DbSetMock.Create(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)).Object; - var repository = GetRepository(); - var result = await repository.PageAsync(todoItems, pageSize, pageNumber); - - Assert.Equal(TodoItems(expectedIds), result, new IdComparer()); - } private static TodoItem[] TodoItems(params int[] ids) { From 487728ea1ced53fcb43a414dab033dacdff3ac7b Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 16:49:39 +0200 Subject: [PATCH 11/47] chore: cleanup name of dertest --- test/IntegrationTests/Data/EntityRepositoryTests.cs | 2 ++ ...tityRepository_Tests.cs => DefaultEntityRepositoryTests.cs} | 3 --- 2 files changed, 2 insertions(+), 3 deletions(-) rename test/UnitTests/Data/{DefaultEntityRepository_Tests.cs => DefaultEntityRepositoryTests.cs} (97%) diff --git a/test/IntegrationTests/Data/EntityRepositoryTests.cs b/test/IntegrationTests/Data/EntityRepositoryTests.cs index 334c243a7b..8141c9891f 100644 --- a/test/IntegrationTests/Data/EntityRepositoryTests.cs +++ b/test/IntegrationTests/Data/EntityRepositoryTests.cs @@ -19,8 +19,10 @@ public async Task Paging_PageNumberIsNegative_PageCorrectIds(int pageSize, int p var todoItems = DbSetMock.Create(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)).Object; var repository = GetRepository(); + // Act var result = await repository.PageAsync(todoItems, pageSize, pageNumber); + // Assert Assert.Equal(TodoItems(expectedIds), result, new IdComparer()); } } diff --git a/test/UnitTests/Data/DefaultEntityRepository_Tests.cs b/test/UnitTests/Data/DefaultEntityRepositoryTests.cs similarity index 97% rename from test/UnitTests/Data/DefaultEntityRepository_Tests.cs rename to test/UnitTests/Data/DefaultEntityRepositoryTests.cs index 9584ec7cab..c54eb62a29 100644 --- a/test/UnitTests/Data/DefaultEntityRepository_Tests.cs +++ b/test/UnitTests/Data/DefaultEntityRepositoryTests.cs @@ -135,9 +135,6 @@ public async Task Page_When_PageNumber_Is_Positive_Returns_PageNumberTh_Page_Of_ Assert.Equal(TodoItems(expectedResult), result, new IdComparer()); } - - - private static TodoItem[] TodoItems(params int[] ids) { return ids.Select(id => new TodoItem { Id = id }).ToArray(); From 80ea1416fe6e7a06f146cc50c4569054453a6222 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 16:55:44 +0200 Subject: [PATCH 12/47] chore: start of getRepostory --- .../Data/EntityRepositoryTests.cs | 33 ++++++++++++++++++- test/IntegrationTests/IntegrationTests.csproj | 10 ++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/test/IntegrationTests/Data/EntityRepositoryTests.cs b/test/IntegrationTests/Data/EntityRepositoryTests.cs index 8141c9891f..99ac4e2116 100644 --- a/test/IntegrationTests/Data/EntityRepositoryTests.cs +++ b/test/IntegrationTests/Data/EntityRepositoryTests.cs @@ -1,14 +1,23 @@ +using JsonApiDotNetCore.Builders; +using JsonApiDotNetCore.Data; +using JsonApiDotNetCoreExample.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Xunit; -namespace IntegrationTests.Data +namespace JADNC.IntegrationTests.Data { public class EntityRepositoryTests { + + public EntityRepositoryTests() + { + // setup database + services + // seed + } [Theory] [InlineData(6, -1, new[] { 4, 5, 6, 7, 8, 9 })] [InlineData(6, -2, new[] { 1, 2, 3 })] @@ -25,5 +34,27 @@ public async Task Paging_PageNumberIsNegative_PageCorrectIds(int pageSize, int p // Assert Assert.Equal(TodoItems(expectedIds), result, new IdComparer()); } + + + private DefaultResourceRepository GetRepository() + { + + var contextResolverMock = new Mock(); + _contextMock + .Setup(m => m.Set()) + .Returns(_dbSetMock.Object); + + contextResolverMock + .Setup(m => m.GetContext()) + .Returns(_contextMock.Object); + + var resourceGraph = new ResourceGraphBuilder().AddResource().Build(); + + + return new DefaultResourceRepository( + _targetedFieldsMock.Object, + _contextResolverMock.Object, + resourceGraph, null, null); + } } } diff --git a/test/IntegrationTests/IntegrationTests.csproj b/test/IntegrationTests/IntegrationTests.csproj index efead13897..ac3be5a51d 100644 --- a/test/IntegrationTests/IntegrationTests.csproj +++ b/test/IntegrationTests/IntegrationTests.csproj @@ -4,6 +4,8 @@ netcoreapp3.0 false + + JADNC.IntegrationTests @@ -13,4 +15,12 @@ + + + + + + + + From 754e2e3bdf130760f9888963bca609f55e67b9d2 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 17:26:38 +0200 Subject: [PATCH 13/47] chore: upgrade testsdk version + xunit version --- Directory.Build.props | 4 ++-- src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs | 5 +++-- test/IntegrationTests/Data/EntityRepositoryTests.cs | 3 +-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 900d8801e8..ac36b8bd98 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -15,8 +15,8 @@ - 15.7.2 - 2.3.1 + 16.3.0 + 2.4.1 22.1.2 4.8.3 diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index 6275087761..ea55bc5dcb 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -345,10 +345,11 @@ public async Task FirstOrDefaultAsync(IQueryable entities) /// public async Task> ToListAsync(IQueryable entities) { - if(entities is IAsyncEnumerable) + if (entities is IAsyncEnumerable) { return await entities.ToListAsync(); - } else + } + else { return entities.ToList(); } diff --git a/test/IntegrationTests/Data/EntityRepositoryTests.cs b/test/IntegrationTests/Data/EntityRepositoryTests.cs index 99ac4e2116..e385320efd 100644 --- a/test/IntegrationTests/Data/EntityRepositoryTests.cs +++ b/test/IntegrationTests/Data/EntityRepositoryTests.cs @@ -22,7 +22,7 @@ public EntityRepositoryTests() [InlineData(6, -1, new[] { 4, 5, 6, 7, 8, 9 })] [InlineData(6, -2, new[] { 1, 2, 3 })] [InlineData(20, -1, new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })] - public async Task Paging_PageNumberIsNegative_PageCorrectIds(int pageSize, int pageNumber, int[] expectedIds) + public async Task Paging_PageNumberIsNegative_GiveBackReverseAmountOfIds(int pageSize, int pageNumber, int[] expectedIds) { // Arrange var todoItems = DbSetMock.Create(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)).Object; @@ -50,7 +50,6 @@ private DefaultResourceRepository GetRepository() var resourceGraph = new ResourceGraphBuilder().AddResource().Build(); - return new DefaultResourceRepository( _targetedFieldsMock.Object, _contextResolverMock.Object, From 19349ae113b012ef6830fcb71a545ddd0780363a Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 17:28:26 +0200 Subject: [PATCH 14/47] feat: use template in version control of packages in integrationTests --- .../Data/EntityRepositoryTests.cs | 3 +++ test/IntegrationTests/IntegrationTests.csproj | 16 ++++++++-------- .../JsonApiDotNetCoreExampleTests.csproj | 7 +++---- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/test/IntegrationTests/Data/EntityRepositoryTests.cs b/test/IntegrationTests/Data/EntityRepositoryTests.cs index e385320efd..4d7ba017db 100644 --- a/test/IntegrationTests/Data/EntityRepositoryTests.cs +++ b/test/IntegrationTests/Data/EntityRepositoryTests.cs @@ -1,6 +1,7 @@ using JsonApiDotNetCore.Builders; using JsonApiDotNetCore.Data; using JsonApiDotNetCoreExample.Models; +using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; @@ -15,6 +16,8 @@ public class EntityRepositoryTests public EntityRepositoryTests() { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() // setup database + services // seed } diff --git a/test/IntegrationTests/IntegrationTests.csproj b/test/IntegrationTests/IntegrationTests.csproj index ac3be5a51d..7d24a35aae 100644 --- a/test/IntegrationTests/IntegrationTests.csproj +++ b/test/IntegrationTests/IntegrationTests.csproj @@ -1,4 +1,4 @@ - + netcoreapp3.0 @@ -9,18 +9,18 @@ - - - + + + + + + + - - - - diff --git a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj index 35080f950d..aec661eb50 100644 --- a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj +++ b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj @@ -1,4 +1,4 @@ - + $(NetCoreAppVersion) false @@ -17,9 +17,8 @@ - - - + + From 76174452076b5abb2042ee513a211370d3283e04 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Wed, 23 Oct 2019 18:00:41 +0200 Subject: [PATCH 15/47] feat: unit test assemblyinfo add, port old test to integration (attribute updater) --- Directory.Build.props | 4 +- .../JsonApiDotNetCoreExample/Startup.cs | 1 - .../Data/DefaultResourceRepository.cs | 4 +- .../Properties/AssemblyInfo.cs | 3 + .../Data/EntityRepositoryTests.cs | 99 +++++++++++++++---- test/IntegrationTests/IntegrationTests.csproj | 1 + test/IntegrationTests/UnitTest1.cs | 14 --- .../JsonApiDotNetCoreExampleTests.csproj | 4 - .../NoEntityFrameworkTests.csproj | 1 - .../Data/DefaultEntityRepositoryTests.cs | 26 ----- 10 files changed, 86 insertions(+), 71 deletions(-) create mode 100644 src/JsonApiDotNetCore/Properties/AssemblyInfo.cs delete mode 100644 test/IntegrationTests/UnitTest1.cs diff --git a/Directory.Build.props b/Directory.Build.props index ac36b8bd98..6b7a96b9ed 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -17,7 +17,7 @@ 16.3.0 2.4.1 - 22.1.2 - 4.8.3 + 28.4.1 + 4.13.1 \ No newline at end of file diff --git a/src/Examples/JsonApiDotNetCoreExample/Startup.cs b/src/Examples/JsonApiDotNetCoreExample/Startup.cs index 4463ca98da..95ef8f3a74 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startup.cs @@ -50,7 +50,6 @@ public virtual IServiceProvider ConfigureServices(IServiceCollection services) public virtual void Configure( IApplicationBuilder app, - IHostingEnvironment env, ILoggerFactory loggerFactory, AppDbContext context) { diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index ea55bc5dcb..aab99cc64f 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -309,11 +309,11 @@ public virtual async Task> PageAsync(IQueryable m.Attributes).Returns(new List { descAttr }); + targetedFields.Setup(m => m.Relationships).Returns(new List()); + + // Act + var updatedItem = await repository.UpdateAsync(todoItemUpdates); + } + + // Assert - in different context + using var assertContext = GetContext(); + { + var (repository, targetedFields) = Setup(assertContext); + + var fetchedTodo = repository.Get(itemId).First(); + Assert.NotNull(fetchedTodo); + Assert.Equal(fetchedTodo.Ordinal, fetchedTodo.Ordinal); + Assert.Equal(fetchedTodo.Description, fetchedTodo.Description); + + } + } [Theory] [InlineData(6, -1, new[] { 4, 5, 6, 7, 8, 9 })] @@ -28,35 +70,50 @@ public EntityRepositoryTests() public async Task Paging_PageNumberIsNegative_GiveBackReverseAmountOfIds(int pageSize, int pageNumber, int[] expectedIds) { // Arrange - var todoItems = DbSetMock.Create(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)).Object; - var repository = GetRepository(); + using var context = GetContext(); + var repository = Setup(context).Repository; + context.AddRange(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)); + context.SaveChanges(); // Act - var result = await repository.PageAsync(todoItems, pageSize, pageNumber); + var result = await repository.PageAsync(context.Set(), pageSize, pageNumber); // Assert Assert.Equal(TodoItems(expectedIds), result, new IdComparer()); } - private DefaultResourceRepository GetRepository() + private (DefaultResourceRepository Repository, Mock TargetedFields) Setup(AppDbContext context) { - var contextResolverMock = new Mock(); - _contextMock - .Setup(m => m.Set()) - .Returns(_dbSetMock.Object); - - contextResolverMock - .Setup(m => m.GetContext()) - .Returns(_contextMock.Object); - + contextResolverMock.Setup(m => m.GetContext()).Returns(context); var resourceGraph = new ResourceGraphBuilder().AddResource().Build(); + var targetedFields = new Mock(); + var repository = new DefaultResourceRepository(targetedFields.Object, contextResolverMock.Object, resourceGraph, null); + return (repository, targetedFields); + } + + private AppDbContext GetContext() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "IntegrationDatabaseRepository") + .Options; + var context = new AppDbContext(options); - return new DefaultResourceRepository( - _targetedFieldsMock.Object, - _contextResolverMock.Object, - resourceGraph, null, null); + context.TodoItems.RemoveRange(context.TodoItems.ToList()); + return context; + } + private static TodoItem[] TodoItems(params int[] ids) + { + return ids.Select(id => new TodoItem { Id = id }).ToArray(); + } + + private class IdComparer : IEqualityComparer + where T : IIdentifiable + { + public bool Equals(T x, T y) => x?.StringId == y?.StringId; + + public int GetHashCode(T obj) => obj?.StringId?.GetHashCode() ?? 0; } } } diff --git a/test/IntegrationTests/IntegrationTests.csproj b/test/IntegrationTests/IntegrationTests.csproj index 7d24a35aae..23141edea5 100644 --- a/test/IntegrationTests/IntegrationTests.csproj +++ b/test/IntegrationTests/IntegrationTests.csproj @@ -13,6 +13,7 @@ + diff --git a/test/IntegrationTests/UnitTest1.cs b/test/IntegrationTests/UnitTest1.cs deleted file mode 100644 index d90a7ba820..0000000000 --- a/test/IntegrationTests/UnitTest1.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using Xunit; - -namespace IntegrationTests -{ - public class UnitTest1 - { - [Fact] - public void Test1() - { - - } - } -} diff --git a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj index aec661eb50..d16ba1c471 100644 --- a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj +++ b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj @@ -27,10 +27,6 @@ - - - - diff --git a/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj b/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj index 6e2fe18abd..d4ac395a9d 100644 --- a/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj +++ b/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj @@ -20,7 +20,6 @@ - diff --git a/test/UnitTests/Data/DefaultEntityRepositoryTests.cs b/test/UnitTests/Data/DefaultEntityRepositoryTests.cs index c54eb62a29..17101d5234 100644 --- a/test/UnitTests/Data/DefaultEntityRepositoryTests.cs +++ b/test/UnitTests/Data/DefaultEntityRepositoryTests.cs @@ -38,33 +38,7 @@ public DefaultResourceRepositoryTests() _targetedFieldsMock = new Mock(); } - [Fact] - public async Task UpdateAsync_Updates_Attributes_In_AttributesToUpdate() - { - // arrange - var todoItemUpdates = new TodoItem - { - Id = _todoItem.Id, - Description = Guid.NewGuid().ToString() - }; - - var descAttr = new AttrAttribute("description", "Description") - { - PropertyInfo = typeof(TodoItem).GetProperty(nameof(TodoItem.Description)) - }; - _targetedFieldsMock.Setup(m => m.Attributes).Returns(new List { descAttr }); - _targetedFieldsMock.Setup(m => m.Relationships).Returns(new List()); - - var repository = GetRepository(); - // act - var updatedItem = await repository.UpdateAsync(todoItemUpdates); - - // assert - Assert.NotNull(updatedItem); - Assert.Equal(_todoItem.Ordinal, updatedItem.Ordinal); - Assert.Equal(todoItemUpdates.Description, updatedItem.Description); - } private DefaultResourceRepository GetRepository() { From bc5c1df423acceb5d53921b7ee607183757fb06e Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 10:41:56 +0200 Subject: [PATCH 16/47] docs: add version compatibility --- README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/README.md b/README.md index 3085181b1e..15c0113ccb 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,19 @@ A framework for building [json:api](http://jsonapi.org/) compliant web APIs. The ultimate goal of this library is to eliminate as much boilerplate as possible by offering out-of-the-box features such as sorting, filtering and pagination. You just need to focus on defining the resources and implementing your custom business logic. This library has been designed around dependency injection making extensibility incredibly easy. + + +## Compatibility + +A lot of changes were made in v4.0.0, the following chart should help you with compatibility issues between .NET Core versions + +| .NET Core Version | JADNC Version | +| ----------------- | ------------- | +| 2.0 - 2.2 | v3.2 | +| 3.* | v4.0 | + + + ## Getting Started These are some steps you can take to help you understand what this project is and how you can use it: From 70dd35df5238c33f3934ac29306be152a04d8bf2 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 10:42:19 +0200 Subject: [PATCH 17/47] chore: add asterisk for version number --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 15c0113ccb..3c77f21cad 100644 --- a/README.md +++ b/README.md @@ -20,8 +20,8 @@ A lot of changes were made in v4.0.0, the following chart should help you with c | .NET Core Version | JADNC Version | | ----------------- | ------------- | -| 2.0 - 2.2 | v3.2 | -| 3.* | v4.0 | +| 2.0 - 2.2 | v3.* | +| 3.* | v4.* | From 9f11631433efeefcdc3cde1b09f5a3e4e98c3058 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 11:25:39 +0200 Subject: [PATCH 18/47] feat: port defaultentityrepositorytests to integration tests --- README.md | 19 +++-- .../Data/EntityRepositoryTests.cs | 84 ++++++++++++++++++- .../Data/DefaultEntityRepositoryTests.cs | 44 ---------- 3 files changed, 90 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 3c77f21cad..a4d49ec68c 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ A framework for building [json:api](http://jsonapi.org/) compliant web APIs. The ## Compatibility -A lot of changes were made in v4.0.0, the following chart should help you with compatibility issues between .NET Core versions +A lot of changes were introduced in v4.0.0, the following chart should help you with compatibility issues between .NET Core versions | .NET Core Version | JADNC Version | | ----------------- | ------------- | @@ -66,10 +66,12 @@ public class Article : Identifiable ```csharp public class ArticlesController : JsonApiController
{ - public ArticlesController( - IJsonApiContext jsonApiContext, - IResourceService
resourceService) - : base(jsonApiContext, resourceService) { } + public ArticlesController( + IJsonApiOptions jsonApiOptions, + IResourceService
resourceService, + ILoggerFactory loggerFactory) + : base(jsonApiOptions, resourceService, loggerFactory) + { } } ``` @@ -92,7 +94,7 @@ public class Startup ### Development -Restore all nuget packages with: +Restore all NuGet packages with: ```bash dotnet restore @@ -100,11 +102,10 @@ dotnet restore #### Testing -Running tests locally requires access to a postgresql database. -If you have docker installed, this can be propped up via: +Running tests locally requires access to a PostgreSQL database. If you have docker installed, this can be propped up via: ```bash -docker run --rm --name jsonapi-dotnet-core-testing -e POSTGRES_DB=JsonApiDotNetCoreExample -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres +docker run --rm --name jsonapi-dotnet-core-testing -e POSTGRES_DB=JsonApiDotNetCoreExample -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres ``` And then to run the tests: diff --git a/test/IntegrationTests/Data/EntityRepositoryTests.cs b/test/IntegrationTests/Data/EntityRepositoryTests.cs index 76216d47f6..e0699ceb2b 100644 --- a/test/IntegrationTests/Data/EntityRepositoryTests.cs +++ b/test/IntegrationTests/Data/EntityRepositoryTests.cs @@ -30,7 +30,8 @@ public async Task UpdateAsync_AttributesUpdated_ShouldHaveSpecificallyThoseAttri { // Arrange var itemId = 213; - using (var arrangeContext = GetContext()) + var seed = Guid.NewGuid(); + using (var arrangeContext = GetContext(seed)) { var (repository, targetedFields) = Setup(arrangeContext); var todoItemUpdates = new TodoItem @@ -38,6 +39,8 @@ public async Task UpdateAsync_AttributesUpdated_ShouldHaveSpecificallyThoseAttri Id = itemId, Description = Guid.NewGuid().ToString() }; + arrangeContext.Add(todoItemUpdates); + arrangeContext.SaveChanges(); var descAttr = new AttrAttribute("description", "Description") { @@ -51,7 +54,7 @@ public async Task UpdateAsync_AttributesUpdated_ShouldHaveSpecificallyThoseAttri } // Assert - in different context - using var assertContext = GetContext(); + using var assertContext = GetContext(seed); { var (repository, targetedFields) = Setup(assertContext); @@ -61,8 +64,79 @@ public async Task UpdateAsync_AttributesUpdated_ShouldHaveSpecificallyThoseAttri Assert.Equal(fetchedTodo.Description, fetchedTodo.Description); } + } + + [Theory] + [InlineData(3, 2, new[] { 4, 5, 6 })] + [InlineData(8, 2, new[] { 9 })] + [InlineData(20, 1, new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })] + public async Task Paging_PageNumberIsPositive_ReturnCorrectIdsAtTheFront(int pageSize, int pageNumber, int[] expectedResult) + { + // Arrange + using var context = GetContext(); + var (repository, targetedFields) = Setup(context); + context.AddRange(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)); + await context.SaveChangesAsync(); + + // Act + var result = await repository.PageAsync(context.Set(), pageSize, pageNumber); + + // Assert + Assert.Equal(TodoItems(expectedResult), result, new IdComparer()); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(-10)] + public async Task Paging_PageSizeNonPositive_DoNothing(int pageSize) + { + // Arrange + using var context = GetContext(); + var (repository, targetedFields) = Setup(context); + var items = TodoItems(2, 3, 1); + context.AddRange(items); + await context.SaveChangesAsync(); + + // Act + var result = await repository.PageAsync(context.Set(), pageSize, 3); + + // Assert + Assert.Equal(items.ToList(), result.ToList(), new IdComparer()); + } + [Fact] + public async Task Paging_PageNumberDoesNotExist_ReturnEmptyAQueryable() + { + // Arrange + var items = TodoItems(2, 3, 1); + using var context = GetContext(); + var (repository, targetedFields) = Setup(context); + context.AddRange(items); + + // Act + var result = await repository.PageAsync(context.Set(), 2, 3); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task Paging_PageNumberIsZero_PretendsItsOne() + { + // Arrange + using var context = GetContext(); + var (repository, targetedFields) = Setup(context); + context.AddRange(TodoItems(2, 3, 4, 5, 6, 7, 8, 9)); + await context.SaveChangesAsync(); + + // Act + var result = await repository.PageAsync(entities: context.Set(), pageSize: 1, pageNumber: 0); + + // Assert + Assert.Equal(TodoItems(2), result, new IdComparer()); } + [Theory] [InlineData(6, -1, new[] { 4, 5, 6, 7, 8, 9 })] [InlineData(6, -2, new[] { 1, 2, 3 })] @@ -93,16 +167,18 @@ public async Task Paging_PageNumberIsNegative_GiveBackReverseAmountOfIds(int pag return (repository, targetedFields); } - private AppDbContext GetContext() + private AppDbContext GetContext(Guid? seed = null) { + Guid actualSeed = seed == null ? Guid.NewGuid() : seed.GetValueOrDefault(); var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: "IntegrationDatabaseRepository") + .UseInMemoryDatabase(databaseName: $"IntegrationDatabaseRepository{actualSeed}") .Options; var context = new AppDbContext(options); context.TodoItems.RemoveRange(context.TodoItems.ToList()); return context; } + private static TodoItem[] TodoItems(params int[] ids) { return ids.Select(id => new TodoItem { Id = id }).ToArray(); diff --git a/test/UnitTests/Data/DefaultEntityRepositoryTests.cs b/test/UnitTests/Data/DefaultEntityRepositoryTests.cs index 17101d5234..de3ff0a412 100644 --- a/test/UnitTests/Data/DefaultEntityRepositoryTests.cs +++ b/test/UnitTests/Data/DefaultEntityRepositoryTests.cs @@ -60,55 +60,11 @@ private DefaultResourceRepository GetRepository() resourceGraph, null, null); } - [Theory] - [InlineData(0)] - [InlineData(-1)] - [InlineData(-10)] - public async Task Page_When_PageSize_Is_NonPositive_Does_Nothing(int pageSize) - { - var todoItems = DbSetMock.Create(TodoItems(2, 3, 1)).Object; - var repository = GetRepository(); - - var result = await repository.PageAsync(todoItems, pageSize, 3); - - Assert.Equal(TodoItems(2, 3, 1), result, new IdComparer()); - } - - [Fact] - public async Task Page_When_PageNumber_Is_Zero_Pretends_PageNumber_Is_One() - { - var todoItems = DbSetMock.Create(TodoItems(2, 3, 1)).Object; - var repository = GetRepository(); - - var result = await repository.PageAsync(todoItems, 1, 0); - Assert.Equal(TodoItems(2), result, new IdComparer()); - } - [Fact] - public async Task Page_When_PageNumber_Of_PageSize_Does_Not_Exist_Return_Empty_Queryable() - { - var todoItems = DbSetMock.Create(TodoItems(2, 3, 1)).Object; - var repository = GetRepository(); - var result = await repository.PageAsync(todoItems, 2, 3); - Assert.Empty(result); - } - [Theory] - [InlineData(3, 2, new[] { 4, 5, 6 })] - [InlineData(8, 2, new[] { 9 })] - [InlineData(20, 1, new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })] - public async Task Page_When_PageNumber_Is_Positive_Returns_PageNumberTh_Page_Of_Size_PageSize(int pageSize, int pageNumber, int[] expectedResult) - { - var todoItems = DbSetMock.Create(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)).Object; - var repository = GetRepository(); - - var result = await repository.PageAsync(todoItems, pageSize, pageNumber); - - Assert.Equal(TodoItems(expectedResult), result, new IdComparer()); - } private static TodoItem[] TodoItems(params int[] ids) { return ids.Select(id => new TodoItem { Id = id }).ToArray(); From 67dd3eb0018d26b1184de380e667888f74e39ad1 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 11:33:49 +0200 Subject: [PATCH 19/47] chore: should add logging, done. --- src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs | 5 +++++ .../Extensions/IServiceCollectionExtensions.cs | 1 + test/UnitTests/UnitTests.csproj | 2 +- 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs index 7942e3774c..2ebbb38e8a 100644 --- a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs @@ -42,6 +42,11 @@ public JsonApiApplicationBuilder(IServiceCollection services, IMvcCoreBuilder mv _mvcBuilder = mvcBuilder; } + internal void ConfigureLogging() + { + _services.AddLogging(); + } + /// /// Executes the action provided by the user to configure /// diff --git a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs index 5e37f416cb..75b9f4cda4 100644 --- a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs @@ -35,6 +35,7 @@ public static IServiceCollection AddJsonApi(this IServiceColle var application = new JsonApiApplicationBuilder(services, mvcBuilder ?? services.AddMvcCore()); if (options != null) application.ConfigureJsonApiOptions(options); + application.ConfigureLogging(); application.ConfigureMvc(); application.ConfigureResources(resources); application.ConfigureServices(); diff --git a/test/UnitTests/UnitTests.csproj b/test/UnitTests/UnitTests.csproj index 4897b8ae60..6a014e783c 100644 --- a/test/UnitTests/UnitTests.csproj +++ b/test/UnitTests/UnitTests.csproj @@ -8,7 +8,7 @@ - + From 15a9402dbc4c2e5eff0f4a669d54fafa177d5eb6 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 11:47:36 +0200 Subject: [PATCH 20/47] tests: bad response from tests --- Directory.Build.props | 4 ++-- .../Extensions/IApplicationBuilderExtensions.cs | 3 --- .../Acceptance/Extensibility/NoEntityFrameworkTests.cs | 6 +++--- .../Create/BeforeCreate_WithDbValues_Tests.cs | 8 ++++---- test/UnitTests/UnitTests.csproj | 2 +- 5 files changed, 10 insertions(+), 13 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 6b7a96b9ed..5014190440 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -8,8 +8,8 @@ 3.* 3.* 3.* - 4.0.0 - 2.1.0 + 4.1.1 + 3.0.1 4.5.0 diff --git a/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs b/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs index e7cbcce43d..0d7830d22a 100644 --- a/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs @@ -18,11 +18,8 @@ public static IApplicationBuilder UseJsonApi(this IApplicationBuilder app, bool { DisableDetailedErrorsIfProduction(app); LogResourceGraphValidations(app); - app.UseEndpointRouting(); - app.UseMiddleware(); - if (useMvc) app.UseMvc(); diff --git a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs index 4ff89428f2..1a9c45e5d2 100644 --- a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs +++ b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs @@ -72,7 +72,7 @@ public async Task Can_Get_TodoItems_By_Id() [Fact] public async Task Can_Create_TodoItems() { - // arrange + // Arrange var description = Guid.NewGuid().ToString(); var client = _fixture.Server.CreateClient(); var httpMethod = new HttpMethod("POST"); @@ -94,12 +94,12 @@ public async Task Can_Create_TodoItems() request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - // act + // Act var response = await client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); var deserializedBody = _fixture.GetDeserializer().DeserializeSingle(responseBody).Data; - // assert + // Assert Assert.Equal(HttpStatusCode.Created, response.StatusCode); Assert.NotNull(deserializedBody); Assert.Equal(description, deserializedBody.Description); diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs index 667f259591..0f1509e94e 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs @@ -1,4 +1,4 @@ -using JsonApiDotNetCore.Hooks; +using JsonApiDotNetCore.Hooks; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using Microsoft.EntityFrameworkCore; @@ -44,15 +44,15 @@ public BeforeCreate_WithDbValues_Tests() [Fact] public void BeforeCreate() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeCreate(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeCreate(It.Is>((entities) => TodoCheck(entities, description)), ResourcePipeline.Post), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship( It.Is>(ids => PersonIdCheck(ids, personId)), diff --git a/test/UnitTests/UnitTests.csproj b/test/UnitTests/UnitTests.csproj index 6a014e783c..6e60b7d4fe 100644 --- a/test/UnitTests/UnitTests.csproj +++ b/test/UnitTests/UnitTests.csproj @@ -9,7 +9,7 @@ - + From 153f9cb67d127837b0db5a9482a24cbc97fa55db Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 14:16:32 +0200 Subject: [PATCH 21/47] chore: fixes for lang version and making ifs more noticable --- .../Builders/JsonApiApplicationBuilder.cs | 1 + .../Data/DefaultResourceRepository.cs | 6 ------ .../IApplicationBuilderExtensions.cs | 19 ++++++++++++------- .../Internal/DefaultRoutingConvention.cs | 18 ++++++++++++++---- .../JsonApiDotNetCore.csproj | 8 ++++---- .../JsonApiDotNetCoreExampleTests.csproj | 2 +- 6 files changed, 32 insertions(+), 22 deletions(-) diff --git a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs index 2ebbb38e8a..c9ec937b7a 100644 --- a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs @@ -74,6 +74,7 @@ public void ConfigureMvc() mvcOptions.Filters.Add(typeMatchFilterProvider.Get()); mvcOptions.InputFormatters.Insert(0, new JsonApiInputFormatter()); mvcOptions.OutputFormatters.Insert(0, new JsonApiOutputFormatter()); + mvcOptions.EnableEndpointRouting = false; }); var routingConvention = intermediateProvider.GetRequiredService(); diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index aab99cc64f..bc03b712b8 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -262,7 +262,6 @@ public async Task UpdateRelationshipsAsync(object parent, RelationshipAttribute await helper.UpdateAsync((IIdentifiable)parent, hasManyThrough, relationshipIds); return; } - var context = _context.Set(relationship.RightType); var updatedValue = relationship is HasManyAttribute ? context.Where(e => relationshipIds.Contains(((IIdentifiable)e).StringId)).Cast(relationship.RightType) @@ -305,13 +304,8 @@ public virtual async Task> PageAsync(IQueryable + /// Adds necessary components such as routing to your application + ///
+ /// + /// + /// public static IApplicationBuilder UseJsonApi(this IApplicationBuilder app, bool useMvc = true) { DisableDetailedErrorsIfProduction(app); LogResourceGraphValidations(app); - app.UseEndpointRouting(); app.UseMiddleware(); + app.UseRouting(); if (useMvc) + { app.UseMvc(); - + } using (var scope = app.ApplicationServices.CreateScope()) { var inverseRelationshipResolver = scope.ServiceProvider.GetService(); inverseRelationshipResolver?.Resolve(); } - return app; } private static void DisableDetailedErrorsIfProduction(IApplicationBuilder app) { - var environment = (IHostingEnvironment)app.ApplicationServices.GetService(typeof(IHostingEnvironment)); - - if (environment.IsProduction()) + var webHostEnvironment = (IWebHostEnvironment) app.ApplicationServices.GetService(typeof(IWebHostEnvironment)); + if (webHostEnvironment.EnvironmentName == "Production") { JsonApiOptions.DisableErrorStackTraces = true; JsonApiOptions.DisableErrorSource = true; diff --git a/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs b/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs index cf25305ca8..eb68142e31 100644 --- a/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs +++ b/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs @@ -73,7 +73,7 @@ public void Apply(ApplicationModel application) } /// - /// verifies if routing convention should be enabled for this controller + /// Verifies if routing convention should be enabled for this controller /// private bool RoutingConventionDisabled(ControllerModel controller) { @@ -90,9 +90,10 @@ private string TemplateFromResource(ControllerModel model) if (_registeredResources.TryGetValue(model.ControllerName, out Type resourceType)) { var template = $"{_namespace}/{_formatter.FormatResourceName(resourceType)}"; - if (_registeredTemplates.Add(template)) + if (_registeredTemplates.Add(template)) + { return template; - + } } return null; } @@ -104,8 +105,13 @@ private string TemplateFromController(ControllerModel model) { var template = $"{_namespace}/{_formatter.ApplyCasingConvention(model.ControllerName)}"; if (_registeredTemplates.Add(template)) + { return template; - return null; + } + else + { + return null; + } } /// @@ -126,12 +132,16 @@ private Type GetResourceTypeFromController(Type type) { var potentialResource = currentBaseType.GetGenericArguments().FirstOrDefault(t => t.Inherits(identifiable)); if (potentialResource != null) + { return potentialResource; + } } currentBaseType = nextBaseType; if (nextBaseType == null) + { break; + } } return currentBaseType?.GetGenericArguments().First(); } diff --git a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj index 25b446f41e..b747656b40 100644 --- a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj +++ b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj @@ -1,10 +1,10 @@  4.0.0 - $(NetStandardVersion) + $(NetCoreAppVersion) JsonApiDotNetCore JsonApiDotNetCore - 7.2 + 8.0 @@ -20,10 +20,10 @@ + - - + diff --git a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj index d16ba1c471..a63c50f6cf 100644 --- a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj +++ b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj @@ -1,4 +1,4 @@ - + $(NetCoreAppVersion) false From 9e6c36be79af2689b0a755b3b386be4515481d13 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 15:02:24 +0200 Subject: [PATCH 22/47] fix: fix routing issue with upgrade to enableendpointrouting --- .../Builders/JsonApiApplicationBuilder.cs | 18 ++++++++-------- .../IApplicationBuilderExtensions.cs | 21 ++++++++++++------- .../Middleware/CurrentRequestMiddleware.cs | 2 ++ .../CamelCasedModelsControllerTests.cs | 5 +++-- 4 files changed, 27 insertions(+), 19 deletions(-) diff --git a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs index c9ec937b7a..124af121a2 100644 --- a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs @@ -68,17 +68,17 @@ public void ConfigureMvc() var exceptionFilterProvider = intermediateProvider.GetRequiredService(); var typeMatchFilterProvider = intermediateProvider.GetRequiredService(); - _mvcBuilder.AddMvcOptions(mvcOptions => + var routingConvention = intermediateProvider.GetRequiredService(); + + _mvcBuilder.AddMvcOptions(options => { - mvcOptions.Filters.Add(exceptionFilterProvider.Get()); - mvcOptions.Filters.Add(typeMatchFilterProvider.Get()); - mvcOptions.InputFormatters.Insert(0, new JsonApiInputFormatter()); - mvcOptions.OutputFormatters.Insert(0, new JsonApiOutputFormatter()); - mvcOptions.EnableEndpointRouting = false; + options.EnableEndpointRouting = true; + options.Filters.Add(exceptionFilterProvider.Get()); + options.Filters.Add(typeMatchFilterProvider.Get()); + options.InputFormatters.Insert(0, new JsonApiInputFormatter()); + options.OutputFormatters.Insert(0, new JsonApiOutputFormatter()); + options.Conventions.Insert(0, routingConvention); }); - - var routingConvention = intermediateProvider.GetRequiredService(); - _mvcBuilder.AddMvcOptions(opt => opt.Conventions.Insert(0, routingConvention)); _services.AddSingleton(routingConvention); } diff --git a/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs b/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs index 06df7d3c00..925d2ab1e2 100644 --- a/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs @@ -20,22 +20,27 @@ public static class IApplicationBuilderExtensions /// /// /// - public static IApplicationBuilder UseJsonApi(this IApplicationBuilder app, bool useMvc = true) + public static void UseJsonApi(this IApplicationBuilder app) { DisableDetailedErrorsIfProduction(app); LogResourceGraphValidations(app); - app.UseMiddleware(); - app.UseRouting(); - if (useMvc) - { - app.UseMvc(); - } using (var scope = app.ApplicationServices.CreateScope()) { var inverseRelationshipResolver = scope.ServiceProvider.GetService(); inverseRelationshipResolver?.Resolve(); } - return app; + + // An endpoint is selected and set on the HttpContext if a match is found + app.UseRouting(); + + // middleware to run after routing occurs. + app.UseMiddleware(); + + // Executes the endpoitns that was selected by routing. + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); } private static void DisableDetailedErrorsIfProduction(IApplicationBuilder app) diff --git a/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs b/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs index 8b8027120a..c14aec358b 100644 --- a/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs +++ b/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs @@ -138,7 +138,9 @@ internal static bool ContainsMediaTypeParameters(string mediaType) // if the content type is not application/vnd.api+json then continue on if (incomingMediaTypeSpan.Length < Constants.ContentType.Length) + { return false; + } var incomingContentType = incomingMediaTypeSpan.Slice(0, Constants.ContentType.Length); if (incomingContentType.SequenceEqual(Constants.ContentType.AsSpan()) == false) diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs index 8399ff36ed..23e53e3096 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs @@ -123,7 +123,7 @@ public async Task Can_Post_CamelCasedModels() } [Fact] - public async Task Can_Patch_CamelCasedModels() + public async Task RoutingPatch_RouteIsCamelcased_ResponseOKAndCompoundAttrIsAvailable() { // Arrange var model = _faker.Generate(); @@ -146,7 +146,8 @@ public async Task Can_Patch_CamelCasedModels() var httpMethod = new HttpMethod("PATCH"); var route = $"api/v1/camelCasedModels/{model.Id}"; var builder = new WebHostBuilder().UseStartup(); - var server = new TestServer(builder); + + using var server = new TestServer(builder); var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); request.Content = new StringContent(JsonConvert.SerializeObject(content)); From bf72324c6eca11a0c56832c678f9cd4e6dd47498 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 15:41:59 +0200 Subject: [PATCH 23/47] chore: HostEnvironment -> IWebHostEnvironment --- .../JsonApiDotNetCoreExample/Startup.cs | 5 ++-- .../NoEntityFrameworkExample/Startup.cs | 5 ++-- .../Builders/JsonApiApplicationBuilder.cs | 3 +-- .../Extensions/ModelStateExtensions.cs | 11 ++++++-- .../Formatters/JsonApiReader.cs | 27 ++++++++++++------- .../CamelCasedModelsControllerTests.cs | 2 +- .../Acceptance/ManyToManyTests.cs | 8 +++--- .../TestStartup.cs | 10 ++++--- 8 files changed, 42 insertions(+), 29 deletions(-) diff --git a/src/Examples/JsonApiDotNetCoreExample/Startup.cs b/src/Examples/JsonApiDotNetCoreExample/Startup.cs index 95ef8f3a74..8f72848359 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startup.cs @@ -14,7 +14,7 @@ public class Startup { public readonly IConfiguration Config; - public Startup(IHostingEnvironment env) + public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) @@ -25,7 +25,7 @@ public Startup(IHostingEnvironment env) Config = builder.Build(); } - public virtual IServiceProvider ConfigureServices(IServiceCollection services) + public virtual void ConfigureServices(IServiceCollection services) { var loggerFactory = new LoggerFactory(); services @@ -45,7 +45,6 @@ public virtual IServiceProvider ConfigureServices(IServiceCollection services) options.LoaDatabaseValues = true; }, discovery => discovery.AddCurrentAssembly()); - return services.BuildServiceProvider(); } public virtual void Configure( diff --git a/src/Examples/NoEntityFrameworkExample/Startup.cs b/src/Examples/NoEntityFrameworkExample/Startup.cs index a438ff9336..7948e6e183 100644 --- a/src/Examples/NoEntityFrameworkExample/Startup.cs +++ b/src/Examples/NoEntityFrameworkExample/Startup.cs @@ -15,7 +15,7 @@ namespace NoEntityFrameworkExample { public class Startup { - public Startup(IHostingEnvironment env) + public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) @@ -28,7 +28,7 @@ public Startup(IHostingEnvironment env) public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. - public virtual IServiceProvider ConfigureServices(IServiceCollection services) + public virtual void ConfigureServices(IServiceCollection services) { // Add framework services. var mvcBuilder = services.AddMvcCore(); @@ -47,7 +47,6 @@ public virtual IServiceProvider ConfigureServices(IServiceCollection services) services.AddSingleton(Configuration); services.AddSingleton(optionsBuilder.Options); services.AddScoped(); - return services.BuildServiceProvider(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs index 124af121a2..ffe3571f19 100644 --- a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs @@ -67,7 +67,6 @@ public void ConfigureMvc() _serviceDiscoveryFacade = intermediateProvider.GetRequiredService(); var exceptionFilterProvider = intermediateProvider.GetRequiredService(); var typeMatchFilterProvider = intermediateProvider.GetRequiredService(); - var routingConvention = intermediateProvider.GetRequiredService(); _mvcBuilder.AddMvcOptions(options => @@ -154,7 +153,7 @@ public void ConfigureServices() _services.AddSingleton(JsonApiOptions); _services.AddSingleton(resourceGraph); _services.AddSingleton(); - _services.AddSingleton(resourceGraph); + _services.AddSingleton(resourceGraph); _services.AddSingleton(resourceGraph); _services.AddScoped(); _services.AddScoped(); diff --git a/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs b/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs index 1c0e233ebb..262e81678e 100644 --- a/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs @@ -15,7 +15,9 @@ public static ErrorCollection ConvertToErrorCollection(this ModelStateDiction foreach (var entry in modelState) { if (entry.Value.Errors.Any() == false) + { continue; + } var targetedProperty = resourceType.GetProperty(entry.Key); var attrName = targetedProperty.GetCustomAttribute().PublicAttributeName; @@ -23,16 +25,21 @@ public static ErrorCollection ConvertToErrorCollection(this ModelStateDiction foreach (var modelError in entry.Value.Errors) { if (modelError.Exception is JsonApiException jex) + { collection.Errors.AddRange(jex.GetError().Errors); + } else + { collection.Errors.Add(new Error( status: 422, title: entry.Key, detail: modelError.ErrorMessage, meta: modelError.Exception != null ? ErrorMeta.FromException(modelError.Exception) : null, - source: attrName == null ? null : new { + source: attrName == null ? null : new + { pointer = $"/data/attributes/{attrName}" - })); + })); + } } } return collection; diff --git a/src/JsonApiDotNetCore/Formatters/JsonApiReader.cs b/src/JsonApiDotNetCore/Formatters/JsonApiReader.cs index d00f47526e..69d04ed3cc 100644 --- a/src/JsonApiDotNetCore/Formatters/JsonApiReader.cs +++ b/src/JsonApiDotNetCore/Formatters/JsonApiReader.cs @@ -23,26 +23,25 @@ public JsonApiReader(IJsonApiDeserializer deserializer, _logger = loggerFactory.CreateLogger(); } - public Task ReadAsync(InputFormatterContext context) + public async Task ReadAsync(InputFormatterContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var request = context.HttpContext.Request; if (request.ContentLength == 0) - return InputFormatterResult.SuccessAsync(null); + { + return await InputFormatterResult.SuccessAsync(null); + } try { - var body = GetRequestBody(context.HttpContext.Request.Body); - + var body = await GetRequestBody(context.HttpContext.Request.Body); object model = _deserializer.Deserialize(body); - if (model == null) { _logger?.LogError("An error occurred while de-serializing the payload"); } - if (context.HttpContext.Request.Method == "PATCH") { bool idMissing; @@ -60,13 +59,13 @@ public Task ReadAsync(InputFormatterContext context) throw new JsonApiException(400, "Payload must include id attribute"); } } - return InputFormatterResult.SuccessAsync(model); + return await InputFormatterResult.SuccessAsync(model); } catch (Exception ex) { _logger?.LogError(new EventId(), ex, "An error occurred while de-serializing the payload"); context.ModelState.AddModelError(context.ModelName, ex, context.Metadata); - return InputFormatterResult.FailureAsync(); + return await InputFormatterResult.FailureAsync(); } } @@ -103,11 +102,19 @@ private bool CheckForId(IList modelList) return false; } - private string GetRequestBody(Stream body) + /// + /// Fetches the request from body asynchronously. + /// + /// Input stream for body + /// String content of body sent to server. + private async Task GetRequestBody(Stream body) { using (var reader = new StreamReader(body)) { - return reader.ReadToEnd(); + // This needs to be set to async because + // Synchronous IO operations are + // https://github.com/aspnet/AspNetCore/issues/7644 + return await reader.ReadToEndAsync(); } } } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs index 23e53e3096..a968d8f2c5 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs @@ -143,7 +143,7 @@ public async Task RoutingPatch_RouteIsCamelcased_ResponseOKAndCompoundAttrIsAvai } } }; - var httpMethod = new HttpMethod("PATCH"); + var httpMethod = HttpMethod.Patch; var route = $"api/v1/camelCasedModels/{model.Id}"; var builder = new WebHostBuilder().UseStartup(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs index 4fe635952d..fb6db14b99 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs @@ -8,6 +8,7 @@ using JsonApiDotNetCore.Models; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; +using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using Xunit; @@ -204,7 +205,7 @@ public async Task Can_Fetch_Many_To_Many_Without_Include() [Fact] public async Task Can_Create_Many_To_Many() { - // arrange + // Arrange var context = _fixture.GetService(); var tag = _tagFaker.Generate(); var author = new Author(); @@ -242,14 +243,13 @@ public async Task Can_Create_Many_To_Many() } } }; - request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - // act + // Act var response = await _fixture.Client.SendAsync(request); - // assert + // Assert var body = await response.Content.ReadAsStringAsync(); Assert.True(HttpStatusCode.Created == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}"); diff --git a/test/JsonApiDotNetCoreExampleTests/TestStartup.cs b/test/JsonApiDotNetCoreExampleTests/TestStartup.cs index 1ea3c03f55..be4f0f08fc 100644 --- a/test/JsonApiDotNetCoreExampleTests/TestStartup.cs +++ b/test/JsonApiDotNetCoreExampleTests/TestStartup.cs @@ -1,8 +1,11 @@ using JsonApiDotNetCore.Extensions; using JsonApiDotNetCore.Services; using JsonApiDotNetCoreExample; +using JsonApiDotNetCoreExample.Data; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using System; using UnitTests; @@ -10,15 +13,14 @@ namespace JsonApiDotNetCoreExampleTests { public class TestStartup : Startup { - public TestStartup(IHostingEnvironment env) : base(env) + public TestStartup(IWebHostEnvironment env) : base(env) { } - public override IServiceProvider ConfigureServices(IServiceCollection services) + public override void ConfigureServices(IServiceCollection services) { base.ConfigureServices(services); services.AddClientSerialization(); services.AddScoped(); - return services.BuildServiceProvider(); } } -} \ No newline at end of file +} From 07840c4d3c4078186799e5ac2f208450a2ecd43b Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 16:18:47 +0200 Subject: [PATCH 24/47] chore: act -> Act, assert -> Assert, arrange -> Arrange --- src/Examples/GettingStarted/Startup.cs | 5 +- .../JsonApiDotNetCoreExample/Startup.cs | 1 - src/Examples/ReportsExample/Startup.cs | 7 +- .../ServiceDiscoveryFacadeTests.cs | 174 +++++++++--------- .../CamelCasedModelsControllerTests.cs | 6 +- .../Extensibility/CustomControllerTests.cs | 14 +- .../NullValuedAttributeHandlingTests.cs | 4 +- .../Extensibility/RequestMetaTests.cs | 6 +- .../HttpReadOnlyTests.cs | 18 +- .../NoHttpDeleteTests.cs | 26 +-- .../NoHttpPatchTests.cs | 26 +-- .../HttpMethodRestrictions/NoHttpPostTests.cs | 26 +-- .../Acceptance/ManyToManyTests.cs | 135 ++++++++++---- .../Acceptance/Spec/AttributeFilterTests.cs | 42 ++--- .../Acceptance/Spec/AttributeSortTests.cs | 6 +- .../Acceptance/Spec/ContentNegotiation.cs | 18 +- .../Acceptance/Spec/CreatingDataTests.cs | 70 +++---- .../Spec/DeeplyNestedInclusionTests.cs | 40 ++-- .../Acceptance/Spec/DeletingDataTests.cs | 2 +- .../Acceptance/Spec/DocumentTests/Included.cs | 66 +++---- .../Acceptance/Spec/DocumentTests/Meta.cs | 30 +-- .../Spec/DocumentTests/PagingTests.cs | 6 +- .../Spec/DocumentTests/Relationships.cs | 24 +-- .../Acceptance/Spec/FetchingDataTests.cs | 12 +- .../Spec/FetchingRelationshipsTests.cs | 12 +- .../Acceptance/Spec/QueryParameters.cs | 6 +- .../Acceptance/Spec/SparseFieldSetTests.cs | 32 ++-- .../Acceptance/Spec/UpdatingDataTests.cs | 6 +- .../Spec/UpdatingRelationshipsTests.cs | 16 +- .../Acceptance/TestFixture.cs | 3 +- .../CamelCaseTestStartup.cs | 5 +- .../Startups/ClientGeneratedIdsStartup.cs | 7 +- .../Helpers/Startups/MetaStartup.cs | 6 +- .../Extensibility/NoEntityFrameworkTests.cs | 12 +- test/NoEntityFrameworkTests/TestStartup.cs | 6 +- .../Builders/ContextGraphBuilder_Tests.cs | 36 ++-- test/UnitTests/Builders/LinkBuilderTests.cs | 18 +- test/UnitTests/Builders/MetaBuilderTests.cs | 18 +- .../BaseJsonApiController_Tests.cs | 108 +++++------ .../JsonApiControllerMixin_Tests.cs | 112 +++++------ .../IServiceCollectionExtensionsTests.cs | 28 +-- .../Extensions/TypeExtensions_Tests.cs | 24 +-- test/UnitTests/Graph/TypeLocator_Tests.cs | 34 ++-- .../Internal/ContextGraphBuilder_Tests.cs | 12 +- test/UnitTests/Internal/TypeHelper_Tests.cs | 40 ++-- test/UnitTests/Models/LinkTests.cs | 20 +- .../UnitTests/Models/RelationshipDataTests.cs | 24 +-- .../Models/ResourceDefinitionTests.cs | 14 +- .../QueryParameters/FilterServiceTests.cs | 14 +- .../QueryParameters/IncludeServiceTests.cs | 28 +-- .../QueryParameters/OmitDefaultService.cs | 14 +- .../QueryParameters/OmitNullService.cs | 14 +- .../QueryParameters/PageServiceTests.cs | 16 +- .../QueryParameters/SortServiceTests.cs | 12 +- .../SparseFieldsServiceTests.cs | 26 +-- .../AffectedEntitiesHelperTests.cs | 34 ++-- .../UnitTests/ResourceHooks/DiscoveryTests.cs | 12 +- .../Create/AfterCreateTests.cs | 24 +-- .../Create/BeforeCreateTests.cs | 24 +-- .../Create/BeforeCreate_WithDbValues_Tests.cs | 30 +-- .../Delete/AfterDeleteTests.cs | 6 +- .../Delete/BeforeDeleteTests.cs | 12 +- .../Delete/BeforeDelete_WithDbValue_Tests.cs | 18 +- .../IdentifiableManyToMany_OnReturnTests.cs | 40 ++-- .../ManyToMany_OnReturnTests.cs | 22 +-- .../Read/BeforeReadTests.cs | 42 ++--- .../IdentifiableManyToMany_AfterReadTests.cs | 34 ++-- .../Read/ManyToMany_AfterReadTests.cs | 24 +-- .../ResourceHookExecutor/ScenarioTests.cs | 18 +- .../Update/AfterUpdateTests.cs | 24 +-- .../Update/BeforeUpdateTests.cs | 24 +-- .../Update/BeforeUpdate_WithDbValues_Tests.cs | 42 ++--- .../Client/RequestSerializerTests.cs | 48 ++--- .../Client/ResponseDeserializerTests.cs | 54 +++--- .../Common/DocumentBuilderTests.cs | 24 +-- .../Common/DocumentParserTests.cs | 92 ++++----- .../Common/ResourceObjectBuilderTests.cs | 62 +++---- .../IncludedResourceObjectBuilderTests.cs | 18 +- .../Server/RequestDeserializerTests.cs | 22 +-- .../ResponseResourceObjectBuilderTests.cs | 24 +-- .../Server/ResponseSerializerTests.cs | 84 ++++----- .../Services/EntityResourceService_Tests.cs | 12 +- 82 files changed, 1202 insertions(+), 1155 deletions(-) diff --git a/src/Examples/GettingStarted/Startup.cs b/src/Examples/GettingStarted/Startup.cs index f3e98948c8..296bcefe11 100644 --- a/src/Examples/GettingStarted/Startup.cs +++ b/src/Examples/GettingStarted/Startup.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; @@ -21,11 +21,10 @@ public void ConfigureServices(IServiceCollection services) discover => discover.AddCurrentAssembly(), mvcBuilder: mvcBuilder); } - public void Configure(IApplicationBuilder app, IHostingEnvironment env, SampleDbContext context) + public void Configure(IApplicationBuilder app, SampleDbContext context) { context.Database.EnsureDeleted(); // indicies need to be reset context.Database.EnsureCreated(); - app.UseJsonApi(); } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Startup.cs b/src/Examples/JsonApiDotNetCoreExample/Startup.cs index 8f72848359..a6ec145a29 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startup.cs @@ -21,7 +21,6 @@ public Startup(IWebHostEnvironment env) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); - Config = builder.Build(); } diff --git a/src/Examples/ReportsExample/Startup.cs b/src/Examples/ReportsExample/Startup.cs index 609847fa04..480f2a0f62 100644 --- a/src/Examples/ReportsExample/Startup.cs +++ b/src/Examples/ReportsExample/Startup.cs @@ -11,7 +11,7 @@ public class Startup { public readonly IConfiguration Config; - public Startup(IHostingEnvironment env) + public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) @@ -29,10 +29,5 @@ public virtual void ConfigureServices(IServiceCollection services) opt => opt.Namespace = "api", discovery => discovery.AddCurrentAssembly(), mvcBuilder: mvcBuilder); } - - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) - { - app.UseMvc(); - } } } diff --git a/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs b/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs index f7f643428f..cf87a3f537 100644 --- a/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs +++ b/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs @@ -1,105 +1,105 @@ -using System.Collections.Generic; -using GettingStarted.Models; -using GettingStarted.ResourceDefinitionExample; -using JsonApiDotNetCore.Builders; +using System.Collections.Generic; +using GettingStarted.Models; +using GettingStarted.ResourceDefinitionExample; +using JsonApiDotNetCore.Builders; using JsonApiDotNetCore.Configuration; -using JsonApiDotNetCore.Data; -using JsonApiDotNetCore.Graph; +using JsonApiDotNetCore.Data; +using JsonApiDotNetCore.Graph; using JsonApiDotNetCore.Hooks; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Internal.Generics; using JsonApiDotNetCore.Managers.Contracts; -using JsonApiDotNetCore.Models; +using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Query; using JsonApiDotNetCore.Serialization; using JsonApiDotNetCore.Serialization.Server.Builders; -using JsonApiDotNetCore.Services; +using JsonApiDotNetCore.Services; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Moq; -using Xunit; - -namespace DiscoveryTests -{ - public class ServiceDiscoveryFacadeTests - { - private readonly IServiceCollection _services = new ServiceCollection(); +using Moq; +using Xunit; + +namespace DiscoveryTests +{ + public class ServiceDiscoveryFacadeTests + { + private readonly IServiceCollection _services = new ServiceCollection(); private readonly ResourceGraphBuilder _resourceGraphBuilder = new ResourceGraphBuilder(); public ServiceDiscoveryFacadeTests() { - var contextMock = new Mock(); - var dbResolverMock = new Mock(); - dbResolverMock.Setup(m => m.GetContext()).Returns(new Mock().Object); + var contextMock = new Mock(); + var dbResolverMock = new Mock(); + dbResolverMock.Setup(m => m.GetContext()).Returns(new Mock().Object); TestModelRepository._dbContextResolver = dbResolverMock.Object; - _services.AddSingleton(new JsonApiOptions()); + _services.AddSingleton(new JsonApiOptions()); _services.AddScoped((_) => new Mock().Object); - _services.AddScoped((_) => new Mock().Object); - _services.AddScoped((_) => new Mock().Object); + _services.AddScoped((_) => new Mock().Object); + _services.AddScoped((_) => new Mock().Object); _services.AddScoped((_) => new Mock().Object); _services.AddScoped((_) => new Mock().Object); _services.AddScoped((_) => new Mock().Object); } - private ServiceDiscoveryFacade _facade => new ServiceDiscoveryFacade(_services, _resourceGraphBuilder); - - [Fact] - public void AddAssembly_Adds_All_Resources_To_Graph() - { - // arrange, act - _facade.AddAssembly(typeof(Person).Assembly); - - // assert - var resourceGraph = _resourceGraphBuilder.Build(); - var personResource = resourceGraph.GetResourceContext(typeof(Person)); - var articleResource = resourceGraph.GetResourceContext(typeof(Article)); - var modelResource = resourceGraph.GetResourceContext(typeof(Model)); - - Assert.NotNull(personResource); - Assert.NotNull(articleResource); - Assert.NotNull(modelResource); - } - - [Fact] - public void AddCurrentAssembly_Adds_Resources_To_Graph() - { - // arrange, act - _facade.AddCurrentAssembly(); - - // assert - var resourceGraph = _resourceGraphBuilder.Build(); - var testModelResource = resourceGraph.GetResourceContext(typeof(TestModel)); - Assert.NotNull(testModelResource); - } - - [Fact] - public void AddCurrentAssembly_Adds_Services_To_Container() + private ServiceDiscoveryFacade _facade => new ServiceDiscoveryFacade(_services, _resourceGraphBuilder); + + [Fact] + public void AddAssembly_Adds_All_Resources_To_Graph() + { + // Arrange, act + _facade.AddAssembly(typeof(Person).Assembly); + + // Assert + var resourceGraph = _resourceGraphBuilder.Build(); + var personResource = resourceGraph.GetResourceContext(typeof(Person)); + var articleResource = resourceGraph.GetResourceContext(typeof(Article)); + var modelResource = resourceGraph.GetResourceContext(typeof(Model)); + + Assert.NotNull(personResource); + Assert.NotNull(articleResource); + Assert.NotNull(modelResource); + } + + [Fact] + public void AddCurrentAssembly_Adds_Resources_To_Graph() + { + // Arrange, act + _facade.AddCurrentAssembly(); + + // Assert + var resourceGraph = _resourceGraphBuilder.Build(); + var testModelResource = resourceGraph.GetResourceContext(typeof(TestModel)); + Assert.NotNull(testModelResource); + } + + [Fact] + public void AddCurrentAssembly_Adds_Services_To_Container() + { + // Arrange, act + _facade.AddCurrentAssembly(); + + // Assert + var services = _services.BuildServiceProvider(); + var service = services.GetService>(); + Assert.IsType(service); + } + + [Fact] + public void AddCurrentAssembly_Adds_Repositories_To_Container() + { + // Arrange, act + _facade.AddCurrentAssembly(); + + // Assert + var services = _services.BuildServiceProvider(); + Assert.IsType(services.GetService>()); + } + + public class TestModel : Identifiable { } + + public class TestModelService : DefaultResourceService { - // arrange, act - _facade.AddCurrentAssembly(); - - // assert - var services = _services.BuildServiceProvider(); - var service = services.GetService>(); - Assert.IsType(service); - } - - [Fact] - public void AddCurrentAssembly_Adds_Repositories_To_Container() - { - // arrange, act - _facade.AddCurrentAssembly(); - - // assert - var services = _services.BuildServiceProvider(); - Assert.IsType(services.GetService>()); - } - - public class TestModel : Identifiable { } - - public class TestModelService : DefaultResourceService - { private static IResourceRepository _repo = new Mock>().Object; public TestModelService(IEnumerable queryParameters, @@ -109,16 +109,16 @@ public TestModelService(IEnumerable queryParameters, IResourceHookExecutor hookExecutor = null, ILoggerFactory loggerFactory = null) : base(queryParameters, options, repository, provider, hookExecutor, loggerFactory) { } - } - - public class TestModelRepository : DefaultResourceRepository - { + } + + public class TestModelRepository : DefaultResourceRepository + { internal static IDbContextResolver _dbContextResolver; public TestModelRepository(ITargetedFields targetedFields, IResourceGraph resourceGraph, IGenericServiceFactory genericServiceFactory) : base(targetedFields, _dbContextResolver, resourceGraph, genericServiceFactory) { } - } - } -} + } + } +} diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs index a968d8f2c5..7c98e7e2c4 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs @@ -66,11 +66,13 @@ public async Task Can_Get_CamelCasedModels_ById() var httpMethod = new HttpMethod("GET"); var route = $"api/v1/camelCasedModels/{model.Id}"; + var request = new HttpRequestMessage(httpMethod, route); + + // unnecessary, will fix in 4.1 var builder = new WebHostBuilder() - .UseStartup(); + .UseStartup(); var server = new TestServer(builder); var client = server.CreateClient(); - var request = new HttpRequestMessage(httpMethod, route); // Act var response = await client.SendAsync(request); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs index 04b530eab8..dc5a564fed 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs @@ -35,7 +35,7 @@ public CustomControllerTests(TestFixture fixture) [Fact] public async Task NonJsonApiControllers_DoNotUse_Dasherized_Routes() { - // arrange + // Arrange var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); @@ -45,10 +45,10 @@ public async Task NonJsonApiControllers_DoNotUse_Dasherized_Routes() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); } @@ -65,10 +65,10 @@ public async Task CustomRouteControllers_Uses_Dasherized_Collection_Route() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); } @@ -92,10 +92,10 @@ public async Task CustomRouteControllers_Uses_Dasherized_Item_Route() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs index 0f2026e07c..3ca3796100 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs @@ -86,12 +86,12 @@ public async Task CheckNullBehaviorCombination(bool? omitNullValuedAttributes, b var route = $"/api/v1/todo-items/{_todoItem.Id}?include=owner{queryString}"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var deserializeBody = JsonConvert.DeserializeObject(body); - // assert: does response contain a null valued attribute? + // Assert: does response contain a null valued attribute? Assert.Equal(omitsNulls, !deserializeBody.SingleData.Attributes.ContainsKey("description")); Assert.Equal(omitsNulls, !deserializeBody.Included[0].Attributes.ContainsKey("last-name")); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs index 31fe906e4a..69eef90224 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs @@ -26,7 +26,7 @@ public RequestMetaTests(TestFixture fixture) [Fact] public async Task Injecting_IRequestMeta_Adds_Meta_Data() { - // arrange + // Arrange var builder = new WebHostBuilder() .UseStartup(); @@ -38,12 +38,12 @@ public async Task Injecting_IRequestMeta_Adds_Meta_Data() var request = new HttpRequestMessage(httpMethod, route); var expectedMeta = (_fixture.GetService>() as IHasMeta).GetMeta(); - // act + // Act var response = await client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var meta = _fixture.GetDeserializer().DeserializeList(body).Meta; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(meta); Assert.NotNull(expectedMeta); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/HttpReadOnlyTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/HttpReadOnlyTests.cs index 88906ba7ab..0d3de444ee 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/HttpReadOnlyTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/HttpReadOnlyTests.cs @@ -28,42 +28,42 @@ public async Task Allows_GET_Requests() [Fact] public async Task Rejects_POST_Requests() { - // arrange + // Arrange const string route = "readonly"; const string method = "POST"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.MethodNotAllowed, statusCode); } [Fact] public async Task Rejects_PATCH_Requests() { - // arrange + // Arrange const string route = "readonly"; const string method = "PATCH"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.MethodNotAllowed, statusCode); } [Fact] public async Task Rejects_DELETE_Requests() { - // arrange + // Arrange const string route = "readonly"; const string method = "DELETE"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.MethodNotAllowed, statusCode); } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpDeleteTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpDeleteTests.cs index 32e7eaf109..e7aa542d9a 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpDeleteTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpDeleteTests.cs @@ -14,56 +14,56 @@ public class nohttpdeleteTests [Fact] public async Task Allows_GET_Requests() { - // arrange + // Arrange const string route = "nohttpdelete"; const string method = "GET"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, statusCode); } [Fact] public async Task Allows_POST_Requests() { - // arrange + // Arrange const string route = "nohttpdelete"; const string method = "POST"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, statusCode); } [Fact] public async Task Allows_PATCH_Requests() { - // arrange + // Arrange const string route = "nohttpdelete"; const string method = "PATCH"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, statusCode); } [Fact] public async Task Rejects_DELETE_Requests() { - // arrange + // Arrange const string route = "nohttpdelete"; const string method = "DELETE"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.MethodNotAllowed, statusCode); } @@ -79,4 +79,4 @@ private async Task MakeRequestAsync(string route, string method) return response.StatusCode; } } -} \ No newline at end of file +} diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPatchTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPatchTests.cs index 5b8a33f16a..573b8dccf7 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPatchTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPatchTests.cs @@ -14,56 +14,56 @@ public class nohttppatchTests [Fact] public async Task Allows_GET_Requests() { - // arrange + // Arrange const string route = "nohttppatch"; const string method = "GET"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, statusCode); } [Fact] public async Task Allows_POST_Requests() { - // arrange + // Arrange const string route = "nohttppatch"; const string method = "POST"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, statusCode); } [Fact] public async Task Rejects_PATCH_Requests() { - // arrange + // Arrange const string route = "nohttppatch"; const string method = "PATCH"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.MethodNotAllowed, statusCode); } [Fact] public async Task Allows_DELETE_Requests() { - // arrange + // Arrange const string route = "nohttppatch"; const string method = "DELETE"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, statusCode); } @@ -79,4 +79,4 @@ private async Task MakeRequestAsync(string route, string method) return response.StatusCode; } } -} \ No newline at end of file +} diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPostTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPostTests.cs index f68a65a037..b1dda90c29 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPostTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPostTests.cs @@ -14,56 +14,56 @@ public class NoHttpPostTests [Fact] public async Task Allows_GET_Requests() { - // arrange + // Arrange const string route = "nohttppost"; const string method = "GET"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, statusCode); } [Fact] public async Task Rejects_POST_Requests() { - // arrange + // Arrange const string route = "nohttppost"; const string method = "POST"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.MethodNotAllowed, statusCode); } [Fact] public async Task Allows_PATCH_Requests() { - // arrange + // Arrange const string route = "nohttppost"; const string method = "PATCH"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, statusCode); } [Fact] public async Task Allows_DELETE_Requests() { - // arrange + // Arrange const string route = "nohttppost"; const string method = "DELETE"; - // act + // Act var statusCode = await MakeRequestAsync(route, method); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, statusCode); } @@ -79,4 +79,4 @@ private async Task MakeRequestAsync(string route, string method) return response.StatusCode; } } -} \ No newline at end of file +} diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs index fb6db14b99..be570c0dbc 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs @@ -6,8 +6,10 @@ using System.Threading.Tasks; using Bogus; using JsonApiDotNetCore.Models; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; +using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; @@ -33,7 +35,7 @@ public ManyToManyTests(TestFixture fixture) [Fact] public async Task Can_Fetch_Many_To_Many_Through_All() { - // arrange + // Arrange var context = _fixture.GetService(); var article = _articleFaker.Generate(); var tag = _tagFaker.Generate(); @@ -48,13 +50,18 @@ public async Task Can_Fetch_Many_To_Many_Through_All() }; context.ArticleTags.Add(articleTag); await context.SaveChangesAsync(); - var route = $"/api/v1/articles?include=tags"; - // act - var response = await _fixture.Client.GetAsync(route); + // @TODO - Use fixture + var builder = new WebHostBuilder() + .UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); - // assert + // Act + var response = await client.GetAsync(route); + + // Assert var body = await response.Content.ReadAsStringAsync(); Assert.True(HttpStatusCode.OK == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}"); @@ -76,7 +83,7 @@ public async Task Can_Fetch_Many_To_Many_Through_All() [Fact] public async Task Can_Fetch_Many_To_Many_Through_GetById() { - // arrange + // Arrange var context = _fixture.GetService(); var article = _articleFaker.Generate(); var tag = _tagFaker.Generate(); @@ -90,10 +97,16 @@ public async Task Can_Fetch_Many_To_Many_Through_GetById() var route = $"/api/v1/articles/{article.Id}?include=tags"; - // act - var response = await _fixture.Client.GetAsync(route); + // @TODO - Use fixture + var builder = new WebHostBuilder() + .UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); + + // Act + var response = await client.GetAsync(route); - // assert + // Assert var body = await response.Content.ReadAsStringAsync(); Assert.True(HttpStatusCode.OK == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}"); @@ -112,7 +125,7 @@ public async Task Can_Fetch_Many_To_Many_Through_GetById() [Fact] public async Task Can_Fetch_Many_To_Many_Through_GetById_Relationship_Link() { - // arrange + // Arrange var context = _fixture.GetService(); var article = _articleFaker.Generate(); var tag = _tagFaker.Generate(); @@ -126,10 +139,16 @@ public async Task Can_Fetch_Many_To_Many_Through_GetById_Relationship_Link() var route = $"/api/v1/articles/{article.Id}/tags"; - // act - var response = await _fixture.Client.GetAsync(route); + // @TODO - Use fixture + var builder = new WebHostBuilder() + .UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); - // assert + // Act + var response = await client.GetAsync(route); + + // Assert var body = await response.Content.ReadAsStringAsync(); Assert.True(HttpStatusCode.OK == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}"); @@ -145,7 +164,7 @@ public async Task Can_Fetch_Many_To_Many_Through_GetById_Relationship_Link() [Fact] public async Task Can_Fetch_Many_To_Many_Through_Relationship_Link() { - // arrange + // Arrange var context = _fixture.GetService(); var article = _articleFaker.Generate(); var tag = _tagFaker.Generate(); @@ -158,11 +177,17 @@ public async Task Can_Fetch_Many_To_Many_Through_Relationship_Link() await context.SaveChangesAsync(); var route = $"/api/v1/articles/{article.Id}/relationships/tags"; + + // @TODO - Use fixture + var builder = new WebHostBuilder() + .UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); - // act - var response = await _fixture.Client.GetAsync(route); + // Act + var response = await client.GetAsync(route); - // assert + // Assert var body = await response.Content.ReadAsStringAsync(); Assert.True(HttpStatusCode.OK == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}"); @@ -177,7 +202,7 @@ public async Task Can_Fetch_Many_To_Many_Through_Relationship_Link() [Fact] public async Task Can_Fetch_Many_To_Many_Without_Include() { - // arrange + // Arrange var context = _fixture.GetService(); var article = _articleFaker.Generate(); var tag = _tagFaker.Generate(); @@ -188,13 +213,18 @@ public async Task Can_Fetch_Many_To_Many_Without_Include() }; context.ArticleTags.Add(articleTag); await context.SaveChangesAsync(); - var route = $"/api/v1/articles/{article.Id}"; - // act - var response = await _fixture.Client.GetAsync(route); + // @TODO - Use fixture + var builder = new WebHostBuilder() + .UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); - // assert + // Act + var response = await client.GetAsync(route); + + // Assert var body = await response.Content.ReadAsStringAsync(); Assert.True(HttpStatusCode.OK == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}"); @@ -246,8 +276,14 @@ public async Task Can_Create_Many_To_Many() request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); + // @TODO - Use fixture + var builder = new WebHostBuilder() + .UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); + // Act - var response = await _fixture.Client.SendAsync(request); + var response = await client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); @@ -267,7 +303,7 @@ public async Task Can_Create_Many_To_Many() [Fact] public async Task Can_Update_Many_To_Many() { - // arrange + // Arrange var context = _fixture.GetService(); var tag = _tagFaker.Generate(); var article = _articleFaker.Generate(); @@ -299,10 +335,16 @@ public async Task Can_Update_Many_To_Many() request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - // act - var response = await _fixture.Client.SendAsync(request); + // @TODO - Use fixture + var builder = new WebHostBuilder() + .UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); + + // Act + var response = await client.SendAsync(request); - // assert + // Assert var body = await response.Content.ReadAsStringAsync(); Assert.True(HttpStatusCode.OK == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}"); @@ -321,7 +363,7 @@ public async Task Can_Update_Many_To_Many() [Fact] public async Task Can_Update_Many_To_Many_With_Complete_Replacement() { - // arrange + // Arrange var context = _fixture.GetService(); var firstTag = _tagFaker.Generate(); var article = _articleFaker.Generate(); @@ -359,10 +401,15 @@ public async Task Can_Update_Many_To_Many_With_Complete_Replacement() request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - // act - var response = await _fixture.Client.SendAsync(request); + // @TODO - Use fixture + var builder = new WebHostBuilder().UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); + + // Act + var response = await client.SendAsync(request); - // assert + // Assert var body = await response.Content.ReadAsStringAsync(); Assert.True(HttpStatusCode.OK == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}"); @@ -380,7 +427,7 @@ public async Task Can_Update_Many_To_Many_With_Complete_Replacement() [Fact] public async Task Can_Update_Many_To_Many_With_Complete_Replacement_With_Overlap() { - // arrange + // Arrange var context = _fixture.GetService(); var firstTag = _tagFaker.Generate(); var article = _articleFaker.Generate(); @@ -422,10 +469,15 @@ public async Task Can_Update_Many_To_Many_With_Complete_Replacement_With_Overlap request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - // act - var response = await _fixture.Client.SendAsync(request); + // @TODO - Use fixture + var builder = new WebHostBuilder().UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); - // assert + // Act + var response = await client.SendAsync(request); + + // Assert var body = await response.Content.ReadAsStringAsync(); Assert.True(HttpStatusCode.OK == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}"); @@ -443,7 +495,7 @@ public async Task Can_Update_Many_To_Many_With_Complete_Replacement_With_Overlap [Fact] public async Task Can_Update_Many_To_Many_Through_Relationship_Link() { - // arrange + // Arrange var context = _fixture.GetService(); var tag = _tagFaker.Generate(); var article = _articleFaker.Generate(); @@ -466,10 +518,15 @@ public async Task Can_Update_Many_To_Many_Through_Relationship_Link() request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - // act - var response = await _fixture.Client.SendAsync(request); + // @TODO - Use fixture + var builder = new WebHostBuilder().UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); + + // Act + var response = await client.SendAsync(request); - // assert + // Assert var body = await response.Content.ReadAsStringAsync(); Assert.True(HttpStatusCode.OK == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}"); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs index 3ae12cfdcb..118491ffcb 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs @@ -37,7 +37,7 @@ public AttributeFilterTests(TestFixture fixture) [Fact] public async Task Can_Filter_On_Guid_Properties() { - // arrange + // Arrange var context = _fixture.GetService(); var todoItem = _todoItemFaker.Generate(); context.TodoItems.Add(todoItem); @@ -47,7 +47,7 @@ public async Task Can_Filter_On_Guid_Properties() var route = $"/api/v1/todo-items?filter[guid-property]={todoItem.GuidProperty}"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var list = _fixture.GetDeserializer().DeserializeList(body).Data; @@ -55,7 +55,7 @@ public async Task Can_Filter_On_Guid_Properties() var todoItemResponse = list.Single(); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(todoItem.Id, todoItemResponse.Id); Assert.Equal(todoItem.GuidProperty, todoItemResponse.GuidProperty); @@ -64,7 +64,7 @@ public async Task Can_Filter_On_Guid_Properties() [Fact] public async Task Can_Filter_On_Related_Attrs() { - // arrange + // Arrange var context = _fixture.GetService(); var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); @@ -76,13 +76,13 @@ public async Task Can_Filter_On_Related_Attrs() var route = $"/api/v1/todo-items?include=owner&filter[owner.first-name]={person.FirstName}"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var list = _fixture.GetDeserializer().DeserializeList(body).Data.First(); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); list.Owner.FirstName = person.FirstName; } @@ -90,22 +90,22 @@ public async Task Can_Filter_On_Related_Attrs() [Fact] public async Task Cannot_Filter_If_Explicitly_Forbidden() { - // arrange + // Arrange var httpMethod = new HttpMethod("GET"); var route = $"/api/v1/todo-items?include=owner&filter[achieved-date]={DateTime.UtcNow.Date}"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await _fixture.Client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } [Fact] public async Task Can_Filter_On_Not_Equal_Values() { - // arrange + // Arrange var context = _fixture.GetService(); var todoItem = _todoItemFaker.Generate(); context.TodoItems.Add(todoItem); @@ -116,12 +116,12 @@ public async Task Can_Filter_On_Not_Equal_Values() var route = $"/api/v1/todo-items?page[size]={totalCount}&filter[ordinal]=ne:{todoItem.Ordinal}"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var list = _fixture.GetDeserializer().DeserializeList(body).Data; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.DoesNotContain(list, x => x.Ordinal == todoItem.Ordinal); } @@ -129,7 +129,7 @@ public async Task Can_Filter_On_Not_Equal_Values() [Fact] public async Task Can_Filter_On_In_Array_Values() { - // arrange + // Arrange var context = _fixture.GetService(); var todoItems = _todoItemFaker.Generate(5); var guids = new List(); @@ -150,14 +150,14 @@ public async Task Can_Filter_On_In_Array_Values() var route = $"/api/v1/todo-items?filter[guid-property]=in:{string.Join(",", guids)}"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var deserializedTodoItems = _fixture .GetDeserializer() .DeserializeList(body).Data; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(guids.Count(), deserializedTodoItems.Count()); foreach (var item in deserializedTodoItems) @@ -170,7 +170,7 @@ public async Task Can_Filter_On_In_Array_Values() [Fact] public async Task Can_Filter_On_Related_In_Array_Values() { - // arrange + // Arrange var context = _fixture.GetService(); var todoItems = _todoItemFaker.Generate(3); var ownerFirstNames = new List(); @@ -187,13 +187,13 @@ public async Task Can_Filter_On_Related_In_Array_Values() var route = $"/api/v1/todo-items?include=owner&filter[owner.first-name]=in:{string.Join(",", ownerFirstNames)}"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var documents = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); var included = documents.Included; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(ownerFirstNames.Count(), documents.ManyData.Count()); Assert.NotNull(included); @@ -206,7 +206,7 @@ public async Task Can_Filter_On_Related_In_Array_Values() [Fact] public async Task Can_Filter_On_Not_In_Array_Values() { - // arrange + // Arrange var context = _fixture.GetService(); context.TodoItems.RemoveRange(context.TodoItems); context.SaveChanges(); @@ -229,14 +229,14 @@ public async Task Can_Filter_On_Not_In_Array_Values() var route = $"/api/v1/todo-items?page[size]={totalCount}&filter[guid-property]=nin:{string.Join(",", notInGuids)}"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var deserializedTodoItems = _fixture .GetDeserializer() .DeserializeList(body).Data; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(totalCount - notInGuids.Count(), deserializedTodoItems.Count()); foreach (var item in deserializedTodoItems) diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs index 4aef3817fe..6449ba669f 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs @@ -18,15 +18,15 @@ public AttributeSortTests(TestFixture fixture) [Fact] public async Task Cannot_Sort_If_Explicitly_Forbidden() { - // arrange + // Arrange var httpMethod = new HttpMethod("GET"); var route = $"/api/v1/todo-items?include=owner&sort=achieved-date"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await _fixture.Client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs index 76f5fa4aa7..a9d234e353 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs @@ -21,7 +21,7 @@ public ContentNegotiation(TestFixture fixture) [Fact] public async Task Server_Sends_Correct_ContentType_Header() { - // arrange + // Arrange var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); @@ -30,10 +30,10 @@ public async Task Server_Sends_Correct_ContentType_Header() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("application/vnd.api+json", response.Content.Headers.ContentType.ToString()); } @@ -41,7 +41,7 @@ public async Task Server_Sends_Correct_ContentType_Header() [Fact] public async Task Server_Responds_415_With_MediaType_Parameters() { - // arrange + // Arrange var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); @@ -53,17 +53,17 @@ public async Task Server_Responds_415_With_MediaType_Parameters() request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); request.Content.Headers.ContentType.CharSet = "ISO-8859-4"; - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.UnsupportedMediaType, response.StatusCode); } [Fact] public async Task ServerResponds_406_If_RequestAcceptHeader_Contains_MediaTypeParameters() { - // arrange + // Arrange var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); @@ -77,10 +77,10 @@ public async Task ServerResponds_406_If_RequestAcceptHeader_Contains_MediaTypePa .Add(acceptHeader); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); } } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs index 96d3133b68..548060b1ed 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs @@ -43,7 +43,7 @@ public CreatingDataTests(TestFixture fixture) : base(fixture) [Fact] public async Task CreateResource_GuidResource_IsCreated() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(e => new { }, e => new { e.Owner }); @@ -52,17 +52,17 @@ public async Task CreateResource_GuidResource_IsCreated() dbContext.SaveChanges(); var todoItemCollection = new TodoItemCollection { Owner = owner }; - // act + // Act var (body, response) = await Post("/api/v1/todo-collections", serializer.Serialize(todoItemCollection)); - // assert + // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); } [Fact] public async Task ClientGeneratedId_IntegerIdAndNotEnabled_IsForbidden() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(e => new { e.Description, e.Ordinal, e.CreatedDate }); @@ -70,10 +70,10 @@ public async Task ClientGeneratedId_IntegerIdAndNotEnabled_IsForbidden() const int clientDefinedId = 9999; todoItem.Id = clientDefinedId; - // act + // Act var (body, response) = await Post("/api/v1/todo-items", serializer.Serialize(todoItem)); - // assert + // Assert AssertEqualStatusCode(HttpStatusCode.Forbidden, response); } @@ -81,7 +81,7 @@ public async Task ClientGeneratedId_IntegerIdAndNotEnabled_IsForbidden() [Fact] public async Task ClientGeneratedId_IntegerIdAndEnabled_IsCreated() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(e => new { e.Description, e.Ordinal, e.CreatedDate }); @@ -89,11 +89,11 @@ public async Task ClientGeneratedId_IntegerIdAndEnabled_IsCreated() const int clientDefinedId = 9999; todoItem.Id = clientDefinedId; - // act + // Act var (body, response) = await Post("/api/v1/todo-items", serializer.Serialize(todoItem)); var responseItem = _deserializer.DeserializeSingle(body).Data; - // assert + // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); Assert.Equal(clientDefinedId, responseItem.Id); } @@ -101,7 +101,7 @@ public async Task ClientGeneratedId_IntegerIdAndEnabled_IsCreated() [Fact] public async Task ClientGeneratedId_GuidIdAndEnabled_IsCreated() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(e => new { }, e => new { e.Owner }); @@ -111,11 +111,11 @@ public async Task ClientGeneratedId_GuidIdAndEnabled_IsCreated() var clientDefinedId = Guid.NewGuid(); var todoItemCollection = new TodoItemCollection { Owner = owner, OwnerId = owner.Id, Id = clientDefinedId }; - // act + // Act var (body, response) = await Post("/api/v1/todo-collections", serializer.Serialize(todoItemCollection)); var responseItem = _deserializer.DeserializeSingle(body).Data; - // assert + // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); Assert.Equal(clientDefinedId, responseItem.Id); } @@ -123,7 +123,7 @@ public async Task ClientGeneratedId_GuidIdAndEnabled_IsCreated() [Fact] public async Task CreateWithRelationship_HasMany_IsCreated() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(e => new { }, e => new { e.TodoItems }); @@ -132,11 +132,11 @@ public async Task CreateWithRelationship_HasMany_IsCreated() dbContext.SaveChanges(); var todoCollection = new TodoItemCollection { TodoItems = new List { todoItem } }; - // act + // Act var (body, response) = await Post("/api/v1/todo-collections", serializer.Serialize(todoCollection)); var responseItem = _deserializer.DeserializeSingle(body).Data; - // assert + // Assert var contextCollection = GetDbContext().TodoItemCollections.AsNoTracking() .Include(c => c.Owner) .Include(c => c.TodoItems) @@ -150,7 +150,7 @@ public async Task CreateWithRelationship_HasMany_IsCreated() [Fact] public async Task CreateWithRelationship_HasManyAndInclude_IsCreatedAndIncludes() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(e => new { }, e => new { e.TodoItems, e.Owner }); @@ -165,11 +165,11 @@ public async Task CreateWithRelationship_HasManyAndInclude_IsCreatedAndIncludes( dbContext.SaveChanges(); var todoCollection = new TodoItemCollection { Owner = owner, TodoItems = new List { todoItem } }; - // act + // Act var (body, response) = await Post("/api/v1/todo-collections?include=todo-items", serializer.Serialize(todoCollection)); var responseItem = _deserializer.DeserializeSingle(body).Data; - // assert + // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); Assert.NotNull(responseItem); @@ -180,7 +180,7 @@ public async Task CreateWithRelationship_HasManyAndInclude_IsCreatedAndIncludes( [Fact] public async Task CreateWithRelationship_HasOne_IsCreated() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(attributes: ti => new { }, relationships: ti => new { ti.Owner }); @@ -190,11 +190,11 @@ public async Task CreateWithRelationship_HasOne_IsCreated() await dbContext.SaveChangesAsync(); todoItem.Owner = owner; - // act + // Act var (body, response) = await Post("/api/v1/todo-items", serializer.Serialize(todoItem)); var responseItem = _deserializer.DeserializeSingle(body).Data; - // assert + // Assert var todoItemResult = GetDbContext().TodoItems.AsNoTracking() .Include(c => c.Owner) .SingleOrDefault(c => c.Id == responseItem.Id); @@ -205,7 +205,7 @@ public async Task CreateWithRelationship_HasOne_IsCreated() [Fact] public async Task CreateWithRelationship_HasOneAndInclude_IsCreatedAndIncludes() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(attributes: ti => new { }, relationships: ti => new { ti.Owner }); @@ -215,11 +215,11 @@ public async Task CreateWithRelationship_HasOneAndInclude_IsCreatedAndIncludes() dbContext.SaveChanges(); todoItem.Owner = owner; - // act + // Act var (body, response) = await Post("/api/v1/todo-items?include=owner", serializer.Serialize(todoItem)); var responseItem = _deserializer.DeserializeSingle(body).Data; - // assert + // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); Assert.NotNull(responseItem); Assert.NotNull(responseItem.Owner); @@ -229,7 +229,7 @@ public async Task CreateWithRelationship_HasOneAndInclude_IsCreatedAndIncludes() [Fact] public async Task CreateWithRelationship_HasOneFromIndependentSide_IsCreated() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(pr => new { }, pr => new { pr.Person }); @@ -238,11 +238,11 @@ public async Task CreateWithRelationship_HasOneFromIndependentSide_IsCreated() dbContext.SaveChanges(); var personRole = new PersonRole { Person = person }; - // act + // Act var (body, response) = await Post("/api/v1/person-roles", serializer.Serialize(personRole)); var responseItem = _deserializer.DeserializeSingle(body).Data; - // assert + // Assert var personRoleResult = dbContext.PersonRoles.AsNoTracking() .Include(c => c.Person) .SingleOrDefault(c => c.Id == responseItem.Id); @@ -254,17 +254,17 @@ public async Task CreateWithRelationship_HasOneFromIndependentSide_IsCreated() [Fact] public async Task CreateResource_SimpleResource_HeaderLocationsAreCorrect() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(ti => new { ti.CreatedDate, ti.Description, ti.Ordinal }); var todoItem = _todoItemFaker.Generate(); - // act + // Act var (body, response) = await Post("/api/v1/todo-items", serializer.Serialize(todoItem)); var responseItem = _deserializer.DeserializeSingle(body).Data; - // assert + // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); Assert.Equal($"/api/v1/todo-items/{responseItem.Id}", response.Headers.Location.ToString()); } @@ -272,7 +272,7 @@ public async Task CreateResource_SimpleResource_HeaderLocationsAreCorrect() [Fact] public async Task CreateResource_EntityTypeMismatch_IsConflict() { - // arrange + // Arrange var dbContext = PrepareTest(); var serializer = GetSerializer(e => new { }, e => new { e.Owner }); var resourceGraph = new ResourceGraphBuilder().AddResource("todo-items").AddResource().AddResource().Build(); @@ -280,10 +280,10 @@ public async Task CreateResource_EntityTypeMismatch_IsConflict() var content = serializer.Serialize(_todoItemFaker.Generate()).Replace("todo-items", "people"); - // act + // Act var (body, response) = await Post("/api/v1/todo-items", content); - // assert + // Assert AssertEqualStatusCode(HttpStatusCode.Conflict, response); } @@ -302,7 +302,7 @@ public async Task CreateRelationship_ToOneWithImplicitRemove_IsCreated() var newPerson = _personFaker.Generate(); newPerson.Passport = passport; - // act + // Act var (body, response) = await Post("/api/v1/people", serializer.Serialize(newPerson)); var responseItem = _deserializer.DeserializeSingle(body).Data; @@ -333,7 +333,7 @@ public async Task CreateRelationship_ToManyWithImplicitRemove_IsCreated() var newPerson = _personFaker.Generate(); newPerson.TodoItems = new List { firstTd, secondTd }; - // act + // Act var (body, response) = await Post("/api/v1/people", serializer.Serialize(newPerson)); var responseItem = _deserializer.DeserializeSingle(body).Data; diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs index 3490f6e949..a98c026463 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; @@ -36,7 +36,7 @@ private void ResetContext(AppDbContext context) [Fact] public async Task Can_Include_Nested_Relationships() { - // arrange + // Arrange const string route = "/api/v1/todo-items?include=collection.owner"; var resourceGraph = new ResourceGraphBuilder().AddResource("todo-items").AddResource().AddResource().Build(); var deserializer = new ResponseDeserializer(resourceGraph); @@ -53,10 +53,10 @@ public async Task Can_Include_Nested_Relationships() context.TodoItems.Add(todoItem); await context.SaveChangesAsync(); - // act + // Act var response = await _fixture.Client.GetAsync(route); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); @@ -72,7 +72,7 @@ public async Task Can_Include_Nested_Relationships() [Fact] public async Task Can_Include_Nested_HasMany_Relationships() { - // arrange + // Arrange const string route = "/api/v1/todo-items?include=collection.todo-items"; var todoItem = new TodoItem @@ -94,10 +94,10 @@ public async Task Can_Include_Nested_HasMany_Relationships() context.TodoItems.Add(todoItem); await context.SaveChangesAsync(); - // act + // Act var response = await _fixture.Client.GetAsync(route); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); @@ -113,7 +113,7 @@ public async Task Can_Include_Nested_HasMany_Relationships() [Fact] public async Task Can_Include_Nested_HasMany_Relationships_BelongsTo() { - // arrange + // Arrange const string route = "/api/v1/todo-items?include=collection.todo-items.owner"; var todoItem = new TodoItem @@ -136,10 +136,10 @@ public async Task Can_Include_Nested_HasMany_Relationships_BelongsTo() context.TodoItems.Add(todoItem); await context.SaveChangesAsync(); - // act + // Act var response = await _fixture.Client.GetAsync(route); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); @@ -156,7 +156,7 @@ public async Task Can_Include_Nested_HasMany_Relationships_BelongsTo() [Fact] public async Task Can_Include_Nested_Relationships_With_Multiple_Paths() { - // arrange + // Arrange const string route = "/api/v1/todo-items?include=collection.owner.role,collection.todo-items.owner"; var todoItem = new TodoItem @@ -182,10 +182,10 @@ public async Task Can_Include_Nested_Relationships_With_Multiple_Paths() context.TodoItems.Add(todoItem); await context.SaveChangesAsync(); - // act + // Act var response = await _fixture.Client.GetAsync(route); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); @@ -203,7 +203,7 @@ public async Task Can_Include_Nested_Relationships_With_Multiple_Paths() [Fact] public async Task Included_Resources_Are_Correct() { - // arrange + // Arrange var role = new PersonRole(); var assignee = new Person { Role = role }; var collectionOwner = new Person(); @@ -236,10 +236,10 @@ public async Task Included_Resources_Are_Correct() "assignee.role," + "assignee.assigned-todo-items"; - // act + // Act var response = await _fixture.Client.GetAsync(route); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); @@ -280,7 +280,7 @@ public async Task Included_Resources_Are_Correct() [Fact] public async Task Can_Include_Doubly_HasMany_Relationships() { - // arrange + // Arrange var person = new Person { TodoItemCollections = new List { new TodoItemCollection { @@ -308,10 +308,10 @@ public async Task Can_Include_Doubly_HasMany_Relationships() string route = "/api/v1/people/" + person.Id + "?include=todo-collections.todo-items"; - // act + // Act var response = await _fixture.Client.GetAsync(route); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); @@ -324,4 +324,4 @@ public async Task Can_Include_Doubly_HasMany_Relationships() Assert.Equal(2, included.CountOfType("todo-collections")); } } -} \ No newline at end of file +} diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs index 8c506f4a33..502d4716b9 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs @@ -32,7 +32,7 @@ public DeletingDataTests(TestFixture fixture) [Fact] public async Task Respond_404_If_EntityDoesNotExist() { - // arrange + // Arrange var maxPersonId = _context.TodoItems.LastOrDefault()?.Id ?? 0; var todoItem = _todoItemFaker.Generate(); var builder = new WebHostBuilder() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs index 5fa44b3e6c..58ab372b3d 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs @@ -43,7 +43,7 @@ public Included(TestFixture fixture) [Fact] public async Task GET_Included_Contains_SideloadeData_ForManyToOne() { - // arrange + // Arrange var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); todoItem.Owner = person; @@ -60,10 +60,10 @@ public async Task GET_Included_Contains_SideloadeData_ForManyToOne() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert var json = await response.Content.ReadAsStringAsync(); var documents = JsonConvert.DeserializeObject(json); // we only care about counting the todo-items that have owners @@ -81,7 +81,7 @@ public async Task GET_Included_Contains_SideloadeData_ForManyToOne() [Fact] public async Task GET_ById_Included_Contains_SideloadeData_ForManyToOne() { - // arrange + // Arrange var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); todoItem.Owner = person; @@ -99,12 +99,12 @@ public async Task GET_ById_Included_Contains_SideloadeData_ForManyToOne() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); var document = JsonConvert.DeserializeObject(responseString); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotEmpty(document.Included); Assert.Equal(person.Id.ToString(), document.Included[0].Id); @@ -119,7 +119,7 @@ public async Task GET_ById_Included_Contains_SideloadeData_ForManyToOne() [Fact] public async Task GET_Included_Contains_SideloadeData_OneToMany() { - // arrange + // Arrange _context.People.RemoveRange(_context.People); // ensure all people have todo-items _context.TodoItems.RemoveRange(_context.TodoItems); var person = _personFaker.Generate(); @@ -138,11 +138,11 @@ public async Task GET_Included_Contains_SideloadeData_OneToMany() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var documents = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotEmpty(documents.Included); Assert.Equal(documents.ManyData.Count, documents.Included.Count); @@ -155,7 +155,7 @@ public async Task GET_Included_Contains_SideloadeData_OneToMany() [Fact] public async Task GET_Included_DoesNot_Duplicate_Records_ForMultipleRelationshipsOfSameType() { - // arrange + // Arrange _context.RemoveRange(_context.TodoItems); _context.RemoveRange(_context.TodoItemCollections); _context.RemoveRange(_context.People); // ensure all people have todo-items @@ -177,11 +177,11 @@ public async Task GET_Included_DoesNot_Duplicate_Records_ForMultipleRelationship var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var documents = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotEmpty(documents.Included); Assert.Single(documents.Included); @@ -194,7 +194,7 @@ public async Task GET_Included_DoesNot_Duplicate_Records_ForMultipleRelationship [Fact] public async Task GET_Included_DoesNot_Duplicate_Records_If_HasOne_Exists_Twice() { - // arrange + // Arrange _context.TodoItemCollections.RemoveRange(_context.TodoItemCollections); _context.People.RemoveRange(_context.People); // ensure all people have todo-items _context.TodoItems.RemoveRange(_context.TodoItems); @@ -216,11 +216,11 @@ public async Task GET_Included_DoesNot_Duplicate_Records_If_HasOne_Exists_Twice( var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var documents = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotEmpty(documents.Included); Assert.Single(documents.Included); @@ -233,7 +233,7 @@ public async Task GET_Included_DoesNot_Duplicate_Records_If_HasOne_Exists_Twice( [Fact] public async Task GET_ById_Included_Contains_SideloadeData_ForOneToMany() { - // arrange + // Arrange const int numberOfTodoItems = 5; var person = _personFaker.Generate(); for (var i = 0; i < numberOfTodoItems; i++) @@ -255,12 +255,12 @@ public async Task GET_ById_Included_Contains_SideloadeData_ForOneToMany() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); var document = JsonConvert.DeserializeObject(responseString); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotEmpty(document.Included); Assert.Equal(numberOfTodoItems, document.Included.Count); @@ -273,7 +273,7 @@ public async Task GET_ById_Included_Contains_SideloadeData_ForOneToMany() [Fact] public async Task Can_Include_MultipleRelationships() { - // arrange + // Arrange var person = _personFaker.Generate(); var todoItemCollection = _todoItemCollectionFaker.Generate(); todoItemCollection.Owner = person; @@ -299,12 +299,12 @@ public async Task Can_Include_MultipleRelationships() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); var document = JsonConvert.DeserializeObject(responseString); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotEmpty(document.Included); Assert.Equal(numberOfTodoItems + 1, document.Included.Count); @@ -317,7 +317,7 @@ public async Task Can_Include_MultipleRelationships() [Fact] public async Task Request_ToIncludeUnknownRelationship_Returns_400() { - // arrange + // Arrange var person = _context.People.First(); var builder = new WebHostBuilder() @@ -331,10 +331,10 @@ public async Task Request_ToIncludeUnknownRelationship_Returns_400() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); server.Dispose(); @@ -345,7 +345,7 @@ public async Task Request_ToIncludeUnknownRelationship_Returns_400() [Fact] public async Task Request_ToIncludeDeeplyNestedRelationships_Returns_400() { - // arrange + // Arrange var person = _context.People.First(); var builder = new WebHostBuilder() @@ -359,10 +359,10 @@ public async Task Request_ToIncludeDeeplyNestedRelationships_Returns_400() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); server.Dispose(); @@ -373,7 +373,7 @@ public async Task Request_ToIncludeDeeplyNestedRelationships_Returns_400() [Fact] public async Task Request_ToIncludeRelationshipMarkedCanIncludeFalse_Returns_400() { - // arrange + // Arrange var person = _context.People.First(); var builder = new WebHostBuilder() @@ -387,10 +387,10 @@ public async Task Request_ToIncludeRelationshipMarkedCanIncludeFalse_Returns_400 var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); server.Dispose(); @@ -401,7 +401,7 @@ public async Task Request_ToIncludeRelationshipMarkedCanIncludeFalse_Returns_400 [Fact] public async Task Can_Ignore_Null_Parent_In_Nested_Include() { - // arrange + // Arrange var todoItem = _todoItemFaker.Generate(); todoItem.Owner = _personFaker.Generate(); todoItem.CreatedDate = DateTime.Now; @@ -425,12 +425,12 @@ public async Task Can_Ignore_Null_Parent_In_Nested_Include() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); var documents = JsonConvert.DeserializeObject(responseString); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Single(documents.Included); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs index 76b1094f67..53bf7ed1bc 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs @@ -29,7 +29,7 @@ public Meta(TestFixture fixture) [Fact] public async Task Total_Record_Count_Included() { - // arrange + // Arrange _context.TodoItems.RemoveRange(_context.TodoItems); _context.TodoItems.Add(new TodoItem()); _context.SaveChanges(); @@ -44,12 +44,12 @@ public async Task Total_Record_Count_Included() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); var documents = JsonConvert.DeserializeObject(responseBody); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(documents.Meta); Assert.Equal((long)expectedCount, (long)documents.Meta["total-records"]); @@ -58,7 +58,7 @@ public async Task Total_Record_Count_Included() [Fact] public async Task Total_Record_Count_Included_When_None() { - // arrange + // Arrange _context.TodoItems.RemoveRange(_context.TodoItems); _context.SaveChanges(); var builder = new WebHostBuilder() @@ -71,12 +71,12 @@ public async Task Total_Record_Count_Included_When_None() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); var documents = JsonConvert.DeserializeObject(responseBody); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(documents.Meta); Assert.Equal(0, (long)documents.Meta["total-records"]); @@ -85,7 +85,7 @@ public async Task Total_Record_Count_Included_When_None() [Fact] public async Task Total_Record_Count_Not_Included_In_POST_Response() { - // arrange + // Arrange _context.TodoItems.RemoveRange(_context.TodoItems); _context.SaveChanges(); var builder = new WebHostBuilder() @@ -112,12 +112,12 @@ public async Task Total_Record_Count_Not_Included_In_POST_Response() request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - // act + // Act var response = await client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); var documents = JsonConvert.DeserializeObject(responseBody); - // assert + // Assert Assert.Equal(HttpStatusCode.Created, response.StatusCode); Assert.False(documents.Meta.ContainsKey("total-records")); } @@ -125,7 +125,7 @@ public async Task Total_Record_Count_Not_Included_In_POST_Response() [Fact] public async Task Total_Record_Count_Not_Included_In_PATCH_Response() { - // arrange + // Arrange _context.TodoItems.RemoveRange(_context.TodoItems); TodoItem todoItem = new TodoItem(); _context.TodoItems.Add(todoItem); @@ -155,12 +155,12 @@ public async Task Total_Record_Count_Not_Included_In_PATCH_Response() request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - // act + // Act var response = await client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); var documents = JsonConvert.DeserializeObject(responseBody); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(documents.Meta.ContainsKey("total-records")); } @@ -168,7 +168,7 @@ public async Task Total_Record_Count_Not_Included_In_PATCH_Response() [Fact] public async Task EntityThatImplements_IHasMeta_Contains_MetaData() { - // arrange + // Arrange var builder = new WebHostBuilder() .UseStartup(); @@ -180,11 +180,11 @@ public async Task EntityThatImplements_IHasMeta_Contains_MetaData() var request = new HttpRequestMessage(httpMethod, route); var expectedMeta = (_fixture.GetService>() as IHasMeta).GetMeta(); - // act + // Act var response = await client.SendAsync(request); var documents = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(documents.Meta); Assert.NotNull(expectedMeta); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/PagingTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/PagingTests.cs index 1dcc5382de..0bf315d7a0 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/PagingTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/PagingTests.cs @@ -32,7 +32,7 @@ public PagingTests(TestFixture fixture) [Fact] public async Task Server_IncludesPagination_Links() { - // arrange + // Arrange var pageSize = 5; const int minimumNumberOfRecords = 11; _context.TodoItems.RemoveRange(_context.TodoItems); @@ -55,12 +55,12 @@ public async Task Server_IncludesPagination_Links() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var documents = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); var links = documents.Links; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotEmpty(links.First); Assert.NotEmpty(links.Next); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs index 483726ab3f..a010dbc8c7 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs @@ -34,7 +34,7 @@ public Relationships(TestFixture fixture) [Fact] public async Task Correct_RelationshipObjects_For_ManyToOne_Relationships() { - // arrange + // Arrange var builder = new WebHostBuilder() .UseStartup(); @@ -49,14 +49,14 @@ public async Task Correct_RelationshipObjects_For_ManyToOne_Relationships() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var document = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); var data = document.SingleData; var expectedOwnerSelfLink = $"http://localhost/api/v1/todo-items/{data.Id}/relationships/owner"; var expectedOwnerRelatedLink = $"http://localhost/api/v1/todo-items/{data.Id}/owner"; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedOwnerSelfLink, data.Relationships["owner"].Links.Self); Assert.Equal(expectedOwnerRelatedLink, data.Relationships["owner"].Links.Related); @@ -65,7 +65,7 @@ public async Task Correct_RelationshipObjects_For_ManyToOne_Relationships() [Fact] public async Task Correct_RelationshipObjects_For_ManyToOne_Relationships_ById() { - // arrange + // Arrange var builder = new WebHostBuilder() .UseStartup(); @@ -80,14 +80,14 @@ public async Task Correct_RelationshipObjects_For_ManyToOne_Relationships_ById() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject(responseString).SingleData; var expectedOwnerSelfLink = $"http://localhost/api/v1/todo-items/{todoItem.Id}/relationships/owner"; var expectedOwnerRelatedLink = $"http://localhost/api/v1/todo-items/{todoItem.Id}/owner"; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedOwnerSelfLink, data.Relationships["owner"].Links?.Self); Assert.Equal(expectedOwnerRelatedLink, data.Relationships["owner"].Links.Related); @@ -96,7 +96,7 @@ public async Task Correct_RelationshipObjects_For_ManyToOne_Relationships_ById() [Fact] public async Task Correct_RelationshipObjects_For_OneToMany_Relationships() { - // arrange + // Arrange var builder = new WebHostBuilder() .UseStartup(); @@ -107,14 +107,14 @@ public async Task Correct_RelationshipObjects_For_OneToMany_Relationships() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var documents = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); var data = documents.ManyData.First(); var expectedOwnerSelfLink = $"http://localhost/api/v1/people/{data.Id}/relationships/todo-items"; var expectedOwnerRelatedLink = $"http://localhost/api/v1/people/{data.Id}/todo-items"; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedOwnerSelfLink, data.Relationships["todo-items"].Links.Self); Assert.Equal(expectedOwnerRelatedLink, data.Relationships["todo-items"].Links.Related); @@ -123,7 +123,7 @@ public async Task Correct_RelationshipObjects_For_OneToMany_Relationships() [Fact] public async Task Correct_RelationshipObjects_For_OneToMany_Relationships_ById() { - // arrange + // Arrange var personId = _context.People.Last().Id; var builder = new WebHostBuilder() @@ -136,14 +136,14 @@ public async Task Correct_RelationshipObjects_For_OneToMany_Relationships_ById() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject(responseString).SingleData; var expectedOwnerSelfLink = $"http://localhost/api/v1/people/{personId}/relationships/todo-items"; var expectedOwnerRelatedLink = $"http://localhost/api/v1/people/{personId}/todo-items"; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedOwnerSelfLink, data.Relationships["todo-items"].Links?.Self); Assert.Equal(expectedOwnerRelatedLink, data.Relationships["todo-items"].Links.Related); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs index 33e9943b3c..91b4b2b1ad 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs @@ -36,7 +36,7 @@ public FetchingDataTests(TestFixture fixture) [Fact] public async Task Request_ForEmptyCollection_Returns_EmptyDataCollection() { - // arrange + // Arrange var context = _fixture.GetService(); context.TodoItems.RemoveRange(context.TodoItems); await context.SaveChangesAsync(); @@ -49,14 +49,14 @@ public async Task Request_ForEmptyCollection_Returns_EmptyDataCollection() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var result = _fixture.GetDeserializer().DeserializeList(body); var items = result.Data; var meta = result.Meta; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("application/vnd.api+json", response.Content.Headers.ContentType.ToString()); Assert.Empty(items); @@ -67,7 +67,7 @@ public async Task Request_ForEmptyCollection_Returns_EmptyDataCollection() [Fact] public async Task Included_Records_Contain_Relationship_Links() { - // arrange + // Arrange var context = _fixture.GetService(); var todoItem = _todoItemFaker.Generate(); var person = _personFaker.Generate(); @@ -83,12 +83,12 @@ public async Task Included_Records_Contain_Relationship_Links() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var deserializedBody = JsonConvert.DeserializeObject(body); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(person.StringId, deserializedBody.Included[0].Id); Assert.NotNull(deserializedBody.Included[0].Relationships); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs index d3be10afa5..adfb0e4dec 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs @@ -29,7 +29,7 @@ public FetchingRelationshipsTests(TestFixture fixture) [Fact] public async Task Request_UnsetRelationship_Returns_Null_DataObject() { - // arrange + // Arrange var context = _fixture.GetService(); var todoItem = _todoItemFaker.Generate(); context.TodoItems.Add(todoItem); @@ -45,11 +45,11 @@ public async Task Request_UnsetRelationship_Returns_Null_DataObject() var request = new HttpRequestMessage(httpMethod, route); var expectedBody = "{\"meta\":{\"copyright\":\"Copyright 2015 Example Corp.\",\"authors\":[\"Jared Nance\",\"Maurits Moeys\"]},\"links\":{\"self\":\"http://localhost/api/v1/people\"},\"data\":null}"; - // act + // Act var response = await client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("application/vnd.api+json", response.Content.Headers.ContentType.ToString()); Assert.Equal(expectedBody, body); @@ -60,7 +60,7 @@ public async Task Request_UnsetRelationship_Returns_Null_DataObject() [Fact] public async Task Request_ForRelationshipLink_ThatDoesNotExist_Returns_404() { - // arrange + // Arrange var context = _fixture.GetService(); var todoItem = _todoItemFaker.Generate(); @@ -80,10 +80,10 @@ public async Task Request_ForRelationshipLink_ThatDoesNotExist_Returns_404() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); context.Dispose(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs index d530f70d40..39aa381f20 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs @@ -22,7 +22,7 @@ public QueryParameters(TestFixture fixture) [Fact] public async Task Server_Returns_400_ForUnknownQueryParam() { - // arrange + // Arrange const string queryKey = "unknownKey"; const string queryValue = "value"; var builder = new WebHostBuilder() @@ -33,12 +33,12 @@ public async Task Server_Returns_400_ForUnknownQueryParam() var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var errorCollection = JsonConvert.DeserializeObject(body); - // assert + // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Single(errorCollection.Errors); Assert.Equal($"[{queryKey}, {queryValue}] is not a valid query.", errorCollection.Errors[0].Title); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs index 2981009adc..dcad4fa838 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs @@ -52,7 +52,7 @@ public SparseFieldSetTests(TestFixture fixture) [Fact] public async Task Can_Select_Sparse_Fieldsets() { - // arrange + // Arrange var fields = new List { "Id", "Description", "CreatedDate", "AchievedDate" }; var todoItem = new TodoItem { @@ -67,7 +67,7 @@ public async Task Can_Select_Sparse_Fieldsets() FROM 'TodoItems' AS 't' WHERE 't'.'Id' = {todoItem.Id}"); - // act + // Act var query = _dbContext .TodoItems .Where(t => t.Id == todoItem.Id) @@ -75,7 +75,7 @@ public async Task Can_Select_Sparse_Fieldsets() var result = await query.FirstAsync(); - // assert + // Assert Assert.Equal(0, result.Ordinal); Assert.Equal(todoItem.Description, result.Description); Assert.Equal(todoItem.CreatedDate.ToString("G"), result.CreatedDate.ToString("G")); @@ -85,7 +85,7 @@ public async Task Can_Select_Sparse_Fieldsets() [Fact] public async Task Fields_Query_Selects_Sparse_Field_Sets() { - // arrange + // Arrange var todoItem = new TodoItem { Description = "description", @@ -104,12 +104,12 @@ public async Task Fields_Query_Selects_Sparse_Field_Sets() var route = $"/api/v1/todo-items/{todoItem.Id}?fields=description,created-date"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var deserializeBody = JsonConvert.DeserializeObject(body); - // assert + // Assert Assert.Equal(todoItem.StringId, deserializeBody.SingleData.Id); Assert.Equal(2, deserializeBody.SingleData.Attributes.Count); Assert.Equal(todoItem.Description, deserializeBody.SingleData.Attributes["description"]); @@ -119,7 +119,7 @@ public async Task Fields_Query_Selects_Sparse_Field_Sets() [Fact] public async Task Fields_Query_Selects_Sparse_Field_Sets_With_Type_As_Navigation() { - // arrange + // Arrange var todoItem = new TodoItem { Description = "description", @@ -137,11 +137,11 @@ public async Task Fields_Query_Selects_Sparse_Field_Sets_With_Type_As_Navigation var route = $"/api/v1/todo-items/{todoItem.Id}?fields[todo-items]=description,created-date"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); - // assert + // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Contains("relationships only", body); @@ -150,7 +150,7 @@ public async Task Fields_Query_Selects_Sparse_Field_Sets_With_Type_As_Navigation [Fact] public async Task Fields_Query_Selects_All_Fieldset_With_HasOne() { - // arrange + // Arrange _dbContext.TodoItems.RemoveRange(_dbContext.TodoItems); _dbContext.SaveChanges(); var owner = _personFaker.Generate(); @@ -174,10 +174,10 @@ public async Task Fields_Query_Selects_All_Fieldset_With_HasOne() var request = new HttpRequestMessage(httpMethod, route); var resourceGraph = new ResourceGraphBuilder().AddResource().AddResource("todo-items").Build(); var deserializer = new ResponseDeserializer(resourceGraph); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); @@ -194,7 +194,7 @@ public async Task Fields_Query_Selects_All_Fieldset_With_HasOne() [Fact] public async Task Fields_Query_Selects_Fieldset_With_HasOne() { - // arrange + // Arrange var owner = _personFaker.Generate(); var todoItem = new TodoItem { @@ -234,7 +234,7 @@ public async Task Fields_Query_Selects_Fieldset_With_HasOne() [Fact] public async Task Fields_Query_Selects_Fieldset_With_HasMany() { - // arrange + // Arrange var owner = _personFaker.Generate(); var todoItems = _todoItemFaker.Generate(2); @@ -252,10 +252,10 @@ public async Task Fields_Query_Selects_Fieldset_With_HasMany() var route = $"/api/v1/people/{owner.Id}?include=todo-items&fields[todo-items]=description"; var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var deserializeBody = JsonConvert.DeserializeObject(body); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs index 74d9e670ef..7e437e425c 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs @@ -118,7 +118,7 @@ public async Task Respond_422_If_IdNotInAttributeList() [Fact] public async Task Can_Patch_Entity() { - // arrange + // Arrange _context.RemoveRange(_context.TodoItemCollections); _context.RemoveRange(_context.TodoItems); _context.RemoveRange(_context.People); @@ -166,7 +166,7 @@ public async Task Can_Patch_Entity() [Fact] public async Task Patch_Entity_With_HasMany_Does_Not_Included_Relationships() { - // arrange + // Arrange var todoItem = _todoItemFaker.Generate(); var person = _personFaker.Generate(); todoItem.Owner = person; @@ -202,7 +202,7 @@ public async Task Patch_Entity_With_HasMany_Does_Not_Included_Relationships() [Fact] public async Task Can_Patch_Entity_And_HasOne_Relationships() { - // arrange + // Arrange var todoItem = _todoItemFaker.Generate(); todoItem.CreatedDate = DateTime.Now; var person = _personFaker.Generate(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs index 27c241bfab..77fdd900ee 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs @@ -231,7 +231,7 @@ public async Task Can_Update_Both_Cyclic_ToOne_And_ToMany_Relationship_By_Patchi [Fact] public async Task Can_Update_ToMany_Relationship_By_Patching_Resource() { - // arrange + // Arrange var todoCollection = new TodoItemCollection(); todoCollection.TodoItems = new List(); var person = _personFaker.Generate(); @@ -305,7 +305,7 @@ public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_When_Targe // in business logic in controllers. In this case, // this user may not be reattached to the db context in the repository. - // arrange + // Arrange var todoCollection = new TodoItemCollection(); todoCollection.TodoItems = new List(); var person = _personFaker.Generate(); @@ -378,7 +378,7 @@ public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_When_Targe [Fact] public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_With_Overlap() { - // arrange + // Arrange var todoCollection = new TodoItemCollection(); todoCollection.TodoItems = new List(); var person = _personFaker.Generate(); @@ -444,7 +444,7 @@ public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_With_Overl [Fact] public async Task Can_Update_ToMany_Relationship_ThroughLink() { - // arrange + // Arrange var person = _personFaker.Generate(); _context.People.Add(person); @@ -490,7 +490,7 @@ public async Task Can_Update_ToMany_Relationship_ThroughLink() [Fact] public async Task Can_Update_ToOne_Relationship_ThroughLink() { - // arrange + // Arrange var person = _personFaker.Generate(); _context.People.Add(person); @@ -527,7 +527,7 @@ public async Task Can_Update_ToOne_Relationship_ThroughLink() [Fact] public async Task Can_Delete_ToOne_Relationship_By_Patching_Resource() { - // arrange + // Arrange var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); todoItem.Owner = person; @@ -581,7 +581,7 @@ public async Task Can_Delete_ToOne_Relationship_By_Patching_Resource() [Fact] public async Task Can_Delete_ToMany_Relationship_By_Patching_Resource() { - // arrange + // Arrange var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); person.TodoItems = new List() { todoItem }; @@ -638,7 +638,7 @@ public async Task Can_Delete_ToMany_Relationship_By_Patching_Resource() [Fact] public async Task Can_Delete_Relationship_By_Patching_Relationship() { - // arrange + // Arrange var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); todoItem.Owner = person; diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs index f4db2a89b1..f1a270a465 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs @@ -22,7 +22,6 @@ public TestFixture() { var builder = new WebHostBuilder() .UseStartup(); - _server = new TestServer(builder); _services = _server.Host.Services; @@ -84,4 +83,4 @@ public void Dispose() Dispose(true); } } -} \ No newline at end of file +} diff --git a/test/JsonApiDotNetCoreExampleTests/CamelCaseTestStartup.cs b/test/JsonApiDotNetCoreExampleTests/CamelCaseTestStartup.cs index 3a092e5e1a..f801c593a7 100644 --- a/test/JsonApiDotNetCoreExampleTests/CamelCaseTestStartup.cs +++ b/test/JsonApiDotNetCoreExampleTests/CamelCaseTestStartup.cs @@ -11,16 +11,15 @@ namespace JsonApiDotNetCoreExampleTests { public class CamelCaseTestStartup : Startup { - public CamelCaseTestStartup(IHostingEnvironment env) : base(env) + public CamelCaseTestStartup(IWebHostEnvironment env) : base(env) { } - public override IServiceProvider ConfigureServices(IServiceCollection services) + public override void ConfigureServices(IServiceCollection services) { services.AddSingleton(); base.ConfigureServices(services); services.AddClientSerialization(); services.AddScoped(); - return services.BuildServiceProvider(); } } } diff --git a/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs b/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs index 64147e5460..8e66723c15 100644 --- a/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs +++ b/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs @@ -12,11 +12,11 @@ namespace JsonApiDotNetCoreExampleTests.Startups { public class ClientGeneratedIdsStartup : Startup { - public ClientGeneratedIdsStartup(IHostingEnvironment env) + public ClientGeneratedIdsStartup(IWebHostEnvironment env) : base (env) { } - public override IServiceProvider ConfigureServices(IServiceCollection services) + public override void ConfigureServices(IServiceCollection services) { var loggerFactory = new LoggerFactory(); var mvcBuilder = services.AddMvcCore(); @@ -37,9 +37,6 @@ public override IServiceProvider ConfigureServices(IServiceCollection services) }, discovery => discovery.AddAssembly(Assembly.Load(nameof(JsonApiDotNetCoreExample))), mvcBuilder: mvcBuilder); - - return services.BuildServiceProvider(); - } } } diff --git a/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/MetaStartup.cs b/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/MetaStartup.cs index 1aa7614a7e..fcd93931ae 100644 --- a/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/MetaStartup.cs +++ b/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/MetaStartup.cs @@ -9,14 +9,14 @@ namespace JsonApiDotNetCoreExampleTests.Startups { public class MetaStartup : Startup { - public MetaStartup(IHostingEnvironment env) + public MetaStartup(IWebHostEnvironment env) : base (env) { } - public override IServiceProvider ConfigureServices(IServiceCollection services) + public override void ConfigureServices(IServiceCollection services) { services.AddScoped(); - return base.ConfigureServices(services); + base.ConfigureServices(services); } } } diff --git a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs index 1a9c45e5d2..0854b1adc0 100644 --- a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs +++ b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs @@ -21,7 +21,7 @@ public NoEntityFrameworkTests(TestFixture fixture) [Fact] public async Task Can_Get_TodoItems() { - // arrange + // Arrange _fixture.Context.TodoItems.Add(new TodoItem()); _fixture.Context.SaveChanges(); @@ -32,12 +32,12 @@ public async Task Can_Get_TodoItems() var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); var deserializedBody = _fixture.GetDeserializer().DeserializeList(responseBody).Data; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(deserializedBody); Assert.NotEmpty(deserializedBody); @@ -46,7 +46,7 @@ public async Task Can_Get_TodoItems() [Fact] public async Task Can_Get_TodoItems_By_Id() { - // arrange + // Arrange var todoItem = new TodoItem(); _fixture.Context.TodoItems.Add(todoItem); _fixture.Context.SaveChanges(); @@ -58,12 +58,12 @@ public async Task Can_Get_TodoItems_By_Id() var request = new HttpRequestMessage(httpMethod, route); - // act + // Act var response = await client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); var deserializedBody = _fixture.GetDeserializer().DeserializeSingle(responseBody).Data; - // assert + // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(deserializedBody); Assert.Equal(todoItem.Id, deserializedBody.Id); diff --git a/test/NoEntityFrameworkTests/TestStartup.cs b/test/NoEntityFrameworkTests/TestStartup.cs index e925e69fd0..3f0cd1fc4c 100644 --- a/test/NoEntityFrameworkTests/TestStartup.cs +++ b/test/NoEntityFrameworkTests/TestStartup.cs @@ -9,14 +9,14 @@ namespace NoEntityFrameworkTests { public class TestStartup : Startup { - public TestStartup(IHostingEnvironment env) : base(env) + public TestStartup(IWebHostEnvironment env) : base(env) { } - public override IServiceProvider ConfigureServices(IServiceCollection services) + public override void ConfigureServices(IServiceCollection services) { base.ConfigureServices(services); services.AddScoped(); - return services.BuildServiceProvider(); + services.BuildServiceProvider(); } } } diff --git a/test/UnitTests/Builders/ContextGraphBuilder_Tests.cs b/test/UnitTests/Builders/ContextGraphBuilder_Tests.cs index f066b20fd8..fae27307d2 100644 --- a/test/UnitTests/Builders/ContextGraphBuilder_Tests.cs +++ b/test/UnitTests/Builders/ContextGraphBuilder_Tests.cs @@ -26,14 +26,14 @@ class TestContext : DbContext [Fact] public void Can_Build_ResourceGraph_Using_Builder() { - // arrange + // Arrange var services = new ServiceCollection(); services.AddJsonApi(resources: builder => builder.AddResource("non-db-resources")); - // act + // Act var container = services.BuildServiceProvider(); - // assert + // Assert var resourceGraph = container.GetRequiredService(); var dbResource = resourceGraph.GetResourceContext("db-resources"); var nonDbResource = resourceGraph.GetResourceContext("non-db-resources"); @@ -45,14 +45,14 @@ public void Can_Build_ResourceGraph_Using_Builder() [Fact] public void Resources_Without_Names_Specified_Will_Use_Default_Formatter() { - // arrange + // Arrange var builder = new ResourceGraphBuilder(); builder.AddResource(); - // act + // Act var resourceGraph = builder.Build(); - // assert + // Assert var resource = resourceGraph.GetResourceContext(typeof(TestResource)); Assert.Equal("test-resources", resource.ResourceName); } @@ -60,14 +60,14 @@ public void Resources_Without_Names_Specified_Will_Use_Default_Formatter() [Fact] public void Resources_Without_Names_Specified_Will_Use_Configured_Formatter() { - // arrange + // Arrange var builder = new ResourceGraphBuilder(new CamelCaseNameFormatter()); builder.AddResource(); - // act + // Act var resourceGraph = builder.Build(); - // assert + // Assert var resource = resourceGraph.GetResourceContext(typeof(TestResource)); Assert.Equal("testResources", resource.ResourceName); } @@ -75,14 +75,14 @@ public void Resources_Without_Names_Specified_Will_Use_Configured_Formatter() [Fact] public void Attrs_Without_Names_Specified_Will_Use_Default_Formatter() { - // arrange + // Arrange var builder = new ResourceGraphBuilder(); builder.AddResource(); - // act + // Act var resourceGraph = builder.Build(); - // assert + // Assert var resource = resourceGraph.GetResourceContext(typeof(TestResource)); Assert.Contains(resource.Attributes, (i) => i.PublicAttributeName == "compound-attribute"); } @@ -90,14 +90,14 @@ public void Attrs_Without_Names_Specified_Will_Use_Default_Formatter() [Fact] public void Attrs_Without_Names_Specified_Will_Use_Configured_Formatter() { - // arrange + // Arrange var builder = new ResourceGraphBuilder(new CamelCaseNameFormatter()); builder.AddResource(); - // act + // Act var resourceGraph = builder.Build(); - // assert + // Assert var resource = resourceGraph.GetResourceContext(typeof(TestResource)); Assert.Contains(resource.Attributes, (i) => i.PublicAttributeName == "compoundAttribute"); } @@ -105,14 +105,14 @@ public void Attrs_Without_Names_Specified_Will_Use_Configured_Formatter() [Fact] public void Relationships_Without_Names_Specified_Will_Use_Default_Formatter() { - // arrange + // Arrange var builder = new ResourceGraphBuilder(); builder.AddResource(); - // act + // Act var resourceGraph = builder.Build(); - // assert + // Assert var resource = resourceGraph.GetResourceContext(typeof(TestResource)); Assert.Equal("related-resource", resource.Relationships.Single(r => r.IsHasOne).PublicRelationshipName); Assert.Equal("related-resources", resource.Relationships.Single(r => r.IsHasMany).PublicRelationshipName); diff --git a/test/UnitTests/Builders/LinkBuilderTests.cs b/test/UnitTests/Builders/LinkBuilderTests.cs index 0d9ce1c98b..0282f52527 100644 --- a/test/UnitTests/Builders/LinkBuilderTests.cs +++ b/test/UnitTests/Builders/LinkBuilderTests.cs @@ -40,16 +40,16 @@ public LinkBuilderTests() [InlineData(Link.None, Link.None, null)] public void BuildResourceLinks_GlobalAndResourceConfiguration_ExpectedResult(Link global, Link resource, object expectedResult) { - // arrange + // Arrange var config = GetConfiguration(resourceLinks: global); var primaryResource = GetResourceContext
(resourceLinks: resource); _provider.Setup(m => m.GetResourceContext("articles")).Returns(primaryResource); var builder = new LinkBuilder(config, GetRequestManager(), null, _provider.Object); - // act + // Act var links = builder.GetResourceLinks("articles", "123"); - // assert + // Assert if (expectedResult == null) Assert.Null(links); else @@ -88,17 +88,17 @@ public void BuildRelationshipLinks_GlobalResourceAndAttrConfiguration_ExpectedLi object expectedSelfLink, object expectedRelatedLink) { - // arrange + // Arrange var config = GetConfiguration(relationshipLinks: global); var primaryResource = GetResourceContext
(relationshipLinks: resource); _provider.Setup(m => m.GetResourceContext(typeof(Article))).Returns(primaryResource); var builder = new LinkBuilder(config, GetRequestManager(), null, _provider.Object); var attr = new HasOneAttribute(links: relationship) { RightType = typeof(Author), PublicRelationshipName = "author" }; - // act + // Act var links = builder.GetRelationshipLinks(attr, new Article { Id = 123 }); - // assert + // Assert if (expectedSelfLink == null && expectedRelatedLink == null) { Assert.Null(links); @@ -136,17 +136,17 @@ public void BuildTopLevelLinks_GlobalAndResourceConfiguration_ExpectedLinks(Link object expectedSelfLink, bool pages) { - // arrange + // Arrange var config = GetConfiguration(topLevelLinks: global); var primaryResource = GetResourceContext
(topLevelLinks: resource); _provider.Setup(m => m.GetResourceContext
()).Returns(primaryResource); var builder = new LinkBuilder(config, GetRequestManager(), _pageService, _provider.Object); - // act + // Act var links = builder.GetTopLevelLinks(primaryResource); - // assert + // Assert if (!pages && expectedSelfLink == null) { Assert.Null(links); diff --git a/test/UnitTests/Builders/MetaBuilderTests.cs b/test/UnitTests/Builders/MetaBuilderTests.cs index c0cf81d4d3..58e35b7bd6 100644 --- a/test/UnitTests/Builders/MetaBuilderTests.cs +++ b/test/UnitTests/Builders/MetaBuilderTests.cs @@ -9,16 +9,16 @@ // [Fact] // public void Can_Add_Key_Value() // { -// // arrange +// // Arrange // var builder = new MetaBuilder(); // var key = "test"; // var value = "testValue"; -// // act +// // Act // builder.Add(key, value); // var result = builder.Build(); -// // assert +// // Assert // Assert.NotEmpty(result); // Assert.Equal(value, result[key]); // } @@ -26,18 +26,18 @@ // [Fact] // public void Can_Add_Multiple_Values() // { -// // arrange +// // Arrange // var builder = new MetaBuilder(); // var input = new Dictionary { // { "key1", "value1" }, // { "key2", "value2" } // }; -// // act +// // Act // builder.Add(input); // var result = builder.Build(); -// // assert +// // Assert // Assert.NotEmpty(result); // foreach (var entry in input) // Assert.Equal(input[entry.Key], result[entry.Key]); @@ -46,7 +46,7 @@ // [Fact] // public void When_Adding_Duplicate_Values_Keep_Newest() // { -// // arrange +// // Arrange // var builder = new MetaBuilder(); // var key = "key"; @@ -60,11 +60,11 @@ // { "key2", "value2" } // }; -// // act +// // Act // builder.Add(input); // var result = builder.Build(); -// // assert +// // Assert // Assert.NotEmpty(result); // Assert.Equal(input.Count, result.Count); // Assert.Equal(input[key], result[key]); diff --git a/test/UnitTests/Controllers/BaseJsonApiController_Tests.cs b/test/UnitTests/Controllers/BaseJsonApiController_Tests.cs index f33ae0aa30..d33ba1da04 100644 --- a/test/UnitTests/Controllers/BaseJsonApiController_Tests.cs +++ b/test/UnitTests/Controllers/BaseJsonApiController_Tests.cs @@ -22,14 +22,14 @@ public class Resource : Identifiable [Fact] public async Task GetAsync_Calls_Service() { - // arrange + // Arrange var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, getAll: serviceMock.Object); - // act + // Act await controller.GetAsync(); - // assert + // Assert serviceMock.Verify(m => m.GetAsync(), Times.Once); } @@ -37,29 +37,29 @@ public async Task GetAsync_Calls_Service() [Fact] public async Task GetAsync_Throws_405_If_No_Service() { - // arrange + // Arrange var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, null); - // act + // Act var exception = await Assert.ThrowsAsync(() => controller.GetAsync()); - // assert + // Assert Assert.Equal(405, exception.GetStatusCode()); } [Fact] public async Task GetAsyncById_Calls_Service() { - // arrange + // Arrange const int id = 0; var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, getById: serviceMock.Object); - // act + // Act await controller.GetAsync(id); - // assert + // Assert serviceMock.Verify(m => m.GetAsync(id), Times.Once); } @@ -67,108 +67,108 @@ public async Task GetAsyncById_Calls_Service() [Fact] public async Task GetAsyncById_Throws_405_If_No_Service() { - // arrange + // Arrange const int id = 0; var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, getById: null); - // act + // Act var exception = await Assert.ThrowsAsync(() => controller.GetAsync(id)); - // assert + // Assert Assert.Equal(405, exception.GetStatusCode()); } [Fact] public async Task GetRelationshipsAsync_Calls_Service() { - // arrange + // Arrange const int id = 0; var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, getRelationships: serviceMock.Object); - // act + // Act await controller.GetRelationshipsAsync(id, string.Empty); - // assert + // Assert serviceMock.Verify(m => m.GetRelationshipsAsync(id, string.Empty), Times.Once); } [Fact] public async Task GetRelationshipsAsync_Throws_405_If_No_Service() { - // arrange + // Arrange const int id = 0; var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, getRelationships: null); - // act + // Act var exception = await Assert.ThrowsAsync(() => controller.GetRelationshipsAsync(id, string.Empty)); - // assert + // Assert Assert.Equal(405, exception.GetStatusCode()); } [Fact] public async Task GetRelationshipAsync_Calls_Service() { - // arrange + // Arrange const int id = 0; var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, getRelationship: serviceMock.Object); - // act + // Act await controller.GetRelationshipAsync(id, string.Empty); - // assert + // Assert serviceMock.Verify(m => m.GetRelationshipAsync(id, string.Empty), Times.Once); } [Fact] public async Task GetRelationshipAsync_Throws_405_If_No_Service() { - // arrange + // Arrange const int id = 0; var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, getRelationship: null); - // act + // Act var exception = await Assert.ThrowsAsync(() => controller.GetRelationshipAsync(id, string.Empty)); - // assert + // Assert Assert.Equal(405, exception.GetStatusCode()); } [Fact] public async Task PatchAsync_Calls_Service() { - // arrange + // Arrange const int id = 0; var resource = new Resource(); var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new JsonApiOptions(), update: serviceMock.Object); - // act + // Act await controller.PatchAsync(id, resource); - // assert + // Assert serviceMock.Verify(m => m.UpdateAsync(id, It.IsAny()), Times.Once); } [Fact] public async Task PatchAsync_ModelStateInvalid_ValidateModelStateDisbled() { - // arrange + // Arrange const int id = 0; var resource = new Resource(); var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new JsonApiOptions(), update: serviceMock.Object); - // act + // Act var response = await controller.PatchAsync(id, resource); - // assert + // Assert serviceMock.Verify(m => m.UpdateAsync(id, It.IsAny()), Times.Once); Assert.IsNotType(response); } @@ -176,7 +176,7 @@ public async Task PatchAsync_ModelStateInvalid_ValidateModelStateDisbled() [Fact] public async Task PatchAsync_ModelStateInvalid_ValidateModelStateEnabled() { - // arrange + // Arrange const int id = 0; var resource = new Resource(); var serviceMock = new Mock>(); @@ -184,10 +184,10 @@ public async Task PatchAsync_ModelStateInvalid_ValidateModelStateEnabled() var controller = new BaseJsonApiController(new JsonApiOptions { ValidateModelState = true }, update: serviceMock.Object); controller.ModelState.AddModelError("TestAttribute", "Failed Validation"); - // act + // Act var response = await controller.PatchAsync(id, resource); - // assert + // Assert serviceMock.Verify(m => m.UpdateAsync(id, It.IsAny()), Times.Never); Assert.IsType(response); Assert.IsType(((UnprocessableEntityObjectResult)response).Value); @@ -196,22 +196,22 @@ public async Task PatchAsync_ModelStateInvalid_ValidateModelStateEnabled() [Fact] public async Task PatchAsync_Throws_405_If_No_Service() { - // arrange + // Arrange const int id = 0; var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, update: null); - // act + // Act var exception = await Assert.ThrowsAsync(() => controller.PatchAsync(id, It.IsAny())); - // assert + // Assert Assert.Equal(405, exception.GetStatusCode()); } [Fact] public async Task PostAsync_Calls_Service() { - // arrange + // Arrange var resource = new Resource(); var serviceMock = new Mock>(); @@ -219,17 +219,17 @@ public async Task PostAsync_Calls_Service() serviceMock.Setup(m => m.CreateAsync(It.IsAny())).ReturnsAsync(resource); controller.ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext { HttpContext = new DefaultHttpContext() }; - // act + // Act await controller.PostAsync(resource); - // assert + // Assert serviceMock.Verify(m => m.CreateAsync(It.IsAny()), Times.Once); } [Fact] public async Task PostAsync_ModelStateInvalid_ValidateModelStateDisabled() { - // arrange + // Arrange var resource = new Resource(); var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new JsonApiOptions { ValidateModelState = false }, create: serviceMock.Object); @@ -237,10 +237,10 @@ public async Task PostAsync_ModelStateInvalid_ValidateModelStateDisabled() serviceMock.Setup(m => m.CreateAsync(It.IsAny())).ReturnsAsync(resource); - // act + // Act var response = await controller.PostAsync(resource); - // assert + // Assert serviceMock.Verify(m => m.CreateAsync(It.IsAny()), Times.Once); Assert.IsNotType(response); } @@ -248,7 +248,7 @@ public async Task PostAsync_ModelStateInvalid_ValidateModelStateDisabled() [Fact] public async Task PostAsync_ModelStateInvalid_ValidateModelStateEnabled() { - // arrange + // Arrange var resource = new Resource(); var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new JsonApiOptions { ValidateModelState = true }, create: serviceMock.Object); @@ -257,10 +257,10 @@ public async Task PostAsync_ModelStateInvalid_ValidateModelStateEnabled() serviceMock.Setup(m => m.CreateAsync(It.IsAny())).ReturnsAsync(resource); - // act + // Act var response = await controller.PostAsync(resource); - // assert + // Assert serviceMock.Verify(m => m.CreateAsync(It.IsAny()), Times.Never); Assert.IsType(response); Assert.IsType(((UnprocessableEntityObjectResult)response).Value); @@ -269,31 +269,31 @@ public async Task PostAsync_ModelStateInvalid_ValidateModelStateEnabled() [Fact] public async Task PatchRelationshipsAsync_Calls_Service() { - // arrange + // Arrange const int id = 0; var resource = new Resource(); var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, updateRelationships: serviceMock.Object); - // act + // Act await controller.PatchRelationshipsAsync(id, string.Empty, null); - // assert + // Assert serviceMock.Verify(m => m.UpdateRelationshipsAsync(id, string.Empty, null), Times.Once); } [Fact] public async Task PatchRelationshipsAsync_Throws_405_If_No_Service() { - // arrange + // Arrange const int id = 0; var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, updateRelationships: null); - // act + // Act var exception = await Assert.ThrowsAsync(() => controller.PatchRelationshipsAsync(id, string.Empty, null)); - // assert + // Assert Assert.Equal(405, exception.GetStatusCode()); } @@ -316,17 +316,17 @@ public async Task DeleteAsync_Calls_Service() [Fact] public async Task DeleteAsync_Throws_405_If_No_Service() { - // arrange + // Arrange const int id = 0; var serviceMock = new Mock>(); var controller = new BaseJsonApiController(new Mock().Object, delete: null); - // act + // Act var exception = await Assert.ThrowsAsync(() => controller.DeleteAsync(id)); - // assert + // Assert Assert.Equal(405, exception.GetStatusCode()); } diff --git a/test/UnitTests/Controllers/JsonApiControllerMixin_Tests.cs b/test/UnitTests/Controllers/JsonApiControllerMixin_Tests.cs index 850c459e32..00f265daed 100644 --- a/test/UnitTests/Controllers/JsonApiControllerMixin_Tests.cs +++ b/test/UnitTests/Controllers/JsonApiControllerMixin_Tests.cs @@ -1,56 +1,56 @@ -using System.Collections.Generic; -using JsonApiDotNetCore.Controllers; -using JsonApiDotNetCore.Internal; -using Microsoft.AspNetCore.Mvc; -using Xunit; - -namespace UnitTests -{ - public class JsonApiControllerMixin_Tests : JsonApiControllerMixin - { - - [Fact] - public void Errors_Correctly_Infers_Status_Code() - { - // arrange - var errors422 = new ErrorCollection { - Errors = new List { - new Error(422, "bad specific"), - new Error(422, "bad other specific"), - } - }; - - var errors400 = new ErrorCollection { - Errors = new List { - new Error(200, "weird"), - new Error(400, "bad"), - new Error(422, "bad specific"), - } - }; - - var errors500 = new ErrorCollection { - Errors = new List { - new Error(200, "weird"), - new Error(400, "bad"), - new Error(422, "bad specific"), - new Error(500, "really bad"), - new Error(502, "really bad specific"), - } - }; - - // act - var result422 = this.Errors(errors422); - var result400 = this.Errors(errors400); - var result500 = this.Errors(errors500); - - // assert - var response422 = Assert.IsType(result422); - var response400 = Assert.IsType(result400); - var response500 = Assert.IsType(result500); - - Assert.Equal(422, response422.StatusCode); - Assert.Equal(400, response400.StatusCode); - Assert.Equal(500, response500.StatusCode); - } - } -} +using System.Collections.Generic; +using JsonApiDotNetCore.Controllers; +using JsonApiDotNetCore.Internal; +using Microsoft.AspNetCore.Mvc; +using Xunit; + +namespace UnitTests +{ + public class JsonApiControllerMixin_Tests : JsonApiControllerMixin + { + + [Fact] + public void Errors_Correctly_Infers_Status_Code() + { + // Arrange + var errors422 = new ErrorCollection { + Errors = new List { + new Error(422, "bad specific"), + new Error(422, "bad other specific"), + } + }; + + var errors400 = new ErrorCollection { + Errors = new List { + new Error(200, "weird"), + new Error(400, "bad"), + new Error(422, "bad specific"), + } + }; + + var errors500 = new ErrorCollection { + Errors = new List { + new Error(200, "weird"), + new Error(400, "bad"), + new Error(422, "bad specific"), + new Error(500, "really bad"), + new Error(502, "really bad specific"), + } + }; + + // Act + var result422 = this.Errors(errors422); + var result400 = this.Errors(errors400); + var result500 = this.Errors(errors500); + + // Assert + var response422 = Assert.IsType(result422); + var response400 = Assert.IsType(result400); + var response500 = Assert.IsType(result500); + + Assert.Equal(422, response422.StatusCode); + Assert.Equal(400, response400.StatusCode); + Assert.Equal(500, response500.StatusCode); + } + } +} diff --git a/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs b/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs index bdcdb002d0..b04f5d8200 100644 --- a/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs +++ b/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs @@ -27,19 +27,19 @@ public class IServiceCollectionExtensionsTests [Fact] public void AddJsonApiInternals_Adds_All_Required_Services() { - // arrange + // Arrange var services = new ServiceCollection(); services.AddDbContext(options => options.UseInMemoryDatabase("UnitTestDb"), ServiceLifetime.Transient); services.AddJsonApi(); - // act + // Act // this is required because the DbContextResolver requires access to the current HttpContext // to get the request scoped DbContext instance services.AddScoped(); var provider = services.BuildServiceProvider(); - // assert + // Assert var currentRequest = provider.GetService(); Assert.NotNull(currentRequest); var resourceGraph = provider.GetService(); @@ -62,13 +62,13 @@ public void AddJsonApiInternals_Adds_All_Required_Services() [Fact] public void AddResourceService_Registers_All_Shorthand_Service_Interfaces() { - // arrange + // Arrange var services = new ServiceCollection(); - // act + // Act services.AddResourceService(); - // assert + // Assert var provider = services.BuildServiceProvider(); Assert.IsType(provider.GetService(typeof(IResourceService))); Assert.IsType(provider.GetService(typeof(IResourceCmdService))); @@ -85,13 +85,13 @@ public void AddResourceService_Registers_All_Shorthand_Service_Interfaces() [Fact] public void AddResourceService_Registers_All_LongForm_Service_Interfaces() { - // arrange + // Arrange var services = new ServiceCollection(); - // act + // Act services.AddResourceService(); - // assert + // Assert var provider = services.BuildServiceProvider(); Assert.IsType(provider.GetService(typeof(IResourceService))); Assert.IsType(provider.GetService(typeof(IResourceCmdService))); @@ -108,25 +108,25 @@ public void AddResourceService_Registers_All_LongForm_Service_Interfaces() [Fact] public void AddResourceService_Throws_If_Type_Does_Not_Implement_Any_Interfaces() { - // arrange + // Arrange var services = new ServiceCollection(); - // act, assert + // Act, assert Assert.Throws(() => services.AddResourceService()); } [Fact] public void AddJsonApi_With_Context_Uses_DbSet_PropertyName_If_NoOtherSpecified() { - // arrange + // Arrange var services = new ServiceCollection(); services.AddScoped(); - // act + // Act services.AddJsonApi(); - // assert + // Assert var provider = services.BuildServiceProvider(); var resourceGraph = provider.GetService(); var resource = resourceGraph.GetResourceContext(typeof(IntResource)); diff --git a/test/UnitTests/Extensions/TypeExtensions_Tests.cs b/test/UnitTests/Extensions/TypeExtensions_Tests.cs index f565019f26..b473ceb5e3 100644 --- a/test/UnitTests/Extensions/TypeExtensions_Tests.cs +++ b/test/UnitTests/Extensions/TypeExtensions_Tests.cs @@ -11,13 +11,13 @@ public class TypeExtensions_Tests [Fact] public void GetCollection_Creates_List_If_T_Implements_Interface() { - // arrange + // Arrange var type = typeof(Model); - // act + // Act var collection = type.GetEmptyCollection(); - // assert + // Assert Assert.NotNull(collection); Assert.Empty(collection); Assert.IsType>(collection); @@ -26,13 +26,13 @@ public void GetCollection_Creates_List_If_T_Implements_Interface() [Fact] public void New_Creates_An_Instance_If_T_Implements_Interface() { - // arrange + // Arrange var type = typeof(Model); - // act + // Act var instance = type.New(); - // assert + // Assert Assert.NotNull(instance); Assert.IsType(instance); } @@ -40,26 +40,26 @@ public void New_Creates_An_Instance_If_T_Implements_Interface() [Fact] public void Implements_Returns_True_If_Type_Implements_Interface() { - // arrange + // Arrange var type = typeof(Model); - // act + // Act var result = type.Implements(); - // assert + // Assert Assert.True(result); } [Fact] public void Implements_Returns_False_If_Type_DoesNot_Implement_Interface() { - // arrange + // Arrange var type = typeof(String); - // act + // Act var result = type.Implements(); - // assert + // Assert Assert.False(result); } diff --git a/test/UnitTests/Graph/TypeLocator_Tests.cs b/test/UnitTests/Graph/TypeLocator_Tests.cs index 860730857e..26381ea1fb 100644 --- a/test/UnitTests/Graph/TypeLocator_Tests.cs +++ b/test/UnitTests/Graph/TypeLocator_Tests.cs @@ -34,21 +34,21 @@ public void GetGenericInterfaceImplementation_Gets_Implementation() [Fact] public void GetDerivedGenericTypes_Gets_Implementation() { - // arrange + // Arrange var assembly = GetType().Assembly; var openGeneric = typeof(BaseType<>); var genericArg = typeof(int); var expectedImplementation = typeof(DerivedType); - // act + // Act var results = TypeLocator.GetDerivedGenericTypes( assembly, openGeneric, genericArg ); - // assert + // Assert Assert.NotNull(results); var result = Assert.Single(results); Assert.Equal(expectedImplementation, result); @@ -72,11 +72,11 @@ public void GetIdType_Correctly_Identifies_JsonApiResource() [Fact] public void GetIdType_Correctly_Identifies_NonJsonApiResource() { - // arrange + // Arrange var type = typeof(DerivedType); Type exextedIdType = null; - // act + // Act var (isJsonApiResource, idType) = TypeLocator.GetIdType(type); // Assert @@ -87,26 +87,26 @@ public void GetIdType_Correctly_Identifies_NonJsonApiResource() [Fact] public void GetIdentifableTypes_Locates_Identifiable_Resource() { - // arrange + // Arrange var resourceType = typeof(Model); - // act + // Act var results = TypeLocator.GetIdentifableTypes(resourceType.Assembly); - // assert + // Assert Assert.Contains(results, r => r.ResourceType == resourceType); } [Fact] public void GetIdentifableTypes__Only_Contains_IIdentifiable_Types() { - // arrange + // Arrange var resourceType = typeof(Model); - // act + // Act var resourceDescriptors = TypeLocator.GetIdentifableTypes(resourceType.Assembly); - // assert + // Assert foreach(var resourceDescriptor in resourceDescriptors) Assert.True(typeof(IIdentifiable).IsAssignableFrom(resourceDescriptor.ResourceType)); } @@ -114,13 +114,13 @@ public void GetIdentifableTypes__Only_Contains_IIdentifiable_Types() [Fact] public void TryGetResourceDescriptor_Returns_True_If_Type_Is_IIdentfiable() { - // arrange + // Arrange var resourceType = typeof(Model); - // act + // Act var isJsonApiResource = TypeLocator.TryGetResourceDescriptor(resourceType, out var descriptor); - // assert + // Assert Assert.True(isJsonApiResource); Assert.Equal(resourceType, descriptor.ResourceType); Assert.Equal(typeof(int), descriptor.IdType); @@ -129,13 +129,13 @@ public void TryGetResourceDescriptor_Returns_True_If_Type_Is_IIdentfiable() [Fact] public void TryGetResourceDescriptor_Returns_False_If_Type_Is_IIdentfiable() { - // arrange + // Arrange var resourceType = typeof(String); - // act + // Act var isJsonApiResource = TypeLocator.TryGetResourceDescriptor(resourceType, out var _); - // assert + // Assert Assert.False(isJsonApiResource); } } diff --git a/test/UnitTests/Internal/ContextGraphBuilder_Tests.cs b/test/UnitTests/Internal/ContextGraphBuilder_Tests.cs index bb61a42da7..cf61c512d7 100644 --- a/test/UnitTests/Internal/ContextGraphBuilder_Tests.cs +++ b/test/UnitTests/Internal/ContextGraphBuilder_Tests.cs @@ -11,28 +11,28 @@ public class ResourceGraphBuilder_Tests [Fact] public void AddDbContext_Does_Not_Throw_If_Context_Contains_Members_That_DoNot_Implement_IIdentifiable() { - // arrange + // Arrange var resourceGraphBuilder = new ResourceGraphBuilder(); - // act + // Act resourceGraphBuilder.AddDbContext(); var resourceGraph = resourceGraphBuilder.Build() as ResourceGraph; - // assert + // Assert Assert.Empty(resourceGraph.GetResourceContexts()); } [Fact] public void Adding_DbContext_Members_That_DoNot_Implement_IIdentifiable_Creates_Warning() { - // arrange + // Arrange var resourceGraphBuilder = new ResourceGraphBuilder(); - // act + // Act resourceGraphBuilder.AddDbContext(); var resourceGraph = resourceGraphBuilder.Build() as ResourceGraph; - // assert + // Assert Assert.Single(resourceGraph.ValidationResults); Assert.Contains(resourceGraph.ValidationResults, v => v.LogLevel == LogLevel.Warning); } diff --git a/test/UnitTests/Internal/TypeHelper_Tests.cs b/test/UnitTests/Internal/TypeHelper_Tests.cs index 1c105659f5..287444aea4 100644 --- a/test/UnitTests/Internal/TypeHelper_Tests.cs +++ b/test/UnitTests/Internal/TypeHelper_Tests.cs @@ -10,45 +10,45 @@ public class TypeHelper_Tests [Fact] public void Can_Convert_DateTimeOffsets() { - // arrange + // Arrange var dto = DateTimeOffset.Now; var formattedString = dto.ToString("O"); - // act + // Act var result = TypeHelper.ConvertType(formattedString, typeof(DateTimeOffset)); - // assert + // Assert Assert.Equal(dto, result); } [Fact] public void Bad_DateTimeOffset_String_Throws() { - // arrange + // Arrange var formattedString = "this_is_not_a_valid_dto"; - // act - // assert + // Act + // Assert Assert.Throws(() => TypeHelper.ConvertType(formattedString, typeof(DateTimeOffset))); } [Fact] public void Can_Convert_Enums() { - // arrange + // Arrange var formattedString = "1"; - // act + // Act var result = TypeHelper.ConvertType(formattedString, typeof(TestEnum)); - // assert + // Assert Assert.Equal(TestEnum.Test, result); } [Fact] public void ConvertType_Returns_Value_If_Type_Is_Same() { - // arrange + // Arrange var val = new ComplexType { Property = 1 @@ -56,17 +56,17 @@ public void ConvertType_Returns_Value_If_Type_Is_Same() var type = val.GetType(); - // act + // Act var result = TypeHelper.ConvertType(val, type); - // assert + // Assert Assert.Equal(val, result); } [Fact] public void ConvertType_Returns_Value_If_Type_Is_Assignable() { - // arrange + // Arrange var val = new ComplexType { Property = 1 @@ -75,11 +75,11 @@ public void ConvertType_Returns_Value_If_Type_Is_Assignable() var baseType = typeof(BaseType); var iType = typeof(IType); - // act + // Act var baseResult = TypeHelper.ConvertType(val, baseType); var iResult = TypeHelper.ConvertType(val, iType); - // assert + // Assert Assert.Equal(val, baseResult); Assert.Equal(val, iResult); } @@ -87,7 +87,7 @@ public void ConvertType_Returns_Value_If_Type_Is_Assignable() [Fact] public void ConvertType_Returns_Default_Value_For_Empty_Strings() { - // arrange -- can't use non-constants in [Theory] + // Arrange -- can't use non-constants in [Theory] var data = new Dictionary { { typeof(int), 0 }, @@ -99,10 +99,10 @@ public void ConvertType_Returns_Default_Value_For_Empty_Strings() foreach (var t in data) { - // act + // Act var result = TypeHelper.ConvertType(string.Empty, t.Key); - // assert + // Assert Assert.Equal(t.Value, result); } } @@ -124,10 +124,10 @@ public void Can_Convert_TimeSpans() [Fact] public void Bad_TimeSpanString_Throws() { - // arrange + // Arrange var formattedString = "this_is_not_a_valid_timespan"; - // act/assert + // Act/assert Assert.Throws(() => TypeHelper.ConvertType(formattedString, typeof(TimeSpan))); } diff --git a/test/UnitTests/Models/LinkTests.cs b/test/UnitTests/Models/LinkTests.cs index 88f56a4a6d..f8f163fa03 100644 --- a/test/UnitTests/Models/LinkTests.cs +++ b/test/UnitTests/Models/LinkTests.cs @@ -9,10 +9,10 @@ public class LinkTests [Fact] public void All_Contains_All_Flags_Except_None() { - // arrange + // Arrange var e = Link.All; - // assert + // Assert Assert.True(e.HasFlag(Link.Self)); Assert.True(e.HasFlag(Link.Paging)); Assert.True(e.HasFlag(Link.Related)); @@ -23,10 +23,10 @@ public void All_Contains_All_Flags_Except_None() [Fact] public void None_Contains_Only_None() { - // arrange + // Arrange var e = Link.None; - // assert + // Assert Assert.False(e.HasFlag(Link.Self)); Assert.False(e.HasFlag(Link.Paging)); Assert.False(e.HasFlag(Link.Related)); @@ -37,10 +37,10 @@ public void None_Contains_Only_None() [Fact] public void Self() { - // arrange + // Arrange var e = Link.Self; - // assert + // Assert Assert.True(e.HasFlag(Link.Self)); Assert.False(e.HasFlag(Link.Paging)); Assert.False(e.HasFlag(Link.Related)); @@ -51,10 +51,10 @@ public void Self() [Fact] public void Paging() { - // arrange + // Arrange var e = Link.Paging; - // assert + // Assert Assert.False(e.HasFlag(Link.Self)); Assert.True(e.HasFlag(Link.Paging)); Assert.False(e.HasFlag(Link.Related)); @@ -65,10 +65,10 @@ public void Paging() [Fact] public void Related() { - // arrange + // Arrange var e = Link.Related; - // assert + // Assert Assert.False(e.HasFlag(Link.Self)); Assert.False(e.HasFlag(Link.Paging)); Assert.True(e.HasFlag(Link.Related)); diff --git a/test/UnitTests/Models/RelationshipDataTests.cs b/test/UnitTests/Models/RelationshipDataTests.cs index 119f50da7a..eaa52440e6 100644 --- a/test/UnitTests/Models/RelationshipDataTests.cs +++ b/test/UnitTests/Models/RelationshipDataTests.cs @@ -10,7 +10,7 @@ public class RelationshipDataTests [Fact] public void Setting_ExposeData_To_List_Sets_ManyData() { - // arrange + // Arrange var relationshipData = new RelationshipEntry(); var relationships = new List { new ResourceIdentifierObject { @@ -19,10 +19,10 @@ public void Setting_ExposeData_To_List_Sets_ManyData() } }; - // act + // Act relationshipData.Data = relationships; - // assert + // Assert Assert.NotEmpty(relationshipData.ManyData); Assert.Equal("authors", relationshipData.ManyData[0].Type); Assert.Equal("9", relationshipData.ManyData[0].Id); @@ -32,7 +32,7 @@ public void Setting_ExposeData_To_List_Sets_ManyData() [Fact] public void Setting_ExposeData_To_JArray_Sets_ManyData() { - // arrange + // Arrange var relationshipData = new RelationshipEntry(); var relationshipsJson = @"[ { @@ -43,10 +43,10 @@ public void Setting_ExposeData_To_JArray_Sets_ManyData() var relationships = JArray.Parse(relationshipsJson); - // act + // Act relationshipData.Data = relationships; - // assert + // Assert Assert.NotEmpty(relationshipData.ManyData); Assert.Equal("authors", relationshipData.ManyData[0].Type); Assert.Equal("9", relationshipData.ManyData[0].Id); @@ -56,17 +56,17 @@ public void Setting_ExposeData_To_JArray_Sets_ManyData() [Fact] public void Setting_ExposeData_To_RIO_Sets_SingleData() { - // arrange + // Arrange var relationshipData = new RelationshipEntry(); var relationship = new ResourceIdentifierObject { Id = "9", Type = "authors" }; - // act + // Act relationshipData.Data = relationship; - // assert + // Assert Assert.NotNull(relationshipData.SingleData); Assert.Equal("authors", relationshipData.SingleData.Type); Assert.Equal("9", relationshipData.SingleData.Id); @@ -76,7 +76,7 @@ public void Setting_ExposeData_To_RIO_Sets_SingleData() [Fact] public void Setting_ExposeData_To_JObject_Sets_SingleData() { - // arrange + // Arrange var relationshipData = new RelationshipEntry(); var relationshipJson = @"{ ""id"": ""9"", @@ -85,10 +85,10 @@ public void Setting_ExposeData_To_JObject_Sets_SingleData() var relationship = JObject.Parse(relationshipJson); - // act + // Act relationshipData.Data = relationship; - // assert + // Assert Assert.NotNull(relationshipData.SingleData); Assert.Equal("authors", relationshipData.SingleData.Type); Assert.Equal("9", relationshipData.SingleData.Id); diff --git a/test/UnitTests/Models/ResourceDefinitionTests.cs b/test/UnitTests/Models/ResourceDefinitionTests.cs index e863e55465..41529fc742 100644 --- a/test/UnitTests/Models/ResourceDefinitionTests.cs +++ b/test/UnitTests/Models/ResourceDefinitionTests.cs @@ -22,26 +22,26 @@ public ResourceDefinition_Scenario_Tests() [Fact] public void Request_Filter_Uses_Member_Expression() { - // arrange + // Arrange var resource = new RequestFilteredResource(isAdmin: true); - // act + // Act var attrs = resource.GetAllowedAttributes(); - // assert + // Assert Assert.DoesNotContain(attrs, a => a.InternalAttributeName == nameof(Model.AlwaysExcluded)); } [Fact] public void Request_Filter_Uses_NewExpression() { - // arrange + // Arrange var resource = new RequestFilteredResource(isAdmin: false); - // act + // Act var attrs = resource.GetAllowedAttributes(); - // assert + // Assert Assert.DoesNotContain(attrs, a => a.InternalAttributeName == nameof(Model.AlwaysExcluded)); Assert.DoesNotContain(attrs, a => a.InternalAttributeName == nameof(Model.Password)); } @@ -75,4 +75,4 @@ public override PropertySortOrder GetDefaultSortOrder() (t => t.Prop, SortDirection.Ascending) }; } -} \ No newline at end of file +} diff --git a/test/UnitTests/QueryParameters/FilterServiceTests.cs b/test/UnitTests/QueryParameters/FilterServiceTests.cs index 7e0e4d4462..68937ee793 100644 --- a/test/UnitTests/QueryParameters/FilterServiceTests.cs +++ b/test/UnitTests/QueryParameters/FilterServiceTests.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using JsonApiDotNetCore.Internal.Query; using JsonApiDotNetCore.Query; @@ -17,13 +17,13 @@ public FilterService GetService() [Fact] public void Name_FilterService_IsCorrect() { - // arrange + // Arrange var filterService = GetService(); - // act + // Act var name = filterService.Name; - // assert + // Assert Assert.Equal("filter", name); } @@ -44,16 +44,16 @@ public void Name_FilterService_IsCorrect() [InlineData("title", "le:", "2017-08-15T22:43:47.0156350-05:00")] public void Parse_ValidFilters_CanParse(string key, string @operator, string value) { - // arrange + // Arrange var queryValue = @operator + value; var query = new KeyValuePair($"filter[{key}]", new StringValues(queryValue)); var filterService = GetService(); - // act + // Act filterService.Parse(query); var filter = filterService.Get().Single(); - // assert + // Assert if (!string.IsNullOrEmpty(@operator)) Assert.Equal(@operator.Replace(":", ""), filter.Operation.ToString("G")); else diff --git a/test/UnitTests/QueryParameters/IncludeServiceTests.cs b/test/UnitTests/QueryParameters/IncludeServiceTests.cs index 6771d53c7d..2230ed0b41 100644 --- a/test/UnitTests/QueryParameters/IncludeServiceTests.cs +++ b/test/UnitTests/QueryParameters/IncludeServiceTests.cs @@ -20,28 +20,28 @@ public IncludeService GetService(ResourceContext resourceContext = null) [Fact] public void Name_IncludeService_IsCorrect() { - // arrange + // Arrange var filterService = GetService(); - // act + // Act var name = filterService.Name; - // assert + // Assert Assert.Equal("include", name); } [Fact] public void Parse_MultipleNestedChains_CanParse() { - // arrange + // Arrange const string chain = "author.blogs.reviewer.favorite-food,reviewer.blogs.author.favorite-song"; var query = new KeyValuePair("include", new StringValues(chain)); var service = GetService(); - // act + // Act service.Parse(query); - // assert + // Assert var chains = service.Get(); Assert.Equal(2, chains.Count); var firstChain = chains[0]; @@ -55,12 +55,12 @@ public void Parse_MultipleNestedChains_CanParse() [Fact] public void Parse_ChainsOnWrongMainResource_ThrowsJsonApiException() { - // arrange + // Arrange const string chain = "author.blogs.reviewer.favorite-food,reviewer.blogs.author.favorite-song"; var query = new KeyValuePair("include", new StringValues(chain)); var service = GetService(_resourceGraph.GetResourceContext()); - // act, assert + // Act, assert var exception = Assert.Throws( () => service.Parse(query)); Assert.Contains("Invalid", exception.Message); } @@ -68,12 +68,12 @@ public void Parse_ChainsOnWrongMainResource_ThrowsJsonApiException() [Fact] public void Parse_NotIncludable_ThrowsJsonApiException() { - // arrange + // Arrange const string chain = "cannot-include"; var query = new KeyValuePair("include", new StringValues(chain)); var service = GetService(); - // act, assert + // Act, assert var exception = Assert.Throws(() => service.Parse(query)); Assert.Contains("not allowed", exception.Message); } @@ -81,12 +81,12 @@ public void Parse_NotIncludable_ThrowsJsonApiException() [Fact] public void Parse_NonExistingRelationship_ThrowsJsonApiException() { - // arrange + // Arrange const string chain = "nonsense"; var query = new KeyValuePair("include", new StringValues(chain)); var service = GetService(); - // act, assert + // Act, assert var exception = Assert.Throws(() => service.Parse(query)); Assert.Contains("Invalid", exception.Message); } @@ -94,12 +94,12 @@ public void Parse_NonExistingRelationship_ThrowsJsonApiException() [Fact] public void Parse_EmptyChain_ThrowsJsonApiException() { - // arrange + // Arrange const string chain = ""; var query = new KeyValuePair("include", new StringValues(chain)); var service = GetService(); - // act, assert + // Act, assert var exception = Assert.Throws(() => service.Parse(query)); Assert.Contains("Include parameter must not be empty if provided", exception.Message); } diff --git a/test/UnitTests/QueryParameters/OmitDefaultService.cs b/test/UnitTests/QueryParameters/OmitDefaultService.cs index e4e64d58b5..522c15049c 100644 --- a/test/UnitTests/QueryParameters/OmitDefaultService.cs +++ b/test/UnitTests/QueryParameters/OmitDefaultService.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Query; using Microsoft.Extensions.Primitives; @@ -21,13 +21,13 @@ public OmitDefaultService GetService(bool @default, bool @override) [Fact] public void Name_OmitNullService_IsCorrect() { - // arrange + // Arrange var service = GetService(true, true); - // act + // Act var name = service.Name; - // assert + // Assert Assert.Equal("omitdefault", name); } @@ -38,14 +38,14 @@ public void Name_OmitNullService_IsCorrect() [InlineData("true", false, false, false)] public void Parse_QueryConfigWithApiSettings_CanParse(string queryConfig, bool @default, bool @override, bool expected) { - // arrange + // Arrange var query = new KeyValuePair($"omitNull", new StringValues(queryConfig)); var service = GetService(@default, @override); - // act + // Act service.Parse(query); - // assert + // Assert Assert.Equal(expected, service.Config); } } diff --git a/test/UnitTests/QueryParameters/OmitNullService.cs b/test/UnitTests/QueryParameters/OmitNullService.cs index f9f8237e50..f4ec0e0ed5 100644 --- a/test/UnitTests/QueryParameters/OmitNullService.cs +++ b/test/UnitTests/QueryParameters/OmitNullService.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Query; using Microsoft.Extensions.Primitives; @@ -21,13 +21,13 @@ public OmitNullService GetService(bool @default, bool @override) [Fact] public void Name_OmitNullService_IsCorrect() { - // arrange + // Arrange var service = GetService(true, true); - // act + // Act var name = service.Name; - // assert + // Assert Assert.Equal("omitnull", name); } @@ -38,14 +38,14 @@ public void Name_OmitNullService_IsCorrect() [InlineData("true", false, false, false)] public void Parse_QueryConfigWithApiSettings_CanParse(string queryConfig, bool @default, bool @override, bool expected) { - // arrange + // Arrange var query = new KeyValuePair($"omitNull", new StringValues(queryConfig)); var service = GetService(@default, @override); - // act + // Act service.Parse(query); - // assert + // Assert Assert.Equal(expected, service.Config); } } diff --git a/test/UnitTests/QueryParameters/PageServiceTests.cs b/test/UnitTests/QueryParameters/PageServiceTests.cs index 003efbe195..22373d7d86 100644 --- a/test/UnitTests/QueryParameters/PageServiceTests.cs +++ b/test/UnitTests/QueryParameters/PageServiceTests.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Query; @@ -17,13 +17,13 @@ public PageService GetService() [Fact] public void Name_PageService_IsCorrect() { - // arrange + // Arrange var filterService = GetService(); - // act + // Act var name = filterService.Name; - // assert + // Assert Assert.Equal("page", name); } @@ -33,11 +33,11 @@ public void Name_PageService_IsCorrect() [InlineData("", 0, true)] public void Parse_PageSize_CanParse(string value, int expectedValue, bool shouldThrow) { - // arrange + // Arrange var query = new KeyValuePair($"page[size]", new StringValues(value)); var service = GetService(); - // act + // Act if (shouldThrow) { var ex = Assert.Throws(() => service.Parse(query)); @@ -56,12 +56,12 @@ public void Parse_PageSize_CanParse(string value, int expectedValue, bool should [InlineData("", 0, true)] public void Parse_PageNumber_CanParse(string value, int expectedValue, bool shouldThrow) { - // arrange + // Arrange var query = new KeyValuePair($"page[number]", new StringValues(value)); var service = GetService(); - // act + // Act if (shouldThrow) { var ex = Assert.Throws(() => service.Parse(query)); diff --git a/test/UnitTests/QueryParameters/SortServiceTests.cs b/test/UnitTests/QueryParameters/SortServiceTests.cs index 278812fa5e..4284b89790 100644 --- a/test/UnitTests/QueryParameters/SortServiceTests.cs +++ b/test/UnitTests/QueryParameters/SortServiceTests.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Query; using Microsoft.Extensions.Primitives; @@ -16,13 +16,13 @@ public SortService GetService() [Fact] public void Name_SortService_IsCorrect() { - // arrange + // Arrange var filterService = GetService(); - // act + // Act var name = filterService.Name; - // assert + // Assert Assert.Equal("sort", name); } @@ -32,11 +32,11 @@ public void Name_SortService_IsCorrect() [InlineData(",,2")] public void Parse_InvalidSortQuery_ThrowsJsonApiException(string stringSortQuery) { - // arrange + // Arrange var query = new KeyValuePair($"sort", stringSortQuery); var sortService = GetService(); - // act, assert + // Act, assert var exception = Assert.Throws(() => sortService.Parse(query)); Assert.Contains("sort", exception.Message); } diff --git a/test/UnitTests/QueryParameters/SparseFieldsServiceTests.cs b/test/UnitTests/QueryParameters/SparseFieldsServiceTests.cs index dfef70051e..a87b9e6927 100644 --- a/test/UnitTests/QueryParameters/SparseFieldsServiceTests.cs +++ b/test/UnitTests/QueryParameters/SparseFieldsServiceTests.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Models; @@ -18,20 +18,20 @@ public SparseFieldsService GetService(ResourceContext resourceContext = null) [Fact] public void Name_SparseFieldsService_IsCorrect() { - // arrange + // Arrange var filterService = GetService(); - // act + // Act var name = filterService.Name; - // assert + // Assert Assert.Equal("fields", name); } [Fact] public void Parse_ValidSelection_CanParse() { - // arrange + // Arrange const string type = "articles"; const string attrName = "some-field"; const string internalAttrName = "SomeField"; @@ -48,11 +48,11 @@ public void Parse_ValidSelection_CanParse() }; var service = GetService(resourceContext); - // act + // Act service.Parse(query); var result = service.Get(); - // assert + // Assert Assert.NotEmpty(result); Assert.Equal(idAttribute, result.First()); Assert.Equal(attribute, result[1]); @@ -61,7 +61,7 @@ public void Parse_ValidSelection_CanParse() [Fact] public void Parse_TypeNameAsNavigation_Throws400ErrorWithRelationshipsOnlyMessage() { - // arrange + // Arrange const string type = "articles"; const string attrName = "some-field"; const string internalAttrName = "SomeField"; @@ -78,7 +78,7 @@ public void Parse_TypeNameAsNavigation_Throws400ErrorWithRelationshipsOnlyMessag }; var service = GetService(resourceContext); - // act, assert + // Act, assert var ex = Assert.Throws(() => service.Parse(query)); Assert.Contains("relationships only", ex.Message); } @@ -86,7 +86,7 @@ public void Parse_TypeNameAsNavigation_Throws400ErrorWithRelationshipsOnlyMessag [Fact] public void Parse_DeeplyNestedSelection_Throws400ErrorWithDeeplyNestedMessage() { - // arrange + // Arrange const string type = "articles"; const string relationship = "author.employer"; const string attrName = "some-field"; @@ -104,7 +104,7 @@ public void Parse_DeeplyNestedSelection_Throws400ErrorWithDeeplyNestedMessage() }; var service = GetService(resourceContext); - // act, assert + // Act, assert var ex = Assert.Throws(() => service.Parse(query)); Assert.Contains("deeply nested", ex.Message); } @@ -112,7 +112,7 @@ public void Parse_DeeplyNestedSelection_Throws400ErrorWithDeeplyNestedMessage() [Fact] public void Parse_InvalidField_ThrowsJsonApiException() { - // arrange + // Arrange const string type = "articles"; const string attrName = "dne"; @@ -127,7 +127,7 @@ public void Parse_InvalidField_ThrowsJsonApiException() var service = GetService(resourceContext); - // act , assert + // Act , assert var ex = Assert.Throws(() => service.Parse(query)); Assert.Equal(400, ex.GetStatusCode()); } diff --git a/test/UnitTests/ResourceHooks/AffectedEntitiesHelperTests.cs b/test/UnitTests/ResourceHooks/AffectedEntitiesHelperTests.cs index bf81006448..2d22742625 100644 --- a/test/UnitTests/ResourceHooks/AffectedEntitiesHelperTests.cs +++ b/test/UnitTests/ResourceHooks/AffectedEntitiesHelperTests.cs @@ -65,30 +65,30 @@ public RelationshipDictionaryTests() [Fact] public void RelationshipsDictionary_GetByRelationships() { - // arrange + // Arrange RelationshipsDictionary relationshipsDictionary = new RelationshipsDictionary(Relationships); - // act + // Act Dictionary> toOnes = relationshipsDictionary.GetByRelationship(); Dictionary> toManies = relationshipsDictionary.GetByRelationship(); Dictionary> notTargeted = relationshipsDictionary.GetByRelationship(); - // assert + // Assert AssertRelationshipDictionaryGetters(relationshipsDictionary, toOnes, toManies, notTargeted); } [Fact] public void RelationshipsDictionary_GetAffected() { - // arrange + // Arrange RelationshipsDictionary relationshipsDictionary = new RelationshipsDictionary(Relationships); - // act + // Act var affectedThroughFirstToOne = relationshipsDictionary.GetAffected(d => d.FirstToOne).ToList(); var affectedThroughSecondToOne = relationshipsDictionary.GetAffected(d => d.SecondToOne).ToList(); var affectedThroughToMany = relationshipsDictionary.GetAffected(d => d.ToManies).ToList(); - // assert + // Assert affectedThroughFirstToOne.ForEach((entitiy) => Assert.Contains(entitiy, FirstToOnesEntities)); affectedThroughSecondToOne.ForEach((entitiy) => Assert.Contains(entitiy, SecondToOnesEntities)); affectedThroughToMany.ForEach((entitiy) => Assert.Contains(entitiy, ToManiesEntities)); @@ -97,10 +97,10 @@ public void RelationshipsDictionary_GetAffected() [Fact] public void EntityHashSet_GetByRelationships() { - // arrange + // Arrange EntityHashSet entities = new EntityHashSet(AllEntities, Relationships); - // act + // Act Dictionary> toOnes = entities.GetByRelationship(); Dictionary> toManies = entities.GetByRelationship(); Dictionary> notTargeted = entities.GetByRelationship(); @@ -118,11 +118,11 @@ public void EntityHashSet_GetByRelationships() [Fact] public void EntityDiff_GetByRelationships() { - // arrange + // Arrange var dbEntities = new HashSet(AllEntities.Select(e => new Dummy { Id = e.Id }).ToList()); DiffableEntityHashSet diffs = new DiffableEntityHashSet(AllEntities, dbEntities, Relationships, null); - // act + // Act Dictionary> toOnes = diffs.GetByRelationship(); Dictionary> toManies = diffs.GetByRelationship(); Dictionary> notTargeted = diffs.GetByRelationship(); @@ -151,7 +151,7 @@ public void EntityDiff_GetByRelationships() [Fact] public void EntityDiff_Loops_Over_Diffs() { - // arrange + // Arrange var dbEntities = new HashSet(AllEntities.Select(e => new Dummy { Id = e.Id })); DiffableEntityHashSet diffs = new DiffableEntityHashSet(AllEntities, dbEntities, Relationships, null); @@ -168,16 +168,16 @@ public void EntityDiff_Loops_Over_Diffs() [Fact] public void EntityDiff_GetAffected_Relationships() { - // arrange + // Arrange var dbEntities = new HashSet(AllEntities.Select(e => new Dummy { Id = e.Id })); DiffableEntityHashSet diffs = new DiffableEntityHashSet(AllEntities, dbEntities, Relationships, null); - // act + // Act var affectedThroughFirstToOne = diffs.GetAffected(d => d.FirstToOne).ToList(); var affectedThroughSecondToOne = diffs.GetAffected(d => d.SecondToOne).ToList(); var affectedThroughToMany = diffs.GetAffected(d => d.ToManies).ToList(); - // assert + // Assert affectedThroughFirstToOne.ForEach((entitiy) => Assert.Contains(entitiy, FirstToOnesEntities)); affectedThroughSecondToOne.ForEach((entitiy) => Assert.Contains(entitiy, SecondToOnesEntities)); affectedThroughToMany.ForEach((entitiy) => Assert.Contains(entitiy, ToManiesEntities)); @@ -186,7 +186,7 @@ public void EntityDiff_GetAffected_Relationships() [Fact] public void EntityDiff_GetAffected_Attributes() { - // arrange + // Arrange var dbEntities = new HashSet(AllEntities.Select(e => new Dummy { Id = e.Id })); var updatedAttributes = new Dictionary> { @@ -194,11 +194,11 @@ public void EntityDiff_GetAffected_Attributes() }; DiffableEntityHashSet diffs = new DiffableEntityHashSet(AllEntities, dbEntities, Relationships, updatedAttributes); - // act + // Act var affectedThroughSomeUpdatedProperty = diffs.GetAffected(d => d.SomeUpdatedProperty).ToList(); var affectedThroughSomeNotUpdatedProperty = diffs.GetAffected(d => d.SomeNotUpdatedProperty).ToList(); - // assert + // Assert Assert.NotEmpty(affectedThroughSomeUpdatedProperty); Assert.Empty(affectedThroughSomeNotUpdatedProperty); } diff --git a/test/UnitTests/ResourceHooks/DiscoveryTests.cs b/test/UnitTests/ResourceHooks/DiscoveryTests.cs index b48adb1af6..3a37184784 100644 --- a/test/UnitTests/ResourceHooks/DiscoveryTests.cs +++ b/test/UnitTests/ResourceHooks/DiscoveryTests.cs @@ -22,9 +22,9 @@ public override void AfterDelete(HashSet entities, ResourcePipeline pipel [Fact] public void Hook_Discovery() { - // arrange & act + // Arrange & act var hookConfig = new HooksDiscovery(); - // assert + // Assert Assert.Contains(ResourceHook.BeforeDelete, hookConfig.ImplementedHooks); Assert.Contains(ResourceHook.AfterDelete, hookConfig.ImplementedHooks); @@ -46,9 +46,9 @@ public AnotherDummyResourceDefinition() : base(new ResourceGraphBuilder().AddRes [Fact] public void Hook_Discovery_With_Inheritance() { - // arrange & act + // Arrange & act var hookConfig = new HooksDiscovery(); - // assert + // Assert Assert.Contains(ResourceHook.BeforeDelete, hookConfig.ImplementedHooks); Assert.Contains(ResourceHook.AfterDelete, hookConfig.ImplementedHooks); } @@ -70,7 +70,7 @@ public void LoaDatabaseValues_Attribute_Not_Allowed() // assert Assert.Throws(() => { - // arrange & act + // Arrange & act var hookConfig = new HooksDiscovery(); }); @@ -95,7 +95,7 @@ public void Multiple_Implementations_Of_ResourceDefinitions() // assert Assert.Throws(() => { - // arrange & act + // Arrange & act var hookConfig = new HooksDiscovery(); }); } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/AfterCreateTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/AfterCreateTests.cs index 80f3966d60..d91231280e 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/AfterCreateTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/AfterCreateTests.cs @@ -13,16 +13,16 @@ public class AfterCreateTests : HooksTestsSetup [Fact] public void AfterCreate() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.AfterCreate(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.AfterCreate(It.IsAny>(), ResourcePipeline.Post), Times.Once()); ownerResourceMock.Verify(rd => rd.AfterUpdateRelationship(It.IsAny>(), ResourcePipeline.Post), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); @@ -31,16 +31,16 @@ public void AfterCreate() [Fact] public void AfterCreate_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.AfterCreate(todoList, ResourcePipeline.Post); - // assert + // Assert ownerResourceMock.Verify(rd => rd.AfterUpdateRelationship(It.IsAny>(), ResourcePipeline.Post), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } @@ -48,16 +48,16 @@ public void AfterCreate_Without_Parent_Hook_Implemented() [Fact] public void AfterCreate_Without_Child_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.AfterCreate(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.AfterCreate(It.IsAny>(), ResourcePipeline.Post), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } @@ -65,16 +65,16 @@ public void AfterCreate_Without_Child_Hook_Implemented() [Fact] public void AfterCreate_Without_Any_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.AfterCreate(todoList, ResourcePipeline.Post); - // assert + // Assert VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreateTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreateTests.cs index a8370067f8..a5438b624d 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreateTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreateTests.cs @@ -13,16 +13,16 @@ public class BeforeCreateTests : HooksTestsSetup [Fact] public void BeforeCreate() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeCreate(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeCreate(It.IsAny>(), ResourcePipeline.Post), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship(It.IsAny>(), It.IsAny>(), ResourcePipeline.Post), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); @@ -31,16 +31,16 @@ public void BeforeCreate() [Fact] public void BeforeCreate_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeCreate(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeCreate(It.IsAny>(), ResourcePipeline.Post), Times.Never()); ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship(It.IsAny>(), It.IsAny>(), ResourcePipeline.Post), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); @@ -48,32 +48,32 @@ public void BeforeCreate_Without_Parent_Hook_Implemented() [Fact] public void BeforeCreate_Without_Child_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeCreate(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeCreate(It.IsAny>(), ResourcePipeline.Post), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } [Fact] public void BeforeCreate_Without_Any_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeCreate(todoList, ResourcePipeline.Post); - // assert + // Assert VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs index 0f1509e94e..ab9d15ad29 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs @@ -69,15 +69,15 @@ public void BeforeCreate() [Fact] public void BeforeCreate_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeCreate(todoList, ResourcePipeline.Post); - // assert + // Assert ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship( It.Is>(ids => PersonIdCheck(ids, personId)), It.IsAny>(), @@ -89,15 +89,15 @@ public void BeforeCreate_Without_Parent_Hook_Implemented() [Fact] public void BeforeCreate_Without_Child_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeCreate(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeCreate(It.Is>((entities) => TodoCheck(entities, description)), ResourcePipeline.Post), Times.Once()); todoResourceMock.Verify(rd => rd.BeforeImplicitUpdateRelationship( It.Is>(rh => TodoCheckRelationships(rh, description + description)), @@ -109,15 +109,15 @@ public void BeforeCreate_Without_Child_Hook_Implemented() [Fact] public void BeforeCreate_NoImplicit() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooksNoImplicit, ResourceHook.BeforeUpdate); var personDiscovery = SetDiscoverableHooks(targetHooksNoImplicit, ResourceHook.BeforeUpdateRelationship); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeCreate(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeCreate(It.Is>((entities) => TodoCheck(entities, description)), ResourcePipeline.Post), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship( It.Is>(ids => PersonIdCheck(ids, personId)), @@ -130,15 +130,15 @@ public void BeforeCreate_NoImplicit() [Fact] public void BeforeCreate_NoImplicit_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooksNoImplicit, ResourceHook.BeforeUpdateRelationship); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeCreate(todoList, ResourcePipeline.Post); - // assert + // Assert ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship( It.Is>(ids => PersonIdCheck(ids, personId)), It.IsAny>(), @@ -150,15 +150,15 @@ public void BeforeCreate_NoImplicit_Without_Parent_Hook_Implemented() [Fact] public void BeforeCreate_NoImplicit_Without_Child_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooksNoImplicit, ResourceHook.BeforeUpdate); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeCreate(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeCreate(It.Is>((entities) => TodoCheck(entities, description)), ResourcePipeline.Post), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/AfterDeleteTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/AfterDeleteTests.cs index 65c8cb4a54..681fa831ef 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/AfterDeleteTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/AfterDeleteTests.cs @@ -29,15 +29,15 @@ public void AfterDelete() [Fact] public void AfterDelete_Without_Any_Hook_Implemented() { - // arrange + // Arrange var discovery = SetDiscoverableHooks(NoHooks, DisableDbValues); (var _, var hookExecutor, var resourceDefinitionMock) = CreateTestObjects(discovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.AfterDelete(todoList, ResourcePipeline.Delete, It.IsAny()); - // assert + // Assert VerifyNoOtherCalls(resourceDefinitionMock); } } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDeleteTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDeleteTests.cs index 15b1c247b1..eda31fe2ac 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDeleteTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDeleteTests.cs @@ -13,15 +13,15 @@ public class BeforeDeleteTests : HooksTestsSetup [Fact] public void BeforeDelete() { - // arrange + // Arrange var discovery = SetDiscoverableHooks(targetHooks, DisableDbValues); (var _, var hookExecutor, var resourceDefinitionMock) = CreateTestObjects(discovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeDelete(todoList, ResourcePipeline.Delete); - // assert + // Assert resourceDefinitionMock.Verify(rd => rd.BeforeDelete(It.IsAny>(), It.IsAny()), Times.Once()); resourceDefinitionMock.VerifyNoOtherCalls(); } @@ -29,15 +29,15 @@ public void BeforeDelete() [Fact] public void BeforeDelete_Without_Any_Hook_Implemented() { - // arrange + // Arrange var discovery = SetDiscoverableHooks(NoHooks, DisableDbValues); (var _, var hookExecutor, var resourceDefinitionMock) = CreateTestObjects(discovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeDelete(todoList, ResourcePipeline.Delete); - // assert + // Assert resourceDefinitionMock.VerifyNoOtherCalls(); } } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDelete_WithDbValue_Tests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDelete_WithDbValue_Tests.cs index a29a0a0664..45db4ecb9a 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDelete_WithDbValue_Tests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDelete_WithDbValue_Tests.cs @@ -36,17 +36,17 @@ public BeforeDelete_WithDbValues_Tests() [Fact] public void BeforeDelete() { - // arrange + // Arrange var personDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var todoDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var passportDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var (_, hookExecutor, personResourceMock, todoResourceMock, passportResourceMock) = CreateTestObjects(personDiscovery, todoDiscovery, passportDiscovery, repoDbContextOptions: options); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeDelete(new List { person }, ResourcePipeline.Delete); - // assert + // Assert personResourceMock.Verify(rd => rd.BeforeDelete(It.IsAny>(), It.IsAny()), Times.Once()); todoResourceMock.Verify(rd => rd.BeforeImplicitUpdateRelationship(It.Is>(rh => CheckImplicitTodos(rh)), ResourcePipeline.Delete), Times.Once()); passportResourceMock.Verify(rd => rd.BeforeImplicitUpdateRelationship(It.Is>(rh => CheckImplicitPassports(rh)), ResourcePipeline.Delete), Times.Once()); @@ -56,17 +56,17 @@ public void BeforeDelete() [Fact] public void BeforeDelete_No_Parent_Hooks() { - // arrange + // Arrange var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var todoDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var passportDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var (_, hookExecutor, personResourceMock, todoResourceMock, passportResourceMock) = CreateTestObjects(personDiscovery, todoDiscovery, passportDiscovery, repoDbContextOptions: options); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeDelete(new List { person }, ResourcePipeline.Delete); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeImplicitUpdateRelationship(It.Is>(rh => CheckImplicitTodos(rh)), ResourcePipeline.Delete), Times.Once()); passportResourceMock.Verify(rd => rd.BeforeImplicitUpdateRelationship(It.Is>(rh => CheckImplicitPassports(rh)), ResourcePipeline.Delete), Times.Once()); VerifyNoOtherCalls(personResourceMock, todoResourceMock, passportResourceMock); @@ -75,17 +75,17 @@ public void BeforeDelete_No_Parent_Hooks() [Fact] public void BeforeDelete_No_Children_Hooks() { - // arrange + // Arrange var personDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var passportDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, personResourceMock, todoResourceMock, passportResourceMock) = CreateTestObjects(personDiscovery, todoDiscovery, passportDiscovery, repoDbContextOptions: options); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeDelete(new List { person }, ResourcePipeline.Delete); - // assert + // Assert personResourceMock.Verify(rd => rd.BeforeDelete(It.IsAny>(), It.IsAny()), Times.Once()); VerifyNoOtherCalls(personResourceMock, todoResourceMock, passportResourceMock); } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/IdentifiableManyToMany_OnReturnTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/IdentifiableManyToMany_OnReturnTests.cs index cc0f89b4a8..c55ad233c9 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/IdentifiableManyToMany_OnReturnTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/IdentifiableManyToMany_OnReturnTests.cs @@ -14,17 +14,17 @@ public class IdentifiableManyToMany_OnReturnTests : HooksTestsSetup [Fact] public void OnReturn() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.OnReturn(It.IsAny>(), ResourcePipeline.Get), Times.Once()); joinResourceMock.Verify(rd => rd.OnReturn(It.Is>((collection) => !collection.Except(joins).Any()), ResourcePipeline.Get), Times.Once()); tagResourceMock.Verify(rd => rd.OnReturn(It.Is>((collection) => !collection.Except(tags).Any()), ResourcePipeline.Get), Times.Once()); @@ -34,17 +34,17 @@ public void OnReturn() [Fact] public void OnReturn_GetRelationship() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.GetRelationship); - // assert + // Assert joinResourceMock.Verify(rd => rd.OnReturn(It.Is>((collection) => !collection.Except(joins).Any()), ResourcePipeline.GetRelationship), Times.Once()); tagResourceMock.Verify(rd => rd.OnReturn(It.Is>((collection) => !collection.Except(tags).Any()), ResourcePipeline.GetRelationship), Times.Once()); VerifyNoOtherCalls(articleResourceMock, joinResourceMock, tagResourceMock); @@ -53,17 +53,17 @@ public void OnReturn_GetRelationship() [Fact] public void OnReturn_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); - // assert + // Assert joinResourceMock.Verify(rd => rd.OnReturn(It.Is>((collection) => !collection.Except(joins).Any()), ResourcePipeline.Get), Times.Once()); tagResourceMock.Verify(rd => rd.OnReturn(It.Is>((collection) => !collection.Except(tags).Any()), ResourcePipeline.Get), Times.Once()); VerifyNoOtherCalls(articleResourceMock, joinResourceMock, tagResourceMock); @@ -72,7 +72,7 @@ public void OnReturn_Without_Parent_Hook_Implemented() [Fact] public void OnReturn_Without_Children_Hooks_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); @@ -80,10 +80,10 @@ public void OnReturn_Without_Children_Hooks_Implemented() var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.OnReturn(It.IsAny>(), ResourcePipeline.Get), Times.Once()); tagResourceMock.Verify(rd => rd.OnReturn(It.Is>((collection) => !collection.Except(tags).Any()), ResourcePipeline.Get), Times.Once()); VerifyNoOtherCalls(articleResourceMock, joinResourceMock, tagResourceMock); @@ -92,17 +92,17 @@ public void OnReturn_Without_Children_Hooks_Implemented() [Fact] public void OnReturn_Without_Grand_Children_Hooks_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.OnReturn(It.IsAny>(), ResourcePipeline.Get), Times.Once()); joinResourceMock.Verify(rd => rd.OnReturn(It.Is>((collection) => !collection.Except(joins).Any()), ResourcePipeline.Get), Times.Once()); VerifyNoOtherCalls(articleResourceMock, joinResourceMock, tagResourceMock); @@ -111,17 +111,17 @@ public void OnReturn_Without_Grand_Children_Hooks_Implemented() [Fact] public void OnReturn_Without_Any_Descendant_Hooks_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.OnReturn(It.IsAny>(), ResourcePipeline.Get), Times.Once()); VerifyNoOtherCalls(articleResourceMock, joinResourceMock, tagResourceMock); } @@ -129,14 +129,14 @@ public void OnReturn_Without_Any_Descendant_Hooks_Implemented() [Fact] public void OnReturn_Without_Any_Hook_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); // asert diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/ManyToMany_OnReturnTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/ManyToMany_OnReturnTests.cs index 88326d3994..963b4ce073 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/ManyToMany_OnReturnTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/ManyToMany_OnReturnTests.cs @@ -44,16 +44,16 @@ public class ManyToMany_OnReturnTests : HooksTestsSetup [Fact] public void OnReturn() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); var (articles, joins, tags) = CreateDummyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.OnReturn(It.IsAny>(), ResourcePipeline.Get), Times.Once()); tagResourceMock.Verify(rd => rd.OnReturn(It.Is>((collection) => !collection.Except(tags).Any()), ResourcePipeline.Get), Times.Once()); VerifyNoOtherCalls(articleResourceMock, tagResourceMock); @@ -62,13 +62,13 @@ public void OnReturn() [Fact] public void OnReturn_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); var (articles, joins, tags) = CreateDummyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); // asser @@ -79,16 +79,16 @@ public void OnReturn_Without_Parent_Hook_Implemented() [Fact] public void OnReturn_Without_Children_Hooks_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); var (articles, joins, tags) = CreateDummyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.OnReturn(It.IsAny>(), ResourcePipeline.Get), Times.Once()); VerifyNoOtherCalls(articleResourceMock, tagResourceMock); } @@ -96,17 +96,17 @@ public void OnReturn_Without_Children_Hooks_Implemented() [Fact] public void OnReturn_Without_Any_Hook_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); var (articles, joins, tags) = CreateDummyData(); - // act + // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); - // assert + // Assert VerifyNoOtherCalls(articleResourceMock, tagResourceMock); } } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/BeforeReadTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/BeforeReadTests.cs index 08d940bb3a..e776868689 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/BeforeReadTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/BeforeReadTests.cs @@ -14,16 +14,16 @@ public class BeforeReadTests : HooksTestsSetup [Fact] public void BeforeRead() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (iqMock, hookExecutor, todoResourceMock) = CreateTestObjects(todoDiscovery); var todoList = CreateTodoWithOwner(); iqMock.Setup(c => c.Get()).Returns(new List>()); - // act + // Act hookExecutor.BeforeRead(ResourcePipeline.Get); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, false, null), Times.Once()); VerifyNoOtherCalls(todoResourceMock); @@ -32,7 +32,7 @@ public void BeforeRead() [Fact] public void BeforeReadWithInclusion() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); @@ -42,9 +42,9 @@ public void BeforeReadWithInclusion() // eg a call on api/todo-items?include=owner,assignee,stake-holders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner", "assignee", "stake-holders")); - // act + // Act hookExecutor.BeforeRead(ResourcePipeline.Get); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, false, null), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, true, null), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); @@ -53,7 +53,7 @@ public void BeforeReadWithInclusion() [Fact] public void BeforeReadWithNestedInclusion() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var passportDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); @@ -64,9 +64,9 @@ public void BeforeReadWithNestedInclusion() // eg a call on api/todo-items?include=owner.passport,assignee,stake-holders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner.passport", "assignee", "stake-holders")); - // act + // Act hookExecutor.BeforeRead(ResourcePipeline.Get); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, false, null), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, true, null), Times.Once()); passportResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, true, null), Times.Once()); @@ -77,7 +77,7 @@ public void BeforeReadWithNestedInclusion() [Fact] public void BeforeReadWithNestedInclusion_No_Parent_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var passportDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); @@ -88,9 +88,9 @@ public void BeforeReadWithNestedInclusion_No_Parent_Hook_Implemented() // eg a call on api/todo-items?include=owner.passport,assignee,stake-holders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner.passport", "assignee", "stake-holders")); - // act + // Act hookExecutor.BeforeRead(ResourcePipeline.Get); - // assert + // Assert ownerResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, true, null), Times.Once()); passportResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, true, null), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock, passportResourceMock); @@ -99,7 +99,7 @@ public void BeforeReadWithNestedInclusion_No_Parent_Hook_Implemented() [Fact] public void BeforeReadWithNestedInclusion_No_Child_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var passportDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); @@ -110,9 +110,9 @@ public void BeforeReadWithNestedInclusion_No_Child_Hook_Implemented() // eg a call on api/todo-items?include=owner.passport,assignee,stake-holders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner.passport", "assignee", "stake-holders")); - // act + // Act hookExecutor.BeforeRead(ResourcePipeline.Get); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, false, null), Times.Once()); passportResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, true, null), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock, passportResourceMock); @@ -121,7 +121,7 @@ public void BeforeReadWithNestedInclusion_No_Child_Hook_Implemented() [Fact] public void BeforeReadWithNestedInclusion_No_Grandchild_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var passportDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); @@ -132,9 +132,9 @@ public void BeforeReadWithNestedInclusion_No_Grandchild_Hook_Implemented() // eg a call on api/todo-items?include=owner.passport,assignee,stake-holders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner.passport", "assignee", "stake-holders")); - // act + // Act hookExecutor.BeforeRead(ResourcePipeline.Get); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, false, null), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeRead(ResourcePipeline.Get, true, null), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock, passportResourceMock); @@ -144,7 +144,7 @@ public void BeforeReadWithNestedInclusion_No_Grandchild_Hook_Implemented() [Fact] public void BeforeReadWithNestedInclusion_Without_Any_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var passportDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); @@ -155,9 +155,9 @@ public void BeforeReadWithNestedInclusion_Without_Any_Hook_Implemented() // eg a call on api/todo-items?include=owner.passport,assignee,stake-holders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner.passport", "assignee", "stake-holders")); - // act + // Act hookExecutor.BeforeRead(ResourcePipeline.Get); - // assert + // Assert VerifyNoOtherCalls(todoResourceMock, ownerResourceMock, passportResourceMock); } } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/IdentifiableManyToMany_AfterReadTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/IdentifiableManyToMany_AfterReadTests.cs index ac58056ca5..e8bb6a5f0a 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/IdentifiableManyToMany_AfterReadTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/IdentifiableManyToMany_AfterReadTests.cs @@ -14,17 +14,17 @@ public class IdentifiableManyToMany_AfterReadTests : HooksTestsSetup [Fact] public void AfterRead() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.AfterRead(It.IsAny>(), ResourcePipeline.Get, false), Times.Once()); joinResourceMock.Verify(rd => rd.AfterRead(It.Is>((collection) => !collection.Except(joins).Any()), ResourcePipeline.Get, true), Times.Once()); tagResourceMock.Verify(rd => rd.AfterRead(It.Is>((collection) => !collection.Except(tags).Any()), ResourcePipeline.Get, true), Times.Once()); @@ -34,17 +34,17 @@ public void AfterRead() [Fact] public void AfterRead_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); - // assert + // Assert joinResourceMock.Verify(rd => rd.AfterRead(It.Is>((collection) => !collection.Except(joins).Any()), ResourcePipeline.Get, true), Times.Once()); tagResourceMock.Verify(rd => rd.AfterRead(It.Is>((collection) => !collection.Except(tags).Any()), ResourcePipeline.Get, true), Times.Once()); VerifyNoOtherCalls(articleResourceMock, joinResourceMock, tagResourceMock); @@ -53,7 +53,7 @@ public void AfterRead_Without_Parent_Hook_Implemented() [Fact] public void AfterRead_Without_Children_Hooks_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); @@ -62,10 +62,10 @@ public void AfterRead_Without_Children_Hooks_Implemented() var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.AfterRead(It.IsAny>(), ResourcePipeline.Get, false), Times.Once()); tagResourceMock.Verify(rd => rd.AfterRead(It.Is>((collection) => !collection.Except(tags).Any()), ResourcePipeline.Get, true), Times.Once()); VerifyNoOtherCalls(articleResourceMock, joinResourceMock, tagResourceMock); @@ -74,17 +74,17 @@ public void AfterRead_Without_Children_Hooks_Implemented() [Fact] public void AfterRead_Without_Grand_Children_Hooks_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.AfterRead(It.IsAny>(), ResourcePipeline.Get, false), Times.Once()); joinResourceMock.Verify(rd => rd.AfterRead(It.Is>((collection) => !collection.Except(joins).Any()), ResourcePipeline.Get, true), Times.Once()); VerifyNoOtherCalls(articleResourceMock, joinResourceMock, tagResourceMock); @@ -93,17 +93,17 @@ public void AfterRead_Without_Grand_Children_Hooks_Implemented() [Fact] public void AfterRead_Without_Any_Descendant_Hooks_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.AfterRead(It.IsAny>(), ResourcePipeline.Get, false), Times.Once()); VerifyNoOtherCalls(articleResourceMock, joinResourceMock, tagResourceMock); } @@ -111,14 +111,14 @@ public void AfterRead_Without_Any_Descendant_Hooks_Implemented() [Fact] public void AfterRead_Without_Any_Hook_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var joinDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); var (articles, joins, tags) = CreateIdentifiableManyToManyData(); - // act + // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); // asert diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/ManyToMany_AfterReadTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/ManyToMany_AfterReadTests.cs index 7f16620469..c3860c935e 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/ManyToMany_AfterReadTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/ManyToMany_AfterReadTests.cs @@ -14,16 +14,16 @@ public class ManyToMany_AfterReadTests : HooksTestsSetup [Fact] public void AfterRead() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); var (articles, joins, tags) = CreateManyToManyData(); - // act + // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.AfterRead(It.IsAny>(), ResourcePipeline.Get, false), Times.Once()); tagResourceMock.Verify(rd => rd.AfterRead(It.Is>((collection) => !collection.Except(tags).Any()), ResourcePipeline.Get, true), Times.Once()); VerifyNoOtherCalls(articleResourceMock, tagResourceMock); @@ -32,16 +32,16 @@ public void AfterRead() [Fact] public void AfterRead_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); var (articles, joins, tags) = CreateManyToManyData(); - // act + // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); - // assert + // Assert tagResourceMock.Verify(rd => rd.AfterRead(It.Is>((collection) => !collection.Except(tags).Any()), ResourcePipeline.Get, true), Times.Once()); VerifyNoOtherCalls(articleResourceMock, tagResourceMock); } @@ -49,16 +49,16 @@ public void AfterRead_Without_Parent_Hook_Implemented() [Fact] public void AfterRead_Without_Children_Hooks_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); var (articles, joins, tags) = CreateManyToManyData(); - // act + // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); - // assert + // Assert articleResourceMock.Verify(rd => rd.AfterRead(It.IsAny>(), ResourcePipeline.Get, false), Times.Once()); VerifyNoOtherCalls(articleResourceMock, tagResourceMock); } @@ -66,16 +66,16 @@ public void AfterRead_Without_Children_Hooks_Implemented() [Fact] public void AfterRead_Without_Any_Hook_Implemented() { - // arrange + // Arrange var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); var (articles, joins, tags) = CreateManyToManyData(); - // act + // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); - // assert + // Assert VerifyNoOtherCalls(articleResourceMock, tagResourceMock); } } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/ScenarioTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/ScenarioTests.cs index a4f84892ed..ca1c96db33 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/ScenarioTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/ScenarioTests.cs @@ -13,7 +13,7 @@ public class SameEntityTypeTests : HooksTestsSetup [Fact] public void Entity_Has_Multiple_Relations_To_Same_Type() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); @@ -25,10 +25,10 @@ public void Entity_Has_Multiple_Relations_To_Same_Type() todo.StakeHolders = new List { person3 }; var todoList = new List() { todo }; - // act + // Act hookExecutor.OnReturn(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.OnReturn(It.IsAny>(), ResourcePipeline.Post), Times.Once()); ownerResourceMock.Verify(rd => rd.OnReturn(It.IsAny>(), ResourcePipeline.Post), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); @@ -37,7 +37,7 @@ public void Entity_Has_Multiple_Relations_To_Same_Type() [Fact] public void Entity_Has_Cyclic_Relations() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); (var contextMock, var hookExecutor, var todoResourceMock) = CreateTestObjects(todoDiscovery); var todo = new TodoItem(); @@ -45,10 +45,10 @@ public void Entity_Has_Cyclic_Relations() todo.ChildrenTodoItems = new List { todo }; var todoList = new List() { todo }; - // act + // Act hookExecutor.OnReturn(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.OnReturn(It.IsAny>(), ResourcePipeline.Post), Times.Once()); VerifyNoOtherCalls(todoResourceMock); } @@ -56,7 +56,7 @@ public void Entity_Has_Cyclic_Relations() [Fact] public void Entity_Has_Nested_Cyclic_Relations() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); (var contextMock, var hookExecutor, var todoResourceMock) = CreateTestObjects(todoDiscovery); var rootTodo = new TodoItem() { Id = 1 }; @@ -69,10 +69,10 @@ public void Entity_Has_Nested_Cyclic_Relations() greatGrandChild.ChildrenTodoItems = new List { rootTodo }; var todoList = new List() { rootTodo }; - // act + // Act hookExecutor.OnReturn(todoList, ResourcePipeline.Post); - // assert + // Assert todoResourceMock.Verify(rd => rd.OnReturn(It.IsAny>(), ResourcePipeline.Post), Times.Exactly(4)); VerifyNoOtherCalls(todoResourceMock); } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/AfterUpdateTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/AfterUpdateTests.cs index c20176b6a2..148c80cf68 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/AfterUpdateTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/AfterUpdateTests.cs @@ -13,16 +13,16 @@ public class AfterUpdateTests : HooksTestsSetup [Fact] public void AfterUpdate() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.AfterUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert todoResourceMock.Verify(rd => rd.AfterUpdate(It.IsAny>(), ResourcePipeline.Patch), Times.Once()); ownerResourceMock.Verify(rd => rd.AfterUpdateRelationship(It.IsAny>(), ResourcePipeline.Patch), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); @@ -31,16 +31,16 @@ public void AfterUpdate() [Fact] public void AfterUpdate_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.AfterUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert ownerResourceMock.Verify(rd => rd.AfterUpdateRelationship(It.IsAny>(), ResourcePipeline.Patch), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } @@ -48,16 +48,16 @@ public void AfterUpdate_Without_Parent_Hook_Implemented() [Fact] public void AfterUpdate_Without_Child_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.AfterUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert todoResourceMock.Verify(rd => rd.AfterUpdate(It.IsAny>(), ResourcePipeline.Patch), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } @@ -65,16 +65,16 @@ public void AfterUpdate_Without_Child_Hook_Implemented() [Fact] public void AfterUpdate_Without_Any_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.AfterUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdateTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdateTests.cs index efc20d313f..65047e81c2 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdateTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdateTests.cs @@ -13,16 +13,16 @@ public class BeforeUpdateTests : HooksTestsSetup [Fact] public void BeforeUpdate() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeUpdate(It.IsAny>(), ResourcePipeline.Patch), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship(It.IsAny>(), It.IsAny>(), ResourcePipeline.Patch), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); @@ -31,16 +31,16 @@ public void BeforeUpdate() [Fact] public void BeforeUpdate_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship(It.IsAny>(), It.IsAny>(), ResourcePipeline.Patch), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } @@ -48,17 +48,17 @@ public void BeforeUpdate_Without_Parent_Hook_Implemented() [Fact] public void BeforeUpdate_Without_Child_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeUpdate(It.IsAny>(), ResourcePipeline.Patch), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } @@ -66,16 +66,16 @@ public void BeforeUpdate_Without_Child_Hook_Implemented() [Fact] public void BeforeUpdate_Without_Any_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var todoList = CreateTodoWithOwner(); - // act + // Act hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdate_WithDbValues_Tests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdate_WithDbValues_Tests.cs index f697411b19..05425ffb8e 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdate_WithDbValues_Tests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdate_WithDbValues_Tests.cs @@ -47,15 +47,15 @@ public BeforeUpdate_WithDbValues_Tests() [Fact] public void BeforeUpdate() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeUpdate(It.Is>((diff) => TodoCheckDiff(diff, description)), ResourcePipeline.Patch), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship( It.Is>(ids => PersonIdCheck(ids, personId)), @@ -77,18 +77,18 @@ public void BeforeUpdate() [Fact] public void BeforeUpdate_Deleting_Relationship() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var (_, ufMock, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); ufMock.Setup(c => c.Relationships).Returns(_resourceGraph.GetRelationships((TodoItem t) => t.ToOnePerson)); - // act + // Act var _todoList = new List() { new TodoItem { Id = this.todoList[0].Id } }; hookExecutor.BeforeUpdate(_todoList, ResourcePipeline.Patch); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeUpdate(It.Is>((diff) => TodoCheckDiff(diff, description)), ResourcePipeline.Patch), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeImplicitUpdateRelationship( It.Is>(rh => PersonCheck(lastName + lastName, rh)), @@ -101,15 +101,15 @@ public void BeforeUpdate_Deleting_Relationship() [Fact] public void BeforeUpdate_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship( It.Is>(ids => PersonIdCheck(ids, personId)), It.Is>(rh => PersonCheck(lastName, rh)), @@ -125,15 +125,15 @@ public void BeforeUpdate_Without_Parent_Hook_Implemented() [Fact] public void BeforeUpdate_Without_Child_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeUpdate(It.Is>((diff) => TodoCheckDiff(diff, description)), ResourcePipeline.Patch), Times.Once()); todoResourceMock.Verify(rd => rd.BeforeImplicitUpdateRelationship( It.Is>(rh => TodoCheck(rh, description + description)), @@ -145,15 +145,15 @@ public void BeforeUpdate_Without_Child_Hook_Implemented() [Fact] public void BeforeUpdate_NoImplicit() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooksNoImplicit, ResourceHook.BeforeUpdate); var personDiscovery = SetDiscoverableHooks(targetHooksNoImplicit, ResourceHook.BeforeUpdateRelationship); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeUpdate(It.Is>((diff) => TodoCheckDiff(diff, description)), ResourcePipeline.Patch), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship( It.Is>(ids => PersonIdCheck(ids, personId)), @@ -166,15 +166,15 @@ public void BeforeUpdate_NoImplicit() [Fact] public void BeforeUpdate_NoImplicit_Without_Parent_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var personDiscovery = SetDiscoverableHooks(targetHooksNoImplicit, ResourceHook.BeforeUpdateRelationship); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert ownerResourceMock.Verify(rd => rd.BeforeUpdateRelationship( It.Is>(ids => PersonIdCheck(ids, personId)), It.Is>(rh => PersonCheck(lastName, rh)), @@ -186,15 +186,15 @@ public void BeforeUpdate_NoImplicit_Without_Parent_Hook_Implemented() [Fact] public void BeforeUpdate_NoImplicit_Without_Child_Hook_Implemented() { - // arrange + // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooksNoImplicit, ResourceHook.BeforeUpdate); var personDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: options); - // act + // Act hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); - // assert + // Assert todoResourceMock.Verify(rd => rd.BeforeUpdate(It.Is>((diff) => TodoCheckDiff(diff, description)), ResourcePipeline.Patch), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); } diff --git a/test/UnitTests/Serialization/Client/RequestSerializerTests.cs b/test/UnitTests/Serialization/Client/RequestSerializerTests.cs index 5c405b09ef..b7f29b083e 100644 --- a/test/UnitTests/Serialization/Client/RequestSerializerTests.cs +++ b/test/UnitTests/Serialization/Client/RequestSerializerTests.cs @@ -23,13 +23,13 @@ public RequestSerializerTests() [Fact] public void SerializeSingle_ResourceWithDefaultTargetFields_CanBuild() { - // arrange + // Arrange var entity = new TestResource() { Id = 1, StringField = "value", NullableIntField = 123 }; - // act + // Act string serialized = _serializer.Serialize(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"":{ @@ -54,14 +54,14 @@ public void SerializeSingle_ResourceWithDefaultTargetFields_CanBuild() [Fact] public void SerializeSingle_ResourceWithTargetedSetAttributes_CanBuild() { - // arrange + // Arrange var entity = new TestResource() { Id = 1, StringField = "value", NullableIntField = 123 }; _serializer.SetAttributesToSerialize(tr => tr.StringField); - // act + // Act string serialized = _serializer.Serialize(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"":{ @@ -79,14 +79,14 @@ public void SerializeSingle_ResourceWithTargetedSetAttributes_CanBuild() [Fact] public void SerializeSingle_NoIdWithTargetedSetAttributes_CanBuild() { - // arrange + // Arrange var entityNoId = new TestResource() { Id = 0, StringField = "value", NullableIntField = 123 }; _serializer.SetAttributesToSerialize(tr => tr.StringField); - // act + // Act string serialized = _serializer.Serialize(entityNoId); - // assert + // Assert var expectedFormatted = @"{ ""data"":{ @@ -104,14 +104,14 @@ public void SerializeSingle_NoIdWithTargetedSetAttributes_CanBuild() [Fact] public void SerializeSingle_ResourceWithoutTargetedAttributes_CanBuild() { - // arrange + // Arrange var entity = new TestResource() { Id = 1, StringField = "value", NullableIntField = 123 }; _serializer.SetAttributesToSerialize(tr => new { }); - // act + // Act string serialized = _serializer.Serialize(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"":{ @@ -127,7 +127,7 @@ public void SerializeSingle_ResourceWithoutTargetedAttributes_CanBuild() [Fact] public void SerializeSingle_ResourceWithTargetedRelationships_CanBuild() { - // arrange + // Arrange var entityWithRelationships = new MultipleRelationshipsPrincipalPart { PopulatedToOne = new OneToOneDependent { Id = 10 }, @@ -135,10 +135,10 @@ public void SerializeSingle_ResourceWithTargetedRelationships_CanBuild() }; _serializer.SetRelationshipsToSerialize(tr => new { tr.EmptyToOne, tr.EmptyToManies, tr.PopulatedToOne, tr.PopulatedToManies }); - // act + // Act string serialized = _serializer.Serialize(entityWithRelationships); Console.WriteLine(serialized); - // assert + // Assert var expectedFormatted = @"{ ""data"":{ @@ -177,7 +177,7 @@ public void SerializeSingle_ResourceWithTargetedRelationships_CanBuild() [Fact] public void SerializeMany_ResourcesWithTargetedAttributes_CanBuild() { - // arrange + // Arrange var entities = new List { new TestResource() { Id = 1, StringField = "value1", NullableIntField = 123 }, @@ -185,10 +185,10 @@ public void SerializeMany_ResourcesWithTargetedAttributes_CanBuild() }; _serializer.SetAttributesToSerialize(tr => tr.StringField); - // act + // Act string serialized = _serializer.Serialize(entities); - // assert + // Assert var expectedFormatted = @"{ ""data"":[ @@ -215,14 +215,14 @@ public void SerializeMany_ResourcesWithTargetedAttributes_CanBuild() [Fact] public void SerializeSingle_Null_CanBuild() { - // arrange + // Arrange _serializer.SetAttributesToSerialize(tr => tr.StringField); - // act + // Act IIdentifiable obj = null; string serialized = _serializer.Serialize(obj); - // assert + // Assert var expectedFormatted = @"{ ""data"":null @@ -234,14 +234,14 @@ public void SerializeSingle_Null_CanBuild() [Fact] public void SerializeMany_EmptyList_CanBuild() { - // arrange + // Arrange var entities = new List { }; _serializer.SetAttributesToSerialize(tr => tr.StringField); - // act + // Act string serialized = _serializer.Serialize(entities); - // assert + // Assert var expectedFormatted = @"{ ""data"":[] diff --git a/test/UnitTests/Serialization/Client/ResponseDeserializerTests.cs b/test/UnitTests/Serialization/Client/ResponseDeserializerTests.cs index 5aeef42e3d..f798e77388 100644 --- a/test/UnitTests/Serialization/Client/ResponseDeserializerTests.cs +++ b/test/UnitTests/Serialization/Client/ResponseDeserializerTests.cs @@ -25,17 +25,17 @@ public ResponseDeserializerTests() [Fact] public void DeserializeSingle_EmptyResponseWithMeta_CanDeserialize() { - // arrange + // Arrange var content = new Document { Meta = new Dictionary { { "foo", "bar" } } }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = _deserializer.DeserializeSingle(body); - // assert + // Assert Assert.Null(result.Data); Assert.NotNull(result.Meta); Assert.Equal("bar", result.Meta["foo"]); @@ -44,17 +44,17 @@ public void DeserializeSingle_EmptyResponseWithMeta_CanDeserialize() [Fact] public void DeserializeSingle_EmptyResponseWithTopLevelLinks_CanDeserialize() { - // arrange + // Arrange var content = new Document { Links = new TopLevelLinks { Self = _linkValues["self"], Next = _linkValues["next"], Last = _linkValues["last"] } }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = _deserializer.DeserializeSingle(body); - // assert + // Assert Assert.Null(result.Data); Assert.NotNull(result.Links); TopLevelLinks links = (TopLevelLinks)result.Links; @@ -66,7 +66,7 @@ public void DeserializeSingle_EmptyResponseWithTopLevelLinks_CanDeserialize() [Fact] public void DeserializeList_EmptyResponseWithTopLevelLinks_CanDeserialize() { - // arrange + // Arrange var content = new Document { Links = new TopLevelLinks { Self = _linkValues["self"], Next = _linkValues["next"], Last = _linkValues["last"] }, @@ -74,10 +74,10 @@ public void DeserializeList_EmptyResponseWithTopLevelLinks_CanDeserialize() }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = _deserializer.DeserializeList(body); - // assert + // Assert Assert.Empty(result.Data); Assert.NotNull(result.Links); TopLevelLinks links = (TopLevelLinks)result.Links; @@ -89,15 +89,15 @@ public void DeserializeList_EmptyResponseWithTopLevelLinks_CanDeserialize() [Fact] public void DeserializeSingle_ResourceWithAttributes_CanDeserialize() { - // arrange + // Arrange var content = CreateTestResourceDocument(); var body = JsonConvert.SerializeObject(content); - // act + // Act var result = _deserializer.DeserializeSingle(body); var entity = result.Data; - // assert + // Assert Assert.Null(result.Links); Assert.Null(result.Meta); Assert.Equal(1, entity.Id); @@ -107,7 +107,7 @@ public void DeserializeSingle_ResourceWithAttributes_CanDeserialize() [Fact] public void DeserializeSingle_MultipleDependentRelationshipsWithIncluded_CanDeserialize() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("multi-principals"); content.SingleData.Relationships.Add("populated-to-one", CreateRelationshipData("one-to-one-dependents")); content.SingleData.Relationships.Add("populated-to-manies", CreateRelationshipData("one-to-many-dependents", isToManyData: true)); @@ -132,11 +132,11 @@ public void DeserializeSingle_MultipleDependentRelationshipsWithIncluded_CanDese }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = _deserializer.DeserializeSingle(body); var entity = result.Data; - // assert + // Assert Assert.Equal(1, entity.Id); Assert.NotNull(entity.PopulatedToOne); Assert.Equal(toOneAttributeValue, entity.PopulatedToOne.AttributeMember); @@ -150,7 +150,7 @@ public void DeserializeSingle_MultipleDependentRelationshipsWithIncluded_CanDese [Fact] public void DeserializeSingle_MultiplePrincipalRelationshipsWithIncluded_CanDeserialize() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("multi-dependents"); content.SingleData.Relationships.Add("populated-to-one", CreateRelationshipData("one-to-one-principals")); content.SingleData.Relationships.Add("populated-to-many", CreateRelationshipData("one-to-many-principals")); @@ -175,11 +175,11 @@ public void DeserializeSingle_MultiplePrincipalRelationshipsWithIncluded_CanDese }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = _deserializer.DeserializeSingle(body); var entity = result.Data; - // assert + // Assert Assert.Equal(1, entity.Id); Assert.NotNull(entity.PopulatedToOne); Assert.Equal(toOneAttributeValue, entity.PopulatedToOne.AttributeMember); @@ -192,7 +192,7 @@ public void DeserializeSingle_MultiplePrincipalRelationshipsWithIncluded_CanDese [Fact] public void DeserializeSingle_NestedIncluded_CanDeserialize() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("multi-principals"); content.SingleData.Relationships.Add("populated-to-manies", CreateRelationshipData("one-to-many-dependents", isToManyData: true)); var toManyAttributeValue = "populated-to-manies member content"; @@ -215,11 +215,11 @@ public void DeserializeSingle_NestedIncluded_CanDeserialize() }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = _deserializer.DeserializeSingle(body); var entity = result.Data; - // assert + // Assert Assert.Equal(1, entity.Id); Assert.Null(entity.PopulatedToOne); Assert.Null(entity.EmptyToManies); @@ -235,7 +235,7 @@ public void DeserializeSingle_NestedIncluded_CanDeserialize() [Fact] public void DeserializeSingle_DeeplyNestedIncluded_CanDeserialize() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("multi-principals"); content.SingleData.Relationships.Add("multi", CreateRelationshipData("multi-principals")); var includedAttributeValue = "multi member content"; @@ -266,11 +266,11 @@ public void DeserializeSingle_DeeplyNestedIncluded_CanDeserialize() }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = _deserializer.DeserializeSingle(body); var entity = result.Data; - // assert + // Assert Assert.Equal(1, entity.Id); var included = entity.Multi; Assert.Equal(10, included.Id); @@ -287,7 +287,7 @@ public void DeserializeSingle_DeeplyNestedIncluded_CanDeserialize() [Fact] public void DeserializeList_DeeplyNestedIncluded_CanDeserialize() { - // arrange + // Arrange var content = new Document { Data = new List { CreateDocumentWithRelationships("multi-principals").SingleData } }; content.ManyData[0].Relationships.Add("multi", CreateRelationshipData("multi-principals")); var includedAttributeValue = "multi member content"; @@ -318,11 +318,11 @@ public void DeserializeList_DeeplyNestedIncluded_CanDeserialize() }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = _deserializer.DeserializeList(body); var entity = result.Data.First(); - // assert + // Assert Assert.Equal(1, entity.Id); var included = entity.Multi; Assert.Equal(10, included.Id); diff --git a/test/UnitTests/Serialization/Common/DocumentBuilderTests.cs b/test/UnitTests/Serialization/Common/DocumentBuilderTests.cs index e7bff25cc6..78fb2f53ef 100644 --- a/test/UnitTests/Serialization/Common/DocumentBuilderTests.cs +++ b/test/UnitTests/Serialization/Common/DocumentBuilderTests.cs @@ -25,13 +25,13 @@ public BaseDocumentBuilderTests() [Fact] public void EntityToDocument_NullEntity_CanBuild() { - // arrange + // Arrange TestResource entity = null; - // act + // Act var document = _builder.Build(entity, null, null); - // assert + // Assert Assert.Null(document.Data); Assert.False(document.IsPopulated); } @@ -40,13 +40,13 @@ public void EntityToDocument_NullEntity_CanBuild() [Fact] public void EntityToDocument_EmptyList_CanBuild() { - // arrange + // Arrange var entities = new List(); - // act + // Act var document = _builder.Build(entities, null, null); - // assert + // Assert Assert.NotNull(document.Data); Assert.Empty(document.ManyData); } @@ -55,13 +55,13 @@ public void EntityToDocument_EmptyList_CanBuild() [Fact] public void EntityToDocument_SingleEntity_CanBuild() { - // arrange + // Arrange IIdentifiable dummy = new Identifiable(); - // act + // Act var document = _builder.Build(dummy, null, null); - // assert + // Assert Assert.NotNull(document.Data); Assert.True(document.IsPopulated); } @@ -69,14 +69,14 @@ public void EntityToDocument_SingleEntity_CanBuild() [Fact] public void EntityToDocument_EntityList_CanBuild() { - // arrange + // Arrange var entities = new List() { new Identifiable(), new Identifiable() }; - // act + // Act var document = _builder.Build(entities, null, null); var data = (List)document.Data; - // assert + // Assert Assert.Equal(2, data.Count); } } diff --git a/test/UnitTests/Serialization/Common/DocumentParserTests.cs b/test/UnitTests/Serialization/Common/DocumentParserTests.cs index ca718affcd..562fb7d2c5 100644 --- a/test/UnitTests/Serialization/Common/DocumentParserTests.cs +++ b/test/UnitTests/Serialization/Common/DocumentParserTests.cs @@ -33,10 +33,10 @@ public void DeserializeResourceIdentifiers_SingleData_CanDeserialize() }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (TestResource)_deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(1, result.Id); } @@ -47,10 +47,10 @@ public void DeserializeResourceIdentifiers_EmptySingleData_CanDeserialize() var content = new Document { }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = _deserializer.Deserialize(body); - // arrange + // Arrange Assert.Null(result); } @@ -71,10 +71,10 @@ public void DeserializeResourceIdentifiers_ArrayData_CanDeserialize() }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (List)_deserializer.Deserialize(body); - // assert + // Assert Assert.Equal("1", result.First().StringId); } @@ -84,10 +84,10 @@ public void DeserializeResourceIdentifiers_EmptyArrayData_CanDeserialize() var content = new Document { Data = new List { } }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (IList)_deserializer.Deserialize(body); - // assert + // Assert Assert.Empty(result); } @@ -106,7 +106,7 @@ public void DeserializeResourceIdentifiers_EmptyArrayData_CanDeserialize() [InlineData("nullable-date-time-field", null)] public void DeserializeAttributes_VariousDataTypes_CanDeserialize(string member, object value, bool expectError = false) { - // arrange + // Arrange var content = new Document { Data = new ResourceObject @@ -121,17 +121,17 @@ public void DeserializeAttributes_VariousDataTypes_CanDeserialize(string member, }; var body = JsonConvert.SerializeObject(content); - // act, assert + // Act, assert if (expectError) { Assert.ThrowsAny(() => _deserializer.Deserialize(body)); return; } - // act + // Act var entity = (TestResource)_deserializer.Deserialize(body); - // assert + // Assert var pi = _resourceGraph.GetResourceContext("test-resource").Attributes.Single(attr => attr.PublicAttributeName == member).PropertyInfo; var deserializedValue = pi.GetValue(entity); @@ -164,7 +164,7 @@ public void DeserializeAttributes_VariousDataTypes_CanDeserialize(string member, [Fact] public void DeserializeAttributes_ComplexType_CanDeserialize() { - // arrange + // Arrange var content = new Document { Data = new ResourceObject @@ -179,10 +179,10 @@ public void DeserializeAttributes_ComplexType_CanDeserialize() }; var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (TestResource)_deserializer.Deserialize(body); - // assert + // Assert Assert.NotNull(result.ComplexField); Assert.Equal("testName", result.ComplexField.CompoundName); } @@ -190,7 +190,7 @@ public void DeserializeAttributes_ComplexType_CanDeserialize() [Fact] public void DeserializeAttributes_ComplexListType_CanDeserialize() { - // arrange + // Arrange var content = new Document { Data = new ResourceObject @@ -206,10 +206,10 @@ public void DeserializeAttributes_ComplexListType_CanDeserialize() var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (TestResourceWithList)_deserializer.Deserialize(body); - // assert + // Assert Assert.NotNull(result.ComplexFields); Assert.NotEmpty(result.ComplexFields); Assert.Equal("testName", result.ComplexFields[0].CompoundName); @@ -218,14 +218,14 @@ public void DeserializeAttributes_ComplexListType_CanDeserialize() [Fact] public void DeserializeRelationships_EmptyOneToOneDependent_NavigationPropertyIsNull() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("one-to-one-principals", "dependent"); var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (OneToOnePrincipal)_deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(1, result.Id); Assert.Null(result.Dependent); Assert.Null(result.AttributeMember); @@ -234,14 +234,14 @@ public void DeserializeRelationships_EmptyOneToOneDependent_NavigationPropertyIs [Fact] public void DeserializeRelationships_PopulatedOneToOneDependent_NavigationPropertyIsPopulated() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("one-to-one-principals", "dependent", "one-to-one-dependents"); var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (OneToOnePrincipal)_deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(1, result.Id); Assert.Equal(10, result.Dependent.Id); Assert.Null(result.AttributeMember); @@ -250,14 +250,14 @@ public void DeserializeRelationships_PopulatedOneToOneDependent_NavigationProper [Fact] public void DeserializeRelationships_EmptyOneToOnePrincipal_NavigationPropertyAndForeignKeyAreNull() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("one-to-one-dependents", "principal"); var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (OneToOneDependent)_deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(1, result.Id); Assert.Null(result.Principal); Assert.Null(result.PrincipalId); @@ -266,25 +266,25 @@ public void DeserializeRelationships_EmptyOneToOnePrincipal_NavigationPropertyAn [Fact] public void DeserializeRelationships_EmptyRequiredOneToOnePrincipal_ThrowsFormatException() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("one-to-one-required-dependents", "principal"); var body = JsonConvert.SerializeObject(content); - // act, assert + // Act, assert Assert.Throws(() => _deserializer.Deserialize(body)); } [Fact] public void DeserializeRelationships_PopulatedOneToOnePrincipal_NavigationPropertyAndForeignKeyArePopulated() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("one-to-one-dependents", "principal", "one-to-one-principals"); var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (OneToOneDependent)_deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(1, result.Id); Assert.NotNull(result.Principal); Assert.Equal(10, result.Principal.Id); @@ -295,14 +295,14 @@ public void DeserializeRelationships_PopulatedOneToOnePrincipal_NavigationProper [Fact] public void DeserializeRelationships_EmptyOneToManyPrincipal_NavigationAndForeignKeyAreNull() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("one-to-many-dependents", "principal"); var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (OneToManyDependent)_deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(1, result.Id); Assert.Null(result.Principal); Assert.Null(result.PrincipalId); @@ -312,25 +312,25 @@ public void DeserializeRelationships_EmptyOneToManyPrincipal_NavigationAndForeig [Fact] public void DeserializeRelationships_EmptyOneToManyRequiredPrincipal_ThrowsFormatException() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("one-to-many-required-dependents", "principal"); var body = JsonConvert.SerializeObject(content); - // act, assert + // Act, assert Assert.Throws(() => _deserializer.Deserialize(body)); } [Fact] public void DeserializeRelationships_PopulatedOneToManyPrincipal_NavigationAndForeignKeyArePopulated() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("one-to-many-dependents", "principal", "one-to-many-principals"); var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (OneToManyDependent)_deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(1, result.Id); Assert.NotNull(result.Principal); Assert.Equal(10, result.Principal.Id); @@ -341,14 +341,14 @@ public void DeserializeRelationships_PopulatedOneToManyPrincipal_NavigationAndFo [Fact] public void DeserializeRelationships_EmptyOneToManyDependent_NavigationIsNull() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("one-to-many-principals", "dependents"); var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (OneToManyPrincipal)_deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(1, result.Id); Assert.Null(result.Dependents); Assert.Null(result.AttributeMember); @@ -357,14 +357,14 @@ public void DeserializeRelationships_EmptyOneToManyDependent_NavigationIsNull() [Fact] public void DeserializeRelationships_PopulatedOneToManyDependent_NavigationIsPopulated() { - // arrange + // Arrange var content = CreateDocumentWithRelationships("one-to-many-principals", "dependents", "one-to-many-dependents", isToManyData: true); var body = JsonConvert.SerializeObject(content); - // act + // Act var result = (OneToManyPrincipal)_deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(1, result.Id); Assert.Single(result.Dependents); Assert.Equal(10, result.Dependents.First().Id); diff --git a/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs b/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs index 16e6519f3d..de04a47a97 100644 --- a/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs +++ b/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs @@ -22,13 +22,13 @@ public ResourceObjectBuilderTests() [Fact] public void EntityToResourceObject_EmptyResource_CanBuild() { - // arrange + // Arrange var entity = new TestResource(); - // act + // Act var resourceObject = _builder.Build(entity); - // assert + // Assert Assert.Null(resourceObject.Attributes); Assert.Null(resourceObject.Relationships); Assert.Null(resourceObject.Id); @@ -38,13 +38,13 @@ public void EntityToResourceObject_EmptyResource_CanBuild() [Fact] public void EntityToResourceObject_ResourceWithId_CanBuild() { - // arrange + // Arrange var entity = new TestResource() { Id = 1 }; - // act + // Act var resourceObject = _builder.Build(entity); - // assert + // Assert Assert.Equal("1", resourceObject.Id); Assert.Null(resourceObject.Attributes); Assert.Null(resourceObject.Relationships); @@ -56,14 +56,14 @@ public void EntityToResourceObject_ResourceWithId_CanBuild() [InlineData("string field", 1)] public void EntityToResourceObject_ResourceWithIncludedAttrs_CanBuild(string stringFieldValue, int? intFieldValue) { - // arrange + // Arrange var entity = new TestResource() { StringField = stringFieldValue, NullableIntField = intFieldValue }; var attrs = _resourceGraph.GetAttributes(tr => new { tr.StringField, tr.NullableIntField }); - // act + // Act var resourceObject = _builder.Build(entity, attrs); - // assert + // Assert Assert.NotNull(resourceObject.Attributes); Assert.Equal(2, resourceObject.Attributes.Keys.Count); Assert.Equal(stringFieldValue, resourceObject.Attributes["string-field"]); @@ -73,13 +73,13 @@ public void EntityToResourceObject_ResourceWithIncludedAttrs_CanBuild(string str [Fact] public void EntityWithRelationshipsToResourceObject_EmptyResource_CanBuild() { - // arrange + // Arrange var entity = new MultipleRelationshipsPrincipalPart(); - // act + // Act var resourceObject = _builder.Build(entity); - // assert + // Assert Assert.Null(resourceObject.Attributes); Assert.Null(resourceObject.Relationships); Assert.Null(resourceObject.Id); @@ -89,16 +89,16 @@ public void EntityWithRelationshipsToResourceObject_EmptyResource_CanBuild() [Fact] public void EntityWithRelationshipsToResourceObject_ResourceWithId_CanBuild() { - // arrange + // Arrange var entity = new MultipleRelationshipsPrincipalPart { PopulatedToOne = new OneToOneDependent { Id = 10 }, }; - // act + // Act var resourceObject = _builder.Build(entity); - // assert + // Assert Assert.Null(resourceObject.Attributes); Assert.Null(resourceObject.Relationships); Assert.Null(resourceObject.Id); @@ -108,7 +108,7 @@ public void EntityWithRelationshipsToResourceObject_ResourceWithId_CanBuild() [Fact] public void EntityWithRelationshipsToResourceObject_WithIncludedRelationshipsAttributes_CanBuild() { - // arrange + // Arrange var entity = new MultipleRelationshipsPrincipalPart { PopulatedToOne = new OneToOneDependent { Id = 10 }, @@ -116,10 +116,10 @@ public void EntityWithRelationshipsToResourceObject_WithIncludedRelationshipsAtt }; var relationships = _resourceGraph.GetRelationships(tr => new { tr.PopulatedToManies, tr.PopulatedToOne, tr.EmptyToOne, tr.EmptyToManies }); - // act + // Act var resourceObject = _builder.Build(entity, relationships: relationships); - // assert + // Assert Assert.Equal(4, resourceObject.Relationships.Count); Assert.Null(resourceObject.Relationships["empty-to-one"].Data); Assert.Empty((IList)resourceObject.Relationships["empty-to-manies"].Data); @@ -136,14 +136,14 @@ public void EntityWithRelationshipsToResourceObject_WithIncludedRelationshipsAtt [Fact] public void EntityWithRelationshipsToResourceObject_DeviatingForeignKeyWhileRelationshipIncluded_IgnoresForeignKeyDuringBuild() { - // arrange + // Arrange var entity = new OneToOneDependent { Principal = new OneToOnePrincipal { Id = 10 }, PrincipalId = 123 }; var relationships = _resourceGraph.GetRelationships(tr => tr.Principal); - // act + // Act var resourceObject = _builder.Build(entity, relationships: relationships); - // assert + // Assert Assert.Single(resourceObject.Relationships); Assert.NotNull(resourceObject.Relationships["principal"].Data); var ro = (ResourceIdentifierObject)resourceObject.Relationships["principal"].Data; @@ -153,28 +153,28 @@ public void EntityWithRelationshipsToResourceObject_DeviatingForeignKeyWhileRela [Fact] public void EntityWithRelationshipsToResourceObject_DeviatingForeignKeyAndNoNavigationWhileRelationshipIncluded_IgnoresForeignKeyDuringBuild() { - // arrange + // Arrange var entity = new OneToOneDependent { Principal = null, PrincipalId = 123 }; var relationships = _resourceGraph.GetRelationships(tr => tr.Principal); - // act + // Act var resourceObject = _builder.Build(entity, relationships: relationships); - // assert + // Assert Assert.Null(resourceObject.Relationships["principal"].Data); } [Fact] public void EntityWithRequiredRelationshipsToResourceObject_DeviatingForeignKeyWhileRelationshipIncluded_IgnoresForeignKeyDuringBuild() { - // arrange + // Arrange var entity = new OneToOneRequiredDependent { Principal = new OneToOnePrincipal { Id = 10 }, PrincipalId = 123 }; var relationships = _resourceGraph.GetRelationships(tr => tr.Principal); - // act + // Act var resourceObject = _builder.Build(entity, relationships: relationships); - // assert + // Assert Assert.Single(resourceObject.Relationships); Assert.NotNull(resourceObject.Relationships["principal"].Data); var ro = (ResourceIdentifierObject)resourceObject.Relationships["principal"].Data; @@ -184,22 +184,22 @@ public void EntityWithRequiredRelationshipsToResourceObject_DeviatingForeignKeyW [Fact] public void EntityWithRequiredRelationshipsToResourceObject_DeviatingForeignKeyAndNoNavigationWhileRelationshipIncluded_ThrowsNotSupportedException() { - // arrange + // Arrange var entity = new OneToOneRequiredDependent { Principal = null, PrincipalId = 123 }; var relationships = _resourceGraph.GetRelationships(tr => tr.Principal); - // act & assert + // Act & assert Assert.ThrowsAny(() => _builder.Build(entity, relationships: relationships)); } [Fact] public void EntityWithRequiredRelationshipsToResourceObject_EmptyResourceWhileRelationshipIncluded_ThrowsNotSupportedException() { - // arrange + // Arrange var entity = new OneToOneRequiredDependent(); var relationships = _resourceGraph.GetRelationships(tr => tr.Principal); - // act & assert + // Act & assert Assert.ThrowsAny(() => _builder.Build(entity, relationships: relationships)); } } diff --git a/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs b/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs index c0f0dd468d..b477023432 100644 --- a/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs +++ b/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs @@ -14,16 +14,16 @@ public class IncludedResourceObjectBuilderTests : SerializerTestsSetup [Fact] public void BuildIncluded_DeeplyNestedCircularChainOfSingleData_CanBuild() { - // arrange + // Arrange var (article, author, authorFood, reviewer, reviewerFood) = GetAuthorChainInstances(); var authorChain = GetIncludedRelationshipsChain("author.blogs.reviewer.favorite-food"); var builder = GetBuilder(); - // act + // Act builder.IncludeRelationshipChain(authorChain, article); var result = builder.Build(); - // assert + // Assert Assert.Equal(6, result.Count); var authorResourceObject = result.Single((ro) => ro.Type == "people" && ro.Id == author.StringId); @@ -38,18 +38,18 @@ public void BuildIncluded_DeeplyNestedCircularChainOfSingleData_CanBuild() [Fact] public void BuildIncluded_DeeplyNestedCircularChainOfManyData_BuildsWithoutDuplicates() { - // arrange + // Arrange var (article, author, _, _, _) = GetAuthorChainInstances(); var secondArticle = _articleFaker.Generate(); secondArticle.Author = author; var builder = GetBuilder(); - // act + // Act var authorChain = GetIncludedRelationshipsChain("author.blogs.reviewer.favorite-food"); builder.IncludeRelationshipChain(authorChain, article); builder.IncludeRelationshipChain(authorChain, secondArticle); - // assert + // Assert var result = builder.Build(); Assert.Equal(6, result.Count); } @@ -57,7 +57,7 @@ public void BuildIncluded_DeeplyNestedCircularChainOfManyData_BuildsWithoutDupli [Fact] public void BuildIncluded_OverlappingDeeplyNestedCirculairChains_CanBuild() { - // arrange + // Arrange var authorChain = GetIncludedRelationshipsChain("author.blogs.reviewer.favorite-food"); var (article, author, authorFood, reviewer, reviewerFood) = GetAuthorChainInstances(); var sharedBlog = author.Blogs.First(); @@ -66,12 +66,12 @@ public void BuildIncluded_OverlappingDeeplyNestedCirculairChains_CanBuild() var reviewerChain = GetIncludedRelationshipsChain("reviewer.blogs.author.favorite-song"); var builder = GetBuilder(); - // act + // Act builder.IncludeRelationshipChain(authorChain, article); builder.IncludeRelationshipChain(reviewerChain, article); var result = builder.Build(); - // assert + // Assert Assert.Equal(10, result.Count); var overlappingBlogResourcObject = result.Single((ro) => ro.Type == "blogs" && ro.Id == sharedBlog.StringId); diff --git a/test/UnitTests/Serialization/Server/RequestDeserializerTests.cs b/test/UnitTests/Serialization/Server/RequestDeserializerTests.cs index 2e4fa17e2e..ac68e8b37b 100644 --- a/test/UnitTests/Serialization/Server/RequestDeserializerTests.cs +++ b/test/UnitTests/Serialization/Server/RequestDeserializerTests.cs @@ -24,15 +24,15 @@ public RequestDeserializerTests() : base() [Fact] public void DeserializeAttributes_VariousUpdatedMembers_RegistersTargetedFields() { - // arrange + // Arrange SetupFieldsManager(out List attributesToUpdate, out List relationshipsToUpdate); Document content = CreateTestResourceDocument(); var body = JsonConvert.SerializeObject(content); - // act + // Act _deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(5, attributesToUpdate.Count); Assert.Empty(relationshipsToUpdate); } @@ -40,7 +40,7 @@ public void DeserializeAttributes_VariousUpdatedMembers_RegistersTargetedFields( [Fact] public void DeserializeAttributes_UpdatedImmutableMember_ThrowsInvalidOperationException() { - // arrange + // Arrange SetupFieldsManager(out List attributesToUpdate, out List relationshipsToUpdate); var content = new Document { @@ -56,14 +56,14 @@ public void DeserializeAttributes_UpdatedImmutableMember_ThrowsInvalidOperationE }; var body = JsonConvert.SerializeObject(content); - // act, assert + // Act, assert Assert.Throws(() => _deserializer.Deserialize(body)); } [Fact] public void DeserializeRelationships_MultipleDependentRelationships_RegistersUpdatedRelationships() { - // arrange + // Arrange SetupFieldsManager(out List attributesToUpdate, out List relationshipsToUpdate); var content = CreateDocumentWithRelationships("multi-principals"); content.SingleData.Relationships.Add("populated-to-one", CreateRelationshipData("one-to-one-dependents")); @@ -72,10 +72,10 @@ public void DeserializeRelationships_MultipleDependentRelationships_RegistersUpd content.SingleData.Relationships.Add("empty-to-manies", CreateRelationshipData(isToManyData: true)); var body = JsonConvert.SerializeObject(content); - // act + // Act _deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(4, relationshipsToUpdate.Count); Assert.Empty(attributesToUpdate); } @@ -83,7 +83,7 @@ public void DeserializeRelationships_MultipleDependentRelationships_RegistersUpd [Fact] public void DeserializeRelationships_MultiplePrincipalRelationships_RegistersUpdatedRelationships() { - // arrange + // Arrange SetupFieldsManager(out List attributesToUpdate, out List relationshipsToUpdate); var content = CreateDocumentWithRelationships("multi-dependents"); content.SingleData.Relationships.Add("populated-to-one", CreateRelationshipData("one-to-one-principals")); @@ -92,10 +92,10 @@ public void DeserializeRelationships_MultiplePrincipalRelationships_RegistersUpd content.SingleData.Relationships.Add("empty-to-many", CreateRelationshipData()); var body = JsonConvert.SerializeObject(content); - // act + // Act _deserializer.Deserialize(body); - // assert + // Assert Assert.Equal(4, relationshipsToUpdate.Count); Assert.Empty(attributesToUpdate); } diff --git a/test/UnitTests/Serialization/Server/ResponseResourceObjectBuilderTests.cs b/test/UnitTests/Serialization/Server/ResponseResourceObjectBuilderTests.cs index cade4043e5..c6fa74e7b1 100644 --- a/test/UnitTests/Serialization/Server/ResponseResourceObjectBuilderTests.cs +++ b/test/UnitTests/Serialization/Server/ResponseResourceObjectBuilderTests.cs @@ -20,14 +20,14 @@ public ResponseResourceObjectBuilderTests() [Fact] public void Build_RelationshipNotIncludedAndLinksEnabled_RelationshipEntryWithLinks() { - // arrange + // Arrange var entity = new OneToManyPrincipal { Id = 10 }; var builder = GetResponseResourceObjectBuilder(relationshipLinks: _dummyRelationshipLinks); - // act + // Act var resourceObject = builder.Build(entity, relationships: _relationshipsForBuild); - // assert + // Assert Assert.True(resourceObject.Relationships.TryGetValue(_relationshipName, out var entry)); Assert.Equal("http://www.dummy.com/dummy-relationship-self-link", entry.Links.Self); Assert.Equal("http://www.dummy.com/dummy-relationship-related-link", entry.Links.Related); @@ -37,28 +37,28 @@ public void Build_RelationshipNotIncludedAndLinksEnabled_RelationshipEntryWithLi [Fact] public void Build_RelationshipNotIncludedAndLinksDisabled_NoRelationshipObject() { - // arrange + // Arrange var entity = new OneToManyPrincipal { Id = 10 }; var builder = GetResponseResourceObjectBuilder(); - // act + // Act var resourceObject = builder.Build(entity, relationships: _relationshipsForBuild); - // assert + // Assert Assert.Null(resourceObject.Relationships); } [Fact] public void Build_RelationshipIncludedAndLinksDisabled_RelationshipEntryWithData() { - // arrange + // Arrange var entity = new OneToManyPrincipal { Id = 10, Dependents = new List { new OneToManyDependent { Id = 20 } } }; var builder = GetResponseResourceObjectBuilder(inclusionChains: new List> { _relationshipsForBuild } ); - // act + // Act var resourceObject = builder.Build(entity, relationships: _relationshipsForBuild); - // assert + // Assert Assert.True(resourceObject.Relationships.TryGetValue(_relationshipName, out var entry)); Assert.Null(entry.Links); Assert.True(entry.IsPopulated); @@ -68,14 +68,14 @@ public void Build_RelationshipIncludedAndLinksDisabled_RelationshipEntryWithData [Fact] public void Build_RelationshipIncludedAndLinksEnabled_RelationshipEntryWithDataAndLinks() { - // arrange + // Arrange var entity = new OneToManyPrincipal { Id = 10, Dependents = new List { new OneToManyDependent { Id = 20 } } }; var builder = GetResponseResourceObjectBuilder(inclusionChains: new List> { _relationshipsForBuild }, relationshipLinks: _dummyRelationshipLinks); - // act + // Act var resourceObject = builder.Build(entity, relationships: _relationshipsForBuild); - // assert + // Assert Assert.True(resourceObject.Relationships.TryGetValue(_relationshipName, out var entry)); Assert.Equal("http://www.dummy.com/dummy-relationship-self-link", entry.Links.Self); Assert.Equal("http://www.dummy.com/dummy-relationship-related-link", entry.Links.Related); diff --git a/test/UnitTests/Serialization/Server/ResponseSerializerTests.cs b/test/UnitTests/Serialization/Server/ResponseSerializerTests.cs index bd806ab61b..cff783d54f 100644 --- a/test/UnitTests/Serialization/Server/ResponseSerializerTests.cs +++ b/test/UnitTests/Serialization/Server/ResponseSerializerTests.cs @@ -15,14 +15,14 @@ public class ResponseSerializerTests : SerializerTestsSetup [Fact] public void SerializeSingle_ResourceWithDefaultTargetFields_CanSerialize() { - // arrange + // Arrange var entity = new TestResource() { Id = 1, StringField = "value", NullableIntField = 123 }; var serializer = GetResponseSerializer(); - // act + // Act string serialized = serializer.SerializeSingle(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"":{ @@ -49,14 +49,14 @@ public void SerializeSingle_ResourceWithDefaultTargetFields_CanSerialize() [Fact] public void SerializeMany_ResourceWithDefaultTargetFields_CanSerialize() { - // arrange + // Arrange var entity = new TestResource() { Id = 1, StringField = "value", NullableIntField = 123 }; var serializer = GetResponseSerializer(); - // act + // Act string serialized = serializer.SerializeMany(new List { entity }); - // assert + // Assert var expectedFormatted = @"{ ""data"":[{ @@ -82,7 +82,7 @@ public void SerializeMany_ResourceWithDefaultTargetFields_CanSerialize() [Fact] public void SerializeSingle_ResourceWithIncludedRelationships_CanSerialize() { - // arrange + // Arrange var entity = new MultipleRelationshipsPrincipalPart { Id = 1, @@ -92,10 +92,10 @@ public void SerializeSingle_ResourceWithIncludedRelationships_CanSerialize() var chain = _resourceGraph.GetRelationships().Select(r => new List { r }).ToList(); var serializer = GetResponseSerializer(inclusionChains: chain); - // act + // Act string serialized = serializer.SerializeSingle(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"":{ @@ -143,7 +143,7 @@ public void SerializeSingle_ResourceWithIncludedRelationships_CanSerialize() [Fact] public void SerializeSingle_ResourceWithDeeplyIncludedRelationships_CanSerialize() { - // arrange + // Arrange var deeplyIncludedEntity = new OneToManyPrincipal { Id = 30, AttributeMember = "deep" }; var includedEntity = new OneToManyDependent { Id = 20, Principal = deeplyIncludedEntity }; var entity = new MultipleRelationshipsPrincipalPart @@ -164,10 +164,10 @@ public void SerializeSingle_ResourceWithDeeplyIncludedRelationships_CanSerialize var serializer = GetResponseSerializer(inclusionChains: chains); - // act + // Act string serialized = serializer.SerializeSingle(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"":{ @@ -232,13 +232,13 @@ public void SerializeSingle_ResourceWithDeeplyIncludedRelationships_CanSerialize [Fact] public void SerializeSingle_Null_CanSerialize() { - // arrange + // Arrange var serializer = GetResponseSerializer(); TestResource entity = null; - // act + // Act string serialized = serializer.SerializeSingle(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"": null }"; var expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); @@ -247,12 +247,12 @@ public void SerializeSingle_Null_CanSerialize() [Fact] public void SerializeList_EmptyList_CanSerialize() { - // arrange + // Arrange var serializer = GetResponseSerializer(); - // act + // Act string serialized = serializer.SerializeMany(new List()); - // assert + // Assert var expectedFormatted = @"{ ""data"": [] }"; var expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); @@ -261,14 +261,14 @@ public void SerializeList_EmptyList_CanSerialize() [Fact] public void SerializeSingle_ResourceWithLinksEnabled_CanSerialize() { - // arrange + // Arrange var entity = new OneToManyPrincipal { Id = 10 }; var serializer = GetResponseSerializer(topLinks: _dummyToplevelLinks, relationshipLinks: _dummyRelationshipLinks, resourceLinks: _dummyResourceLinks); - // act + // Act string serialized = serializer.SerializeSingle(entity); - // assert + // Assert var expectedFormatted = @"{ ""links"":{ @@ -305,15 +305,15 @@ public void SerializeSingle_ResourceWithLinksEnabled_CanSerialize() [Fact] public void SerializeSingle_ResourceWithMeta_IncludesMetaInResult() { - // arrange + // Arrange var meta = new Dictionary { { "test", "meta" } }; var entity = new OneToManyPrincipal { Id = 10 }; var serializer = GetResponseSerializer(metaDict: meta); - // act + // Act string serialized = serializer.SerializeSingle(entity); - // assert + // Assert var expectedFormatted = @"{ ""meta"":{ ""test"": ""meta"" }, @@ -333,15 +333,15 @@ public void SerializeSingle_ResourceWithMeta_IncludesMetaInResult() [Fact] public void SerializeSingle_NullWithLinksAndMeta_StillShowsLinksAndMeta() { - // arrange + // Arrange var meta = new Dictionary { { "test", "meta" } }; OneToManyPrincipal entity = null; var serializer = GetResponseSerializer(metaDict: meta, topLinks: _dummyToplevelLinks, relationshipLinks: _dummyRelationshipLinks, resourceLinks: _dummyResourceLinks); - // act + // Act string serialized = serializer.SerializeSingle(entity); Console.WriteLine(serialized); - // assert + // Assert var expectedFormatted = @"{ ""meta"":{ ""test"": ""meta"" }, @@ -362,16 +362,16 @@ public void SerializeSingle_NullWithLinksAndMeta_StillShowsLinksAndMeta() [Fact] public void SerializeSingleWithRequestRelationship_NullToOneRelationship_CanSerialize() { - // arrange + // Arrange var entity = new OneToOnePrincipal() { Id = 2, Dependent = null }; var serializer = GetResponseSerializer(); var requestRelationship = _resourceGraph.GetRelationships((OneToOnePrincipal t) => t.Dependent).First(); serializer.RequestRelationship = requestRelationship; - // act + // Act string serialized = serializer.SerializeSingle(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"": null}"; var expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); @@ -380,17 +380,17 @@ public void SerializeSingleWithRequestRelationship_NullToOneRelationship_CanSeri [Fact] public void SerializeSingleWithRequestRelationship_PopulatedToOneRelationship_CanSerialize() { - // arrange + // Arrange var entity = new OneToOnePrincipal() { Id = 2, Dependent = new OneToOneDependent { Id = 1 } }; var serializer = GetResponseSerializer(); var requestRelationship = _resourceGraph.GetRelationships((OneToOnePrincipal t) => t.Dependent).First(); serializer.RequestRelationship = requestRelationship; - // act + // Act string serialized = serializer.SerializeSingle(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"":{ @@ -407,17 +407,17 @@ public void SerializeSingleWithRequestRelationship_PopulatedToOneRelationship_Ca [Fact] public void SerializeSingleWithRequestRelationship_EmptyToManyRelationship_CanSerialize() { - // arrange + // Arrange var entity = new OneToManyPrincipal() { Id = 2, Dependents = new List() }; var serializer = GetResponseSerializer(); var requestRelationship = _resourceGraph.GetRelationships((OneToManyPrincipal t) => t.Dependents).First(); serializer.RequestRelationship = requestRelationship; - // act + // Act string serialized = serializer.SerializeSingle(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"": [] }"; var expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); @@ -426,17 +426,17 @@ public void SerializeSingleWithRequestRelationship_EmptyToManyRelationship_CanSe [Fact] public void SerializeSingleWithRequestRelationship_PopulatedToManyRelationship_CanSerialize() { - // arrange + // Arrange var entity = new OneToManyPrincipal() { Id = 2, Dependents = new List { new OneToManyDependent { Id = 1 } } }; var serializer = GetResponseSerializer(); var requestRelationship = _resourceGraph.GetRelationships((OneToManyPrincipal t) => t.Dependents).First(); serializer.RequestRelationship = requestRelationship; - // act + // Act string serialized = serializer.SerializeSingle(entity); - // assert + // Assert var expectedFormatted = @"{ ""data"":[{ @@ -453,7 +453,7 @@ public void SerializeSingleWithRequestRelationship_PopulatedToManyRelationship_C [Fact] public void SerializeError_CustomError_CanSerialize() { - // arrange + // Arrange var error = new CustomError(507, "title", "detail", "custom"); var errorCollection = new ErrorCollection(); errorCollection.Add(error); @@ -471,10 +471,10 @@ public void SerializeError_CustomError_CanSerialize() }); var serializer = GetResponseSerializer(); - // act + // Act var result = serializer.Serialize(errorCollection); - // assert + // Assert Assert.Equal(expectedJson, result); } diff --git a/test/UnitTests/Services/EntityResourceService_Tests.cs b/test/UnitTests/Services/EntityResourceService_Tests.cs index 3451dd955a..9834c2477c 100644 --- a/test/UnitTests/Services/EntityResourceService_Tests.cs +++ b/test/UnitTests/Services/EntityResourceService_Tests.cs @@ -42,7 +42,7 @@ public EntityResourceService_Tests() [Fact] public async Task GetRelationshipAsync_Passes_Public_ResourceName_To_Repository() { - // arrange + // Arrange const int id = 1; const string relationshipName = "collection"; var relationship = new RelationshipAttribute[] { new HasOneAttribute(relationshipName) }; @@ -56,10 +56,10 @@ public async Task GetRelationshipAsync_Passes_Public_ResourceName_To_Repository( var service = GetService(); - // act + // Act await service.GetRelationshipAsync(id, relationshipName); - // assert + // Assert _repositoryMock.Verify(m => m.Get(id), Times.Once); _repositoryMock.Verify(m => m.Include(query, relationship), Times.Once); _repositoryMock.Verify(m => m.FirstOrDefaultAsync(query), Times.Once); @@ -68,7 +68,7 @@ public async Task GetRelationshipAsync_Passes_Public_ResourceName_To_Repository( [Fact] public async Task GetRelationshipAsync_Returns_Relationship_Value() { - // arrange + // Arrange const int id = 1; const string relationshipName = "collection"; var relationship = new RelationshipAttribute[] { new HasOneAttribute(relationshipName) }; @@ -86,10 +86,10 @@ public async Task GetRelationshipAsync_Returns_Relationship_Value() var repository = GetService(); - // act + // Act var result = await repository.GetRelationshipAsync(id, relationshipName); - // assert + // Assert Assert.NotNull(result); var collection = Assert.IsType(result); Assert.Equal(todoItem.Collection.Id, collection.Id); From 9ee71f53c659890bf49c8e12e3afff1f1427abc8 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 16:47:10 +0200 Subject: [PATCH 25/47] chore: fix tests --- .../Resources/UserResource.cs | 7 +++++-- .../JsonApiDotNetCoreExample/Startup.cs | 2 ++ .../CamelCasedModelsControllerTests.cs | 4 ++-- .../Extensibility/CustomControllerTests.cs | 4 ++-- .../NullValuedAttributeHandlingTests.cs | 5 +++-- .../Extensibility/RequestMetaTests.cs | 5 +++-- .../Acceptance/ManyToManyTests.cs | 4 ++-- .../ResourceDefinitions/QueryFiltersTests.cs | 21 +++++++++++++++---- .../ResourceDefinitionTests.cs | 6 ++++-- .../Acceptance/Spec/AttributeFilterTests.cs | 5 +++-- .../Acceptance/Spec/AttributeSortTests.cs | 7 ++++--- .../Acceptance/Spec/ContentNegotiation.cs | 4 ++-- .../Acceptance/Spec/CreatingDataTests.cs | 2 +- .../Spec/DeeplyNestedInclusionTests.cs | 5 +++-- .../Acceptance/Spec/DeletingDataTests.cs | 4 ++-- .../Acceptance/Spec/DocumentTests/Included.cs | 2 +- .../Acceptance/Spec/DocumentTests/Meta.cs | 4 ++-- .../Spec/DocumentTests/PagingTests.cs | 2 +- .../Spec/DocumentTests/Relationships.cs | 4 ++-- .../Acceptance/Spec/EndToEndTest.cs | 9 ++++---- .../Acceptance/Spec/FetchingDataTests.cs | 4 ++-- .../Spec/FetchingRelationshipsTests.cs | 4 ++-- .../Acceptance/Spec/PagingTests.cs | 7 ++++--- .../Acceptance/Spec/QueryParameters.cs | 4 ++-- .../Acceptance/Spec/SparseFieldSetTests.cs | 2 +- .../Acceptance/Spec/UpdatingDataTests.cs | 4 ++-- .../Spec/UpdatingRelationshipsTests.cs | 4 ++-- .../Acceptance/TestFixture.cs | 5 +++++ .../Acceptance/TodoItemsControllerTests.cs | 5 +++-- .../TestStartup.cs | 4 ++-- .../WebHostCollection.cs | 4 ++-- 31 files changed, 93 insertions(+), 60 deletions(-) diff --git a/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs b/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs index a8d6f039e4..543026db20 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs @@ -26,10 +26,13 @@ private IQueryable FirstCharacterFilter(IQueryable users, FilterQuer { switch (filterQuery.Operation) { + // need to cast to list first because getting the first + // char in a string is apparently not something LINQ can translate + // to a query. case "lt": - return users.Where(u => u.Username[0] < filterQuery.Value[0]); + return users.ToList().Where(u => u.Username.First() < filterQuery.Value[0]).AsQueryable(); default: - return users.Where(u => u.Username[0] == filterQuery.Value[0]); + return users.ToList().Where(u => u.Username.First() == filterQuery.Value[0]).AsQueryable(); } } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Startup.cs b/src/Examples/JsonApiDotNetCoreExample/Startup.cs index a6ec145a29..a9cb0529f3 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startup.cs @@ -44,6 +44,7 @@ public virtual void ConfigureServices(IServiceCollection services) options.LoaDatabaseValues = true; }, discovery => discovery.AddCurrentAssembly()); + services.AddClientSerialization(); } public virtual void Configure( @@ -51,6 +52,7 @@ public virtual void Configure( ILoggerFactory loggerFactory, AppDbContext context) { + context.Database.EnsureCreated(); app.UseJsonApi(); } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs index 7c98e7e2c4..a9b827ebc5 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/CamelCasedModelsControllerTests.cs @@ -17,11 +17,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance [Collection("WebHostCollection")] public class CamelCasedModelsControllerTests { - private TestFixture _fixture; + private TestFixture _fixture; private AppDbContext _context; private Faker _faker; - public CamelCasedModelsControllerTests(TestFixture fixture) + public CamelCasedModelsControllerTests(TestFixture fixture) { _fixture = fixture; _context = fixture.GetService(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs index dc5a564fed..4a23da42ac 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs @@ -17,11 +17,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Extensibility [Collection("WebHostCollection")] public class CustomControllerTests { - private TestFixture _fixture; + private TestFixture _fixture; private Faker _todoItemFaker; private Faker _personFaker; - public CustomControllerTests(TestFixture fixture) + public CustomControllerTests(TestFixture fixture) { _fixture = fixture; _todoItemFaker = new Faker() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs index 3ca3796100..9081dac41e 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Models; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using Newtonsoft.Json; @@ -13,11 +14,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Extensibility [Collection("WebHostCollection")] public class NullValuedAttributeHandlingTests : IAsyncLifetime { - private readonly TestFixture _fixture; + private readonly TestFixture _fixture; private readonly AppDbContext _dbContext; private readonly TodoItem _todoItem; - public NullValuedAttributeHandlingTests(TestFixture fixture) + public NullValuedAttributeHandlingTests(TestFixture fixture) { _fixture = fixture; _dbContext = fixture.GetService(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs index 69eef90224..af40693824 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs @@ -10,15 +10,16 @@ using System.Collections; using JsonApiDotNetCoreExampleTests.Startups; using JsonApiDotNetCoreExample.Resources; +using JsonApiDotNetCoreExample; namespace JsonApiDotNetCoreExampleTests.Acceptance.Extensibility { [Collection("WebHostCollection")] public class RequestMetaTests { - private TestFixture _fixture; + private TestFixture _fixture; - public RequestMetaTests(TestFixture fixture) + public RequestMetaTests(TestFixture fixture) { _fixture = fixture; } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs index be570c0dbc..1df5593fb0 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs @@ -26,8 +26,8 @@ public class ManyToManyTests private static readonly Faker _tagFaker = new Faker().RuleFor(a => a.Name, f => f.Random.AlphaNumeric(10)); - private TestFixture _fixture; - public ManyToManyTests(TestFixture fixture) + private TestFixture _fixture; + public ManyToManyTests(TestFixture fixture) { _fixture = fixture; } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/QueryFiltersTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/QueryFiltersTests.cs index 0a7a56ee9e..6c3c23b125 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/QueryFiltersTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/QueryFiltersTests.cs @@ -3,8 +3,11 @@ using System.Net.Http; using System.Threading.Tasks; using Bogus; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; using Xunit; namespace JsonApiDotNetCoreExampleTests.Acceptance @@ -12,11 +15,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance [Collection("WebHostCollection")] public class QueryFiltersTests { - private TestFixture _fixture; + private TestFixture _fixture; private AppDbContext _context; private Faker _userFaker; - public QueryFiltersTests(TestFixture fixture) + public QueryFiltersTests(TestFixture fixture) { _fixture = fixture; _context = fixture.GetService(); @@ -38,8 +41,13 @@ public async Task FiltersWithCustomQueryFiltersEquals() var route = $"/api/v1/users?filter[first-character]=eq:{firstUsernameCharacter}"; var request = new HttpRequestMessage(httpMethod, route); + // @TODO - Use fixture + var builder = new WebHostBuilder().UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); + // Act - var response = await _fixture.Client.SendAsync(request); + var response = await client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -66,8 +74,13 @@ public async Task FiltersWithCustomQueryFiltersLessThan() var route = $"/api/v1/users?filter[first-character]=lt:{median}"; var request = new HttpRequestMessage(httpMethod, route); + // @TODO - Use fixture + var builder = new WebHostBuilder().UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); + // Act - var response = await _fixture.Client.SendAsync(request); + var response = await client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/ResourceDefinitionTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/ResourceDefinitionTests.cs index ad4994cc7a..0ae0806574 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/ResourceDefinitionTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/ResourceDefinitionTests.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Bogus; using JsonApiDotNetCore.Models; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using Microsoft.EntityFrameworkCore; @@ -18,7 +19,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance [Collection("WebHostCollection")] public class ResourceDefinitionTests { - private TestFixture _fixture; + private TestFixture _fixture; private AppDbContext _context; private Faker _userFaker; private Faker _todoItemFaker; @@ -28,7 +29,7 @@ public class ResourceDefinitionTests .RuleFor(a => a.Author, f => new Author()); private static readonly Faker _tagFaker = new Faker().RuleFor(a => a.Name, f => f.Random.AlphaNumeric(10)); - public ResourceDefinitionTests(TestFixture fixture) + public ResourceDefinitionTests(TestFixture fixture) { _fixture = fixture; _context = fixture.GetService(); @@ -73,6 +74,7 @@ public async Task Can_Create_User_With_Password() var user = _userFaker.Generate(); var serializer = _fixture.GetSerializer(p => new { p.Password, p.Username }); + var httpMethod = new HttpMethod("POST"); var route = $"/api/v1/users"; diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs index 118491ffcb..25fd53c6f3 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Bogus; using JsonApiDotNetCore.Models; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using Newtonsoft.Json; @@ -17,11 +18,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class AttributeFilterTests { - private TestFixture _fixture; + private TestFixture _fixture; private Faker _todoItemFaker; private readonly Faker _personFaker; - public AttributeFilterTests(TestFixture fixture) + public AttributeFilterTests(TestFixture fixture) { _fixture = fixture; _todoItemFaker = new Faker() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs index 6449ba669f..4b81073a48 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs @@ -1,4 +1,5 @@ -using System.Net; +using JsonApiDotNetCoreExample; +using System.Net; using System.Net.Http; using System.Threading.Tasks; using Xunit; @@ -8,9 +9,9 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class AttributeSortTests { - private TestFixture _fixture; + private TestFixture _fixture; - public AttributeSortTests(TestFixture fixture) + public AttributeSortTests(TestFixture fixture) { _fixture = fixture; } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs index a9d234e353..9397af4dce 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs @@ -12,8 +12,8 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class ContentNegotiation { - private TestFixture _fixture; - public ContentNegotiation(TestFixture fixture) + private TestFixture _fixture; + public ContentNegotiation(TestFixture fixture) { _fixture = fixture; } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs index 548060b1ed..3a1dca1c25 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs @@ -27,7 +27,7 @@ public class CreatingDataTests : EndToEndTest private readonly Faker _todoItemFaker; private readonly Faker _personFaker; - public CreatingDataTests(TestFixture fixture) : base(fixture) + public CreatingDataTests(TestFixture fixture) : base(fixture) { _fixture = fixture; _todoItemFaker = new Faker() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs index a98c026463..2299ee2ba2 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs @@ -5,6 +5,7 @@ using JsonApiDotNetCore.Builders; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Serialization.Client; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using JsonApiDotNetCoreExampleTests.Helpers.Extensions; @@ -18,9 +19,9 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class DeeplyNestedInclusionTests { - private TestFixture _fixture; + private TestFixture _fixture; - public DeeplyNestedInclusionTests(TestFixture fixture) + public DeeplyNestedInclusionTests(TestFixture fixture) { _fixture = fixture; } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs index 502d4716b9..50a312d2eb 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs @@ -15,11 +15,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class DeletingDataTests { - private TestFixture _fixture; + private TestFixture _fixture; private AppDbContext _context; private Faker _todoItemFaker; - public DeletingDataTests(TestFixture fixture) + public DeletingDataTests(TestFixture fixture) { _fixture = fixture; _context = fixture.GetService(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs index 58ab372b3d..1471b0410b 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs @@ -24,7 +24,7 @@ public class Included private readonly Faker _todoItemFaker; private readonly Faker _todoItemCollectionFaker; - public Included(TestFixture fixture) + public Included(TestFixture fixture) { _context = fixture.GetService(); _personFaker = new Faker() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs index 53bf7ed1bc..314933c3d5 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs @@ -18,9 +18,9 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec.DocumentTests [Collection("WebHostCollection")] public class Meta { - private TestFixture _fixture; + private TestFixture _fixture; private AppDbContext _context; - public Meta(TestFixture fixture) + public Meta(TestFixture fixture) { _fixture = fixture; _context = fixture.GetService(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/PagingTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/PagingTests.cs index 0bf315d7a0..a15c92a38d 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/PagingTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/PagingTests.cs @@ -20,7 +20,7 @@ public class PagingTests private readonly AppDbContext _context; private readonly Faker _todoItemFaker; - public PagingTests(TestFixture fixture) + public PagingTests(TestFixture fixture) { _context = fixture.GetService(); _todoItemFaker = new Faker() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs index a010dbc8c7..502eeb0284 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs @@ -17,11 +17,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec.DocumentTests [Collection("WebHostCollection")] public class Relationships { - private TestFixture _fixture; + private TestFixture _fixture; private AppDbContext _context; private Faker _todoItemFaker; - public Relationships(TestFixture fixture) + public Relationships(TestFixture fixture) { _fixture = fixture; _context = fixture.GetService(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/EndToEndTest.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/EndToEndTest.cs index 3f70526bf3..e287e1ae20 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/EndToEndTest.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/EndToEndTest.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq.Expressions; using System.Net; using System.Net.Http; @@ -6,6 +6,7 @@ using System.Threading.Tasks; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Serialization.Client; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; @@ -17,9 +18,9 @@ public class EndToEndTest { public static MediaTypeHeaderValue JsonApiContentType = new MediaTypeHeaderValue("application/vnd.api+json"); private HttpClient _client; - protected TestFixture _fixture; + protected TestFixture _fixture; protected readonly IResponseDeserializer _deserializer; - public EndToEndTest(TestFixture fixture) + public EndToEndTest(TestFixture fixture) { _fixture = fixture; _deserializer = GetDeserializer(); @@ -71,7 +72,7 @@ public IResponseDeserializer GetDeserializer() } protected void AssertEqualStatusCode(HttpStatusCode expected, HttpResponseMessage response) - { + { Assert.True(expected == response.StatusCode, $"Got {response.StatusCode} status code with payload instead of {expected}. Payload: {response.Content.ReadAsStringAsync().Result}"); } } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs index 91b4b2b1ad..77be87e23a 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs @@ -17,11 +17,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class FetchingDataTests { - private TestFixture _fixture; + private TestFixture _fixture; private Faker _todoItemFaker; private Faker _personFaker; - public FetchingDataTests(TestFixture fixture) + public FetchingDataTests(TestFixture fixture) { _fixture = fixture; _todoItemFaker = new Faker() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs index adfb0e4dec..0abf4221cf 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs @@ -14,10 +14,10 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class FetchingRelationshipsTests { - private TestFixture _fixture; + private TestFixture _fixture; private Faker _todoItemFaker; - public FetchingRelationshipsTests(TestFixture fixture) + public FetchingRelationshipsTests(TestFixture fixture) { _fixture = fixture; _todoItemFaker = new Faker() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs index 9904acb19f..2f6321c6e9 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using Bogus; using JsonApiDotNetCore.Models; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Models; using Xunit; using Person = JsonApiDotNetCoreExample.Models.Person; @@ -11,12 +12,12 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class PagingTests : TestFixture + public class PagingTests : TestFixture { - private TestFixture _fixture; + private TestFixture _fixture; private readonly Faker _todoItemFaker; - public PagingTests(TestFixture fixture) + public PagingTests(TestFixture fixture) { _fixture = fixture; _todoItemFaker = new Faker() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs index 39aa381f20..4a7a8cfdcf 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs @@ -13,8 +13,8 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class QueryParameters { - private TestFixture _fixture; - public QueryParameters(TestFixture fixture) + private TestFixture _fixture; + public QueryParameters(TestFixture fixture) { _fixture = fixture; } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs index dcad4fa838..b39dcdb012 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs @@ -34,7 +34,7 @@ public class SparseFieldSetTests private readonly Faker _personFaker; private readonly Faker _todoItemFaker; - public SparseFieldSetTests(TestFixture fixture) + public SparseFieldSetTests(TestFixture fixture) { _dbContext = fixture.GetService(); _resourceGraph = fixture.GetService(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs index 7e437e425c..483848efd6 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs @@ -22,12 +22,12 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class UpdatingDataTests { - private TestFixture _fixture; + private TestFixture _fixture; private AppDbContext _context; private Faker _todoItemFaker; private Faker _personFaker; - public UpdatingDataTests(TestFixture fixture) + public UpdatingDataTests(TestFixture fixture) { _fixture = fixture; _context = fixture.GetService(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs index 77fdd900ee..6dd6744210 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs @@ -23,12 +23,12 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec [Collection("WebHostCollection")] public class UpdatingRelationshipsTests { - private TestFixture _fixture; + private TestFixture _fixture; private AppDbContext _context; private Bogus.Faker _personFaker; private Faker _todoItemFaker; - public UpdatingRelationshipsTests(TestFixture fixture) + public UpdatingRelationshipsTests(TestFixture fixture) { _fixture = fixture; _context = fixture.GetService(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs index f1a270a465..90c7d0e926 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs @@ -11,6 +11,7 @@ using JsonApiDotNetCore.Builders; using JsonApiDotNetCoreExampleTests.Helpers.Models; using JsonApiDotNetCoreExample.Models; +using JsonApiDotNetCoreExample; namespace JsonApiDotNetCoreExampleTests.Acceptance { @@ -35,9 +36,13 @@ public IRequestSerializer GetSerializer(Expression(); if (attributes != null) + { serializer.SetAttributesToSerialize(attributes); + } if (relationships != null) + { serializer.SetRelationshipsToSerialize(relationships); + } return serializer; } public IResponseDeserializer GetDeserializer() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/TodoItemsControllerTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/TodoItemsControllerTests.cs index 3065dd47be..a69ae3a70a 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/TodoItemsControllerTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/TodoItemsControllerTests.cs @@ -8,6 +8,7 @@ using Bogus; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Models; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using JsonApiDotNetCoreExampleTests.Helpers.Models; @@ -21,12 +22,12 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance [Collection("WebHostCollection")] public class TodoItemControllerTests { - private TestFixture _fixture; + private TestFixture _fixture; private AppDbContext _context; private Faker _todoItemFaker; private Faker _personFaker; - public TodoItemControllerTests(TestFixture fixture) + public TodoItemControllerTests(TestFixture fixture) { _fixture = fixture; _context = fixture.GetService(); diff --git a/test/JsonApiDotNetCoreExampleTests/TestStartup.cs b/test/JsonApiDotNetCoreExampleTests/TestStartup.cs index be4f0f08fc..f2bae23fa8 100644 --- a/test/JsonApiDotNetCoreExampleTests/TestStartup.cs +++ b/test/JsonApiDotNetCoreExampleTests/TestStartup.cs @@ -19,8 +19,8 @@ public TestStartup(IWebHostEnvironment env) : base(env) public override void ConfigureServices(IServiceCollection services) { base.ConfigureServices(services); - services.AddClientSerialization(); - services.AddScoped(); + //services.AddClientSerialization(); + //services.AddScoped(); } } } diff --git a/test/JsonApiDotNetCoreExampleTests/WebHostCollection.cs b/test/JsonApiDotNetCoreExampleTests/WebHostCollection.cs index 561d86bbb0..edf8bac897 100644 --- a/test/JsonApiDotNetCoreExampleTests/WebHostCollection.cs +++ b/test/JsonApiDotNetCoreExampleTests/WebHostCollection.cs @@ -1,10 +1,10 @@ +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExampleTests.Acceptance; using Xunit; namespace JsonApiDotNetCoreExampleTests { [CollectionDefinition("WebHostCollection")] - public class WebHostCollection - : ICollectionFixture> + public class WebHostCollection : ICollectionFixture> { } } From 9000421c0e21228b0b2fba89f3aeec4302940cc9 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 17:30:50 +0200 Subject: [PATCH 26/47] chore: re-add unit test for defaultentityrepository for test IAsyncQueryProvider that's actually a List --- .../Resources/PersonResource.cs | 2 +- .../Data/DefaultResourceRepository.cs | 47 ++++++++--- .../Acceptance/Spec/PagingTests.cs | 9 +-- .../Acceptance/Spec/UpdatingDataTests.cs | 4 +- .../Extensibility/NoEntityFrameworkTests.cs | 9 ++- test/NoEntityFrameworkTests/TestFixture.cs | 3 +- .../Data/DefaultEntityRepositoryTest.cs | 74 +++++++++++++++++ .../Data/DefaultEntityRepositoryTests.cs | 81 ------------------- test/UnitTests/UnitTests.csproj | 1 + 9 files changed, 126 insertions(+), 104 deletions(-) create mode 100644 test/UnitTests/Data/DefaultEntityRepositoryTest.cs delete mode 100644 test/UnitTests/Data/DefaultEntityRepositoryTests.cs diff --git a/src/Examples/JsonApiDotNetCoreExample/Resources/PersonResource.cs b/src/Examples/JsonApiDotNetCoreExample/Resources/PersonResource.cs index da8fc957b7..4c786b238c 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Resources/PersonResource.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Resources/PersonResource.cs @@ -31,7 +31,7 @@ public Dictionary GetMeta() { return new Dictionary { { "copyright", "Copyright 2015 Example Corp." }, - { "authors", new string[] { "Jared Nance", "Maurits Moeys" } } + { "authors", new string[] { "Jared Nance", "Maurits Moeys", "Harro van der Kroft" } } }; } } diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index bc03b712b8..7f03caccfd 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -10,6 +10,7 @@ using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Serialization; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.Extensions.Logging; namespace JsonApiDotNetCore.Data @@ -298,21 +299,43 @@ public virtual IQueryable Include(IQueryable entities, IEn /// public virtual async Task> PageAsync(IQueryable entities, int pageSize, int pageNumber) { + // the IQueryable returned from the hook executor is sometimes consumed here. + // In this case, it does not support .ToListAsync(), so we use the method below. if (pageNumber >= 0) { - // the IQueryable returned from the hook executor is sometimes consumed here. - // In this case, it does not support .ToListAsync(), so we use the method below. - return await this.ToListAsync(entities.PageForward(pageSize, pageNumber)); + entities = entities.PageForward(pageSize, pageNumber); + if (entities is IAsyncQueryProvider) + { + return await entities.ToListAsync(); + } + else + { + return entities.ToList(); + } + } + else + { + if (!(entities is IAsyncQueryProvider)) + { + entities = entities.Reverse(); + int firstIndex = pageSize * Math.Abs(pageNumber) - 1; + int numberOfElementsInPage = Math.Min(pageSize, firstIndex + pageSize); + + return entities.Skip(firstIndex).Take(numberOfElementsInPage); + } + else + { + // since EntityFramework does not support IQueryable.Reverse(), we need to know the number of queried entities + var totalCount = await entities.CountAsync(); + + int virtualFirstIndex = totalCount - pageSize * Math.Abs(pageNumber); + int numberOfElementsInPage = Math.Min(pageSize, virtualFirstIndex + pageSize); + + return await ToListAsync(entities + .Skip(virtualFirstIndex) + .Take(numberOfElementsInPage)); + } } - // since EntityFramework does not support IQueryable.Reverse(), we need to know the number of queried entities - var totalCount = await entities.CountAsync(); - // may be negative - int virtualFirstIndex = totalCount - pageSize * Math.Abs(pageNumber); - int numberOfElementsInPage = Math.Min(pageSize, virtualFirstIndex + pageSize); - - return await ToListAsync(entities - .Skip(virtualFirstIndex) - .Take(numberOfElementsInPage)); } /// diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs index 2f6321c6e9..ee605bf5ab 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs @@ -95,23 +95,20 @@ public async Task Can_Paginate_TodoItems_From_End() var totalCount = expectedEntitiesPerPage * 2; var person = new Person(); var todoItems = _todoItemFaker.Generate(totalCount).ToList(); - - foreach (var todoItem in todoItems) - todoItem.Owner = person; + todoItems.ForEach(ti => ti.Owner = person); Context.TodoItems.RemoveRange(Context.TodoItems); Context.TodoItems.AddRange(todoItems); Context.SaveChanges(); - var route = $"/api/v1/todo-items?page[size]={expectedEntitiesPerPage}&page[number]=-1"; // Act var response = await Client.GetAsync(route); // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var body = await response.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var deserializedBody = _fixture.GetDeserializer().DeserializeList(body).Data; var expectedTodoItems = new[] { todoItems[totalCount - 2], todoItems[totalCount - 1] }; diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs index 483848efd6..48184b724f 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs @@ -70,7 +70,7 @@ public async Task Response400IfUpdatingNotSettableAttribute() public async Task Respond_404_If_EntityDoesNotExist() { // Arrange - var maxPersonId = _context.TodoItems.LastOrDefault()?.Id ?? 0; + var maxPersonId = _context.TodoItems.ToList().LastOrDefault()?.Id ?? 0; var todoItem = _todoItemFaker.Generate(); todoItem.Id = maxPersonId + 100; todoItem.CreatedDate = DateTime.Now; @@ -95,7 +95,7 @@ public async Task Respond_404_If_EntityDoesNotExist() public async Task Respond_422_If_IdNotInAttributeList() { // Arrange - var maxPersonId = _context.TodoItems.LastOrDefault()?.Id ?? 0; + var maxPersonId = _context.TodoItems.ToList().LastOrDefault()?.Id ?? 0; var todoItem = _todoItemFaker.Generate(); todoItem.CreatedDate = DateTime.Now; var builder = new WebHostBuilder() diff --git a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs index 0854b1adc0..7bca584b63 100644 --- a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs +++ b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs @@ -3,7 +3,10 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Models; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; using Newtonsoft.Json; using Xunit; @@ -74,7 +77,6 @@ public async Task Can_Create_TodoItems() { // Arrange var description = Guid.NewGuid().ToString(); - var client = _fixture.Server.CreateClient(); var httpMethod = new HttpMethod("POST"); var route = $"/api/v1/custom-todo-items/"; var content = new @@ -94,6 +96,11 @@ public async Task Can_Create_TodoItems() request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); + var builder = new WebHostBuilder() + .UseStartup(); + var server = new TestServer(builder); + var client = server.CreateClient(); + // Act var response = await client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); diff --git a/test/NoEntityFrameworkTests/TestFixture.cs b/test/NoEntityFrameworkTests/TestFixture.cs index b11f7ff118..7f15df56fb 100644 --- a/test/NoEntityFrameworkTests/TestFixture.cs +++ b/test/NoEntityFrameworkTests/TestFixture.cs @@ -1,6 +1,7 @@ using JsonApiDotNetCore.Builders; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Serialization.Client; +using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using JsonApiDotNetCoreExampleTests.Helpers.Extensions; @@ -19,7 +20,7 @@ public class TestFixture : IDisposable private IServiceProvider _services; public TestFixture() { - var builder = new WebHostBuilder().UseStartup(); + var builder = new WebHostBuilder().UseStartup(); Server = new TestServer(builder); Context = Server.GetService(); Context.Database.EnsureCreated(); diff --git a/test/UnitTests/Data/DefaultEntityRepositoryTest.cs b/test/UnitTests/Data/DefaultEntityRepositoryTest.cs new file mode 100644 index 0000000000..1428ab3376 --- /dev/null +++ b/test/UnitTests/Data/DefaultEntityRepositoryTest.cs @@ -0,0 +1,74 @@ +using JsonApiDotNetCore.Builders; +using JsonApiDotNetCore.Data; +using JsonApiDotNetCore.Internal.Contracts; +using JsonApiDotNetCore.Serialization; +using JsonApiDotNetCoreExample.Data; +using JsonApiDotNetCoreExample.Models; +using Microsoft.EntityFrameworkCore; +using Moq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Xunit; + +namespace UnitTests.Data +{ + public class DefaultEntityRepositoryTest + { + + [Fact] + public async Task PageAsync_IQueryableIsAListAndPageNumberPositive_CanStillCount() + { + // If IQueryable is actually a list (this can happen after a filter or hook) + // It needs to not do CountAsync, because well.. its not asynchronous. + + // Arrange + var repository = Setup(); + var todoItems = new List() { + new TodoItem{ Id = 1 }, + new TodoItem{ Id = 2 } + }; + + // Act + var result = await repository.PageAsync(todoItems.AsQueryable(), pageSize: 1, pageNumber: 2); + + // Assert + Assert.True(result.ElementAt(0).Id == todoItems[1].Id); + } + + [Fact] + public async Task PageAsync_IQueryableIsAListAndPageNumberNegative_CanStillCount() + { + // If IQueryable is actually a list (this can happen after a filter or hook) + // It needs to not do CountAsync, because well.. its not asynchronous. + + // Arrange + var repository = Setup(); + var todoItems = new List() { + new TodoItem{ Id = 1 }, + new TodoItem{ Id = 2 }, + new TodoItem{ Id = 3 }, + new TodoItem{ Id = 4 } + }; + + // Act + var result = await repository.PageAsync(todoItems.AsQueryable(), pageSize: 1, pageNumber: -2); + + // Assert + Assert.True(result.First().Id == 3); + } + + private DefaultResourceRepository Setup() + { + var contextResolverMock = new Mock(); + contextResolverMock.Setup(m => m.GetContext()).Returns(new Mock().Object); + var resourceGraph = new Mock(); + var targetedFields = new Mock(); + var repository = new DefaultResourceRepository(targetedFields.Object, contextResolverMock.Object, resourceGraph.Object, null); + return repository; + } + + } +} diff --git a/test/UnitTests/Data/DefaultEntityRepositoryTests.cs b/test/UnitTests/Data/DefaultEntityRepositoryTests.cs deleted file mode 100644 index de3ff0a412..0000000000 --- a/test/UnitTests/Data/DefaultEntityRepositoryTests.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Collections.Generic; -using JsonApiDotNetCore.Controllers; -using Xunit; -using Moq; -using Microsoft.EntityFrameworkCore; -using JsonApiDotNetCoreExample.Models; -using JsonApiDotNetCore.Extensions; -using JsonApiDotNetCore.Data; -using JsonApiDotNetCore.Models; -using System.Threading.Tasks; -using System.Linq; -using JsonApiDotNetCore.Serialization; -using JsonApiDotNetCore.Builders; -using JsonApiDotNetCore.Managers.Contracts; - -namespace UnitTests.Data -{ - public class DefaultResourceRepositoryTests : JsonApiControllerMixin - { - private readonly Mock> _dbSetMock; - private readonly Mock _contextMock; - private readonly Mock _targetedFieldsMock; - private readonly Mock _contextResolverMock; - private readonly TodoItem _todoItem; - - public DefaultResourceRepositoryTests() - { - _todoItem = new TodoItem - { - Id = 1, - Description = Guid.NewGuid().ToString(), - Ordinal = 10 - }; - _dbSetMock = DbSetMock.Create(new[] { _todoItem }); - _contextMock = new Mock(); - _contextResolverMock = new Mock(); - _targetedFieldsMock = new Mock(); - } - - - - private DefaultResourceRepository GetRepository() - { - - _contextMock - .Setup(m => m.Set()) - .Returns(_dbSetMock.Object); - - _contextResolverMock - .Setup(m => m.GetContext()) - .Returns(_contextMock.Object); - - var resourceGraph = new ResourceGraphBuilder().AddResource().Build(); - - - return new DefaultResourceRepository( - _targetedFieldsMock.Object, - _contextResolverMock.Object, - resourceGraph, null, null); - } - - - - - - - private static TodoItem[] TodoItems(params int[] ids) - { - return ids.Select(id => new TodoItem { Id = id }).ToArray(); - } - - private class IdComparer : IEqualityComparer - where T : IIdentifiable - { - public bool Equals(T x, T y) => x?.StringId == y?.StringId; - - public int GetHashCode(T obj) => obj?.StringId?.GetHashCode() ?? 0; - } - } -} diff --git a/test/UnitTests/UnitTests.csproj b/test/UnitTests/UnitTests.csproj index 6e60b7d4fe..7374a96ae6 100644 --- a/test/UnitTests/UnitTests.csproj +++ b/test/UnitTests/UnitTests.csproj @@ -23,6 +23,7 @@ + From 28431110430a066cd94e5b5edaf4cc6fab6eacc3 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 17:32:35 +0200 Subject: [PATCH 27/47] refactor: make if statements more conscise --- .../Data/DefaultResourceRepository.cs | 30 +++++++------------ 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index 7f03caccfd..a60af5e793 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -304,26 +304,11 @@ public virtual async Task> PageAsync(IQueryable= 0) { entities = entities.PageForward(pageSize, pageNumber); - if (entities is IAsyncQueryProvider) - { - return await entities.ToListAsync(); - } - else - { - return entities.ToList(); - } + return entities is IAsyncQueryProvider ? await entities.ToListAsync() : entities.ToList(); } else { - if (!(entities is IAsyncQueryProvider)) - { - entities = entities.Reverse(); - int firstIndex = pageSize * Math.Abs(pageNumber) - 1; - int numberOfElementsInPage = Math.Min(pageSize, firstIndex + pageSize); - - return entities.Skip(firstIndex).Take(numberOfElementsInPage); - } - else + if (entities is IAsyncQueryProvider) { // since EntityFramework does not support IQueryable.Reverse(), we need to know the number of queried entities var totalCount = await entities.CountAsync(); @@ -331,9 +316,14 @@ public virtual async Task> PageAsync(IQueryable Date: Thu, 24 Oct 2019 19:10:09 +0200 Subject: [PATCH 28/47] chore: final stretch --- .../JsonApiDotNetCoreExample/Startup.cs | 5 ++- .../Builders/ResourceGraphBuilder.cs | 5 +-- .../IServiceCollectionExtensions.cs | 10 +++-- .../Internal/DefaultRoutingConvention.cs | 34 ++++++++++++-- .../Extensibility/NoEntityFrameworkTests.cs | 3 +- test/NoEntityFrameworkTests/TestFixture.cs | 20 +++++++-- .../Routing/DefaultRoutingConventionTests.cs | 45 +++++++++++++++++++ test/UnitTests/UnitTests.csproj | 1 + 8 files changed, 106 insertions(+), 17 deletions(-) create mode 100644 test/UnitTests/Routing/DefaultRoutingConventionTests.cs diff --git a/src/Examples/JsonApiDotNetCoreExample/Startup.cs b/src/Examples/JsonApiDotNetCoreExample/Startup.cs index a9cb0529f3..6da2c75f0d 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startup.cs @@ -25,7 +25,7 @@ public Startup(IWebHostEnvironment env) } public virtual void ConfigureServices(IServiceCollection services) - { + { services.AddJsonApi(); var loggerFactory = new LoggerFactory(); services .AddSingleton(loggerFactory) @@ -44,6 +44,8 @@ public virtual void ConfigureServices(IServiceCollection services) options.LoaDatabaseValues = true; }, discovery => discovery.AddCurrentAssembly()); + + services.AddClientSerialization(); } @@ -54,6 +56,7 @@ public virtual void Configure( { context.Database.EnsureCreated(); + app.UseJsonApi(); } diff --git a/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs b/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs index 405fe64936..fe96d6d52e 100644 --- a/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs @@ -59,11 +59,8 @@ public IResourceGraphBuilder AddResource(string pluralizedTypeNa public IResourceGraphBuilder AddResource(Type entityType, Type idType, string pluralizedTypeName = null) { AssertEntityIsNotAlreadyDefined(entityType); - - pluralizedTypeName = pluralizedTypeName ?? _resourceNameFormatter.FormatResourceName(entityType); - + pluralizedTypeName ??= _resourceNameFormatter.FormatResourceName(entityType); _entities.Add(GetEntity(pluralizedTypeName, entityType, idType)); - return this; } diff --git a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs index 75b9f4cda4..b1c1eb724c 100644 --- a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs @@ -36,9 +36,10 @@ public static IServiceCollection AddJsonApi(this IServiceColle if (options != null) application.ConfigureJsonApiOptions(options); application.ConfigureLogging(); - application.ConfigureMvc(); application.ConfigureResources(resources); application.ConfigureServices(); + application.ConfigureMvc(); + return services; } @@ -58,12 +59,13 @@ public static IServiceCollection AddJsonApi(this IServiceCollection services, var application = new JsonApiApplicationBuilder(services, mvcBuilder ?? services.AddMvcCore()); if (options != null) application.ConfigureJsonApiOptions(options); - application.ConfigureMvc(); - if (discovery != null) - application.AutoDiscover(discovery); if (resources != null) application.ConfigureResources(resources); application.ConfigureServices(); + application.ConfigureMvc(); + if (discovery != null) + application.AutoDiscover(discovery); + return services; } diff --git a/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs b/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs index eb68142e31..d015ee8ee9 100644 --- a/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs +++ b/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs @@ -6,6 +6,7 @@ using JsonApiDotNetCore.Controllers; using JsonApiDotNetCore.Extensions; using JsonApiDotNetCore.Graph; +using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationModels; @@ -37,12 +38,14 @@ public class DefaultRoutingConvention : IJsonApiRoutingConvention, IControllerRe { private readonly string _namespace; private readonly IResourceNameFormatter _formatter; + private readonly IResourceGraph _resourceGraph; private readonly HashSet _registeredTemplates = new HashSet(); private readonly Dictionary _registeredResources = new Dictionary(); - public DefaultRoutingConvention(IJsonApiOptions options, IResourceNameFormatter formatter) + public DefaultRoutingConvention(IJsonApiOptions options, IResourceNameFormatter formatter, IResourceGraph resourceGraph) { _namespace = options.Namespace; _formatter = formatter; + _resourceGraph = resourceGraph; } /// @@ -58,18 +61,43 @@ public void Apply(ApplicationModel application) foreach (var controller in application.Controllers) { var resourceType = GetResourceTypeFromController(controller.ControllerType); + if (resourceType != null) + { _registeredResources.Add(controller.ControllerName, resourceType); + } if (RoutingConventionDisabled(controller) == false) + { continue; + } + // if defined in resourcegraph, it should be used + var contexts = _resourceGraph.GetResourceContexts(); + + var foundResourceGraph = contexts.First(c => c.ResourceType == resourceType); + string template = null; + if (foundResourceGraph != null) + { + template = $"{_namespace}/{foundResourceGraph.ResourceName}"; + } + else + { + template = TemplateFromResource(controller) ?? TemplateFromController(controller); + } - var template = TemplateFromResource(controller) ?? TemplateFromController(controller); if (template == null) + { throw new JsonApiSetupException($"Controllers with overlapping route templates detected: {controller.ControllerType.FullName}"); + } controller.Selectors[0].AttributeRouteModel = new AttributeRouteModel { Template = template }; } + + } + + public void HandleControllers(IList controllers) + { + } /// @@ -128,7 +156,7 @@ private Type GetResourceTypeFromController(Type type) { var nextBaseType = currentBaseType.BaseType; - if ( (nextBaseType == controllerBase || nextBaseType == jsonApiMixin) && currentBaseType.IsGenericType) + if ((nextBaseType == controllerBase || nextBaseType == jsonApiMixin) && currentBaseType.IsGenericType) { var potentialResource = currentBaseType.GetGenericArguments().FirstOrDefault(t => t.Inherits(identifiable)); if (potentialResource != null) diff --git a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs index 7bca584b63..babbaf7e8b 100644 --- a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs +++ b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs @@ -96,8 +96,7 @@ public async Task Can_Create_TodoItems() request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - var builder = new WebHostBuilder() - .UseStartup(); + var builder = new WebHostBuilder().UseStartup(); var server = new TestServer(builder); var client = server.CreateClient(); diff --git a/test/NoEntityFrameworkTests/TestFixture.cs b/test/NoEntityFrameworkTests/TestFixture.cs index 7f15df56fb..700b9c2281 100644 --- a/test/NoEntityFrameworkTests/TestFixture.cs +++ b/test/NoEntityFrameworkTests/TestFixture.cs @@ -1,4 +1,5 @@ using JsonApiDotNetCore.Builders; +using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Serialization.Client; using JsonApiDotNetCoreExample; @@ -23,6 +24,7 @@ public TestFixture() var builder = new WebHostBuilder().UseStartup(); Server = new TestServer(builder); Context = Server.GetService(); + Context.Database.EnsureCreated(); _services = Server.Host.Services; } @@ -38,7 +40,13 @@ public IRequestSerializer GetSerializer(Expression() .AddResource
() .AddResource() @@ -49,10 +57,16 @@ public IResponseDeserializer GetDeserializer() .AddResource() .AddResource("custom-todo-items") .AddResource().Build(); - return new ResponseDeserializer(resourceGraph); } - public T GetService() => (T)_services.GetService(typeof(T)); + public T GetService() + { + if(typeof(T) == typeof(IResourceGraph)) + { + return (T) GetResourceGraph(); + } + return (T)_services.GetService(typeof(T)); + } public void Dispose() { diff --git a/test/UnitTests/Routing/DefaultRoutingConventionTests.cs b/test/UnitTests/Routing/DefaultRoutingConventionTests.cs new file mode 100644 index 0000000000..b6a378af2f --- /dev/null +++ b/test/UnitTests/Routing/DefaultRoutingConventionTests.cs @@ -0,0 +1,45 @@ +using JsonApiDotNetCore.Builders; +using JsonApiDotNetCore.Configuration; +using JsonApiDotNetCore.Graph; +using JsonApiDotNetCore.Internal; +using JsonApiDotNetCoreExample.Models; +using Moq; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.ApplicationModels; +using JsonApiDotNetCoreExample.Controllers; +using System.Reflection; +using Xunit; +using System.Linq; + +namespace UnitTests.Routing +{ + public class DefaultRoutingConventionTests + { + + [Fact] + public void DefaultRoutingCustomRoute_CustomRouteRegistered_ShouldBeRegisteredAsTemplate() + { + // Arrange + var mockOptions = new Mock(); + var mockFormatter = new Mock(); + var resourceGraph = new ResourceGraphBuilder().AddResource("customRouteForMe").Build(); + var convention = new DefaultRoutingConvention(mockOptions.Object, mockFormatter.Object, resourceGraph); + var attributes = new List().AsReadOnly(); + var controllerModel = new ControllerModel(typeof(TodoItemsController).GetTypeInfo(), attributes); + controllerModel.ControllerName = "Test"; + var sModel = new SelectorModel(); + controllerModel.Selectors.Add(sModel); + var appModel = new ApplicationModel(); + appModel.Controllers.Add(controllerModel); + + // Act + convention.Apply(appModel); + + // Assert + Assert.Equal("/customRouteForMe", controllerModel.Selectors[0].AttributeRouteModel.Template); + } + } +} diff --git a/test/UnitTests/UnitTests.csproj b/test/UnitTests/UnitTests.csproj index 7374a96ae6..3ec3c41d3d 100644 --- a/test/UnitTests/UnitTests.csproj +++ b/test/UnitTests/UnitTests.csproj @@ -10,6 +10,7 @@ + From 98b1119381eb9b09bf802de7e733b323e255a3d4 Mon Sep 17 00:00:00 2001 From: Harro van der Kroft Date: Thu, 24 Oct 2019 19:10:31 +0200 Subject: [PATCH 29/47] tests: revert for good tests --- .../Extensions/IServiceCollectionExtensions.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs index b1c1eb724c..75b9f4cda4 100644 --- a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs @@ -36,10 +36,9 @@ public static IServiceCollection AddJsonApi(this IServiceColle if (options != null) application.ConfigureJsonApiOptions(options); application.ConfigureLogging(); + application.ConfigureMvc(); application.ConfigureResources(resources); application.ConfigureServices(); - application.ConfigureMvc(); - return services; } @@ -59,13 +58,12 @@ public static IServiceCollection AddJsonApi(this IServiceCollection services, var application = new JsonApiApplicationBuilder(services, mvcBuilder ?? services.AddMvcCore()); if (options != null) application.ConfigureJsonApiOptions(options); - if (resources != null) - application.ConfigureResources(resources); - application.ConfigureServices(); application.ConfigureMvc(); if (discovery != null) application.AutoDiscover(discovery); - + if (resources != null) + application.ConfigureResources(resources); + application.ConfigureServices(); return services; } From cd7e19c2ecd235cb7c8d03e3ff8484c1f2039935 Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 09:37:14 +0100 Subject: [PATCH 30/47] Revert "tests: revert for good tests" This reverts commit 98b1119381eb9b09bf802de7e733b323e255a3d4. --- .../Extensions/IServiceCollectionExtensions.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs index 75b9f4cda4..b1c1eb724c 100644 --- a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs @@ -36,9 +36,10 @@ public static IServiceCollection AddJsonApi(this IServiceColle if (options != null) application.ConfigureJsonApiOptions(options); application.ConfigureLogging(); - application.ConfigureMvc(); application.ConfigureResources(resources); application.ConfigureServices(); + application.ConfigureMvc(); + return services; } @@ -58,12 +59,13 @@ public static IServiceCollection AddJsonApi(this IServiceCollection services, var application = new JsonApiApplicationBuilder(services, mvcBuilder ?? services.AddMvcCore()); if (options != null) application.ConfigureJsonApiOptions(options); - application.ConfigureMvc(); - if (discovery != null) - application.AutoDiscover(discovery); if (resources != null) application.ConfigureResources(resources); application.ConfigureServices(); + application.ConfigureMvc(); + if (discovery != null) + application.AutoDiscover(discovery); + return services; } From 90ebfca7511166aa864f8cc4ff2cbe3f6caf36ed Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 09:37:26 +0100 Subject: [PATCH 31/47] Revert "chore: final stretch" This reverts commit d6f763f6f45fc4d4b1b7b493d554dcab396a7a79. --- .../JsonApiDotNetCoreExample/Startup.cs | 5 +-- .../Builders/ResourceGraphBuilder.cs | 5 ++- .../IServiceCollectionExtensions.cs | 10 ++--- .../Internal/DefaultRoutingConvention.cs | 34 ++------------ .../Extensibility/NoEntityFrameworkTests.cs | 3 +- test/NoEntityFrameworkTests/TestFixture.cs | 20 ++------- .../Routing/DefaultRoutingConventionTests.cs | 45 ------------------- test/UnitTests/UnitTests.csproj | 1 - 8 files changed, 17 insertions(+), 106 deletions(-) delete mode 100644 test/UnitTests/Routing/DefaultRoutingConventionTests.cs diff --git a/src/Examples/JsonApiDotNetCoreExample/Startup.cs b/src/Examples/JsonApiDotNetCoreExample/Startup.cs index 6da2c75f0d..a9cb0529f3 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startup.cs @@ -25,7 +25,7 @@ public Startup(IWebHostEnvironment env) } public virtual void ConfigureServices(IServiceCollection services) - { services.AddJsonApi(); + { var loggerFactory = new LoggerFactory(); services .AddSingleton(loggerFactory) @@ -44,8 +44,6 @@ public virtual void ConfigureServices(IServiceCollection services) options.LoaDatabaseValues = true; }, discovery => discovery.AddCurrentAssembly()); - - services.AddClientSerialization(); } @@ -56,7 +54,6 @@ public virtual void Configure( { context.Database.EnsureCreated(); - app.UseJsonApi(); } diff --git a/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs b/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs index fe96d6d52e..405fe64936 100644 --- a/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs @@ -59,8 +59,11 @@ public IResourceGraphBuilder AddResource(string pluralizedTypeNa public IResourceGraphBuilder AddResource(Type entityType, Type idType, string pluralizedTypeName = null) { AssertEntityIsNotAlreadyDefined(entityType); - pluralizedTypeName ??= _resourceNameFormatter.FormatResourceName(entityType); + + pluralizedTypeName = pluralizedTypeName ?? _resourceNameFormatter.FormatResourceName(entityType); + _entities.Add(GetEntity(pluralizedTypeName, entityType, idType)); + return this; } diff --git a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs index b1c1eb724c..75b9f4cda4 100644 --- a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs @@ -36,10 +36,9 @@ public static IServiceCollection AddJsonApi(this IServiceColle if (options != null) application.ConfigureJsonApiOptions(options); application.ConfigureLogging(); + application.ConfigureMvc(); application.ConfigureResources(resources); application.ConfigureServices(); - application.ConfigureMvc(); - return services; } @@ -59,13 +58,12 @@ public static IServiceCollection AddJsonApi(this IServiceCollection services, var application = new JsonApiApplicationBuilder(services, mvcBuilder ?? services.AddMvcCore()); if (options != null) application.ConfigureJsonApiOptions(options); - if (resources != null) - application.ConfigureResources(resources); - application.ConfigureServices(); application.ConfigureMvc(); if (discovery != null) application.AutoDiscover(discovery); - + if (resources != null) + application.ConfigureResources(resources); + application.ConfigureServices(); return services; } diff --git a/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs b/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs index d015ee8ee9..eb68142e31 100644 --- a/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs +++ b/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs @@ -6,7 +6,6 @@ using JsonApiDotNetCore.Controllers; using JsonApiDotNetCore.Extensions; using JsonApiDotNetCore.Graph; -using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationModels; @@ -38,14 +37,12 @@ public class DefaultRoutingConvention : IJsonApiRoutingConvention, IControllerRe { private readonly string _namespace; private readonly IResourceNameFormatter _formatter; - private readonly IResourceGraph _resourceGraph; private readonly HashSet _registeredTemplates = new HashSet(); private readonly Dictionary _registeredResources = new Dictionary(); - public DefaultRoutingConvention(IJsonApiOptions options, IResourceNameFormatter formatter, IResourceGraph resourceGraph) + public DefaultRoutingConvention(IJsonApiOptions options, IResourceNameFormatter formatter) { _namespace = options.Namespace; _formatter = formatter; - _resourceGraph = resourceGraph; } /// @@ -61,43 +58,18 @@ public void Apply(ApplicationModel application) foreach (var controller in application.Controllers) { var resourceType = GetResourceTypeFromController(controller.ControllerType); - if (resourceType != null) - { _registeredResources.Add(controller.ControllerName, resourceType); - } if (RoutingConventionDisabled(controller) == false) - { continue; - } - // if defined in resourcegraph, it should be used - var contexts = _resourceGraph.GetResourceContexts(); - - var foundResourceGraph = contexts.First(c => c.ResourceType == resourceType); - string template = null; - if (foundResourceGraph != null) - { - template = $"{_namespace}/{foundResourceGraph.ResourceName}"; - } - else - { - template = TemplateFromResource(controller) ?? TemplateFromController(controller); - } + var template = TemplateFromResource(controller) ?? TemplateFromController(controller); if (template == null) - { throw new JsonApiSetupException($"Controllers with overlapping route templates detected: {controller.ControllerType.FullName}"); - } controller.Selectors[0].AttributeRouteModel = new AttributeRouteModel { Template = template }; } - - } - - public void HandleControllers(IList controllers) - { - } /// @@ -156,7 +128,7 @@ private Type GetResourceTypeFromController(Type type) { var nextBaseType = currentBaseType.BaseType; - if ((nextBaseType == controllerBase || nextBaseType == jsonApiMixin) && currentBaseType.IsGenericType) + if ( (nextBaseType == controllerBase || nextBaseType == jsonApiMixin) && currentBaseType.IsGenericType) { var potentialResource = currentBaseType.GetGenericArguments().FirstOrDefault(t => t.Inherits(identifiable)); if (potentialResource != null) diff --git a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs index babbaf7e8b..7bca584b63 100644 --- a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs +++ b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs @@ -96,7 +96,8 @@ public async Task Can_Create_TodoItems() request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - var builder = new WebHostBuilder().UseStartup(); + var builder = new WebHostBuilder() + .UseStartup(); var server = new TestServer(builder); var client = server.CreateClient(); diff --git a/test/NoEntityFrameworkTests/TestFixture.cs b/test/NoEntityFrameworkTests/TestFixture.cs index 700b9c2281..7f15df56fb 100644 --- a/test/NoEntityFrameworkTests/TestFixture.cs +++ b/test/NoEntityFrameworkTests/TestFixture.cs @@ -1,5 +1,4 @@ using JsonApiDotNetCore.Builders; -using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Serialization.Client; using JsonApiDotNetCoreExample; @@ -24,7 +23,6 @@ public TestFixture() var builder = new WebHostBuilder().UseStartup(); Server = new TestServer(builder); Context = Server.GetService(); - Context.Database.EnsureCreated(); _services = Server.Host.Services; } @@ -40,13 +38,7 @@ public IRequestSerializer GetSerializer(Expression() .AddResource
() .AddResource() @@ -57,16 +49,10 @@ private static IResourceGraph GetResourceGraph() .AddResource() .AddResource("custom-todo-items") .AddResource().Build(); + return new ResponseDeserializer(resourceGraph); } - public T GetService() - { - if(typeof(T) == typeof(IResourceGraph)) - { - return (T) GetResourceGraph(); - } - return (T)_services.GetService(typeof(T)); - } + public T GetService() => (T)_services.GetService(typeof(T)); public void Dispose() { diff --git a/test/UnitTests/Routing/DefaultRoutingConventionTests.cs b/test/UnitTests/Routing/DefaultRoutingConventionTests.cs deleted file mode 100644 index b6a378af2f..0000000000 --- a/test/UnitTests/Routing/DefaultRoutingConventionTests.cs +++ /dev/null @@ -1,45 +0,0 @@ -using JsonApiDotNetCore.Builders; -using JsonApiDotNetCore.Configuration; -using JsonApiDotNetCore.Graph; -using JsonApiDotNetCore.Internal; -using JsonApiDotNetCoreExample.Models; -using Moq; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc.ApplicationModels; -using JsonApiDotNetCoreExample.Controllers; -using System.Reflection; -using Xunit; -using System.Linq; - -namespace UnitTests.Routing -{ - public class DefaultRoutingConventionTests - { - - [Fact] - public void DefaultRoutingCustomRoute_CustomRouteRegistered_ShouldBeRegisteredAsTemplate() - { - // Arrange - var mockOptions = new Mock(); - var mockFormatter = new Mock(); - var resourceGraph = new ResourceGraphBuilder().AddResource("customRouteForMe").Build(); - var convention = new DefaultRoutingConvention(mockOptions.Object, mockFormatter.Object, resourceGraph); - var attributes = new List().AsReadOnly(); - var controllerModel = new ControllerModel(typeof(TodoItemsController).GetTypeInfo(), attributes); - controllerModel.ControllerName = "Test"; - var sModel = new SelectorModel(); - controllerModel.Selectors.Add(sModel); - var appModel = new ApplicationModel(); - appModel.Controllers.Add(controllerModel); - - // Act - convention.Apply(appModel); - - // Assert - Assert.Equal("/customRouteForMe", controllerModel.Selectors[0].AttributeRouteModel.Template); - } - } -} diff --git a/test/UnitTests/UnitTests.csproj b/test/UnitTests/UnitTests.csproj index 3ec3c41d3d..7374a96ae6 100644 --- a/test/UnitTests/UnitTests.csproj +++ b/test/UnitTests/UnitTests.csproj @@ -10,7 +10,6 @@ - From 5f7d33075c6c081fa35ab947d972f629352c6aac Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 09:50:16 +0100 Subject: [PATCH 32/47] fix: client generated id tests --- .../ClientGeneratedIdsStartup.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) rename {test/JsonApiDotNetCoreExampleTests/Helpers/Startups => src/Examples/JsonApiDotNetCoreExample}/ClientGeneratedIdsStartup.cs (85%) diff --git a/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs b/src/Examples/JsonApiDotNetCoreExample/ClientGeneratedIdsStartup.cs similarity index 85% rename from test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs rename to src/Examples/JsonApiDotNetCoreExample/ClientGeneratedIdsStartup.cs index 8e66723c15..10255d6727 100644 --- a/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/ClientGeneratedIdsStartup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/ClientGeneratedIdsStartup.cs @@ -4,12 +4,14 @@ using JsonApiDotNetCoreExample.Data; using Microsoft.EntityFrameworkCore; using JsonApiDotNetCore.Extensions; -using System; -using JsonApiDotNetCoreExample; using System.Reflection; -namespace JsonApiDotNetCoreExampleTests.Startups +namespace JsonApiDotNetCoreExample { + /// + /// This should be in JsonApiDotNetCoreExampleTests project but changes in .net core 3.0 + /// do no longer allow that. See https://github.com/aspnet/AspNetCore/issues/15373. + /// public class ClientGeneratedIdsStartup : Startup { public ClientGeneratedIdsStartup(IWebHostEnvironment env) From f149bc9dc22a1fc7045d844754240b6830a60ba6 Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 09:52:43 +0100 Subject: [PATCH 33/47] fix: create data tests with workaround for efcore 3.0 bug --- .../Data/DefaultResourceRepository.cs | 31 +++++++++++-------- .../Middleware/CurrentRequestMiddleware.cs | 4 ++- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index a60af5e793..5b6cb7527e 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -153,25 +153,30 @@ private bool IsHasOneRelationship(string internalRelationshipName, Type type) private void DetachRelationships(TResource entity) { - foreach (var relationshipAttr in _targetedFields.Relationships) + foreach (var relationship in _targetedFields.Relationships) { - if (relationshipAttr is HasOneAttribute hasOneAttr) - { - var relationshipValue = (IIdentifiable)hasOneAttr.GetValue(entity); - if (relationshipValue == null) continue; - _context.Entry(relationshipValue).State = EntityState.Detached; - } - else + var value = relationship.GetValue(entity); + if (value == null) + continue; + + if (value is IEnumerable collection) { - IEnumerable relationshipValueList = (IEnumerable)relationshipAttr.GetValue(entity); - if (relationshipValueList == null) continue; - foreach (var pointer in relationshipValueList) - _context.Entry(pointer).State = EntityState.Detached; + foreach (IIdentifiable single in ((IEnumerable)collection).ToList()) + _context.Entry(single).State = EntityState.Detached; + /// detaching has many relationships is not sufficient to /// trigger a full reload of relationships: the navigation /// property actually needs to be nulled out, otherwise /// EF will still add duplicate instances to the collection - relationshipAttr.SetValue(entity, null); + relationship.SetValue(entity, null); + } + else + { + _context.Entry(value).State = EntityState.Detached; + + /// temporary work around for https://github.com/aspnet/EntityFrameworkCore/issues/18621 + /// as soon as ef core 3.1 lands we can get rid of this again. + _context.Entry(entity).State = EntityState.Detached; } } } diff --git a/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs b/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs index c14aec358b..dcff276470 100644 --- a/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs +++ b/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs @@ -165,7 +165,9 @@ private void FlushResponse(HttpContext context, int statusCode) /// private ResourceContext GetCurrentEntity() { - var controllerName = (string)_httpContext.GetRouteData().Values["controller"]; + var controllerName = (string)_httpContext.GetRouteValue("controller"); + if (controllerName == null) + return null; var resourceType = _controllerResourceMapping.GetAssociatedResource(controllerName); var requestResource = _resourceGraph.GetResourceContext(resourceType); if (requestResource == null) From f8e95232ae5f4f979012268541179f2172e1c17e Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 09:54:35 +0100 Subject: [PATCH 34/47] refactor: DetachRelationships usage of is operator --- src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index 5b6cb7527e..b4fe140e13 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -159,11 +159,10 @@ private void DetachRelationships(TResource entity) if (value == null) continue; - if (value is IEnumerable collection) + if (value is IEnumerable collection) { - foreach (IIdentifiable single in ((IEnumerable)collection).ToList()) + foreach (IIdentifiable single in collection.ToList()) _context.Entry(single).State = EntityState.Detached; - /// detaching has many relationships is not sufficient to /// trigger a full reload of relationships: the navigation /// property actually needs to be nulled out, otherwise From 9ff0709deb846de9cc7f208a6100252c8fb0b00e Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 09:59:11 +0100 Subject: [PATCH 35/47] fix: move MetaStartup to other assembly as .net core 3 bug workaround --- .../JsonApiDotNetCoreExample.csproj | 3 ++ .../ClientGeneratedIdsStartup.cs | 0 .../Startups/MetaStartup.cs | 34 +++++++++++++++++++ .../{ => Startups}/Startup.cs | 0 .../Extensibility/RequestMetaTests.cs | 3 -- .../Acceptance/Spec/CreatingDataTests.cs | 4 --- .../Acceptance/Spec/DocumentTests/Meta.cs | 1 - .../Helpers/Services/IAuthorizationService.cs | 7 ---- .../Helpers/Services/MetaService.cs | 15 -------- .../Helpers/Startups/MetaStartup.cs | 22 ------------ .../JsonApiDotNetCoreExampleTests.csproj | 1 + 11 files changed, 38 insertions(+), 52 deletions(-) rename src/Examples/JsonApiDotNetCoreExample/{ => Startups}/ClientGeneratedIdsStartup.cs (100%) create mode 100644 src/Examples/JsonApiDotNetCoreExample/Startups/MetaStartup.cs rename src/Examples/JsonApiDotNetCoreExample/{ => Startups}/Startup.cs (100%) delete mode 100644 test/JsonApiDotNetCoreExampleTests/Helpers/Services/IAuthorizationService.cs delete mode 100644 test/JsonApiDotNetCoreExampleTests/Helpers/Services/MetaService.cs delete mode 100644 test/JsonApiDotNetCoreExampleTests/Helpers/Startups/MetaStartup.cs diff --git a/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj b/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj index aa72c2e15e..d67f773ea7 100644 --- a/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj +++ b/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj @@ -28,4 +28,7 @@ + + + diff --git a/src/Examples/JsonApiDotNetCoreExample/ClientGeneratedIdsStartup.cs b/src/Examples/JsonApiDotNetCoreExample/Startups/ClientGeneratedIdsStartup.cs similarity index 100% rename from src/Examples/JsonApiDotNetCoreExample/ClientGeneratedIdsStartup.cs rename to src/Examples/JsonApiDotNetCoreExample/Startups/ClientGeneratedIdsStartup.cs diff --git a/src/Examples/JsonApiDotNetCoreExample/Startups/MetaStartup.cs b/src/Examples/JsonApiDotNetCoreExample/Startups/MetaStartup.cs new file mode 100644 index 0000000000..32accb087a --- /dev/null +++ b/src/Examples/JsonApiDotNetCoreExample/Startups/MetaStartup.cs @@ -0,0 +1,34 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using JsonApiDotNetCore.Services; +using System.Collections.Generic; + +namespace JsonApiDotNetCoreExample +{ + /// + /// This should be in JsonApiDotNetCoreExampleTests project but changes in .net core 3.0 + /// do no longer allow that. See https://github.com/aspnet/AspNetCore/issues/15373. + /// + public class MetaStartup : Startup + { + public MetaStartup(IWebHostEnvironment env) + : base (env) + { } + + public override void ConfigureServices(IServiceCollection services) + { + services.AddScoped(); + base.ConfigureServices(services); + } + } + + public class MetaService : IRequestMeta + { + public Dictionary GetMeta() + { + return new Dictionary { + { "request-meta", "request-meta-value" } + }; + } + } +} diff --git a/src/Examples/JsonApiDotNetCoreExample/Startup.cs b/src/Examples/JsonApiDotNetCoreExample/Startups/Startup.cs similarity index 100% rename from src/Examples/JsonApiDotNetCoreExample/Startup.cs rename to src/Examples/JsonApiDotNetCoreExample/Startups/Startup.cs diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs index af40693824..5f31c447b6 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs @@ -5,11 +5,8 @@ using Microsoft.AspNetCore.TestHost; using Xunit; using JsonApiDotNetCoreExample.Models; -using Newtonsoft.Json; using JsonApiDotNetCore.Models; using System.Collections; -using JsonApiDotNetCoreExampleTests.Startups; -using JsonApiDotNetCoreExample.Resources; using JsonApiDotNetCoreExample; namespace JsonApiDotNetCoreExampleTests.Acceptance.Extensibility diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs index 3a1dca1c25..32ac423eee 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; using System.Threading.Tasks; using Bogus; using JsonApiDotNetCore.Builders; @@ -12,9 +10,7 @@ using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using JsonApiDotNetCoreExampleTests.Helpers.Models; -using JsonApiDotNetCoreExampleTests.Startups; using Microsoft.EntityFrameworkCore; -using Newtonsoft.Json; using Xunit; using Person = JsonApiDotNetCoreExample.Models.Person; diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs index 314933c3d5..b1e4b33017 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs @@ -7,7 +7,6 @@ using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; -using JsonApiDotNetCoreExampleTests.Startups; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Newtonsoft.Json; diff --git a/test/JsonApiDotNetCoreExampleTests/Helpers/Services/IAuthorizationService.cs b/test/JsonApiDotNetCoreExampleTests/Helpers/Services/IAuthorizationService.cs deleted file mode 100644 index b994c7f8bd..0000000000 --- a/test/JsonApiDotNetCoreExampleTests/Helpers/Services/IAuthorizationService.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace JsonApiDotNetCoreExampleTests.Services -{ - public interface IAuthorizationService - { - int CurrentUserId { get; set; } - } -} diff --git a/test/JsonApiDotNetCoreExampleTests/Helpers/Services/MetaService.cs b/test/JsonApiDotNetCoreExampleTests/Helpers/Services/MetaService.cs deleted file mode 100644 index 91de8fda5e..0000000000 --- a/test/JsonApiDotNetCoreExampleTests/Helpers/Services/MetaService.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Collections.Generic; -using JsonApiDotNetCore.Services; - -namespace JsonApiDotNetCoreExampleTests.Services -{ - public class MetaService : IRequestMeta - { - public Dictionary GetMeta() - { - return new Dictionary { - { "request-meta", "request-meta-value" } - }; - } - } -} diff --git a/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/MetaStartup.cs b/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/MetaStartup.cs deleted file mode 100644 index fcd93931ae..0000000000 --- a/test/JsonApiDotNetCoreExampleTests/Helpers/Startups/MetaStartup.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using System; -using JsonApiDotNetCoreExample; -using JsonApiDotNetCore.Services; -using JsonApiDotNetCoreExampleTests.Services; - -namespace JsonApiDotNetCoreExampleTests.Startups -{ - public class MetaStartup : Startup - { - public MetaStartup(IWebHostEnvironment env) - : base (env) - { } - - public override void ConfigureServices(IServiceCollection services) - { - services.AddScoped(); - base.ConfigureServices(services); - } - } -} diff --git a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj index a63c50f6cf..7a099cdf48 100644 --- a/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj +++ b/test/JsonApiDotNetCoreExampleTests/JsonApiDotNetCoreExampleTests.csproj @@ -30,6 +30,7 @@ + From 9b2ecdfaa31598a2e424041b5d82bd525c670019 Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 10:37:49 +0100 Subject: [PATCH 36/47] fix: UpdatingRelationshipTests locally evaluated queries error --- .../Data/DefaultResourceRepository.cs | 18 ++++++++++++++---- .../Services/DefaultResourceService.cs | 18 +++++++++++------- 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index b4fe140e13..2d765ed360 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading.Tasks; using JsonApiDotNetCore.Extensions; +using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Internal.Generics; using JsonApiDotNetCore.Internal.Query; @@ -268,11 +269,20 @@ public async Task UpdateRelationshipsAsync(object parent, RelationshipAttribute return; } var context = _context.Set(relationship.RightType); - var updatedValue = relationship is HasManyAttribute - ? context.Where(e => relationshipIds.Contains(((IIdentifiable)e).StringId)).Cast(relationship.RightType) - : context.FirstOrDefault(e => relationshipIds.First() == ((IIdentifiable)e).StringId); - relationship.SetValue(parent, updatedValue); + if (relationship is HasManyAttribute) + { + // todo: we should be to do this with an expression that can be translated into a query + var value = relationshipIds.Any() ? context.AsEnumerable().Where(e => relationshipIds.Contains(((IIdentifiable)e).StringId)).Cast(relationship.RightType) : TypeHelper.CreateListFor(relationship.RightType); + relationship.SetValue(parent, value); + } + else + { + // todo: we should be to do this with an expression that can be translated into a query + var value = relationshipIds.Any() ? context.AsEnumerable().FirstOrDefault(e => relationshipIds.First() == ((IIdentifiable)e).StringId) : null; + relationship.SetValue(parent, value); + } + await _context.SaveChangesAsync(); } diff --git a/src/JsonApiDotNetCore/Services/DefaultResourceService.cs b/src/JsonApiDotNetCore/Services/DefaultResourceService.cs index 116fa009f8..ea6f4c7a87 100644 --- a/src/JsonApiDotNetCore/Services/DefaultResourceService.cs +++ b/src/JsonApiDotNetCore/Services/DefaultResourceService.cs @@ -177,15 +177,19 @@ public virtual async Task UpdateRelationshipsAsync(TId id, string relationshipNa if (entity == null) throw new JsonApiException(404, $"Entity with id {id} could not be found."); - List relatedEntities; + entity = IsNull(_hookExecutor) ? entity : _hookExecutor.BeforeUpdate(AsList(entity), ResourcePipeline.PatchRelationship).SingleOrDefault(); - if (relationship is HasOneAttribute) - relatedEntities = new List { (IIdentifiable)related }; - else relatedEntities = (List)related; - var relationshipIds = relatedEntities.Select(r => r?.StringId); + string[] relationshipIds = null; + if (related != null) + { + if (relationship is HasOneAttribute) + relationshipIds = new string[] { ((IIdentifiable)related).StringId }; + else + relationshipIds = ((IEnumerable)related).Select(e => e.StringId).ToArray(); + } + + await _repository.UpdateRelationshipsAsync(entity, relationship, relationshipIds ?? new string[0] ); - entity = IsNull(_hookExecutor) ? entity : _hookExecutor.BeforeUpdate(AsList(entity), ResourcePipeline.PatchRelationship).SingleOrDefault(); - await _repository.UpdateRelationshipsAsync(entity, relationship, relationshipIds); if (!IsNull(_hookExecutor, entity)) _hookExecutor.AfterUpdate(AsList(entity), ResourcePipeline.PatchRelationship); } From 57c5da1ce0a28686a97835598f6bf2048941c545 Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 13:04:44 +0100 Subject: [PATCH 37/47] feat: reintroduced generic processor (RepositoryRelationshipUpdateHelper) to fix locally evaluated expressions issue --- .../Builders/JsonApiApplicationBuilder.cs | 2 +- .../Data/DefaultResourceRepository.cs | 24 +--- .../Generics/HasManyThroughUpdateHelper.cs | 80 ------------ .../RepositoryRelationshipUpdateHelper.cs | 123 ++++++++++++++++++ .../IServiceCollectionExtensionsTests.cs | 2 +- 5 files changed, 130 insertions(+), 101 deletions(-) delete mode 100644 src/JsonApiDotNetCore/Internal/Generics/HasManyThroughUpdateHelper.cs create mode 100644 src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs diff --git a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs index ffe3571f19..3c5b835507 100644 --- a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs @@ -160,7 +160,7 @@ public void ConfigureServices() _services.AddScoped(); _services.AddScoped(); _services.AddScoped(); - _services.AddScoped(typeof(HasManyThroughUpdateHelper<>)); + _services.AddScoped(typeof(RepositoryRelationshipUpdateHelper<,>)); _services.AddScoped(); _services.AddScoped(); _services.AddScoped(); diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index 2d765ed360..1536c03f23 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -262,26 +262,12 @@ private IIdentifiable GetTrackedHasOneRelationshipValue(IIdentifiable relationsh /// public async Task UpdateRelationshipsAsync(object parent, RelationshipAttribute relationship, IEnumerable relationshipIds) { - if (relationship is HasManyThroughAttribute hasManyThrough) - { - var helper = _genericServiceFactory.Get(typeof(HasManyThroughUpdateHelper<>), hasManyThrough.ThroughType); - await helper.UpdateAsync((IIdentifiable)parent, hasManyThrough, relationshipIds); - return; - } - var context = _context.Set(relationship.RightType); + var typeToUpdate = (relationship is HasManyThroughAttribute hasManyThrough) + ? hasManyThrough.ThroughType + : relationship.RightType; - if (relationship is HasManyAttribute) - { - // todo: we should be to do this with an expression that can be translated into a query - var value = relationshipIds.Any() ? context.AsEnumerable().Where(e => relationshipIds.Contains(((IIdentifiable)e).StringId)).Cast(relationship.RightType) : TypeHelper.CreateListFor(relationship.RightType); - relationship.SetValue(parent, value); - } - else - { - // todo: we should be to do this with an expression that can be translated into a query - var value = relationshipIds.Any() ? context.AsEnumerable().FirstOrDefault(e => relationshipIds.First() == ((IIdentifiable)e).StringId) : null; - relationship.SetValue(parent, value); - } + var helper = _genericServiceFactory.Get(typeof(RepositoryRelationshipUpdateHelper<,>), typeToUpdate, typeof(int)); + await helper.UpdateRelationshipAsync((IIdentifiable)parent, relationship, relationshipIds); await _context.SaveChangesAsync(); } diff --git a/src/JsonApiDotNetCore/Internal/Generics/HasManyThroughUpdateHelper.cs b/src/JsonApiDotNetCore/Internal/Generics/HasManyThroughUpdateHelper.cs deleted file mode 100644 index c98560015e..0000000000 --- a/src/JsonApiDotNetCore/Internal/Generics/HasManyThroughUpdateHelper.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading.Tasks; -using JsonApiDotNetCore.Data; -using JsonApiDotNetCore.Extensions; -using JsonApiDotNetCore.Models; -using Microsoft.EntityFrameworkCore; - -namespace JsonApiDotNetCore.Internal.Generics -{ - /// - /// A special helper service that gets instantiated for the right-type of a many-to-many relationship and is responsible for - /// processing updates for that relationships. - /// - public interface IHasManyThroughUpdateHelper - { - /// - /// Processes updates of has many through relationship. - /// - Task UpdateAsync(IIdentifiable parent, HasManyThroughAttribute relationship, IEnumerable relationshipIds); - } - - /// - public class HasManyThroughUpdateHelper : IHasManyThroughUpdateHelper where T : class - { - private readonly DbContext _context; - public HasManyThroughUpdateHelper(IDbContextResolver contextResolver) - { - _context = contextResolver.GetContext(); - } - - /// - public virtual async Task UpdateAsync(IIdentifiable parent, HasManyThroughAttribute relationship, IEnumerable relationshipIds) - { - // we need to create a transaction for the HasManyThrough case so we can get and remove any existing - // join entities and only commit if all operations are successful - using (var transaction = await _context.GetCurrentOrCreateTransactionAsync()) - { - // ArticleTag - ParameterExpression parameter = Expression.Parameter(relationship.ThroughType); - - // ArticleTag.ArticleId - Expression property = Expression.Property(parameter, relationship.LeftIdProperty); - - // article.Id - var parentId = TypeHelper.ConvertType(parent.StringId, relationship.LeftIdProperty.PropertyType); - Expression target = Expression.Constant(parentId); - - // ArticleTag.ArticleId.Equals(article.Id) - Expression equals = Expression.Call(property, "Equals", null, target); - - var lambda = Expression.Lambda>(equals, parameter); - - // TODO: we shouldn't need to do this instead we should try updating the existing? - // the challenge here is if a composite key is used, then we will fail to - // create due to a unique key violation - var oldLinks = _context - .Set() - .Where(lambda.Compile()) - .ToList(); - - _context.RemoveRange(oldLinks); - - var newLinks = relationshipIds.Select(x => { - var link = Activator.CreateInstance(relationship.ThroughType); - relationship.LeftIdProperty.SetValue(link, TypeHelper.ConvertType(parentId, relationship.LeftIdProperty.PropertyType)); - relationship.RightIdProperty.SetValue(link, TypeHelper.ConvertType(x, relationship.RightIdProperty.PropertyType)); - return link; - }); - - _context.AddRange(newLinks); - await _context.SaveChangesAsync(); - - transaction.Commit(); - } - } - } -} diff --git a/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs b/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs new file mode 100644 index 0000000000..5c6272a65d --- /dev/null +++ b/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; +using JsonApiDotNetCore.Data; +using JsonApiDotNetCore.Extensions; +using JsonApiDotNetCore.Models; +using Microsoft.EntityFrameworkCore; + +namespace JsonApiDotNetCore.Internal.Generics +{ + /// + /// A special helper that processes updates of relationships + /// + /// + /// This service required to be able translate involved expressions into queries + /// instead of having them evaluated on the client side. In particular, for all three types of relationship + /// a lookup is performed based on an id. Expressions that use IIdentifiable.StringId can never + /// be translated into queries because this property only exists at runtime after the query is performed. + /// Instead we will need to use IIdentifiable{TId}.Id, and to use that we need to access the DbSet{T} with appropiate + /// generic constraints. + /// + public interface IRepositoryRelationshipUpdateHelper + { + /// + /// Processes updates of relationships + /// + Task UpdateRelationshipAsync(IIdentifiable parent, RelationshipAttribute relationship, IEnumerable relationshipIds); + } + + /// + public class RepositoryRelationshipUpdateHelper : IRepositoryRelationshipUpdateHelper where TRelatedResource : class, IIdentifiable + { + private readonly DbContext _context; + public RepositoryRelationshipUpdateHelper(IDbContextResolver contextResolver) + { + _context = contextResolver.GetContext(); + } + + /// + public virtual async Task UpdateRelationshipAsync(IIdentifiable parent, RelationshipAttribute relationship, IEnumerable relationshipIds) + { + if (relationship is HasManyThroughAttribute hasManyThrough) + await UpdateManyToManyAsync(parent, hasManyThrough, relationshipIds); + else if (relationship is HasManyAttribute) + await UpdateOneToManyAsync(parent, relationship, relationshipIds); + else + await UpdateOneToOneAsync(parent, relationship, relationshipIds); + + } + + private async Task UpdateOneToOneAsync(IIdentifiable parent, RelationshipAttribute relationship, IEnumerable relationshipIds) + { + if (!relationshipIds.Any()) + { + relationship.SetValue(parent, null); + } + else + { + var value = await _context.Set().FirstAsync(e => relationshipIds.First().Equals(e.Id.ToString())); + relationship.SetValue(parent, value); + } + } + + private async Task UpdateOneToManyAsync(IIdentifiable parent, RelationshipAttribute relationship, IEnumerable relationshipIds) + { + + if (!relationshipIds.Any()) + { + relationship.SetValue(parent, TypeHelper.CreateListFor(typeof(TRelatedResource))); + } + else + { + var value = await _context.Set().Where(e => relationshipIds.Contains(e.Id.ToString())).ToListAsync(); + relationship.SetValue(parent, value); + } + } + + private async Task UpdateManyToManyAsync(IIdentifiable parent, HasManyThroughAttribute relationship, IEnumerable relationshipIds) + { + // we need to create a transaction for the HasManyThrough case so we can get and remove any existing + // join entities and only commit if all operations are successful + var transaction = await _context.GetCurrentOrCreateTransactionAsync(); + // ArticleTag + ParameterExpression parameter = Expression.Parameter(relationship.ThroughType); + + // ArticleTag.ArticleId + Expression property = Expression.Property(parameter, relationship.LeftIdProperty); + + // article.Id + var parentId = TypeHelper.ConvertType(parent.StringId, relationship.LeftIdProperty.PropertyType); + Expression target = Expression.Constant(parentId); + + // ArticleTag.ArticleId.Equals(article.Id) + Expression equals = Expression.Call(property, "Equals", null, target); + + var lambda = Expression.Lambda>(equals, parameter); + + // TODO: we shouldn't need to do this instead we should try updating the existing? + // the challenge here is if a composite key is used, then we will fail to + // create due to a unique key violation + var oldLinks = _context + .Set() + .Where(lambda.Compile()) + .ToList(); + + _context.RemoveRange(oldLinks); + + var newLinks = relationshipIds.Select(x => + { + var link = Activator.CreateInstance(relationship.ThroughType); + relationship.LeftIdProperty.SetValue(link, TypeHelper.ConvertType(parentId, relationship.LeftIdProperty.PropertyType)); + relationship.RightIdProperty.SetValue(link, TypeHelper.ConvertType(x, relationship.RightIdProperty.PropertyType)); + return link; + }); + + _context.AddRange(newLinks); + await _context.SaveChangesAsync(); + transaction.Commit(); + } + } +} diff --git a/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs b/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs index b04f5d8200..6d0495083e 100644 --- a/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs +++ b/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs @@ -56,7 +56,7 @@ public void AddJsonApiInternals_Adds_All_Required_Services() Assert.NotNull(provider.GetService()); Assert.NotNull(provider.GetService()); Assert.NotNull(provider.GetService()); - Assert.NotNull(provider.GetService(typeof(HasManyThroughUpdateHelper))); + Assert.NotNull(provider.GetService(typeof(RepositoryRelationshipUpdateHelper))); } [Fact] From 7faa5008ec7154c025dd6f421048348a65fa4111 Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 14:42:05 +0100 Subject: [PATCH 38/47] feat: full sql support for UpdateRelationshipsAsync using expression trees --- .../Builders/JsonApiApplicationBuilder.cs | 2 +- .../Data/DefaultResourceRepository.cs | 2 +- .../RepositoryRelationshipUpdateHelper.cs | 60 ++++++++++--------- .../IServiceCollectionExtensionsTests.cs | 2 +- 4 files changed, 35 insertions(+), 31 deletions(-) diff --git a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs index 3c5b835507..302aeb831f 100644 --- a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs @@ -160,7 +160,7 @@ public void ConfigureServices() _services.AddScoped(); _services.AddScoped(); _services.AddScoped(); - _services.AddScoped(typeof(RepositoryRelationshipUpdateHelper<,>)); + _services.AddScoped(typeof(RepositoryRelationshipUpdateHelper<>)); _services.AddScoped(); _services.AddScoped(); _services.AddScoped(); diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index 1536c03f23..55711f5052 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -266,7 +266,7 @@ public async Task UpdateRelationshipsAsync(object parent, RelationshipAttribute ? hasManyThrough.ThroughType : relationship.RightType; - var helper = _genericServiceFactory.Get(typeof(RepositoryRelationshipUpdateHelper<,>), typeToUpdate, typeof(int)); + var helper = _genericServiceFactory.Get(typeof(RepositoryRelationshipUpdateHelper<>), typeToUpdate); await helper.UpdateRelationshipAsync((IIdentifiable)parent, relationship, relationshipIds); await _context.SaveChangesAsync(); diff --git a/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs b/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs index 5c6272a65d..1345b288ed 100644 --- a/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs +++ b/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs @@ -18,8 +18,8 @@ namespace JsonApiDotNetCore.Internal.Generics /// instead of having them evaluated on the client side. In particular, for all three types of relationship /// a lookup is performed based on an id. Expressions that use IIdentifiable.StringId can never /// be translated into queries because this property only exists at runtime after the query is performed. - /// Instead we will need to use IIdentifiable{TId}.Id, and to use that we need to access the DbSet{T} with appropiate - /// generic constraints. + /// We will have to build expression trees if we want to use IIdentifiable{TId}.TId, for which we minimally a + /// generic execution to DbContext.Set{T}(). /// public interface IRepositoryRelationshipUpdateHelper { @@ -30,7 +30,7 @@ public interface IRepositoryRelationshipUpdateHelper } /// - public class RepositoryRelationshipUpdateHelper : IRepositoryRelationshipUpdateHelper where TRelatedResource : class, IIdentifiable + public class RepositoryRelationshipUpdateHelper : IRepositoryRelationshipUpdateHelper where TRelatedResource : class { private readonly DbContext _context; public RepositoryRelationshipUpdateHelper(IDbContextResolver contextResolver) @@ -52,29 +52,38 @@ public virtual async Task UpdateRelationshipAsync(IIdentifiable parent, Relation private async Task UpdateOneToOneAsync(IIdentifiable parent, RelationshipAttribute relationship, IEnumerable relationshipIds) { - if (!relationshipIds.Any()) - { - relationship.SetValue(parent, null); - } - else - { - var value = await _context.Set().FirstAsync(e => relationshipIds.First().Equals(e.Id.ToString())); - relationship.SetValue(parent, value); + TRelatedResource value = null; + if (relationshipIds.Any()) + { // newOwner.id + var target = Expression.Constant(TypeHelper.ConvertType(relationshipIds.First(), TypeHelper.GetIdentifierType(relationship.RightType))); + // (Person p) => ... + ParameterExpression parameter = Expression.Parameter(typeof(TRelatedResource)); + // (Person p) => p.Id + Expression idMember = Expression.Property(parameter, nameof(Identifiable.Id)); + // newOwner.Id.Equals(p.Id) + Expression callEquals = Expression.Call(idMember, nameof(object.Equals), null, target); + var equalsLambda = Expression.Lambda>(callEquals, parameter); + value = await _context.Set().FirstOrDefaultAsync(equalsLambda); } + relationship.SetValue(parent, value); } private async Task UpdateOneToManyAsync(IIdentifiable parent, RelationshipAttribute relationship, IEnumerable relationshipIds) { - - if (!relationshipIds.Any()) - { - relationship.SetValue(parent, TypeHelper.CreateListFor(typeof(TRelatedResource))); - } - else - { - var value = await _context.Set().Where(e => relationshipIds.Contains(e.Id.ToString())).ToListAsync(); - relationship.SetValue(parent, value); + var value = new List(); + if (relationshipIds.Any()) + { // [1, 2, 3] + var target = Expression.Constant(TypeHelper.ConvertListType(relationshipIds, TypeHelper.GetIdentifierType(relationship.RightType))); + // (Person p) => ... + ParameterExpression parameter = Expression.Parameter(typeof(TRelatedResource)); + // (Person p) => p.Id + Expression idMember = Expression.Property(parameter, nameof(Identifiable.Id)); + // [1,2,3].Contains(p.Id) + var callContains = Expression.Call(typeof(Enumerable), nameof(Enumerable.Contains), new[] { idMember.Type }, target, idMember); + var containsLamdda = Expression.Lambda>(callContains, parameter); + value = await _context.Set().Where(containsLamdda).ToListAsync(); } + relationship.SetValue(parent, value); } private async Task UpdateManyToManyAsync(IIdentifiable parent, HasManyThroughAttribute relationship, IEnumerable relationshipIds) @@ -84,19 +93,14 @@ private async Task UpdateManyToManyAsync(IIdentifiable parent, HasManyThroughAtt var transaction = await _context.GetCurrentOrCreateTransactionAsync(); // ArticleTag ParameterExpression parameter = Expression.Parameter(relationship.ThroughType); - // ArticleTag.ArticleId - Expression property = Expression.Property(parameter, relationship.LeftIdProperty); - + Expression idMember = Expression.Property(parameter, relationship.LeftIdProperty); // article.Id var parentId = TypeHelper.ConvertType(parent.StringId, relationship.LeftIdProperty.PropertyType); Expression target = Expression.Constant(parentId); - // ArticleTag.ArticleId.Equals(article.Id) - Expression equals = Expression.Call(property, "Equals", null, target); - - var lambda = Expression.Lambda>(equals, parameter); - + Expression callEquals = Expression.Call(idMember, "Equals", null, target); + var lambda = Expression.Lambda>(callEquals, parameter); // TODO: we shouldn't need to do this instead we should try updating the existing? // the challenge here is if a composite key is used, then we will fail to // create due to a unique key violation diff --git a/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs b/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs index 6d0495083e..d23b1f4d9d 100644 --- a/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs +++ b/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs @@ -56,7 +56,7 @@ public void AddJsonApiInternals_Adds_All_Required_Services() Assert.NotNull(provider.GetService()); Assert.NotNull(provider.GetService()); Assert.NotNull(provider.GetService()); - Assert.NotNull(provider.GetService(typeof(RepositoryRelationshipUpdateHelper))); + Assert.NotNull(provider.GetService(typeof(RepositoryRelationshipUpdateHelper))); } [Fact] From 73f43e9fd1e66b982b1362d81788f5a7ee9e248d Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 14:49:07 +0100 Subject: [PATCH 39/47] fix: DeletingDataTest --- .../Generics/RepositoryRelationshipUpdateHelper.cs | 1 - .../Acceptance/Spec/DeletingDataTests.cs | 8 +++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs b/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs index 1345b288ed..ec4a4f0bbb 100644 --- a/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs +++ b/src/JsonApiDotNetCore/Internal/Generics/RepositoryRelationshipUpdateHelper.cs @@ -47,7 +47,6 @@ public virtual async Task UpdateRelationshipAsync(IIdentifiable parent, Relation await UpdateOneToManyAsync(parent, relationship, relationshipIds); else await UpdateOneToOneAsync(parent, relationship, relationshipIds); - } private async Task UpdateOneToOneAsync(IIdentifiable parent, RelationshipAttribute relationship, IEnumerable relationshipIds) diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs index 50a312d2eb..00abbdec85 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs @@ -8,6 +8,7 @@ using JsonApiDotNetCoreExample.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using Microsoft.EntityFrameworkCore; using Xunit; namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec @@ -33,8 +34,9 @@ public DeletingDataTests(TestFixture fixture) public async Task Respond_404_If_EntityDoesNotExist() { // Arrange - var maxPersonId = _context.TodoItems.LastOrDefault()?.Id ?? 0; - var todoItem = _todoItemFaker.Generate(); + var lastTodo = _context.TodoItems.AsEnumerable().LastOrDefault(); + var lastTodoId = lastTodo?.Id ?? 0; + var builder = new WebHostBuilder() .UseStartup(); @@ -42,7 +44,7 @@ public async Task Respond_404_If_EntityDoesNotExist() var client = server.CreateClient(); var httpMethod = new HttpMethod("DELETE"); - var route = $"/api/v1/todo-items/{maxPersonId + 100}"; + var route = $"/api/v1/todo-items/{lastTodoId + 100}"; var request = new HttpRequestMessage(httpMethod, route); // Act From fe67998006d223b8aa999637fa1125addbb337bb Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 15:18:17 +0100 Subject: [PATCH 40/47] fix: paging test --- .../Data/DefaultResourceRepository.cs | 24 +++++++------------ .../Spec/DocumentTests/Relationships.cs | 2 +- .../Spec/FetchingRelationshipsTests.cs | 2 +- .../Acceptance/Spec/PagingTests.cs | 11 +++++---- 4 files changed, 17 insertions(+), 22 deletions(-) diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index 55711f5052..7745de8fd1 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -306,26 +306,18 @@ public virtual async Task> PageAsync(IQueryable diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs index 502eeb0284..50c0848956 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs @@ -124,7 +124,7 @@ public async Task Correct_RelationshipObjects_For_OneToMany_Relationships() public async Task Correct_RelationshipObjects_For_OneToMany_Relationships_ById() { // Arrange - var personId = _context.People.Last().Id; + var personId = _context.People.AsEnumerable().Last().Id; var builder = new WebHostBuilder() .UseStartup(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs index 0abf4221cf..0380d13487 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs @@ -43,7 +43,7 @@ public async Task Request_UnsetRelationship_Returns_Null_DataObject() var server = new TestServer(builder); var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); - var expectedBody = "{\"meta\":{\"copyright\":\"Copyright 2015 Example Corp.\",\"authors\":[\"Jared Nance\",\"Maurits Moeys\"]},\"links\":{\"self\":\"http://localhost/api/v1/people\"},\"data\":null}"; + var expectedBody = "{\"meta\":{\"copyright\":\"Copyright 2015 Example Corp.\",\"authors\":[\"Jared Nance\",\"Maurits Moeys\",\"Harro van der Kroft\"]},\"links\":{\"self\":\"http://localhost/api/v1/people\"},\"data\":null}"; // Act var response = await client.SendAsync(request); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs index ee605bf5ab..e404b605d4 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs @@ -6,6 +6,7 @@ using JsonApiDotNetCore.Models; using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Models; +using JsonApiDotNetCoreExampleTests.Helpers.Models; using Xunit; using Person = JsonApiDotNetCoreExample.Models.Person; @@ -95,7 +96,8 @@ public async Task Can_Paginate_TodoItems_From_End() var totalCount = expectedEntitiesPerPage * 2; var person = new Person(); var todoItems = _todoItemFaker.Generate(totalCount).ToList(); - todoItems.ForEach(ti => ti.Owner = person); + foreach (var ti in todoItems) + ti.Owner = person; Context.TodoItems.RemoveRange(Context.TodoItems); Context.TodoItems.AddRange(todoItems); @@ -109,10 +111,11 @@ public async Task Can_Paginate_TodoItems_From_End() var body = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var deserializedBody = _fixture.GetDeserializer().DeserializeList(body).Data; + var deserializedBody = _fixture.GetDeserializer().DeserializeList(body).Data.Select(ti => ti.Id).ToArray(); - var expectedTodoItems = new[] { todoItems[totalCount - 2], todoItems[totalCount - 1] }; - Assert.Equal(expectedTodoItems, deserializedBody, new IdComparer()); + var expectedTodoItems = new[] { todoItems[totalCount - 2].Id, todoItems[totalCount - 1].Id }; + for (int i = 0; i < expectedEntitiesPerPage-1 ; i++) + Assert.Contains(expectedTodoItems[i], deserializedBody); } private class IdComparer : IEqualityComparer From 82005ec8daac925676d4e2cb2993b230b79e81fb Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 15:33:50 +0100 Subject: [PATCH 41/47] fix: paging unit tests --- .../Data/DefaultResourceRepository.cs | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index 7745de8fd1..83f0a3fd28 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Threading.Tasks; using JsonApiDotNetCore.Extensions; -using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Internal.Generics; using JsonApiDotNetCore.Internal.Query; @@ -242,11 +241,13 @@ private IList GetTrackedManyRelationshipValue(IEnumerable relatio if (relationshipValueList == null) return null; bool _wasAlreadyAttached = false; var trackedPointerCollection = relationshipValueList.Select(pointer => - { // convert each element in the value list to relationshipAttr.DependentType. - var tracked = AttachOrGetTracked(pointer); - if (tracked != null) _wasAlreadyAttached = true; - return Convert.ChangeType(tracked ?? pointer, relationshipAttr.RightType); - }).ToList().Cast(relationshipAttr.RightType); + { // convert each element in the value list to relationshipAttr.DependentType. + var tracked = AttachOrGetTracked(pointer); + if (tracked != null) _wasAlreadyAttached = true; + return Convert.ChangeType(tracked ?? pointer, relationshipAttr.RightType); + }) + .ToList() + .Cast(relationshipAttr.RightType); if (_wasAlreadyAttached) wasAlreadyAttached = true; return (IList)trackedPointerCollection; } @@ -285,7 +286,9 @@ public virtual async Task DeleteAsync(TId id) public virtual IQueryable Include(IQueryable entities, IEnumerable inclusionChain = null) { if (inclusionChain == null || !inclusionChain.Any()) + { return entities; + } string internalRelationshipPath = null; foreach (var relationship in inclusionChain) @@ -306,7 +309,7 @@ public virtual async Task> PageAsync(IQueryable) { // since EntityFramework does not support IQueryable.Reverse(), we need to know the number of queried entities var totalCount = await entities.CountAsync(); @@ -315,9 +318,12 @@ public virtual async Task> PageAsync(IQueryable @@ -327,10 +333,7 @@ public async Task CountAsync(IQueryable entities) { return await entities.CountAsync(); } - else - { - return entities.Count(); - } + return entities.Count(); } /// @@ -348,10 +351,7 @@ public async Task> ToListAsync(IQueryable en { return await entities.ToListAsync(); } - else - { - return entities.ToList(); - } + return entities.ToList(); } /// From 4a3296eef396c805dc3381dfc4871d1326c609c0 Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 15:41:38 +0100 Subject: [PATCH 42/47] chore: remove RE-split models, duplicate models to NoEntityFrameworkExample --- .../Data/AppDbContext.cs | 18 ----- .../Models/Entities/CourseEntity.cs | 31 -------- .../Models/Entities/CourseStudentEntity.cs | 50 ------------ .../Models/Entities/DepartmentEntity.cs | 17 ---- .../Models/Entities/StudentEntity.cs | 25 ------ .../Models/Resources/CourseResource.cs | 28 ------- .../Models/Resources/CourseStudentResource.cs | 23 ------ .../Models/Resources/DepartmentResource.cs | 14 ---- .../Models/Resources/StudentResource.cs | 23 ------ .../Controllers/CustomTodoItemsController.cs | 2 +- .../Data/AppDbContext.cs | 22 ++++++ .../Models/Article.cs | 27 +++++++ .../Models/ArticleTag.cs | 27 +++++++ .../NoEntityFrameworkExample/Models/Author.cs | 15 ++++ .../Models/CamelCasedModel.cs | 11 +++ .../Models/IIsLockable.cs | 7 ++ .../Models/NonJsonApiResource.cs | 7 ++ .../Models/Passport.cs | 13 ++++ .../NoEntityFrameworkExample/Models/Person.cs | 56 +++++++++++++ .../NoEntityFrameworkExample/Models/Tag.cs | 10 +++ .../Models/TodoItem.cs | 78 +++++++++++++++++++ .../Models/TodoItemCollection.cs | 20 +++++ .../NoEntityFrameworkExample/Models/User.cs | 11 +++ .../NoEntityFrameworkExample.csproj | 3 +- .../Services/TodoItemService.cs | 2 +- .../NoEntityFrameworkExample/Startup.cs | 4 +- .../NoEntityFrameworkExample/appsettings.json | 2 +- test/NoEntityFrameworkTests/TestFixture.cs | 1 + 28 files changed, 312 insertions(+), 235 deletions(-) delete mode 100644 src/Examples/JsonApiDotNetCoreExample/Models/Entities/CourseEntity.cs delete mode 100644 src/Examples/JsonApiDotNetCoreExample/Models/Entities/CourseStudentEntity.cs delete mode 100644 src/Examples/JsonApiDotNetCoreExample/Models/Entities/DepartmentEntity.cs delete mode 100644 src/Examples/JsonApiDotNetCoreExample/Models/Entities/StudentEntity.cs delete mode 100644 src/Examples/JsonApiDotNetCoreExample/Models/Resources/CourseResource.cs delete mode 100644 src/Examples/JsonApiDotNetCoreExample/Models/Resources/CourseStudentResource.cs delete mode 100644 src/Examples/JsonApiDotNetCoreExample/Models/Resources/DepartmentResource.cs delete mode 100644 src/Examples/JsonApiDotNetCoreExample/Models/Resources/StudentResource.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/Article.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/ArticleTag.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/Author.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/CamelCasedModel.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/IIsLockable.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/NonJsonApiResource.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/Passport.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/Person.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/Tag.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/TodoItemCollection.cs create mode 100644 src/Examples/NoEntityFrameworkExample/Models/User.cs mode change 100755 => 100644 src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj diff --git a/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs b/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs index 6a6f7994fb..68b274b9d8 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs @@ -1,6 +1,5 @@ using JsonApiDotNetCoreExample.Models; using Microsoft.EntityFrameworkCore; -using JsonApiDotNetCoreExample.Models.Entities; namespace JsonApiDotNetCoreExample.Data { @@ -25,19 +24,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .WithMany(p => p.TodoItems) .HasForeignKey(t => t.OwnerId); - modelBuilder.Entity() - .HasKey(r => new { r.CourseId, r.StudentId }); - - modelBuilder.Entity() - .HasOne(r => r.Course) - .WithMany(c => c.Students) - .HasForeignKey(r => r.CourseId); - - modelBuilder.Entity() - .HasOne(r => r.Student) - .WithMany(s => s.Courses) - .HasForeignKey(r => r.StudentId); - modelBuilder.Entity() .HasKey(bc => new { bc.ArticleId, bc.TagId }); @@ -84,10 +70,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public DbSet Authors { get; set; } public DbSet NonJsonApiResources { get; set; } public DbSet Users { get; set; } - public DbSet Courses { get; set; } - public DbSet Departments { get; set; } - public DbSet Registrations { get; set; } - public DbSet Students { get; set; } public DbSet PersonRoles { get; set; } public DbSet ArticleTags { get; set; } public DbSet IdentifiableArticleTags { get; set; } diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Entities/CourseEntity.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Entities/CourseEntity.cs deleted file mode 100644 index a5e2c45f52..0000000000 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Entities/CourseEntity.cs +++ /dev/null @@ -1,31 +0,0 @@ -using JsonApiDotNetCore.Models; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace JsonApiDotNetCoreExample.Models.Entities -{ - [Table("Course")] - public class CourseEntity : Identifiable - { - [Column("number")] - [Required] - public int Number { get; set; } - - [Column("title")] - [Required] - [StringLength(255)] - public string Title { get; set; } - - [Column("description")] - [StringLength(4000)] - public string Description { get; set; } - - public DepartmentEntity Department { get; set; } - - [Column("department_id")] - public int? DepartmentId { get; set; } - - public List Students { get; set; } - } -} diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Entities/CourseStudentEntity.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Entities/CourseStudentEntity.cs deleted file mode 100644 index 3fe23cdc67..0000000000 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Entities/CourseStudentEntity.cs +++ /dev/null @@ -1,50 +0,0 @@ -using JsonApiDotNetCore.Models; -using Microsoft.EntityFrameworkCore.Infrastructure; -using System.ComponentModel.DataAnnotations.Schema; - -namespace JsonApiDotNetCoreExample.Models.Entities -{ - [Table("CourseStudent")] - public class CourseStudentEntity : Identifiable - { - private CourseEntity _course; - private StudentEntity _student; - private ILazyLoader _loader { get; set; } - private CourseStudentEntity(ILazyLoader loader) - { - _loader = loader; - } - - public CourseStudentEntity(int courseId, int studentId) - { - CourseId = courseId; - StudentId = studentId; - } - - public CourseStudentEntity(CourseEntity course, StudentEntity student) - { - Course = course; - CourseId = course.Id; - Student = student; - StudentId = student.Id; - } - - [Column("course_id")] - public int CourseId { get; set; } - - public CourseEntity Course - { - get => _loader.Load(this, ref _course); - set => _course = value; - } - - [Column("student_id")] - public int StudentId { get; set; } - - public StudentEntity Student - { - get => _loader.Load(this, ref _student); - set => _student = value; - } - } -} diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Entities/DepartmentEntity.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Entities/DepartmentEntity.cs deleted file mode 100644 index 337de4279f..0000000000 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Entities/DepartmentEntity.cs +++ /dev/null @@ -1,17 +0,0 @@ -using JsonApiDotNetCore.Models; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace JsonApiDotNetCoreExample.Models.Entities -{ - [Table("Department")] - public class DepartmentEntity : Identifiable - { - [Required] - [StringLength(255, MinimumLength = 3)] - public string Name { get; set; } - - public List Courses { get; set; } - } -} diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Entities/StudentEntity.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Entities/StudentEntity.cs deleted file mode 100644 index 1e23a471c5..0000000000 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Entities/StudentEntity.cs +++ /dev/null @@ -1,25 +0,0 @@ -using JsonApiDotNetCore.Models; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace JsonApiDotNetCoreExample.Models.Entities -{ - [Table("Student")] - public class StudentEntity : Identifiable - { - [Column("firstname")] - [Required] - public string FirstName { get; set; } - - [Column("lastname")] - [Required] - [StringLength(255, MinimumLength = 3)] - public string LastName { get; set; } - - [Column("address")] - public string Address { get; set; } - - public List Courses { get; set; } - } -} diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Resources/CourseResource.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Resources/CourseResource.cs deleted file mode 100644 index e981c70cc9..0000000000 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Resources/CourseResource.cs +++ /dev/null @@ -1,28 +0,0 @@ -using JsonApiDotNetCore.Models; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using JsonApiDotNetCoreExample.Models.Entities; - -namespace JsonApiDotNetCoreExample.Models.Resources -{ - public class CourseResource : Identifiable - { - [Attr("number")] - [Required] - public int Number { get; set; } - - [Attr("title")] - [Required] - public string Title { get; set; } - - [Attr("description")] - public string Description { get; set; } - - [HasOne("department", mappedBy: "Department")] - public DepartmentResource Department { get; set; } - public int? DepartmentId { get; set; } - - [HasMany("students")] - public List Students { get; set; } - } -} diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Resources/CourseStudentResource.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Resources/CourseStudentResource.cs deleted file mode 100644 index c6a6619ab8..0000000000 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Resources/CourseStudentResource.cs +++ /dev/null @@ -1,23 +0,0 @@ -using JsonApiDotNetCore.Models; - -namespace JsonApiDotNetCoreExample.Models.Resources -{ - /// - /// Note: EF Core *requires* the creation of an additional entity - /// for many to many relationships and no longer implicitly creates - /// it. While it may not make sense to create a corresponding "resource" - /// for that relationship, due to the need to make the underlying - /// framework and mapping understand the explicit navigation entity, - /// a mirroring DTO resource is also required. - /// - public class CourseStudentResource : Identifiable - { - [HasOne("course")] - public CourseResource Course { get; set; } - public int CourseId { get; set; } - - [HasOne("student")] - public StudentResource Student { get; set; } - public int StudentId { get; set; } - } -} diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Resources/DepartmentResource.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Resources/DepartmentResource.cs deleted file mode 100644 index 47648afcdf..0000000000 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Resources/DepartmentResource.cs +++ /dev/null @@ -1,14 +0,0 @@ -using JsonApiDotNetCore.Models; -using System.Collections.Generic; - -namespace JsonApiDotNetCoreExample.Models.Resources -{ - public class DepartmentResource : Identifiable - { - [Attr("name")] - public string Name { get; set; } - - [HasMany("courses", mappedBy: "Courses")] - public List Courses { get; set; } - } -} diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Resources/StudentResource.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Resources/StudentResource.cs deleted file mode 100644 index 086d81614b..0000000000 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Resources/StudentResource.cs +++ /dev/null @@ -1,23 +0,0 @@ -using JsonApiDotNetCore.Models; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; - -namespace JsonApiDotNetCoreExample.Models.Resources -{ - public class StudentResource : Identifiable - { - [Attr("firstname")] - [Required] - public string FirstName { get; set; } - - [Attr("lastname")] - [Required] - public string LastName { get; set; } - - [Attr("address")] - public string Address { get; set; } - - [HasMany("courses")] - public List Courses { get; set; } - } -} diff --git a/src/Examples/NoEntityFrameworkExample/Controllers/CustomTodoItemsController.cs b/src/Examples/NoEntityFrameworkExample/Controllers/CustomTodoItemsController.cs index 9a593cfa9f..637c4f2e10 100644 --- a/src/Examples/NoEntityFrameworkExample/Controllers/CustomTodoItemsController.cs +++ b/src/Examples/NoEntityFrameworkExample/Controllers/CustomTodoItemsController.cs @@ -1,7 +1,7 @@ using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Controllers; using JsonApiDotNetCore.Services; -using JsonApiDotNetCoreExample.Models; +using NoEntityFrameworkExample.Models; using Microsoft.Extensions.Logging; namespace NoEntityFrameworkExample.Controllers diff --git a/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs b/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs new file mode 100644 index 0000000000..85d65b6ed1 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs @@ -0,0 +1,22 @@ +using NoEntityFrameworkExample.Models; +using Microsoft.EntityFrameworkCore; + +namespace NoEntityFrameworkExample.Data +{ + public class AppDbContext : DbContext + { + public AppDbContext(DbContextOptions options) + : base(options) + { } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity() + .Property(t => t.CreatedDate).HasDefaultValueSql("CURRENT_TIMESTAMP").IsRequired(); + } + + public DbSet TodoItems { get; set; } + } + + +} diff --git a/src/Examples/NoEntityFrameworkExample/Models/Article.cs b/src/Examples/NoEntityFrameworkExample/Models/Article.cs new file mode 100644 index 0000000000..12839c9146 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/Article.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using JsonApiDotNetCore.Models; + +namespace NoEntityFrameworkExample.Models +{ + public class Article : Identifiable + { + [Attr("name")] + public string Name { get; set; } + + [HasOne("author")] + public Author Author { get; set; } + public int AuthorId { get; set; } + + [NotMapped] + [HasManyThrough(nameof(ArticleTags))] + public List Tags { get; set; } + public List ArticleTags { get; set; } + + + [NotMapped] + [HasManyThrough(nameof(IdentifiableArticleTags))] + public List IdentifiableTags { get; set; } + public List IdentifiableArticleTags { get; set; } + } +} diff --git a/src/Examples/NoEntityFrameworkExample/Models/ArticleTag.cs b/src/Examples/NoEntityFrameworkExample/Models/ArticleTag.cs new file mode 100644 index 0000000000..18f4e7a0f8 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/ArticleTag.cs @@ -0,0 +1,27 @@ +using JsonApiDotNetCore.Models; + +namespace NoEntityFrameworkExample.Models +{ + public class ArticleTag + { + public int ArticleId { get; set; } + public Article Article { get; set; } + + public int TagId { get; set; } + public Tag Tag { get; set; } + } + + + public class IdentifiableArticleTag : Identifiable + { + public int ArticleId { get; set; } + [HasOne("article")] + public Article Article { get; set; } + + public int TagId { get; set; } + [HasOne("Tag")] + public Tag Tag { get; set; } + + public string SomeMetaData { get; set; } + } +} \ No newline at end of file diff --git a/src/Examples/NoEntityFrameworkExample/Models/Author.cs b/src/Examples/NoEntityFrameworkExample/Models/Author.cs new file mode 100644 index 0000000000..d0da0c5c3a --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/Author.cs @@ -0,0 +1,15 @@ +using JsonApiDotNetCore.Models; +using System.Collections.Generic; + +namespace NoEntityFrameworkExample.Models +{ + public class Author : Identifiable + { + [Attr("name")] + public string Name { get; set; } + + [HasMany("articles")] + public List
Articles { get; set; } + } +} + diff --git a/src/Examples/NoEntityFrameworkExample/Models/CamelCasedModel.cs b/src/Examples/NoEntityFrameworkExample/Models/CamelCasedModel.cs new file mode 100644 index 0000000000..48b0ec2b48 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/CamelCasedModel.cs @@ -0,0 +1,11 @@ +using JsonApiDotNetCore.Models; + +namespace NoEntityFrameworkExample.Models +{ + [Resource("camelCasedModels")] + public class CamelCasedModel : Identifiable + { + [Attr("compoundAttr")] + public string CompoundAttr { get; set; } + } +} diff --git a/src/Examples/NoEntityFrameworkExample/Models/IIsLockable.cs b/src/Examples/NoEntityFrameworkExample/Models/IIsLockable.cs new file mode 100644 index 0000000000..cae2587f08 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/IIsLockable.cs @@ -0,0 +1,7 @@ +namespace NoEntityFrameworkExample.Models +{ + public interface IIsLockable + { + bool IsLocked { get; set; } + } +} \ No newline at end of file diff --git a/src/Examples/NoEntityFrameworkExample/Models/NonJsonApiResource.cs b/src/Examples/NoEntityFrameworkExample/Models/NonJsonApiResource.cs new file mode 100644 index 0000000000..b66abd3ac1 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/NonJsonApiResource.cs @@ -0,0 +1,7 @@ +namespace NoEntityFrameworkExample.Models +{ + public class NonJsonApiResource + { + public int Id { get; set; } + } +} diff --git a/src/Examples/NoEntityFrameworkExample/Models/Passport.cs b/src/Examples/NoEntityFrameworkExample/Models/Passport.cs new file mode 100644 index 0000000000..8aa395a5a0 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/Passport.cs @@ -0,0 +1,13 @@ +using JsonApiDotNetCore.Models; + +namespace NoEntityFrameworkExample.Models +{ + public class Passport : Identifiable + { + public virtual int? SocialSecurityNumber { get; set; } + public virtual bool IsLocked { get; set; } + + [HasOne("person")] + public virtual Person Person { get; set; } + } +} \ No newline at end of file diff --git a/src/Examples/NoEntityFrameworkExample/Models/Person.cs b/src/Examples/NoEntityFrameworkExample/Models/Person.cs new file mode 100644 index 0000000000..f17af325b0 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/Person.cs @@ -0,0 +1,56 @@ +using System.Collections.Generic; +using JsonApiDotNetCore.Models; +using JsonApiDotNetCore.Models.Links; + +namespace NoEntityFrameworkExample.Models +{ + public class PersonRole : Identifiable + { + [HasOne("person")] + public Person Person { get; set; } + } + + public class Person : Identifiable, IIsLockable + { + public bool IsLocked { get; set; } + + [Attr("first-name")] + public string FirstName { get; set; } + + [Attr("last-name")] + public string LastName { get; set; } + + [Attr("age")] + public int Age { get; set; } + + [HasMany("todo-items")] + public virtual List TodoItems { get; set; } + + [HasMany("assigned-todo-items")] + public virtual List AssignedTodoItems { get; set; } + + [HasMany("todo-collections")] + public virtual List TodoItemCollections { get; set; } + + [HasOne("role")] + public virtual PersonRole Role { get; set; } + public int? PersonRoleId { get; set; } + + [HasOne("one-to-one-todo-item")] + public virtual TodoItem ToOneTodoItem { get; set; } + + + [HasOne("stake-holder-todo-item")] + public virtual TodoItem StakeHolderTodo { get; set; } + public virtual int? StakeHolderTodoId { get; set; } + + [HasOne("unincludeable-item", links: Link.All, canInclude: false)] + public virtual TodoItem UnIncludeableItem { get; set; } + + public int? PassportId { get; set; } + + [HasOne("passport")] + public virtual Passport Passport { get; set; } + + } +} diff --git a/src/Examples/NoEntityFrameworkExample/Models/Tag.cs b/src/Examples/NoEntityFrameworkExample/Models/Tag.cs new file mode 100644 index 0000000000..941cfb8428 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/Tag.cs @@ -0,0 +1,10 @@ +using JsonApiDotNetCore.Models; + +namespace NoEntityFrameworkExample.Models +{ + public class Tag : Identifiable + { + [Attr] + public string Name { get; set; } + } +} \ No newline at end of file diff --git a/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs b/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs new file mode 100644 index 0000000000..d35d4a0218 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using JsonApiDotNetCore.Models; + +namespace NoEntityFrameworkExample.Models +{ + public class TodoItem : Identifiable, IIsLockable + { + public TodoItem() + { + GuidProperty = Guid.NewGuid(); + } + + public bool IsLocked { get; set; } + + [Attr("description")] + public string Description { get; set; } + + [Attr("ordinal")] + public long Ordinal { get; set; } + + [Attr("guid-property")] + public Guid GuidProperty { get; set; } + + [Attr("created-date")] + public DateTime CreatedDate { get; set; } + + [Attr("achieved-date", isFilterable: false, isSortable: false)] + public DateTime? AchievedDate { get; set; } + + [Attr("updated-date")] + public DateTime? UpdatedDate { get; set; } + + [Attr("calculated-value", isImmutable: true)] + public string CalculatedValue + { + get => "joe"; + } + + [Attr("offset-date")] + public DateTimeOffset? OffsetDate { get; set; } + + public int? OwnerId { get; set; } + public int? AssigneeId { get; set; } + public Guid? CollectionId { get; set; } + + [HasOne("owner")] + public virtual Person Owner { get; set; } + + [HasOne("assignee")] + public virtual Person Assignee { get; set; } + + [HasOne("one-to-one-person")] + public virtual Person ToOnePerson { get; set; } + public virtual int? ToOnePersonId { get; set; } + + + [HasMany("stake-holders")] + public virtual List StakeHolders { get; set; } + + [HasOne("collection")] + public virtual TodoItemCollection Collection { get; set; } + + + // cyclical to-one structure + public virtual int? DependentTodoItemId { get; set; } + [HasOne("dependent-on-todo")] + public virtual TodoItem DependentTodoItem { get; set; } + + + // cyclical to-many structure + public virtual int? ParentTodoItemId {get; set;} + [HasOne("parent-todo")] + public virtual TodoItem ParentTodoItem { get; set; } + [HasMany("children-todos")] + public virtual List ChildrenTodoItems { get; set; } + } +} diff --git a/src/Examples/NoEntityFrameworkExample/Models/TodoItemCollection.cs b/src/Examples/NoEntityFrameworkExample/Models/TodoItemCollection.cs new file mode 100644 index 0000000000..2689b29fc0 --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/TodoItemCollection.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using JsonApiDotNetCore.Models; + +namespace NoEntityFrameworkExample.Models +{ + [Resource("todo-collections")] + public class TodoItemCollection : Identifiable + { + [Attr("name")] + public string Name { get; set; } + + [HasMany("todo-items")] + public virtual List TodoItems { get; set; } + + [HasOne("owner")] + public virtual Person Owner { get; set; } + public int? OwnerId { get; set; } + } +} diff --git a/src/Examples/NoEntityFrameworkExample/Models/User.cs b/src/Examples/NoEntityFrameworkExample/Models/User.cs new file mode 100644 index 0000000000..54e29a3d4c --- /dev/null +++ b/src/Examples/NoEntityFrameworkExample/Models/User.cs @@ -0,0 +1,11 @@ +using System; +using JsonApiDotNetCore.Models; + +namespace NoEntityFrameworkExample.Models +{ + public class User : Identifiable + { + [Attr] public string Username { get; set; } + [Attr] public string Password { get; set; } + } +} diff --git a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj old mode 100755 new mode 100644 index 2a1deb3db0..4f2ad79952 --- a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj +++ b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj @@ -6,11 +6,12 @@ + + - diff --git a/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs b/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs index b99c99c85a..a19aea76f4 100644 --- a/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs +++ b/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs @@ -7,7 +7,7 @@ using Npgsql; using Dapper; using System.Data; -using JsonApiDotNetCoreExample.Models; +using NoEntityFrameworkExample.Models; using System.Linq; namespace NoEntityFrameworkExample.Services diff --git a/src/Examples/NoEntityFrameworkExample/Startup.cs b/src/Examples/NoEntityFrameworkExample/Startup.cs index 7948e6e183..5056f59648 100644 --- a/src/Examples/NoEntityFrameworkExample/Startup.cs +++ b/src/Examples/NoEntityFrameworkExample/Startup.cs @@ -1,7 +1,5 @@ using JsonApiDotNetCore.Extensions; using JsonApiDotNetCore.Services; -using JsonApiDotNetCoreExample.Data; -using JsonApiDotNetCoreExample.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; @@ -10,6 +8,8 @@ using NoEntityFrameworkExample.Services; using Microsoft.EntityFrameworkCore; using System; +using NoEntityFrameworkExample.Data; +using NoEntityFrameworkExample.Models; namespace NoEntityFrameworkExample { diff --git a/src/Examples/NoEntityFrameworkExample/appsettings.json b/src/Examples/NoEntityFrameworkExample/appsettings.json index 42da2105cc..3430871815 100755 --- a/src/Examples/NoEntityFrameworkExample/appsettings.json +++ b/src/Examples/NoEntityFrameworkExample/appsettings.json @@ -1,6 +1,6 @@ { "Data": { - "DefaultConnection": "Host=localhost;Port=5432;Database=JsonApiDotNetCoreExample;User ID=postgres;Password=" + "DefaultConnection": "Host=localhost;Port=5432;Database=NoEntityFrameworkExample;User ID=postgres;Password=" }, "Logging": { "IncludeScopes": false, diff --git a/test/NoEntityFrameworkTests/TestFixture.cs b/test/NoEntityFrameworkTests/TestFixture.cs index 7f15df56fb..243f57c644 100644 --- a/test/NoEntityFrameworkTests/TestFixture.cs +++ b/test/NoEntityFrameworkTests/TestFixture.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.TestHost; using System; using System.Linq.Expressions; +using Startup = NoEntityFrameworkExample.Startup; namespace NoEntityFrameworkTests { From e83abfdf025f602a18b20dd993227f8e435a7491 Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 16:14:18 +0100 Subject: [PATCH 43/47] fix: NoEntityFrameworkExample tests fixed by workaround assembly problem --- ...msController.cs => TodoItemsController.cs} | 4 +- .../Data/AppDbContext.cs | 6 -- .../Models/Article.cs | 27 --------- .../Models/ArticleTag.cs | 27 --------- .../NoEntityFrameworkExample/Models/Author.cs | 15 ----- .../Models/CamelCasedModel.cs | 11 ---- .../Models/IIsLockable.cs | 7 --- .../Models/NonJsonApiResource.cs | 7 --- .../Models/Passport.cs | 13 ----- .../NoEntityFrameworkExample/Models/Person.cs | 56 ------------------- .../NoEntityFrameworkExample/Models/Tag.cs | 10 ---- .../Models/TodoItem.cs | 44 +-------------- .../Models/TodoItemCollection.cs | 20 ------- .../NoEntityFrameworkExample/Models/User.cs | 11 ---- .../Services/TodoItemService.cs | 6 +- .../NoEntityFrameworkExample/Startup.cs | 9 ++- .../Extensibility/NoEntityFrameworkTests.cs | 12 ++-- .../NoEntityFrameworkTests.csproj | 4 +- test/NoEntityFrameworkTests/TestFixture.cs | 23 ++------ 19 files changed, 21 insertions(+), 291 deletions(-) rename src/Examples/NoEntityFrameworkExample/Controllers/{CustomTodoItemsController.cs => TodoItemsController.cs} (80%) delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/Article.cs delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/ArticleTag.cs delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/Author.cs delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/CamelCasedModel.cs delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/IIsLockable.cs delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/NonJsonApiResource.cs delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/Passport.cs delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/Person.cs delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/Tag.cs delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/TodoItemCollection.cs delete mode 100644 src/Examples/NoEntityFrameworkExample/Models/User.cs diff --git a/src/Examples/NoEntityFrameworkExample/Controllers/CustomTodoItemsController.cs b/src/Examples/NoEntityFrameworkExample/Controllers/TodoItemsController.cs similarity index 80% rename from src/Examples/NoEntityFrameworkExample/Controllers/CustomTodoItemsController.cs rename to src/Examples/NoEntityFrameworkExample/Controllers/TodoItemsController.cs index 637c4f2e10..cf18987700 100644 --- a/src/Examples/NoEntityFrameworkExample/Controllers/CustomTodoItemsController.cs +++ b/src/Examples/NoEntityFrameworkExample/Controllers/TodoItemsController.cs @@ -6,9 +6,9 @@ namespace NoEntityFrameworkExample.Controllers { - public class CustomTodoItemsController : JsonApiController + public class TodoItemsController : JsonApiController { - public CustomTodoItemsController( + public TodoItemsController( IJsonApiOptions jsonApiOptions, IResourceService resourceService, ILoggerFactory loggerFactory) diff --git a/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs b/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs index 85d65b6ed1..b9fd379a68 100644 --- a/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs +++ b/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs @@ -9,12 +9,6 @@ public AppDbContext(DbContextOptions options) : base(options) { } - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity() - .Property(t => t.CreatedDate).HasDefaultValueSql("CURRENT_TIMESTAMP").IsRequired(); - } - public DbSet TodoItems { get; set; } } diff --git a/src/Examples/NoEntityFrameworkExample/Models/Article.cs b/src/Examples/NoEntityFrameworkExample/Models/Article.cs deleted file mode 100644 index 12839c9146..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/Article.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; -using JsonApiDotNetCore.Models; - -namespace NoEntityFrameworkExample.Models -{ - public class Article : Identifiable - { - [Attr("name")] - public string Name { get; set; } - - [HasOne("author")] - public Author Author { get; set; } - public int AuthorId { get; set; } - - [NotMapped] - [HasManyThrough(nameof(ArticleTags))] - public List Tags { get; set; } - public List ArticleTags { get; set; } - - - [NotMapped] - [HasManyThrough(nameof(IdentifiableArticleTags))] - public List IdentifiableTags { get; set; } - public List IdentifiableArticleTags { get; set; } - } -} diff --git a/src/Examples/NoEntityFrameworkExample/Models/ArticleTag.cs b/src/Examples/NoEntityFrameworkExample/Models/ArticleTag.cs deleted file mode 100644 index 18f4e7a0f8..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/ArticleTag.cs +++ /dev/null @@ -1,27 +0,0 @@ -using JsonApiDotNetCore.Models; - -namespace NoEntityFrameworkExample.Models -{ - public class ArticleTag - { - public int ArticleId { get; set; } - public Article Article { get; set; } - - public int TagId { get; set; } - public Tag Tag { get; set; } - } - - - public class IdentifiableArticleTag : Identifiable - { - public int ArticleId { get; set; } - [HasOne("article")] - public Article Article { get; set; } - - public int TagId { get; set; } - [HasOne("Tag")] - public Tag Tag { get; set; } - - public string SomeMetaData { get; set; } - } -} \ No newline at end of file diff --git a/src/Examples/NoEntityFrameworkExample/Models/Author.cs b/src/Examples/NoEntityFrameworkExample/Models/Author.cs deleted file mode 100644 index d0da0c5c3a..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/Author.cs +++ /dev/null @@ -1,15 +0,0 @@ -using JsonApiDotNetCore.Models; -using System.Collections.Generic; - -namespace NoEntityFrameworkExample.Models -{ - public class Author : Identifiable - { - [Attr("name")] - public string Name { get; set; } - - [HasMany("articles")] - public List
Articles { get; set; } - } -} - diff --git a/src/Examples/NoEntityFrameworkExample/Models/CamelCasedModel.cs b/src/Examples/NoEntityFrameworkExample/Models/CamelCasedModel.cs deleted file mode 100644 index 48b0ec2b48..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/CamelCasedModel.cs +++ /dev/null @@ -1,11 +0,0 @@ -using JsonApiDotNetCore.Models; - -namespace NoEntityFrameworkExample.Models -{ - [Resource("camelCasedModels")] - public class CamelCasedModel : Identifiable - { - [Attr("compoundAttr")] - public string CompoundAttr { get; set; } - } -} diff --git a/src/Examples/NoEntityFrameworkExample/Models/IIsLockable.cs b/src/Examples/NoEntityFrameworkExample/Models/IIsLockable.cs deleted file mode 100644 index cae2587f08..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/IIsLockable.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace NoEntityFrameworkExample.Models -{ - public interface IIsLockable - { - bool IsLocked { get; set; } - } -} \ No newline at end of file diff --git a/src/Examples/NoEntityFrameworkExample/Models/NonJsonApiResource.cs b/src/Examples/NoEntityFrameworkExample/Models/NonJsonApiResource.cs deleted file mode 100644 index b66abd3ac1..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/NonJsonApiResource.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace NoEntityFrameworkExample.Models -{ - public class NonJsonApiResource - { - public int Id { get; set; } - } -} diff --git a/src/Examples/NoEntityFrameworkExample/Models/Passport.cs b/src/Examples/NoEntityFrameworkExample/Models/Passport.cs deleted file mode 100644 index 8aa395a5a0..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/Passport.cs +++ /dev/null @@ -1,13 +0,0 @@ -using JsonApiDotNetCore.Models; - -namespace NoEntityFrameworkExample.Models -{ - public class Passport : Identifiable - { - public virtual int? SocialSecurityNumber { get; set; } - public virtual bool IsLocked { get; set; } - - [HasOne("person")] - public virtual Person Person { get; set; } - } -} \ No newline at end of file diff --git a/src/Examples/NoEntityFrameworkExample/Models/Person.cs b/src/Examples/NoEntityFrameworkExample/Models/Person.cs deleted file mode 100644 index f17af325b0..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/Person.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Collections.Generic; -using JsonApiDotNetCore.Models; -using JsonApiDotNetCore.Models.Links; - -namespace NoEntityFrameworkExample.Models -{ - public class PersonRole : Identifiable - { - [HasOne("person")] - public Person Person { get; set; } - } - - public class Person : Identifiable, IIsLockable - { - public bool IsLocked { get; set; } - - [Attr("first-name")] - public string FirstName { get; set; } - - [Attr("last-name")] - public string LastName { get; set; } - - [Attr("age")] - public int Age { get; set; } - - [HasMany("todo-items")] - public virtual List TodoItems { get; set; } - - [HasMany("assigned-todo-items")] - public virtual List AssignedTodoItems { get; set; } - - [HasMany("todo-collections")] - public virtual List TodoItemCollections { get; set; } - - [HasOne("role")] - public virtual PersonRole Role { get; set; } - public int? PersonRoleId { get; set; } - - [HasOne("one-to-one-todo-item")] - public virtual TodoItem ToOneTodoItem { get; set; } - - - [HasOne("stake-holder-todo-item")] - public virtual TodoItem StakeHolderTodo { get; set; } - public virtual int? StakeHolderTodoId { get; set; } - - [HasOne("unincludeable-item", links: Link.All, canInclude: false)] - public virtual TodoItem UnIncludeableItem { get; set; } - - public int? PassportId { get; set; } - - [HasOne("passport")] - public virtual Passport Passport { get; set; } - - } -} diff --git a/src/Examples/NoEntityFrameworkExample/Models/Tag.cs b/src/Examples/NoEntityFrameworkExample/Models/Tag.cs deleted file mode 100644 index 941cfb8428..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/Tag.cs +++ /dev/null @@ -1,10 +0,0 @@ -using JsonApiDotNetCore.Models; - -namespace NoEntityFrameworkExample.Models -{ - public class Tag : Identifiable - { - [Attr] - public string Name { get; set; } - } -} \ No newline at end of file diff --git a/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs b/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs index d35d4a0218..b1021d18f5 100644 --- a/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs +++ b/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs @@ -1,10 +1,9 @@ using System; -using System.Collections.Generic; using JsonApiDotNetCore.Models; namespace NoEntityFrameworkExample.Models { - public class TodoItem : Identifiable, IIsLockable + public class TodoItem : Identifiable { public TodoItem() { @@ -31,48 +30,7 @@ public TodoItem() [Attr("updated-date")] public DateTime? UpdatedDate { get; set; } - [Attr("calculated-value", isImmutable: true)] - public string CalculatedValue - { - get => "joe"; - } - [Attr("offset-date")] public DateTimeOffset? OffsetDate { get; set; } - - public int? OwnerId { get; set; } - public int? AssigneeId { get; set; } - public Guid? CollectionId { get; set; } - - [HasOne("owner")] - public virtual Person Owner { get; set; } - - [HasOne("assignee")] - public virtual Person Assignee { get; set; } - - [HasOne("one-to-one-person")] - public virtual Person ToOnePerson { get; set; } - public virtual int? ToOnePersonId { get; set; } - - - [HasMany("stake-holders")] - public virtual List StakeHolders { get; set; } - - [HasOne("collection")] - public virtual TodoItemCollection Collection { get; set; } - - - // cyclical to-one structure - public virtual int? DependentTodoItemId { get; set; } - [HasOne("dependent-on-todo")] - public virtual TodoItem DependentTodoItem { get; set; } - - - // cyclical to-many structure - public virtual int? ParentTodoItemId {get; set;} - [HasOne("parent-todo")] - public virtual TodoItem ParentTodoItem { get; set; } - [HasMany("children-todos")] - public virtual List ChildrenTodoItems { get; set; } } } diff --git a/src/Examples/NoEntityFrameworkExample/Models/TodoItemCollection.cs b/src/Examples/NoEntityFrameworkExample/Models/TodoItemCollection.cs deleted file mode 100644 index 2689b29fc0..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/TodoItemCollection.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using JsonApiDotNetCore.Models; - -namespace NoEntityFrameworkExample.Models -{ - [Resource("todo-collections")] - public class TodoItemCollection : Identifiable - { - [Attr("name")] - public string Name { get; set; } - - [HasMany("todo-items")] - public virtual List TodoItems { get; set; } - - [HasOne("owner")] - public virtual Person Owner { get; set; } - public int? OwnerId { get; set; } - } -} diff --git a/src/Examples/NoEntityFrameworkExample/Models/User.cs b/src/Examples/NoEntityFrameworkExample/Models/User.cs deleted file mode 100644 index 54e29a3d4c..0000000000 --- a/src/Examples/NoEntityFrameworkExample/Models/User.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using JsonApiDotNetCore.Models; - -namespace NoEntityFrameworkExample.Models -{ - public class User : Identifiable - { - [Attr] public string Username { get; set; } - [Attr] public string Password { get; set; } - } -} diff --git a/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs b/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs index a19aea76f4..a7897acfab 100644 --- a/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs +++ b/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs @@ -14,12 +14,8 @@ namespace NoEntityFrameworkExample.Services { public class TodoItemService : IResourceService { - private readonly string _connectionString; + private readonly string _connectionString = "Host=localhost;Port=5432;Database=JsonApiDotNetCoreExample;User ID=postgres;Password=postgres"; - public TodoItemService(IConfiguration config) - { - _connectionString = config.GetValue("Data:DefaultConnection"); - } private IDbConnection Connection { diff --git a/src/Examples/NoEntityFrameworkExample/Startup.cs b/src/Examples/NoEntityFrameworkExample/Startup.cs index 5056f59648..50d63bd4eb 100644 --- a/src/Examples/NoEntityFrameworkExample/Startup.cs +++ b/src/Examples/NoEntityFrameworkExample/Startup.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Logging; using NoEntityFrameworkExample.Services; using Microsoft.EntityFrameworkCore; -using System; using NoEntityFrameworkExample.Data; using NoEntityFrameworkExample.Models; @@ -37,13 +36,13 @@ public virtual void ConfigureServices(IServiceCollection services) builder.AddConfiguration(Configuration.GetSection("Logging")); builder.AddConsole(); }).AddJsonApi( - options => options.Namespace = "api/v1", - resources: resources => resources.AddResource("custom-todo-items"), + options => options.Namespace = "api/v1", + resources: resources => resources.AddResource("todo-items"), mvcBuilder: mvcBuilder - ); + ); ; services.AddScoped, TodoItemService>(); var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseNpgsql(Configuration.GetValue("Data:DefaultConnection")); + optionsBuilder.UseNpgsql("Host=localhost;Port=5432;Database=JsonApiDotNetCoreExample;User ID=postgres;Password=postgres"); services.AddSingleton(Configuration); services.AddSingleton(optionsBuilder.Options); services.AddScoped(); diff --git a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs index 7bca584b63..06dd96a854 100644 --- a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs +++ b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs @@ -3,12 +3,12 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; -using JsonApiDotNetCoreExample; -using JsonApiDotNetCoreExample.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Newtonsoft.Json; using Xunit; +using Startup = NoEntityFrameworkExample.Startup; +using TodoItem = NoEntityFrameworkExample.Models.TodoItem; namespace NoEntityFrameworkTests.Acceptance.Extensibility { @@ -31,7 +31,7 @@ public async Task Can_Get_TodoItems() var client = _fixture.Server.CreateClient(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/custom-todo-items"; + var route = $"/api/v1/todo-items"; var request = new HttpRequestMessage(httpMethod, route); @@ -57,7 +57,7 @@ public async Task Can_Get_TodoItems_By_Id() var client = _fixture.Server.CreateClient(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/custom-todo-items/{todoItem.Id}"; + var route = $"/api/v1/todo-items/{todoItem.Id}"; var request = new HttpRequestMessage(httpMethod, route); @@ -78,12 +78,12 @@ public async Task Can_Create_TodoItems() // Arrange var description = Guid.NewGuid().ToString(); var httpMethod = new HttpMethod("POST"); - var route = $"/api/v1/custom-todo-items/"; + var route = $"/api/v1/todo-items/"; var content = new { data = new { - type = "custom-todo-items", + type = "todo-items", attributes = new { description, diff --git a/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj b/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj index d4ac395a9d..a53c1e90ce 100644 --- a/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj +++ b/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj @@ -14,10 +14,9 @@ - - + @@ -25,6 +24,7 @@ + diff --git a/test/NoEntityFrameworkTests/TestFixture.cs b/test/NoEntityFrameworkTests/TestFixture.cs index 243f57c644..82836a8a06 100644 --- a/test/NoEntityFrameworkTests/TestFixture.cs +++ b/test/NoEntityFrameworkTests/TestFixture.cs @@ -1,13 +1,10 @@ using JsonApiDotNetCore.Builders; using JsonApiDotNetCore.Models; -using JsonApiDotNetCore.Serialization.Client; -using JsonApiDotNetCoreExample; -using JsonApiDotNetCoreExample.Data; -using JsonApiDotNetCoreExample.Models; -using JsonApiDotNetCoreExampleTests.Helpers.Extensions; -using JsonApiDotNetCoreExampleTests.Helpers.Models; +using JsonApiDotNetCore.Serialization.Client; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using NoEntityFrameworkExample.Data; +using NoEntityFrameworkExample.Models; using System; using System.Linq.Expressions; using Startup = NoEntityFrameworkExample.Startup; @@ -23,7 +20,7 @@ public TestFixture() { var builder = new WebHostBuilder().UseStartup(); Server = new TestServer(builder); - Context = Server.GetService(); + Context = (AppDbContext)Server.Services.GetService(typeof(AppDbContext)); Context.Database.EnsureCreated(); _services = Server.Host.Services; } @@ -39,17 +36,7 @@ public IRequestSerializer GetSerializer(Expression() - .AddResource
() - .AddResource() - .AddResource() - .AddResource() - .AddResource() - .AddResource() - .AddResource() - .AddResource("custom-todo-items") - .AddResource().Build(); + var resourceGraph = new ResourceGraphBuilder().AddResource("todo-items").Build(); return new ResponseDeserializer(resourceGraph); } From a81b6ac5cc9f0fda1814b7e631058aad4b0f66ed Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 16:19:11 +0100 Subject: [PATCH 44/47] fix: connection string e2e test projects --- .../Services/TodoItemService.cs | 7 +++++-- src/Examples/NoEntityFrameworkExample/Startup.cs | 6 ++++-- .../NoEntityFrameworkExample/appsettings.json | 16 ++++++++-------- .../Acceptance/TestFixture.cs | 1 - 4 files changed, 17 insertions(+), 13 deletions(-) mode change 100755 => 100644 src/Examples/NoEntityFrameworkExample/appsettings.json diff --git a/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs b/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs index a7897acfab..12d26f2eb5 100644 --- a/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs +++ b/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Services; using Microsoft.Extensions.Configuration; using Npgsql; @@ -14,8 +13,12 @@ namespace NoEntityFrameworkExample.Services { public class TodoItemService : IResourceService { - private readonly string _connectionString = "Host=localhost;Port=5432;Database=JsonApiDotNetCoreExample;User ID=postgres;Password=postgres"; + private readonly string _connectionString; + public TodoItemService(IConfiguration config) + { + _connectionString = config["Data:DefaultConnection"]; + } private IDbConnection Connection { diff --git a/src/Examples/NoEntityFrameworkExample/Startup.cs b/src/Examples/NoEntityFrameworkExample/Startup.cs index 50d63bd4eb..1d6aef07c5 100644 --- a/src/Examples/NoEntityFrameworkExample/Startup.cs +++ b/src/Examples/NoEntityFrameworkExample/Startup.cs @@ -39,10 +39,10 @@ public virtual void ConfigureServices(IServiceCollection services) options => options.Namespace = "api/v1", resources: resources => resources.AddResource("todo-items"), mvcBuilder: mvcBuilder - ); ; + ); services.AddScoped, TodoItemService>(); var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseNpgsql("Host=localhost;Port=5432;Database=JsonApiDotNetCoreExample;User ID=postgres;Password=postgres"); + optionsBuilder.UseNpgsql(GetDbConnectionString()); services.AddSingleton(Configuration); services.AddSingleton(optionsBuilder.Options); services.AddScoped(); @@ -54,5 +54,7 @@ public void Configure(IApplicationBuilder app, AppDbContext context) context.Database.EnsureCreated(); app.UseJsonApi(); } + + public string GetDbConnectionString() => Configuration["Data:DefaultConnection"]; } } diff --git a/src/Examples/NoEntityFrameworkExample/appsettings.json b/src/Examples/NoEntityFrameworkExample/appsettings.json old mode 100755 new mode 100644 index 3430871815..ed7d5999d7 --- a/src/Examples/NoEntityFrameworkExample/appsettings.json +++ b/src/Examples/NoEntityFrameworkExample/appsettings.json @@ -1,11 +1,11 @@ { - "Data": { - "DefaultConnection": "Host=localhost;Port=5432;Database=NoEntityFrameworkExample;User ID=postgres;Password=" - }, - "Logging": { - "IncludeScopes": false, - "LogLevel": { - "Default": "Warning" + "Data": { + "DefaultConnection": "Host=localhost;Port=5432;Database=JsonApiDotNetCoreExample;User ID=postgres;Password=postgres" + }, + "Logging": { + "IncludeScopes": false, + "LogLevel": { + "Default": "Warning" + } } - } } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs index 90c7d0e926..a24bf58208 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs @@ -11,7 +11,6 @@ using JsonApiDotNetCore.Builders; using JsonApiDotNetCoreExampleTests.Helpers.Models; using JsonApiDotNetCoreExample.Models; -using JsonApiDotNetCoreExample; namespace JsonApiDotNetCoreExampleTests.Acceptance { From 518e4d0fa37e59e1a8b876404f7afad626e12fe4 Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 16:23:03 +0100 Subject: [PATCH 45/47] chore: minor cleanup --- README.md | 25 +++++++++---------- src/Examples/GettingStarted/Startup.cs | 1 - .../Resources/UserResource.cs | 5 ++-- .../Startups/Startup.cs | 1 - .../TestStartup.cs | 8 ++---- 5 files changed, 16 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index a4d49ec68c..8126e7f1d8 100644 --- a/README.md +++ b/README.md @@ -12,19 +12,6 @@ A framework for building [json:api](http://jsonapi.org/) compliant web APIs. The ultimate goal of this library is to eliminate as much boilerplate as possible by offering out-of-the-box features such as sorting, filtering and pagination. You just need to focus on defining the resources and implementing your custom business logic. This library has been designed around dependency injection making extensibility incredibly easy. - - -## Compatibility - -A lot of changes were introduced in v4.0.0, the following chart should help you with compatibility issues between .NET Core versions - -| .NET Core Version | JADNC Version | -| ----------------- | ------------- | -| 2.0 - 2.2 | v3.* | -| 3.* | v4.* | - - - ## Getting Started These are some steps you can take to help you understand what this project is and how you can use it: @@ -121,3 +108,15 @@ Sometimes the compiled files can be dirty / corrupt from other branches / failed ```bash dotnet clean ``` + + +## Compatibility + +A lot of changes were introduced in v4.0.0, the following chart should help you with compatibility issues between .NET Core versions + +| .NET Core Version | JADNC Version | +| ----------------- | ------------- | +| 2.0 - 2.2 | v3.* | +| 3.* | v4.* | + + diff --git a/src/Examples/GettingStarted/Startup.cs b/src/Examples/GettingStarted/Startup.cs index 296bcefe11..e9de7a0c4a 100644 --- a/src/Examples/GettingStarted/Startup.cs +++ b/src/Examples/GettingStarted/Startup.cs @@ -24,7 +24,6 @@ public void ConfigureServices(IServiceCollection services) public void Configure(IApplicationBuilder app, SampleDbContext context) { context.Database.EnsureDeleted(); // indicies need to be reset - context.Database.EnsureCreated(); app.UseJsonApi(); } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs b/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs index 543026db20..9aa8d8397f 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs @@ -26,9 +26,8 @@ private IQueryable FirstCharacterFilter(IQueryable users, FilterQuer { switch (filterQuery.Operation) { - // need to cast to list first because getting the first - // char in a string is apparently not something LINQ can translate - // to a query. + /// In EF core >= 3.0 we need to explicitly evaluate the query first. This could probably be translated + /// into a query by building expression trees. case "lt": return users.ToList().Where(u => u.Username.First() < filterQuery.Value[0]).AsQueryable(); default: diff --git a/src/Examples/JsonApiDotNetCoreExample/Startups/Startup.cs b/src/Examples/JsonApiDotNetCoreExample/Startups/Startup.cs index a9cb0529f3..ba7404cc04 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startups/Startup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startups/Startup.cs @@ -44,7 +44,6 @@ public virtual void ConfigureServices(IServiceCollection services) options.LoaDatabaseValues = true; }, discovery => discovery.AddCurrentAssembly()); - services.AddClientSerialization(); } public virtual void Configure( diff --git a/test/JsonApiDotNetCoreExampleTests/TestStartup.cs b/test/JsonApiDotNetCoreExampleTests/TestStartup.cs index f2bae23fa8..73cc900b51 100644 --- a/test/JsonApiDotNetCoreExampleTests/TestStartup.cs +++ b/test/JsonApiDotNetCoreExampleTests/TestStartup.cs @@ -1,12 +1,8 @@ using JsonApiDotNetCore.Extensions; using JsonApiDotNetCore.Services; using JsonApiDotNetCoreExample; -using JsonApiDotNetCoreExample.Data; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using System; using UnitTests; namespace JsonApiDotNetCoreExampleTests @@ -19,8 +15,8 @@ public TestStartup(IWebHostEnvironment env) : base(env) public override void ConfigureServices(IServiceCollection services) { base.ConfigureServices(services); - //services.AddClientSerialization(); - //services.AddScoped(); + services.AddClientSerialization(); + services.AddScoped(); } } } From 78452501e2b8479a62f00109956fe12fa8df372d Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 16:39:12 +0100 Subject: [PATCH 46/47] chore: minor cleanup --- src/Examples/GettingStarted/Startup.cs | 1 - .../NoEntityFrameworkExample/Data/AppDbContext.cs | 2 -- .../NoEntityFrameworkExample.csproj | 9 --------- .../NoEntityFrameworkExample/Services/TodoItemService.cs | 4 ++-- .../Extensions/IApplicationBuilderExtensions.cs | 4 +--- 5 files changed, 3 insertions(+), 17 deletions(-) diff --git a/src/Examples/GettingStarted/Startup.cs b/src/Examples/GettingStarted/Startup.cs index e9de7a0c4a..75a4704301 100644 --- a/src/Examples/GettingStarted/Startup.cs +++ b/src/Examples/GettingStarted/Startup.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using JsonApiDotNetCore.Extensions; diff --git a/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs b/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs index b9fd379a68..e7247108dd 100644 --- a/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs +++ b/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs @@ -11,6 +11,4 @@ public AppDbContext(DbContextOptions options) public DbSet TodoItems { get; set; } } - - } diff --git a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj index 4f2ad79952..b387f93746 100644 --- a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj +++ b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj @@ -3,22 +3,13 @@ $(NetCoreAppVersion) InProcess - - - - - - - - - diff --git a/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs b/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs index 12d26f2eb5..09078cda2c 100644 --- a/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs +++ b/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs @@ -17,9 +17,9 @@ public class TodoItemService : IResourceService public TodoItemService(IConfiguration config) { - _connectionString = config["Data:DefaultConnection"]; + _connectionString = config.GetValue("Data:DefaultConnection"); } - + private IDbConnection Connection { get diff --git a/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs b/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs index 925d2ab1e2..80396785be 100644 --- a/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs @@ -5,7 +5,6 @@ using JsonApiDotNetCore.Middleware; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -18,7 +17,6 @@ public static class IApplicationBuilderExtensions /// Adds necessary components such as routing to your application ///
/// - /// /// public static void UseJsonApi(this IApplicationBuilder app) { @@ -36,7 +34,7 @@ public static void UseJsonApi(this IApplicationBuilder app) // middleware to run after routing occurs. app.UseMiddleware(); - // Executes the endpoitns that was selected by routing. + // Executes the endpoints that was selected by routing. app.UseEndpoints(endpoints => { endpoints.MapControllers(); From 6e8ddf4c52fbdd98b73a499096e085072b9c37a7 Mon Sep 17 00:00:00 2001 From: Maurits Moeys Date: Tue, 29 Oct 2019 16:40:28 +0100 Subject: [PATCH 47/47] chore: cleanup --- .../Extensions/IApplicationBuilderExtensions.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs b/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs index 80396785be..5f4aeb53dd 100644 --- a/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs @@ -35,10 +35,7 @@ public static void UseJsonApi(this IApplicationBuilder app) app.UseMiddleware(); // Executes the endpoints that was selected by routing. - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); + app.UseEndpoints(endpoints => endpoints.MapControllers()); } private static void DisableDetailedErrorsIfProduction(IApplicationBuilder app)