├── .gitignore ├── LICENSE ├── README.md ├── RendleLabs.OpenApi.sln ├── RendleLabs.OpenApi.sln.DotSettings ├── experiments └── ApiBase │ ├── Api │ ├── Books.cs │ ├── BooksBase.cs │ └── MapApiExtension.cs │ ├── ApiBase.csproj │ ├── Data │ └── BookData.cs │ ├── Models │ └── Book.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── appsettings.Development.json │ └── appsettings.json ├── global.json ├── src ├── Analyzer │ ├── Analyzer.csproj │ ├── AttributeHelper.cs │ ├── ControllerAnalyzer.cs │ ├── Facts │ │ ├── IsActionMethodExtension.cs │ │ └── IsController.cs │ ├── NamespaceHelper.cs │ ├── TextHelpers.cs │ └── TypeHelper.cs ├── Build │ ├── Build.csproj │ ├── Builder.cs │ ├── OpenApiDiagnosticWrite.cs │ ├── Program.cs │ ├── ReferenceVisitor.cs │ └── SchemaLoader.cs ├── Bundle │ ├── Bundle.csproj │ ├── BundleException.cs │ ├── Bundler.cs │ ├── FragmentFinder.cs │ ├── OpenApiDiagnosticWrite.cs │ ├── Program.cs │ ├── ReferenceInfo.cs │ ├── ReferenceInfoCollection.cs │ ├── ReferenceLoader.cs │ ├── ReferencePath.cs │ ├── ReferenceResolver.cs │ ├── ReferenceVisitor.cs │ ├── ReferenceWalker.cs │ ├── SchemaLoader.cs │ └── YamlMappingNodeExtensions.cs ├── Generator │ ├── ApiFirst │ │ ├── ApiBaseGenerator.cs │ │ ├── ApiFirstGenerator.cs │ │ ├── CSharpHelpers.cs │ │ ├── ModelDefinition.cs │ │ ├── ModelFinder.cs │ │ ├── ModelGenerator.cs │ │ ├── ModelProperty.cs │ │ ├── ParameterHelpers.cs │ │ ├── PathItemHelpers.cs │ │ ├── ResultHelper.cs │ │ ├── SchemaHelpers.cs │ │ └── StatusCodeHelper.cs │ ├── Controllers │ │ ├── ActionMethodParameter.cs │ │ └── BaseActionMethodGenerator.cs │ ├── Generate.cs │ ├── Generator.csproj │ ├── Internal │ │ └── IndentedTextWriterExtensions.cs │ ├── MinimalApi │ │ ├── MinimalApiGenerator.cs │ │ └── Project.xml │ └── Program.cs ├── Testing.Xunit │ ├── Testing.Xunit.csproj │ └── XunitAssertExtension.cs ├── Testing │ ├── HttpClientExtensions.cs │ ├── Internal │ │ ├── JsonDocumentExtensions.cs │ │ ├── LinqExtensions.cs │ │ ├── OpenApiModelExtensions.cs │ │ ├── QueryString.cs │ │ ├── YamlExtensions.cs │ │ └── YamlToJson.cs │ ├── JsonAssert.cs │ ├── JsonEqualException.cs │ ├── OpenApiTest.cs │ ├── OpenApiTestBody.cs │ ├── OpenApiTestDocument.cs │ ├── OpenApiTestDocumentParser.cs │ ├── OpenApiTestElement.cs │ ├── OpenApiTestExpect.cs │ ├── OpenApiTestPath.cs │ ├── OpenApiTestRequest.cs │ ├── OpenApiTestResponse.cs │ ├── OpenApiTheoryData.cs │ └── Testing.csproj └── Web │ ├── ElementsEndpoint.cs │ ├── EndpointConventionBuilderExtensions.cs │ ├── RedocEndpoint.cs │ ├── Resources │ ├── elements.html │ └── redoc.html │ ├── StaticOpenApiEndpointRouteBuilderExtensions.cs │ ├── StaticOpenApiLoadException.cs │ ├── StaticOpenApiOptions.cs │ ├── SwaggerUiEndpoints.cs │ ├── Web.csproj │ ├── package-lock.json │ └── package.json ├── test ├── Analyzer.Tests │ ├── Analyzer.Tests.csproj │ ├── UnitTest1.cs │ └── Usings.cs ├── Bundle.Tests │ ├── Bundle.Tests.csproj │ ├── FragmentFinderTests.cs │ ├── ReferenceWalkerTests.cs │ ├── TestData │ │ ├── Responses │ │ │ └── InternalServerError.yaml │ │ ├── Schema │ │ │ ├── Country.json │ │ │ ├── IsoCountryCode.json │ │ │ └── ProblemDetails.json │ │ ├── openapi.json │ │ └── openapi.yaml │ ├── Usings.cs │ └── YamlTest.cs ├── Generator.Tests │ ├── ApiBaseGeneratorTests.cs │ ├── BaseActionMethodGeneratorTests.cs │ ├── Generator.Tests.csproj │ ├── ModelFinderTests.cs │ ├── ModelGeneratorTests.cs │ ├── Usings.cs │ ├── Writer.cs │ └── openapi.yaml ├── Testing.Api │ ├── Data │ │ ├── Book.cs │ │ ├── BookData.cs │ │ └── NewBook.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Testing.Api.csproj │ ├── appsettings.Development.json │ └── appsettings.json ├── Testing.Tests │ ├── Api │ │ └── openapi.tests.yaml │ ├── ApiTests.cs │ ├── HttpBin │ │ ├── json │ │ │ ├── openapi.json │ │ │ └── openapi.tests.json │ │ └── yaml │ │ │ ├── openapi.tests.yaml │ │ │ └── openapi.yaml │ ├── MemberDataTests.cs │ ├── OpenApiTestDocumentParserTests.cs │ ├── OpenTheoryDataTests.cs │ ├── ResourceStrings.cs │ ├── SequenceTests.cs │ ├── Testing.Tests.csproj │ └── Usings.cs ├── Testing.WebApi │ ├── Controllers │ │ └── WeatherForecastImpl.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Testing.WebApi.csproj │ ├── WeatherForecast.cs │ ├── appsettings.Development.json │ └── appsettings.json ├── Web.TestApp │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Web.TestApp.csproj │ ├── api.md │ ├── appsettings.Development.json │ ├── appsettings.json │ └── openapi.yaml └── WebApi.TestApp │ ├── Controllers │ └── WeatherForecastController.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── WeatherForecast.cs │ ├── WebApi.TestApp.csproj │ ├── appsettings.Development.json │ └── appsettings.json └── ui ├── package-lock.json └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Rider 35 | .idea/ 36 | 37 | # Visual Studio 2015/2017 cache/options directory 38 | .vs/ 39 | # Uncomment if you have tasks that create the project's static files in wwwroot 40 | #wwwroot/ 41 | 42 | # Visual Studio 2017 auto generated files 43 | Generated\ Files/ 44 | 45 | # MSTest test Results 46 | [Tt]est[Rr]esult*/ 47 | [Bb]uild[Ll]og.* 48 | 49 | # NUnit 50 | *.VisualState.xml 51 | TestResult.xml 52 | nunit-*.xml 53 | 54 | # Build Results of an ATL Project 55 | [Dd]ebugPS/ 56 | [Rr]eleasePS/ 57 | dlldata.c 58 | 59 | # Benchmark Results 60 | BenchmarkDotNet.Artifacts/ 61 | 62 | # .NET Core 63 | project.lock.json 64 | project.fragment.lock.json 65 | artifacts/ 66 | 67 | # StyleCop 68 | StyleCopReport.xml 69 | 70 | # Files built by Visual Studio 71 | *_i.c 72 | *_p.c 73 | *_h.h 74 | *.ilk 75 | *.meta 76 | *.obj 77 | *.iobj 78 | *.pch 79 | *.pdb 80 | *.ipdb 81 | *.pgc 82 | *.pgd 83 | *.rsp 84 | *.sbr 85 | *.tlb 86 | *.tli 87 | *.tlh 88 | *.tmp 89 | *.tmp_proj 90 | *_wpftmp.csproj 91 | *.log 92 | *.vspscc 93 | *.vssscc 94 | .builds 95 | *.pidb 96 | *.svclog 97 | *.scc 98 | 99 | # Chutzpah Test files 100 | _Chutzpah* 101 | 102 | # Visual C++ cache files 103 | ipch/ 104 | *.aps 105 | *.ncb 106 | *.opendb 107 | *.opensdf 108 | *.sdf 109 | *.cachefile 110 | *.VC.db 111 | *.VC.VC.opendb 112 | 113 | # Visual Studio profiler 114 | *.psess 115 | *.vsp 116 | *.vspx 117 | *.sap 118 | 119 | # Visual Studio Trace Files 120 | *.e2e 121 | 122 | # TFS 2012 Local Workspace 123 | $tf/ 124 | 125 | # Guidance Automation Toolkit 126 | *.gpState 127 | 128 | # ReSharper is a .NET coding add-in 129 | _ReSharper*/ 130 | *.[Rr]e[Ss]harper 131 | *.DotSettings.user 132 | 133 | # TeamCity is a build add-in 134 | _TeamCity* 135 | 136 | # DotCover is a Code Coverage Tool 137 | *.dotCover 138 | 139 | # AxoCover is a Code Coverage Tool 140 | .axoCover/* 141 | !.axoCover/settings.json 142 | 143 | # Visual Studio code coverage results 144 | *.coverage 145 | *.coveragexml 146 | 147 | # NCrunch 148 | _NCrunch_* 149 | .*crunch*.local.xml 150 | nCrunchTemp_* 151 | 152 | # MightyMoose 153 | *.mm.* 154 | AutoTest.Net/ 155 | 156 | # Web workbench (sass) 157 | .sass-cache/ 158 | 159 | # Installshield output folder 160 | [Ee]xpress/ 161 | 162 | # DocProject is a documentation generator add-in 163 | DocProject/buildhelp/ 164 | DocProject/Help/*.HxT 165 | DocProject/Help/*.HxC 166 | DocProject/Help/*.hhc 167 | DocProject/Help/*.hhk 168 | DocProject/Help/*.hhp 169 | DocProject/Help/Html2 170 | DocProject/Help/html 171 | 172 | # Click-Once directory 173 | publish/ 174 | 175 | # Publish Web Output 176 | *.[Pp]ublish.xml 177 | *.azurePubxml 178 | # Note: Comment the next line if you want to checkin your web deploy settings, 179 | # but database connection strings (with potential passwords) will be unencrypted 180 | *.pubxml 181 | *.publishproj 182 | 183 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 184 | # checkin your Azure Web App publish settings, but sensitive information contained 185 | # in these scripts will be unencrypted 186 | PublishScripts/ 187 | 188 | # NuGet Packages 189 | *.nupkg 190 | # NuGet Symbol Packages 191 | *.snupkg 192 | # The packages folder can be ignored because of Package Restore 193 | **/[Pp]ackages/* 194 | # except build/, which is used as an MSBuild target. 195 | !**/[Pp]ackages/build/ 196 | # Uncomment if necessary however generally it will be regenerated when needed 197 | #!**/[Pp]ackages/repositories.config 198 | # NuGet v3's project.json files produces more ignorable files 199 | *.nuget.props 200 | *.nuget.targets 201 | 202 | # Microsoft Azure Build Output 203 | csx/ 204 | *.build.csdef 205 | 206 | # Microsoft Azure Emulator 207 | ecf/ 208 | rcf/ 209 | 210 | # Windows Store app package directories and files 211 | AppPackages/ 212 | BundleArtifacts/ 213 | Package.StoreAssociation.xml 214 | _pkginfo.txt 215 | *.appx 216 | *.appxbundle 217 | *.appxupload 218 | 219 | # Visual Studio cache files 220 | # files ending in .cache can be ignored 221 | *.[Cc]ache 222 | # but keep track of directories ending in .cache 223 | !?*.[Cc]ache/ 224 | 225 | # Others 226 | ClientBin/ 227 | ~$* 228 | *~ 229 | *.dbmdl 230 | *.dbproj.schemaview 231 | *.jfm 232 | *.pfx 233 | *.publishsettings 234 | orleans.codegen.cs 235 | 236 | # Including strong name files can present a security risk 237 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 238 | #*.snk 239 | 240 | # Since there are multiple workflows, uncomment next line to ignore bower_components 241 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 242 | #bower_components/ 243 | 244 | # RIA/Silverlight projects 245 | Generated_Code/ 246 | 247 | # Backup & report files from converting an old project file 248 | # to a newer Visual Studio version. Backup files are not needed, 249 | # because we have git ;-) 250 | _UpgradeReport_Files/ 251 | Backup*/ 252 | UpgradeLog*.XML 253 | UpgradeLog*.htm 254 | ServiceFabricBackup/ 255 | *.rptproj.bak 256 | 257 | # SQL Server files 258 | *.mdf 259 | *.ldf 260 | *.ndf 261 | 262 | # Business Intelligence projects 263 | *.rdl.data 264 | *.bim.layout 265 | *.bim_*.settings 266 | *.rptproj.rsuser 267 | *- [Bb]ackup.rdl 268 | *- [Bb]ackup ([0-9]).rdl 269 | *- [Bb]ackup ([0-9][0-9]).rdl 270 | 271 | # Microsoft Fakes 272 | FakesAssemblies/ 273 | 274 | # GhostDoc plugin setting file 275 | *.GhostDoc.xml 276 | 277 | # Node.js Tools for Visual Studio 278 | .ntvs_analysis.dat 279 | node_modules/ 280 | 281 | # Visual Studio 6 build log 282 | *.plg 283 | 284 | # Visual Studio 6 workspace options file 285 | *.opt 286 | 287 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 288 | *.vbw 289 | 290 | # Visual Studio LightSwitch build output 291 | **/*.HTMLClient/GeneratedArtifacts 292 | **/*.DesktopClient/GeneratedArtifacts 293 | **/*.DesktopClient/ModelManifest.xml 294 | **/*.Server/GeneratedArtifacts 295 | **/*.Server/ModelManifest.xml 296 | _Pvt_Extensions 297 | 298 | # Paket dependency manager 299 | .paket/paket.exe 300 | paket-files/ 301 | 302 | # FAKE - F# Make 303 | .fake/ 304 | 305 | # CodeRush personal settings 306 | .cr/personal 307 | 308 | # Python Tools for Visual Studio (PTVS) 309 | __pycache__/ 310 | *.pyc 311 | 312 | # Cake - Uncomment if you are using it 313 | # tools/** 314 | # !tools/packages.config 315 | 316 | # Tabs Studio 317 | *.tss 318 | 319 | # Telerik's JustMock configuration file 320 | *.jmconfig 321 | 322 | # BizTalk build output 323 | *.btp.cs 324 | *.btm.cs 325 | *.odx.cs 326 | *.xsd.cs 327 | 328 | # OpenCover UI analysis results 329 | OpenCover/ 330 | 331 | # Azure Stream Analytics local run output 332 | ASALocalRun/ 333 | 334 | # MSBuild Binary and Structured Log 335 | *.binlog 336 | 337 | # NVidia Nsight GPU debugger configuration file 338 | *.nvuser 339 | 340 | # MFractors (Xamarin productivity tool) working folder 341 | .mfractor/ 342 | 343 | # Local History for Visual Studio 344 | .localhistory/ 345 | 346 | # BeatPulse healthcheck temp database 347 | healthchecksdb 348 | 349 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 350 | MigrationBackup/ 351 | 352 | # Ionide (cross platform F# VS Code tools) working folder 353 | .ionide/ 354 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 RendleLabs 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenApi 2 | Libraries for working with static OpenApi files and testing OpenApi implementations 3 | -------------------------------------------------------------------------------- /RendleLabs.OpenApi.sln.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True 3 | True 4 | True -------------------------------------------------------------------------------- /experiments/ApiBase/Api/Books.cs: -------------------------------------------------------------------------------- 1 | using ApiBase.Data; 2 | using ApiBase.Models; 3 | 4 | namespace ApiBase.Api; 5 | 6 | public sealed class Books : BooksBase 7 | { 8 | private readonly BookData _data; 9 | private readonly ILogger _logger; 10 | 11 | public Books(BookData data, ILogger logger) 12 | { 13 | _data = data; 14 | _logger = logger; 15 | } 16 | 17 | protected override ValueTask Get(int id, HttpContext context) 18 | { 19 | try 20 | { 21 | var book = _data.Get(id); 22 | return new ValueTask(book is null 23 | ? NotFound() 24 | : Ok(book)); 25 | } 26 | catch (Exception ex) 27 | { 28 | _logger.LogError(ex, "Books.Get failed"); 29 | throw; 30 | } 31 | } 32 | 33 | protected override ValueTask Add(Book book, HttpContext context) 34 | { 35 | book = _data.Add(book); 36 | return new ValueTask(Created(Links.Get(book.Id))); 37 | } 38 | } -------------------------------------------------------------------------------- /experiments/ApiBase/Api/BooksBase.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using System.Text; 3 | using Microsoft.AspNetCore.Mvc; 4 | using ApiBase.Models; 5 | 6 | namespace ApiBase.Api; 7 | 8 | [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] 9 | public abstract partial class BooksBase 10 | { 11 | private static readonly IResult NotImplementedResult = Results.StatusCode(501); 12 | 13 | private static void __Map(WebApplication app, Func builder) where T : BooksBase 14 | { 15 | app.MapGet("/books/{id:int}", (int id, HttpContext context) => 16 | { 17 | var impl = context.RequestServices.GetService() ?? builder(context.RequestServices); 18 | return impl.Get(id, context); 19 | }); 20 | 21 | app.MapPost("/books", ([FromBody] Book book, HttpContext context) => 22 | { 23 | var impl = context.RequestServices.GetService() ?? builder(context.RequestServices); 24 | return impl.Add(book, context); 25 | }); 26 | } 27 | 28 | protected static IResult Ok(Book book) => Results.Ok(book); 29 | protected static IResult Created(Uri uri) => Results.Created(uri, null); 30 | protected static IResult NotFound() => Results.NotFound(); 31 | 32 | public static LinkProvider Links { get; } = new LinkProvider(); 33 | 34 | public readonly struct LinkProvider 35 | { 36 | public Uri Get(int id, string? format = null) => new($"/books/{id}{GetQueryString(format)}", UriKind.Relative); 37 | public Uri Add() => new Uri("/books", UriKind.Relative); 38 | 39 | private static string GetQueryString(string? format) 40 | { 41 | if (format is null) return string.Empty; 42 | var builder = new StringBuilder(); 43 | if (format is not null) 44 | { 45 | if (builder.Length == 0) 46 | { 47 | builder.Append('?'); 48 | } 49 | else 50 | { 51 | builder.Append('&'); 52 | } 53 | 54 | builder.Append($"format={Uri.EscapeDataString(format)}"); 55 | } 56 | 57 | return builder.ToString(); 58 | } 59 | } 60 | 61 | protected virtual ValueTask Get(int id, HttpContext context) => new(NotImplementedResult); 62 | 63 | protected virtual ValueTask Add(Book book, HttpContext context) => new(NotImplementedResult); 64 | } -------------------------------------------------------------------------------- /experiments/ApiBase/Api/MapApiExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace ApiBase.Api; 4 | 5 | public static class MapApiExtension 6 | { 7 | public static WebApplication MapApi(this WebApplication app) 8 | { 9 | var mapMethod = GetMapMethod(); 10 | mapMethod.Invoke(null, new object[]{ app, CreateBuilder() }); 11 | return app; 12 | } 13 | 14 | private static MethodInfo GetMapMethod() 15 | { 16 | var type = typeof(T); 17 | MethodInfo? mapMethod = null; 18 | while (mapMethod is null && type is not null) 19 | { 20 | mapMethod = type.GetMethod("__Map", BindingFlags.Static | BindingFlags.NonPublic); 21 | type = type.BaseType; 22 | } 23 | 24 | if (mapMethod is null) throw new InvalidOperationException(); 25 | return mapMethod.MakeGenericMethod(typeof(T)); 26 | } 27 | 28 | private static Func CreateBuilder() 29 | { 30 | var ctors = typeof(T).GetConstructors(BindingFlags.Public | BindingFlags.Instance); 31 | var ctor = ctors.FirstOrDefault(); 32 | if (ctor is null) return _ => Activator.CreateInstance(); 33 | var parameterTypes = ctor.GetParameters(); 34 | return services => 35 | { 36 | int length = parameterTypes.Length; 37 | object[] parameters = new object[length]; 38 | for (int i = 0; i < length; i++) 39 | { 40 | var parameterType = parameterTypes[i].ParameterType; 41 | parameters[i] = services.GetRequiredService(parameterType); 42 | } 43 | 44 | return (T)Activator.CreateInstance(typeof(T), parameters)!; 45 | }; 46 | } 47 | } -------------------------------------------------------------------------------- /experiments/ApiBase/ApiBase.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /experiments/ApiBase/Data/BookData.cs: -------------------------------------------------------------------------------- 1 | using ApiBase.Models; 2 | 3 | namespace ApiBase.Data; 4 | 5 | public class BookData 6 | { 7 | private readonly Dictionary _books = new() 8 | { 9 | [1] = new Book { Id = 1, Title = "Mort", Author = "Terry Pratchett", Year = 1987 }, 10 | [42] = new Book { Id = 42, Title = "The Hitchhiker's Guide to the Galaxy", Author = "Douglas Adams", Year = 1979 }, 11 | }; 12 | 13 | private readonly object _mutex = new(); 14 | 15 | public Book? Get(int id) 16 | { 17 | return _books.TryGetValue(id, out var book) ? book : null; 18 | } 19 | 20 | public Book Add(Book book) 21 | { 22 | lock (_mutex) 23 | { 24 | var id = _books.Keys.Max() + 1; 25 | book = new Book 26 | { 27 | Id = id, 28 | Title = book.Title, 29 | Author = book.Author, 30 | Year = book.Year 31 | }; 32 | _books.Add(id, book); 33 | } 34 | 35 | return book; 36 | } 37 | } -------------------------------------------------------------------------------- /experiments/ApiBase/Models/Book.cs: -------------------------------------------------------------------------------- 1 | namespace ApiBase.Models; 2 | 3 | public partial class Book 4 | { 5 | public int Id { get; init; } 6 | public string Title { get; set; } 7 | public string Author { get; set; } 8 | public int Year { get; set; } 9 | } -------------------------------------------------------------------------------- /experiments/ApiBase/Program.cs: -------------------------------------------------------------------------------- 1 | using ApiBase.Api; 2 | using ApiBase.Data; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | builder.Services.AddSingleton(); 7 | 8 | var app = builder.Build(); 9 | 10 | app.MapGet("/", () => "Hello World!"); 11 | 12 | app.MapApi(); 13 | 14 | app.Run(); 15 | -------------------------------------------------------------------------------- /experiments/ApiBase/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "ApiBase": { 4 | "commandName": "Project", 5 | "dotnetRunMessages": true, 6 | "launchBrowser": false, 7 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 8 | "environmentVariables": { 9 | "ASPNETCORE_ENVIRONMENT": "Development" 10 | } 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /experiments/ApiBase/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /experiments/ApiBase/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "rollForward": "latestFeature", 4 | "version": "6.0.400" 5 | } 6 | } -------------------------------------------------------------------------------- /src/Analyzer/Analyzer.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | enable 6 | enable 7 | latest 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/Analyzer/AttributeHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace Analyzer; 4 | 5 | internal static class AttributeHelper 6 | { 7 | public static bool HasHttpMethodAttribute(this IMethodSymbol methodSymbol) 8 | { 9 | foreach (var attribute in methodSymbol.GetAttributes().AsSpan()) 10 | { 11 | if (IsHttpMethodAttribute(attribute.AttributeClass)) return true; 12 | } 13 | 14 | return false; 15 | } 16 | 17 | private static bool IsHttpMethodAttribute(INamedTypeSymbol? namedTypeSymbol) 18 | { 19 | return namedTypeSymbol is not null 20 | && HttpMethodAttributes.Contains(namedTypeSymbol.Name) 21 | && namedTypeSymbol.ContainingNamespace.Is("Microsoft.AspNetCore.Mvc"); 22 | } 23 | 24 | private static readonly HashSet HttpMethodAttributes = new() 25 | { 26 | "HttpGetAttribute", "HttpPostAttribute", "HttpPutAttribute", "HttpPatchAttribute", 27 | "HttpDeleteAttribute", "HttpOptionsAttribute", "HttpHeadAttribute" 28 | }; 29 | } -------------------------------------------------------------------------------- /src/Analyzer/ControllerAnalyzer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using Microsoft.CodeAnalysis; 3 | using Microsoft.CodeAnalysis.Diagnostics; 4 | 5 | namespace Analyzer; 6 | 7 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 8 | public class ControllerAnalyzer : DiagnosticAnalyzer 9 | { 10 | public const string DiagnosticId = "DotLabs.OpenApi"; 11 | 12 | public override void Initialize(AnalysisContext context) 13 | { 14 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 15 | context.EnableConcurrentExecution(); 16 | 17 | context.RegisterSymbolAction(AnalyzeNamedType, SymbolKind.NamedType); 18 | context.RegisterSymbolAction(AnalyzeMethod, SymbolKind.Method); 19 | } 20 | 21 | private static void AnalyzeNamedType(SymbolAnalysisContext context) 22 | { 23 | } 24 | 25 | private static void AnalyzeMethod(SymbolAnalysisContext context) 26 | { 27 | var symbol = (IMethodSymbol)context.Symbol; 28 | 29 | if (!symbol.ContainingType.Inherits("Microsoft.AspNetCore.Mvc.ControllerBase")) return; 30 | 31 | if (!symbol.HasHttpMethodAttribute()) return; 32 | 33 | } 34 | 35 | public override ImmutableArray SupportedDiagnostics { get; } 36 | } 37 | 38 | internal static class AttributeHelper 39 | { 40 | public static bool HasHttpMethodAttribute(this IMethodSymbol methodSymbol) 41 | { 42 | foreach (var attribute in methodSymbol.GetAttributes().AsSpan()) 43 | { 44 | if (IsHttpMethodAttribute(attribute.AttributeClass)) return true; 45 | } 46 | 47 | return false; 48 | } 49 | 50 | private static bool IsHttpMethodAttribute(INamedTypeSymbol? namedTypeSymbol) 51 | { 52 | return namedTypeSymbol is not null 53 | && HttpMethodAttributes.Contains(namedTypeSymbol.Name) 54 | && namedTypeSymbol.ContainingNamespace.Is("Microsoft.AspNetCore.Mvc"); 55 | } 56 | 57 | private static readonly HashSet HttpMethodAttributes = new() 58 | { 59 | "HttpGetAttribute", "HttpPostAttribute", "HttpPutAttribute", "HttpPatchAttribute", 60 | "HttpDeleteAttribute", "HttpOptionsAttribute", "HttpHeadAttribute" 61 | }; 62 | } 63 | 64 | internal static class TypeHelper 65 | { 66 | public static bool Inherits(this INamedTypeSymbol namedTypeSymbol, string fullTypeName) => Inherits(namedTypeSymbol, fullTypeName.AsSpan()); 67 | 68 | public static bool Inherits(this INamedTypeSymbol namedTypeSymbol, ReadOnlySpan fullTypeName) 69 | { 70 | var typeName = TextHelpers.GetLastToken(ref fullTypeName, '.'); 71 | 72 | for (var baseType = namedTypeSymbol.BaseType; baseType is not null; baseType = baseType.BaseType) 73 | { 74 | if (baseType.Name.AsSpan() == typeName && baseType.ContainingNamespace.Is("Microsoft.AspNetCore.Mvc")) 75 | { 76 | } 77 | } 78 | 79 | return false; 80 | } 81 | } 82 | 83 | internal static class NamespaceHelper 84 | { 85 | public static bool Is(this INamespaceSymbol namespaceSymbol, string name) => Is(namespaceSymbol, name.AsSpan()); 86 | 87 | public static bool Is(this INamespaceSymbol namespaceSymbol, ReadOnlySpan name) 88 | { 89 | while (name.Length > 0) 90 | { 91 | var section = TextHelpers.GetLastToken(ref name, '.'); 92 | if (section != namespaceSymbol.Name.AsSpan()) 93 | { 94 | return false; 95 | } 96 | 97 | namespaceSymbol = namespaceSymbol.ContainingNamespace; 98 | } 99 | 100 | return namespaceSymbol.IsGlobalNamespace; 101 | } 102 | } 103 | 104 | public static class TextHelpers 105 | { 106 | public static ReadOnlySpan GetLastToken(ref ReadOnlySpan text, char delimiter) 107 | { 108 | int index = text.LastIndexOf(delimiter); 109 | ReadOnlySpan result; 110 | if (index < 0) 111 | { 112 | result = text.Slice(0); 113 | text = ReadOnlySpan.Empty; 114 | } 115 | else 116 | { 117 | result = text.Slice(index + 1); 118 | text = text.Slice(0, index); 119 | } 120 | 121 | return result; 122 | } 123 | } -------------------------------------------------------------------------------- /src/Analyzer/Facts/IsActionMethodExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace Analyzer.Facts; 4 | 5 | public static class IsActionMethodExtension 6 | { 7 | public static bool IsAction(this IMethodSymbol methodSymbol) 8 | { 9 | if (methodSymbol.MethodKind != MethodKind.Ordinary) return false; 10 | if (methodSymbol.DeclaredAccessibility != Accessibility.Public) return false; 11 | if (!methodSymbol.ContainingType.IsController()) return false; 12 | if (methodSymbol.GetAttributes().Any(IsNonActionAttribute)) return false; 13 | 14 | return true; 15 | } 16 | 17 | private static bool IsNonActionAttribute(AttributeData a) => 18 | a.AttributeClass.Name == "NonActionAttribute" 19 | && a.AttributeClass.ContainingNamespace.Is("Microsoft.AspNetCore.Mvc"); 20 | } -------------------------------------------------------------------------------- /src/Analyzer/Facts/IsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace Analyzer.Facts; 4 | 5 | public static class IsControllerExtension 6 | { 7 | public static bool IsController(this INamedTypeSymbol symbol) 8 | { 9 | return InheritsControllerBase(symbol) 10 | || HasApiControllerAttribute(symbol); 11 | } 12 | 13 | private static bool InheritsControllerBase(INamedTypeSymbol symbol) => 14 | symbol.Inherits("Microsoft.AspNetCore.Mvc.ControllerBase"); 15 | 16 | private static bool HasApiControllerAttribute(INamedTypeSymbol symbol) => 17 | symbol.GetAttributes() 18 | .Any(IsApiControllerAttribute); 19 | 20 | private static bool IsApiControllerAttribute(AttributeData a) => 21 | a.AttributeClass.Name == "ApiController" 22 | && a.AttributeClass.ContainingNamespace.Is("Microsoft.AspNetCore.Mvc"); 23 | } -------------------------------------------------------------------------------- /src/Analyzer/NamespaceHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace Analyzer; 4 | 5 | internal static class NamespaceHelper 6 | { 7 | public static bool Is(this INamespaceSymbol namespaceSymbol, string name) => Is(namespaceSymbol, name.AsSpan()); 8 | 9 | public static bool Is(this INamespaceSymbol namespaceSymbol, ReadOnlySpan name) 10 | { 11 | while (name.Length > 0) 12 | { 13 | var section = TextHelpers.GetLastToken(ref name, '.'); 14 | if (section != namespaceSymbol.Name.AsSpan()) 15 | { 16 | return false; 17 | } 18 | 19 | namespaceSymbol = namespaceSymbol.ContainingNamespace; 20 | } 21 | 22 | return namespaceSymbol.IsGlobalNamespace; 23 | } 24 | } -------------------------------------------------------------------------------- /src/Analyzer/TextHelpers.cs: -------------------------------------------------------------------------------- 1 | namespace Analyzer; 2 | 3 | public static class TextHelpers 4 | { 5 | public static ReadOnlySpan GetLastToken(ref ReadOnlySpan text, char delimiter) 6 | { 7 | int index = text.LastIndexOf(delimiter); 8 | ReadOnlySpan result; 9 | if (index < 0) 10 | { 11 | result = text.Slice(0); 12 | text = ReadOnlySpan.Empty; 13 | } 14 | else 15 | { 16 | result = text.Slice(index + 1); 17 | text = text.Slice(0, index); 18 | } 19 | 20 | return result; 21 | } 22 | } -------------------------------------------------------------------------------- /src/Analyzer/TypeHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using Microsoft.CodeAnalysis; 3 | using Microsoft.CodeAnalysis.CSharp.Syntax; 4 | 5 | namespace Analyzer; 6 | 7 | internal static class TypeHelper 8 | { 9 | public static bool Inherits(this INamedTypeSymbol namedTypeSymbol, string fullTypeName) => Inherits(namedTypeSymbol, fullTypeName.AsSpan()); 10 | 11 | public static bool Inherits(this INamedTypeSymbol namedTypeSymbol, ReadOnlySpan fullTypeName) 12 | { 13 | var typeName = TextHelpers.GetLastToken(ref fullTypeName, '.'); 14 | 15 | for (var baseType = namedTypeSymbol.BaseType; baseType is not null; baseType = baseType.BaseType) 16 | { 17 | if (baseType.Name.AsSpan() == typeName && baseType.ContainingNamespace.Is("Microsoft.AspNetCore.Mvc")) 18 | { 19 | } 20 | } 21 | 22 | return false; 23 | } 24 | 25 | public static bool TryGetNamedType(this SemanticModel model, ExpressionSyntax syntax, out INamedTypeSymbol? namedTypeSymbol) 26 | { 27 | if (model.GetTypeInfo(syntax).Type is INamedTypeSymbol symbol) 28 | { 29 | namedTypeSymbol = symbol; 30 | return true; 31 | } 32 | 33 | namedTypeSymbol = null; 34 | return false; 35 | } 36 | } 37 | 38 | internal static class MethodHelpers 39 | { 40 | public static ImmutableHashSet GetReturnedTypes(this IMethodSymbol methodSymbol, Compilation compilation, CancellationToken cancellation) 41 | { 42 | var builder = ImmutableHashSet.CreateBuilder(SymbolEqualityComparer.Default); 43 | 44 | foreach (var syntaxReference in methodSymbol.DeclaringSyntaxReferences) 45 | { 46 | var semanticModel = compilation.GetSemanticModel(syntaxReference.SyntaxTree); 47 | 48 | var node = (MethodDeclarationSyntax)syntaxReference.GetSyntax(cancellation); 49 | 50 | if (node.Body is not null) 51 | { 52 | var returnStatements = node.DescendantNodes() 53 | .OfType(); 54 | 55 | foreach (var returnStatement in returnStatements) 56 | { 57 | if (semanticModel.TryGetNamedType(returnStatement.Expression, out var namedTypeSymbol)) 58 | { 59 | builder.Add(namedTypeSymbol); 60 | } 61 | } 62 | } 63 | else if (node.ExpressionBody is not null) 64 | { 65 | if (semanticModel.TryGetNamedType(node.ExpressionBody.Expression, out var namedTypeSymbol)) 66 | { 67 | builder.Add(namedTypeSymbol); 68 | } 69 | } 70 | } 71 | 72 | return builder.ToImmutable(); 73 | } 74 | } -------------------------------------------------------------------------------- /src/Build/Build.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/Build/Builder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | using Microsoft.OpenApi.Readers; 3 | using Microsoft.OpenApi.Services; 4 | 5 | namespace Build; 6 | 7 | public sealed class Builder : IDisposable 8 | { 9 | private readonly Stream _source; 10 | private readonly string _filePath; 11 | private readonly string _directory; 12 | 13 | public Builder(Stream source, string filePath) 14 | { 15 | _source = source; 16 | _filePath = filePath; 17 | _directory = Path.GetDirectoryName(filePath)!; 18 | } 19 | 20 | public async Task Build() 21 | { 22 | // var settings = new OpenApiReaderSettings 23 | // { 24 | // LoadExternalRefs = true, 25 | // BaseUrl = new Uri(_filePath), 26 | // }; 27 | 28 | var result = await new OpenApiStreamReader().ReadAsync(_source); 29 | 30 | result.OpenApiDiagnostic.Write(); 31 | 32 | if (result.OpenApiDiagnostic.Errors is { Count: > 0 } errors) 33 | { 34 | return null; 35 | } 36 | 37 | var referenceVisitor = new ReferenceVisitor(result.OpenApiDocument, _directory); 38 | var walker = new OpenApiWalker(referenceVisitor); 39 | 40 | do 41 | { 42 | referenceVisitor.AnyChanges = false; 43 | walker.Walk(result.OpenApiDocument); 44 | } while (referenceVisitor.AnyChanges); 45 | 46 | return result.OpenApiDocument; 47 | } 48 | 49 | public void Dispose() 50 | { 51 | _source.Dispose(); 52 | } 53 | } -------------------------------------------------------------------------------- /src/Build/OpenApiDiagnosticWrite.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | using Microsoft.OpenApi.Readers; 3 | 4 | namespace Build; 5 | 6 | internal static class OpenApiDiagnosticWrite 7 | { 8 | public static void Write(this OpenApiDiagnostic diagnostic) 9 | { 10 | if (diagnostic.Warnings is { Count: > 0 } warnings) 11 | { 12 | WriteWarnings(warnings); 13 | } 14 | 15 | if (diagnostic.Errors is { Count: > 0 } errors) 16 | { 17 | WriteErrors(errors); 18 | } 19 | } 20 | 21 | private static void WriteErrors(IList errors) 22 | { 23 | foreach (var error in errors) 24 | { 25 | Console.WriteLine($"ERROR: [{error.Pointer}] {error.Message}"); 26 | } 27 | } 28 | 29 | private static void WriteWarnings(IList warnings) 30 | { 31 | foreach (var warning in warnings) 32 | { 33 | Console.WriteLine($"WARNING: [{warning.Pointer}] {warning.Message}"); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/Build/Program.cs: -------------------------------------------------------------------------------- 1 | // See https://aka.ms/new-console-template for more information 2 | Console.WriteLine("Hello, World!"); 3 | -------------------------------------------------------------------------------- /src/Build/ReferenceVisitor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Interfaces; 2 | using Microsoft.OpenApi.Models; 3 | using Microsoft.OpenApi.Services; 4 | using Path = System.IO.Path; 5 | 6 | namespace Build; 7 | 8 | public class ReferenceVisitor : OpenApiVisitorBase 9 | { 10 | private readonly OpenApiDocument _document; 11 | private readonly string _baseDirectory; 12 | private readonly SchemaLoader _schemaLoader; 13 | 14 | public bool AnyChanges { get; set; } 15 | public Dictionary PathToIdLookup { get; } = new(StringComparer.OrdinalIgnoreCase); 16 | 17 | public ReferenceVisitor(OpenApiDocument document, string baseDirectory) 18 | { 19 | _schemaLoader = new SchemaLoader(); 20 | _document = document; 21 | _baseDirectory = baseDirectory; 22 | } 23 | 24 | public override void Visit(IOpenApiReferenceable referenceable) 25 | { 26 | if (referenceable is not OpenApiSchema) return; 27 | if (!referenceable.UnresolvedReference) return; 28 | if (!referenceable.Reference.IsExternal) return; 29 | if (referenceable.Reference.ExternalResource is not { Length: > 0 } externalResource) return; 30 | 31 | var path = Path.GetFullPath(externalResource, _baseDirectory); 32 | 33 | if (!PathToIdLookup.TryGetValue(path, out var id)) 34 | { 35 | var schema = _schemaLoader.LoadSchema(path, out var diagnostic); 36 | if (schema is null) return; 37 | 38 | AnyChanges = true; 39 | 40 | id = GetComponentId(path); 41 | 42 | PathToIdLookup[path] = id; 43 | 44 | _document.Components ??= new OpenApiComponents(); 45 | _document.Components.Schemas[id] = schema; 46 | } 47 | 48 | referenceable.Reference = new OpenApiReference 49 | { 50 | Id = id, 51 | Type = ReferenceType.Schema, 52 | HostDocument = _document, 53 | }; 54 | referenceable.UnresolvedReference = false; 55 | } 56 | 57 | private static string GetComponentId(string path) 58 | { 59 | var fileName = Path.GetFileNameWithoutExtension(path.AsSpan()).TrimStart('.'); 60 | int dot = fileName.IndexOf('.'); 61 | if (dot > -1) 62 | { 63 | fileName = fileName[..dot]; 64 | } 65 | 66 | return new string(fileName); 67 | } 68 | } -------------------------------------------------------------------------------- /src/Build/SchemaLoader.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using Microsoft.OpenApi; 3 | using Microsoft.OpenApi.Models; 4 | using Microsoft.OpenApi.Readers; 5 | 6 | namespace Build; 7 | 8 | public class SchemaLoader 9 | { 10 | private static readonly HashSet IgnoreErrors = new HashSet 11 | { 12 | "$schema is not a valid property at #/", 13 | "$id is not a valid property at #/", 14 | }; 15 | public OpenApiSchema? LoadSchema(string path, out OpenApiDiagnostic diagnostic) 16 | { 17 | var text = File.ReadAllText(path); 18 | var reader = new OpenApiStringReader(); 19 | var schema = reader.ReadFragment(text, OpenApiSpecVersion.OpenApi3_0, out diagnostic); 20 | var ignored = diagnostic.Errors.Where(e => IgnoreErrors.Contains(e.Message)).ToArray(); 21 | if (ignored.Length > 0) 22 | { 23 | foreach (var error in ignored) 24 | { 25 | diagnostic.Errors.Remove(error); 26 | } 27 | } 28 | diagnostic.Write(); 29 | return schema; 30 | } 31 | } -------------------------------------------------------------------------------- /src/Bundle/Bundle.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | RendleLabs.OpenApi.Bundle 9 | RendleLabs.OpenApi.Bundle 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/Bundle/BundleException.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Readers; 2 | 3 | namespace RendleLabs.OpenApi.Bundle; 4 | 5 | public class BundleException : Exception 6 | { 7 | public BundleException(string message) : base(message) 8 | { 9 | } 10 | 11 | public BundleException(string message, Exception inner) : base(message, inner) 12 | { 13 | } 14 | 15 | public BundleException(string message, OpenApiDiagnostic diagnostic) : base(message) 16 | { 17 | Diagnostic = diagnostic; 18 | } 19 | 20 | public BundleException(string message, OpenApiDiagnostic diagnostic, Exception inner) : base(message, inner) 21 | { 22 | Diagnostic = diagnostic; 23 | } 24 | 25 | public OpenApiDiagnostic? Diagnostic { get; } 26 | } -------------------------------------------------------------------------------- /src/Bundle/Bundler.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | using Microsoft.OpenApi.Readers; 3 | using Microsoft.OpenApi.Services; 4 | 5 | namespace RendleLabs.OpenApi.Bundle; 6 | 7 | public sealed class Bundler : IDisposable 8 | { 9 | private readonly Stream _source; 10 | private readonly string _directory; 11 | 12 | public Bundler(Stream source, string filePath) 13 | { 14 | _source = source; 15 | _directory = Path.GetDirectoryName(filePath)!; 16 | } 17 | 18 | public async Task Build() 19 | { 20 | var result = await new OpenApiStreamReader().ReadAsync(_source); 21 | 22 | result.OpenApiDiagnostic.Write(); 23 | 24 | if (result.OpenApiDiagnostic.Errors is { Count: > 0 } errors) 25 | { 26 | return null; 27 | } 28 | 29 | var document = result.OpenApiDocument; 30 | 31 | var references = new ReferenceInfoCollection(); 32 | 33 | var referenceVisitor = new ReferenceVisitor(_directory, references); 34 | var walker = new OpenApiWalker(referenceVisitor); 35 | walker.Walk(document); 36 | if (references.Count == 0) return document; 37 | 38 | return document; 39 | } 40 | 41 | public void Dispose() 42 | { 43 | _source.Dispose(); 44 | } 45 | } -------------------------------------------------------------------------------- /src/Bundle/FragmentFinder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi; 2 | using Microsoft.OpenApi.Interfaces; 3 | using Microsoft.OpenApi.Readers; 4 | using SharpYaml.Serialization; 5 | 6 | namespace RendleLabs.OpenApi.Bundle; 7 | 8 | internal static class FragmentFinder 9 | { 10 | public static T Find(string source, string path) where T : IOpenApiElement 11 | { 12 | int hash = path.IndexOf('#'); 13 | if (hash > 0) path = path.Substring(hash).Trim('#', '/'); 14 | var parts = path.Split('/'); 15 | 16 | var yaml = ParseYaml(source); 17 | 18 | YamlMappingNode? node = null; 19 | 20 | foreach (var document in yaml.Documents) 21 | { 22 | node = (YamlMappingNode)document.RootNode; 23 | foreach (var part in parts) 24 | { 25 | if (!node.TryGetMappingNode(part, out node)) 26 | { 27 | break; 28 | } 29 | } 30 | 31 | if (node is not null) break; 32 | } 33 | 34 | var fragment = node?.ToText(); 35 | 36 | var reader = new OpenApiStringReader(); 37 | var element = reader.ReadFragment(fragment, OpenApiSpecVersion.OpenApi3_0, out var diagnostic); 38 | 39 | if (diagnostic.Errors is { Count: > 0 }) 40 | { 41 | if (diagnostic.Errors.Any(e => !e.Message.Contains("is not a valid property"))) 42 | { 43 | throw new BundleException("Error reading fragment", diagnostic); 44 | } 45 | } 46 | 47 | return element; 48 | } 49 | 50 | private static YamlStream ParseYaml(string source) 51 | { 52 | var yaml = new YamlStream(); 53 | using var stringReader = new StringReader(source); 54 | yaml.Load(stringReader); 55 | 56 | return yaml; 57 | } 58 | } -------------------------------------------------------------------------------- /src/Bundle/OpenApiDiagnosticWrite.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | using Microsoft.OpenApi.Readers; 3 | 4 | namespace RendleLabs.OpenApi.Bundle; 5 | 6 | internal static class OpenApiDiagnosticWrite 7 | { 8 | public static void Write(this OpenApiDiagnostic diagnostic) 9 | { 10 | if (diagnostic.Warnings is { Count: > 0 } warnings) 11 | { 12 | WriteWarnings(warnings); 13 | } 14 | 15 | if (diagnostic.Errors is { Count: > 0 } errors) 16 | { 17 | WriteErrors(errors); 18 | } 19 | } 20 | 21 | private static void WriteErrors(IList errors) 22 | { 23 | foreach (var error in errors) 24 | { 25 | Console.WriteLine($"ERROR: [{error.Pointer}] {error.Message}"); 26 | } 27 | } 28 | 29 | private static void WriteWarnings(IList warnings) 30 | { 31 | foreach (var warning in warnings) 32 | { 33 | Console.WriteLine($"WARNING: [{warning.Pointer}] {warning.Message}"); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/Bundle/Program.cs: -------------------------------------------------------------------------------- 1 | // See https://aka.ms/new-console-template for more information 2 | Console.WriteLine("Hello, World!"); 3 | -------------------------------------------------------------------------------- /src/Bundle/ReferenceInfo.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Interfaces; 2 | using Microsoft.OpenApi.Models; 3 | 4 | namespace RendleLabs.OpenApi.Bundle; 5 | 6 | public abstract class ReferenceInfo 7 | { 8 | protected static readonly Dictionary ReferenceTypes = new() 9 | { 10 | [typeof(OpenApiCallback)] = ReferenceType.Callback, 11 | [typeof(OpenApiExample)] = ReferenceType.Example, 12 | [typeof(OpenApiHeader)] = ReferenceType.Header, 13 | [typeof(OpenApiLink)] = ReferenceType.Link, 14 | [typeof(OpenApiParameter)] = ReferenceType.Parameter, 15 | [typeof(OpenApiRequestBody)] = ReferenceType.RequestBody, 16 | [typeof(OpenApiResponse)] = ReferenceType.Response, 17 | [typeof(OpenApiSchema)] = ReferenceType.Schema, 18 | [typeof(OpenApiSecurityScheme)] = ReferenceType.SecurityScheme, 19 | [typeof(OpenApiTag)] = ReferenceType.Tag, 20 | }; 21 | 22 | protected ReferenceInfo(string path) 23 | { 24 | Path = path; 25 | ReadOnlySpan id; 26 | if (ReferencePath.IsHttp(path)) 27 | { 28 | var uri = new Uri(path); 29 | id = System.IO.Path.GetFileNameWithoutExtension(uri.AbsolutePath); 30 | } 31 | else 32 | { 33 | id = System.IO.Path.GetFileName(path); 34 | } 35 | 36 | id = id.TrimStart('.'); 37 | 38 | var dot = id.IndexOf('.'); 39 | if (dot > 0) 40 | { 41 | id = id[..dot]; 42 | } 43 | 44 | Id = new string(id); 45 | } 46 | 47 | public string Path { get; } 48 | public string Id { get; set; } 49 | 50 | public abstract ReferenceType Type { get; } 51 | } 52 | 53 | public class ReferenceInfo : ReferenceInfo where T : IOpenApiReferenceable 54 | { 55 | public List References { get; } 56 | 57 | public T? ResolvedReference { get; set; } 58 | 59 | public ReferenceInfo(string path) : base(path) 60 | { 61 | References = new List(); 62 | } 63 | 64 | public override ReferenceType Type => ReferenceTypes[typeof(T)]; 65 | } -------------------------------------------------------------------------------- /src/Bundle/ReferenceInfoCollection.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using Microsoft.OpenApi.Interfaces; 3 | 4 | namespace RendleLabs.OpenApi.Bundle; 5 | 6 | public class ReferenceInfoCollection : KeyedCollection 7 | { 8 | protected override string GetKeyForItem(ReferenceInfo item) => item.Path; 9 | 10 | public ReferenceInfo GetOrAdd(string path) where T : IOpenApiReferenceable 11 | { 12 | if (TryGetValue(path, out var info)) 13 | { 14 | return (ReferenceInfo)info; 15 | } 16 | 17 | var referenceInfo = new ReferenceInfo(path); 18 | Add(referenceInfo); 19 | return referenceInfo; 20 | } 21 | } -------------------------------------------------------------------------------- /src/Bundle/ReferenceLoader.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi; 2 | using Microsoft.OpenApi.Interfaces; 3 | using Microsoft.OpenApi.Readers; 4 | 5 | namespace RendleLabs.OpenApi.Bundle; 6 | 7 | public class ReferenceLoader : IDisposable 8 | { 9 | private readonly HttpClient _client = new(); 10 | private readonly Dictionary _cache = new(StringComparer.OrdinalIgnoreCase); 11 | 12 | public async Task LoadAsync(ReferenceInfo referenceInfo) where T : IOpenApiReferenceable 13 | { 14 | string text; 15 | if (ReferencePath.IsHttp(referenceInfo.Path)) 16 | { 17 | text = await LoadHttpAsync(referenceInfo.Path); 18 | } 19 | else 20 | { 21 | text = await LoadFileAsync(referenceInfo.Path); 22 | } 23 | 24 | 25 | if (referenceInfo.Path.Contains('#')) 26 | { 27 | return FragmentFinder.Find(text, referenceInfo.Path); 28 | } 29 | 30 | var reader = new OpenApiStringReader(); 31 | var fragment = reader.ReadFragment(text, OpenApiSpecVersion.OpenApi3_0, out var diagnostic); 32 | 33 | if (diagnostic.Errors is { Count: > 0 }) 34 | { 35 | if (diagnostic.Errors.Any(e => !e.Message.Contains("is not a valid property"))) 36 | { 37 | throw new BundleException($"Error parsing {typeof(T).Name}", diagnostic); 38 | } 39 | } 40 | 41 | return fragment; 42 | } 43 | 44 | private async Task LoadFileAsync(string path) 45 | { 46 | path = RemoveFragment(path); 47 | 48 | if (_cache.TryGetValue(path, out var text)) return text; 49 | 50 | try 51 | { 52 | text = await File.ReadAllTextAsync(path); 53 | _cache[path] = text; 54 | return text; 55 | } 56 | catch (Exception ex) 57 | { 58 | throw new BundleException("Could not load file '{path}'", ex); 59 | } 60 | } 61 | 62 | private async Task LoadHttpAsync(string uri) 63 | { 64 | uri = RemoveFragment(uri); 65 | 66 | if (_cache.TryGetValue(uri, out var text)) return text; 67 | 68 | try 69 | { 70 | text = await _client.GetStringAsync(uri); 71 | _cache[uri] = text; 72 | return text; 73 | } 74 | catch (HttpRequestException ex) 75 | { 76 | int status = (int)ex.StatusCode.GetValueOrDefault(0); 77 | throw new BundleException($"GET {uri} returned status {status}", ex); 78 | } 79 | } 80 | 81 | private static string RemoveFragment(string path) 82 | { 83 | int hash = path.IndexOf('#'); 84 | if (hash > 0) path = path[..hash]; 85 | return path; 86 | } 87 | 88 | public void Dispose() 89 | { 90 | _client.Dispose(); 91 | } 92 | } -------------------------------------------------------------------------------- /src/Bundle/ReferencePath.cs: -------------------------------------------------------------------------------- 1 | using System.Text.RegularExpressions; 2 | 3 | namespace RendleLabs.OpenApi.Bundle; 4 | 5 | internal static class ReferencePath 6 | { 7 | private static readonly Regex IsHttpRegex = new Regex(@"^https?:\/\/", RegexOptions.Compiled | RegexOptions.IgnoreCase); 8 | 9 | public static bool IsHttp(string path) => IsHttpRegex.IsMatch(path); 10 | } -------------------------------------------------------------------------------- /src/Bundle/ReferenceVisitor.cs: -------------------------------------------------------------------------------- 1 | using System.Text.RegularExpressions; 2 | using Microsoft.OpenApi.Interfaces; 3 | using Microsoft.OpenApi.Models; 4 | using Microsoft.OpenApi.Services; 5 | using Path = System.IO.Path; 6 | 7 | namespace RendleLabs.OpenApi.Bundle; 8 | 9 | public class ReferenceVisitor : OpenApiVisitorBase 10 | { 11 | 12 | private readonly string _basePath; 13 | private readonly ReferenceInfoCollection _references; 14 | 15 | public bool AnyChanges { get; set; } 16 | public Dictionary PathToIdLookup { get; } = new(StringComparer.OrdinalIgnoreCase); 17 | 18 | public ReferenceVisitor(string basePath, ReferenceInfoCollection references) 19 | { 20 | _basePath = basePath; 21 | _references = references; 22 | } 23 | 24 | private void VisitReference(T element) where T : IOpenApiReferenceable 25 | { 26 | if (!element.UnresolvedReference) return; 27 | if (!element.Reference.IsExternal) return; 28 | if (element.Reference.ExternalResource is not { Length: > 0 } externalResource) return; 29 | 30 | if (ReferencePath.IsHttp(_basePath)) 31 | { 32 | if (ReferencePath.IsHttp(externalResource)) 33 | { 34 | element.Reference.ExternalResource = externalResource; 35 | } 36 | else 37 | { 38 | var baseUri = new Uri(_basePath); 39 | element.Reference.ExternalResource = new Uri(baseUri, externalResource).ToString(); 40 | } 41 | } 42 | else 43 | { 44 | element.Reference.ExternalResource = Path.GetFullPath(externalResource, _basePath); 45 | } 46 | 47 | var info = _references.GetOrAdd(element.Reference.ExternalResource); 48 | info.References.Add(element); 49 | } 50 | 51 | public override void Visit(IOpenApiReferenceable referenceable) 52 | { 53 | switch (referenceable) 54 | { 55 | case OpenApiCallback callback: 56 | VisitReference(callback); 57 | break; 58 | case OpenApiExample example: 59 | VisitReference(example); 60 | break; 61 | case OpenApiHeader header: 62 | VisitReference(header); 63 | break; 64 | case OpenApiLink link: 65 | VisitReference(link); 66 | break; 67 | case OpenApiParameter parameter: 68 | VisitReference(parameter); 69 | break; 70 | case OpenApiPathItem pathItem: 71 | VisitReference(pathItem); 72 | break; 73 | case OpenApiRequestBody requestBody: 74 | VisitReference(requestBody); 75 | break; 76 | case OpenApiResponse response: 77 | VisitReference(response); 78 | break; 79 | case OpenApiSchema schema: 80 | VisitReference(schema); 81 | break; 82 | case OpenApiSecurityScheme securityScheme: 83 | VisitReference(securityScheme); 84 | break; 85 | } 86 | } 87 | } -------------------------------------------------------------------------------- /src/Bundle/ReferenceWalker.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Interfaces; 2 | using Microsoft.OpenApi.Models; 3 | using Microsoft.OpenApi.Services; 4 | 5 | namespace RendleLabs.OpenApi.Bundle; 6 | 7 | public sealed class ReferenceWalker 8 | { 9 | public ReferenceWalker() 10 | { 11 | } 12 | 13 | public void Walk(OpenApiDocument document, string directory, ReferenceInfoCollection references) 14 | { 15 | var referenceVisitor = new ReferenceVisitor(directory, references); 16 | var walker = new OpenApiWalker(referenceVisitor); 17 | walker.Walk(document); 18 | } 19 | } -------------------------------------------------------------------------------- /src/Bundle/SchemaLoader.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi; 2 | using Microsoft.OpenApi.Models; 3 | using Microsoft.OpenApi.Readers; 4 | 5 | namespace RendleLabs.OpenApi.Bundle; 6 | 7 | public class SchemaLoader 8 | { 9 | private static readonly HashSet IgnoreErrors = new() 10 | { 11 | "$schema is not a valid property at #/", 12 | "$id is not a valid property at #/", 13 | }; 14 | 15 | public OpenApiSchema? LoadSchema(string path, out OpenApiDiagnostic diagnostic) 16 | { 17 | if (path.StartsWith("http://") || path.StartsWith("https://")) 18 | { 19 | 20 | } 21 | var text = File.ReadAllText(path); 22 | var reader = new OpenApiStringReader(); 23 | var schema = reader.ReadFragment(text, OpenApiSpecVersion.OpenApi3_0, out diagnostic); 24 | var ignored = diagnostic.Errors.Where(e => IgnoreErrors.Contains(e.Message)).ToArray(); 25 | if (ignored.Length > 0) 26 | { 27 | foreach (var error in ignored) 28 | { 29 | diagnostic.Errors.Remove(error); 30 | } 31 | } 32 | diagnostic.Write(); 33 | return schema; 34 | } 35 | } -------------------------------------------------------------------------------- /src/Bundle/YamlMappingNodeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using System.Text; 3 | using SharpYaml.Serialization; 4 | 5 | namespace RendleLabs.OpenApi.Bundle; 6 | 7 | internal static class YamlMappingNodeExtensions 8 | { 9 | public static bool TryGetMappingNode(this YamlMappingNode parent, string name, [NotNullWhen(true)] out YamlMappingNode? node) 10 | { 11 | foreach (var (key, value) in parent) 12 | { 13 | if (key is YamlScalarNode scalarNode && scalarNode.Value == name) 14 | { 15 | node = value as YamlMappingNode; 16 | return node is not null; 17 | } 18 | } 19 | 20 | node = null; 21 | return false; 22 | } 23 | 24 | public static string ToText(this YamlMappingNode node) 25 | { 26 | var document = new YamlDocument(node); 27 | var builder = new StringBuilder(); 28 | using var writer = new StringWriter(builder); 29 | var yaml = new YamlStream(document); 30 | yaml.Save(writer, true); 31 | return builder.ToString(); 32 | } 33 | } -------------------------------------------------------------------------------- /src/Generator/ApiFirst/ApiFirstGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | 3 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 4 | 5 | public class ApiFirstGenerator 6 | { 7 | } -------------------------------------------------------------------------------- /src/Generator/ApiFirst/CSharpHelpers.cs: -------------------------------------------------------------------------------- 1 | using System.Text.RegularExpressions; 2 | 3 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 4 | 5 | internal static class CSharpHelpers 6 | { 7 | private static readonly Regex NonAlphaNumeric = new("[^a-zA-Z0-9]", RegexOptions.Compiled); 8 | 9 | public static string ClassName(string openApiName) => PascalCase(openApiName); 10 | public static string PropertyName(string openApiName) => PascalCase(openApiName); 11 | 12 | private static string PascalCase(string openApiName) 13 | { 14 | var name = NonAlphaNumeric.Replace(openApiName, string.Empty); 15 | if (name is not { Length: > 0 }) 16 | { 17 | throw new InvalidOperationException($"Cannot get C# name from '{openApiName}'"); 18 | } 19 | 20 | if (char.IsUpper(name[0])) return name; 21 | if (name.Length == 1) return name.ToUpperInvariant(); 22 | return char.ToUpperInvariant(name[0]) + name[1..]; 23 | } 24 | } -------------------------------------------------------------------------------- /src/Generator/ApiFirst/ModelDefinition.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | 3 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 4 | 5 | public class ModelDefinition 6 | { 7 | private readonly Dictionary _properties = new(); 8 | public ModelDefinition(string openApiName) 9 | { 10 | OpenApiName = openApiName; 11 | CSharpName = CSharpHelpers.ClassName(openApiName); 12 | } 13 | 14 | public string OpenApiName { get; } 15 | public string CSharpName { get; } 16 | 17 | public void AddProperty(string name, OpenApiSchema schema) 18 | { 19 | var property = new ModelProperty(name, schema); 20 | _properties[property.CSharpName] = property; 21 | } 22 | 23 | public ICollection Properties => _properties.Values; 24 | } -------------------------------------------------------------------------------- /src/Generator/ApiFirst/ModelFinder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | 3 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 4 | 5 | public static class ModelFinder 6 | { 7 | public static IEnumerable FindModels(OpenApiDocument document) 8 | { 9 | return FindRequestModels(document).Concat(FindResponseModels(document)); 10 | } 11 | 12 | private static IEnumerable FindRequestModels(OpenApiDocument document) 13 | { 14 | return document.Paths.Values 15 | .Where(p => p.Operations.Values is { Count: > 0 }) 16 | .SelectMany(p => p.Operations.Values) 17 | .Where(o => o.RequestBody?.Content is { Count: > 0 }) 18 | .SelectMany(o => o.RequestBody.Content.Values) 19 | .Where(m => m.Schema is not null) 20 | .Select(m => FixUp(m.Schema)) 21 | .WhereNotNull(); 22 | } 23 | 24 | private static IEnumerable FindResponseModels(OpenApiDocument document) 25 | { 26 | return document.Paths.Values 27 | .Where(p => p.Operations.Values is { Count: > 0 }) 28 | .SelectMany(p => p.Operations.Values) 29 | .Where(o => o.Responses is { Count: > 0 }) 30 | .SelectMany(o => o.Responses.Values) 31 | .Where(r => r.Content is { Count: > 0 }) 32 | .SelectMany(r => r.Content.Values) 33 | .Where(m => m.Schema is not null) 34 | .Select(m => FixUp(m.Schema)) 35 | .WhereNotNull(); 36 | } 37 | 38 | private static OpenApiSchema? FixUp(OpenApiSchema schema) 39 | { 40 | while (schema?.Type == "array") 41 | { 42 | schema = schema.Items; 43 | } 44 | 45 | if (schema is null) return null; 46 | 47 | if (schema.Title is not { Length: > 0 }) 48 | { 49 | schema.Title = schema.Reference?.Id; 50 | } 51 | 52 | return schema; 53 | } 54 | } 55 | 56 | internal static class NotNullExtension 57 | { 58 | public static IEnumerable WhereNotNull(this IEnumerable source) where T : class 59 | { 60 | foreach (var item in source) 61 | { 62 | if (item is not null) yield return item; 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /src/Generator/ApiFirst/ModelGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.CodeDom.Compiler; 2 | using Microsoft.OpenApi.Models; 3 | 4 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 5 | 6 | public class ModelGenerator 7 | { 8 | private readonly List _openApiSchemata = new(); 9 | 10 | public void AddSchema(OpenApiSchema openApiSchema) 11 | { 12 | _openApiSchemata.Add(openApiSchema); 13 | } 14 | 15 | public async Task GenerateAsync(TextWriter writer) 16 | { 17 | var indentedTextWriter = writer as IndentedTextWriter ?? new IndentedTextWriter(writer); 18 | 19 | var definitions = CreateModelDefinitions(); 20 | foreach (var definition in definitions.OrderBy(d => d.CSharpName)) 21 | { 22 | await Generate(indentedTextWriter, definition); 23 | } 24 | 25 | await indentedTextWriter.FlushAsync(); 26 | } 27 | 28 | private static async Task Generate(IndentedTextWriter writer, ModelDefinition definition) 29 | { 30 | await writer.WriteLineAsync($"public partial class {definition.CSharpName}"); 31 | 32 | using (writer.OpenBrace()) 33 | { 34 | foreach (var property in definition.Properties) 35 | { 36 | await writer.WriteLineAsync($"[global::System.Text.Json.Serialization.JsonPropertyName(\"{property.OpenApiName}\")]"); 37 | await writer.WriteLineAsync($"public {property.CSharpType}? {property.CSharpName} {{ get; set; }}"); 38 | } 39 | } 40 | 41 | await writer.WriteLineNoTabsAsync(); 42 | } 43 | 44 | private ModelDefinition[] CreateModelDefinitions() 45 | { 46 | var definitions = new Dictionary(); 47 | 48 | foreach (var openApiSchema in _openApiSchemata) 49 | { 50 | if (!definitions.TryGetValue(openApiSchema.Title, out var definition)) 51 | { 52 | definitions[openApiSchema.Title] = definition = new ModelDefinition(openApiSchema.Title); 53 | } 54 | 55 | foreach (var (name, schema) in openApiSchema.Properties) 56 | { 57 | definition.AddProperty(name, schema); 58 | } 59 | } 60 | 61 | return definitions.Values.ToArray(); 62 | } 63 | } -------------------------------------------------------------------------------- /src/Generator/ApiFirst/ModelProperty.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | 3 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 4 | 5 | public class ModelProperty 6 | { 7 | public ModelProperty(string openApiName, OpenApiSchema schema) 8 | { 9 | OpenApiName = openApiName; 10 | OpenApiType = schema.Type; 11 | CSharpName = CSharpHelpers.PropertyName(openApiName); 12 | CSharpType = SchemaHelpers.SchemaTypeToDotNetType(schema); 13 | } 14 | 15 | public string OpenApiName { get; } 16 | public string OpenApiType { get; } 17 | public string CSharpName { get; } 18 | public string CSharpType { get; } 19 | } -------------------------------------------------------------------------------- /src/Generator/ApiFirst/ParameterHelpers.cs: -------------------------------------------------------------------------------- 1 | using System.Text.RegularExpressions; 2 | using Microsoft.OpenApi.Models; 3 | 4 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 5 | 6 | internal static class ParameterHelpers 7 | { 8 | private static readonly Regex NonAlphaNumeric = new("[^a-zA-Z0-9]", RegexOptions.Compiled); 9 | 10 | public static string CSharpName(this OpenApiParameter parameter) 11 | { 12 | var name = NonAlphaNumeric.Replace(parameter.Name, string.Empty); 13 | if (name is not { Length: > 0 }) 14 | { 15 | throw new InvalidOperationException($"Cannot get C# name from '{parameter.Name}'"); 16 | } 17 | 18 | if (name.Length == 1) return name.ToLowerInvariant(); 19 | if (char.IsLower(name[0])) return name; 20 | return char.ToLowerInvariant(name[0]) + name[1..]; 21 | } 22 | } -------------------------------------------------------------------------------- /src/Generator/ApiFirst/PathItemHelpers.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | 3 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 4 | 5 | internal static class PathItemHelpers 6 | { 7 | public static IEnumerable GetPathParameters(this OpenApiPathItem pathItem) => 8 | GetParametersIn(pathItem, ParameterLocation.Path); 9 | 10 | public static IEnumerable GetQueryParameters(this OpenApiPathItem pathItem) => 11 | GetParametersIn(pathItem, ParameterLocation.Query); 12 | 13 | public static IEnumerable GetQueryParameters(this OpenApiOperation operation) => 14 | operation.Parameters.Where(p => p.In == ParameterLocation.Query); 15 | 16 | public static IEnumerable GetHeaderParameters(this OpenApiPathItem pathItem) => 17 | GetParametersIn(pathItem, ParameterLocation.Header); 18 | 19 | public static IEnumerable GetCookieParameters(this OpenApiPathItem pathItem) => 20 | GetParametersIn(pathItem, ParameterLocation.Cookie); 21 | 22 | private static IEnumerable GetParametersIn(OpenApiPathItem pathItem, ParameterLocation location) => 23 | pathItem.Parameters.Where(p => p.In == location); 24 | 25 | public static IEnumerable> GetOperationsWithTag(this OpenApiPathItem pathItem, string tag) => 26 | pathItem.Operations 27 | .Where(o => o.Value.Tags.Any(t => t.Name.Equals(tag))); 28 | } -------------------------------------------------------------------------------- /src/Generator/ApiFirst/ResultHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | 3 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 4 | 5 | internal static class ResultHelper 6 | { 7 | public static ResultType[] GetStatusCodes(OpenApiDocument document, string tag) 8 | { 9 | return EnumerateStatusCodes(document, tag) 10 | .Distinct() 11 | .OrderBy(s => s.StatusCode) 12 | .ThenBy(s => s.Type) 13 | .ToArray(); 14 | } 15 | 16 | private static IEnumerable EnumerateStatusCodes(OpenApiDocument document, string tag) 17 | { 18 | foreach (var (_, path) in document.Paths) 19 | { 20 | foreach (var (_, operation) in path.Operations) 21 | { 22 | if (!operation.Tags.Any(t => t.Name.Equals(tag, StringComparison.OrdinalIgnoreCase))) continue; 23 | 24 | foreach (var (codeStr, response) in operation.Responses) 25 | { 26 | if (int.TryParse(codeStr, out var code)) 27 | { 28 | yield return GetResultType(code, response); 29 | } 30 | } 31 | } 32 | } 33 | } 34 | 35 | private static ResultType GetResultType(int statusCode, OpenApiResponse response) 36 | { 37 | foreach (var (_, mediaType) in response.Content) 38 | { 39 | if (mediaType.Schema.Title is { Length: > 0 } typeName) 40 | { 41 | return new ResultType(statusCode, typeName); 42 | } 43 | 44 | if (mediaType.Schema.Type == "array") 45 | { 46 | if (mediaType.Schema.Items.Title is { Length: > 0 } arrayTypeName) 47 | { 48 | return new ResultType(statusCode, arrayTypeName, true); 49 | } 50 | } 51 | } 52 | 53 | return new ResultType(statusCode); 54 | } 55 | } 56 | 57 | internal record ResultType(int StatusCode, string? Type = null, bool IsArray = false); 58 | -------------------------------------------------------------------------------- /src/Generator/ApiFirst/SchemaHelpers.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | 3 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 4 | 5 | internal static class SchemaHelpers 6 | { 7 | public static string SchemaTypeToDotNetType(OpenApiSchema schema) 8 | { 9 | var type = schema.Type switch 10 | { 11 | "boolean" => "bool", 12 | "number" => "double", 13 | "string" => StringSchemaType(schema), 14 | "integer" => SchemaTypeToInteger(schema), 15 | _ => "object", 16 | }; 17 | if (schema.Nullable) type += '?'; 18 | return type; 19 | } 20 | 21 | private static string StringSchemaType(OpenApiSchema schema) 22 | { 23 | return schema.Format switch 24 | { 25 | "date-time" => "DateTime", 26 | "time" => "TimeOnly", 27 | "date" => "DateOnly", 28 | "duration" => "TimeSpan", 29 | "uuid" => "Guid", 30 | "uri" => "Uri", 31 | _ => "string", 32 | }; 33 | } 34 | 35 | private static string SchemaTypeToInteger(OpenApiSchema schema) 36 | { 37 | return schema.Maximum > int.MaxValue ? "long" : "int"; 38 | } 39 | } -------------------------------------------------------------------------------- /src/Generator/ApiFirst/StatusCodeHelper.cs: -------------------------------------------------------------------------------- 1 | namespace RendleLabs.OpenApi.Generator.ApiFirst; 2 | 3 | internal static class StatusCodeHelper 4 | { 5 | public static string GetMethod(int status, string? typeName, bool isArray) 6 | { 7 | string parameterName; 8 | if (typeName is { Length: > 0 }) 9 | { 10 | parameterName = typeName.ToCamelCase(); 11 | if (isArray) 12 | { 13 | parameterName += "s"; 14 | typeName = $"IList<{typeName}>"; 15 | } 16 | } 17 | else 18 | { 19 | typeName = "object"; 20 | parameterName = "obj"; 21 | } 22 | return status switch 23 | { 24 | 200 => $"Ok({typeName}? {parameterName} = null) => Results.Ok({parameterName})", 25 | 201 => $"Created(Uri uri, {typeName}? {parameterName} = null) => Results.Created(uri, {parameterName})", 26 | 202 => $"Accepted(Uri? uri = null, {typeName}? {parameterName} = null) => Results.Accepted(uri.ToString(), {parameterName})", 27 | 204 => "NoContent() => Results.NoContent()", 28 | 301 => "MovedPermanently(Uri uri) => Results.Redirect(uri.ToString(), true, false)", 29 | 302 => "Found(Uri uri) => Results.Redirect(uri.ToString(), false, false)", 30 | 307 => "TemporaryRedirect(Uri uri) => Results.Redirect(uri.ToString(), false, true)", 31 | 308 => "PermanentRedirect(Uri uri) => Results.Redirect(uri.ToString(), true, true)", 32 | 400 => "BadRequest(object? errors = null) => Results.BadRequest(errors)", 33 | 401 => "Unauthorized() => Results.Unauthorized()", 34 | 402 => "PaymentRequired() => Results.StatusCode(402)", 35 | 403 => "Forbidden() => Results.Forbid()", 36 | 404 => "NotFound() => Results.NotFound()", 37 | 405 => "MethodNotAllowed() => Results.StatusCode(405)", 38 | 406 => "NotAcceptable() => Results.StatusCode(406)", 39 | 409 => "Conflict(object? errors = null) => Results.Conflict(errors)", 40 | 410 => "Gone() => Results.StatusCode(410)", 41 | 411 => "LengthRequired() => Results.StatusCode(411)", 42 | 412 => "PreconditionFailed() => Results.StatusCode(412)", 43 | 415 => "UnsupportedMediaType() => Results.StatusCode(415)", 44 | 416 => "RangeNotSatisfiable() => Results.StatusCode(416)", 45 | 417 => "ExpectationFailed() => Results.StatusCode(417)", 46 | 418 => "ImATeapot() => Results.StatusCode(418)", 47 | 425 => "TooEarly() => Results.StatusCode(425)", 48 | 428 => "PreconditionRequired() => Results.StatusCode(428)", 49 | 429 => "TooManyRequests() => Results.StatusCode(429)", 50 | 451 => "UnavailableForLegalReasons() => Results.StatusCode(451)", 51 | _ => $"Status{status}() => Results.StatusCode({status})", 52 | }; 53 | } 54 | } -------------------------------------------------------------------------------- /src/Generator/Controllers/ActionMethodParameter.cs: -------------------------------------------------------------------------------- 1 | namespace RendleLabs.OpenApi.Generator.Controllers; 2 | 3 | internal record ActionMethodParameter(string? From, string Type, string Name) 4 | { 5 | public override string ToString() 6 | { 7 | return From is not null ? $"[From{From}] {Type} {Name}" : $"{Type} {Name}"; 8 | } 9 | } -------------------------------------------------------------------------------- /src/Generator/Controllers/BaseActionMethodGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.CodeDom.Compiler; 2 | using System.Diagnostics.CodeAnalysis; 3 | using Microsoft.OpenApi.Models; 4 | 5 | namespace RendleLabs.OpenApi.Generator.Controllers; 6 | 7 | public class BaseActionMethodGenerator 8 | { 9 | private readonly string _path; 10 | private readonly OperationType _operationType; 11 | private readonly OpenApiOperation _operation; 12 | 13 | public BaseActionMethodGenerator(string path, OperationType operationType, OpenApiOperation operation) 14 | { 15 | _path = path; 16 | _operationType = operationType; 17 | _operation = operation; 18 | } 19 | 20 | public void Generate(IndentedTextWriter writer) 21 | { 22 | writer.WriteLine($"[Http{_operationType}(\"{_path}\", Name = \"{_operation.OperationId}\"]"); 23 | 24 | var model = GetModelName(); 25 | var returnType = model is null ? "IActionResult" : $"ActionResult<{model}>"; 26 | var parameters = GetParameters().ToArray(); 27 | 28 | writer.Write($"public Task<{returnType}> {_operation.OperationId}("); 29 | if (parameters.Length > 0) 30 | { 31 | writer.Write(string.Join(", ", parameters.Select(p => p.ToString()))); 32 | writer.Write(", "); 33 | } 34 | 35 | if (TryGetBodyName(out var bodyName, out var array)) 36 | { 37 | writer.Write($"[FromBody] Models.{bodyName}"); 38 | if (array) 39 | { 40 | writer.Write("[]"); 41 | } 42 | 43 | writer.Write(' '); 44 | writer.Write(char.ToLowerInvariant(bodyName[0])); 45 | writer.Write(bodyName.AsSpan().Slice(1)); 46 | writer.Write(", "); 47 | } 48 | 49 | writer.WriteLine("CancellationToken cancellationToken) => Task.FromResult(StatusCode(501));"); 50 | } 51 | 52 | private bool TryGetBodyName([NotNullWhen(true)] out string? name, out bool array) 53 | { 54 | array = false; 55 | if (_operation.RequestBody?.Content is { Count: > 0 }) 56 | { 57 | if (_operation.RequestBody.Content.TryGetValue("application/json", out var content)) 58 | { 59 | if (content.Schema?.Type == "array") 60 | { 61 | array = true; 62 | if (content.Schema.Items?.Title is { Length: > 0 } title) 63 | { 64 | name = title; 65 | } 66 | else 67 | { 68 | name = $"{_operation.OperationId}RequestContent"; 69 | } 70 | } 71 | else 72 | { 73 | if (content.Schema?.Title is { Length: > 0 } title) 74 | { 75 | name = title; 76 | } 77 | else 78 | { 79 | name = $"{_operation.OperationId}RequestContent"; 80 | } 81 | } 82 | 83 | return true; 84 | } 85 | } 86 | 87 | name = null; 88 | return false; 89 | } 90 | 91 | private string? GetModelName() 92 | { 93 | var anon = false; 94 | foreach (var (statusStr, response) in _operation.Responses) 95 | { 96 | if (response.Content is null) continue; 97 | 98 | if (statusStr is "200" or "201" or "202") 99 | { 100 | if (response.Content.TryGetValue("application/json", out var content)) 101 | { 102 | anon = true; 103 | if (content.Schema.Type == "array" && content.Schema.Items.Title is { Length: > 0 }) 104 | { 105 | return $"List"; 106 | } 107 | 108 | if (content.Schema.Title is { Length: > 0 }) 109 | { 110 | return $"Models.{content.Schema.Title}"; 111 | } 112 | } 113 | } 114 | } 115 | 116 | return anon ? $"Models.{_operation.OperationId}Model" : null; 117 | } 118 | 119 | private IEnumerable GetParameters() 120 | { 121 | foreach (var apiParameter in _operation.Parameters) 122 | { 123 | var from = apiParameter.In switch 124 | { 125 | ParameterLocation.Query => "Query", 126 | ParameterLocation.Header => "Header", 127 | ParameterLocation.Path => "Route", 128 | _ => null 129 | }; 130 | var type = apiParameter.Schema.Type.ToLower() switch 131 | { 132 | "string" => "string", 133 | "number" => "double", 134 | "integer" => apiParameter.Schema.Maximum.HasValue && apiParameter.Schema.Maximum.Value > int.MaxValue ? "long" : "int", 135 | "boolean" => "bool", 136 | _ => "object" 137 | }; 138 | 139 | if (!apiParameter.Required) 140 | { 141 | type += "?"; 142 | } 143 | 144 | yield return new ActionMethodParameter(from, type, apiParameter.Name); 145 | } 146 | } 147 | } -------------------------------------------------------------------------------- /src/Generator/Generate.cs: -------------------------------------------------------------------------------- 1 | using System.CommandLine; 2 | using RendleLabs.OpenApi.Generator.MinimalApi; 3 | 4 | namespace RendleLabs.OpenApi.Generator; 5 | 6 | public class Generate 7 | { 8 | public static Command CreateCommand() 9 | { 10 | var command = new Command("generate", "Generate an API project from an OpenAPI spec."); 11 | command.AddAlias("gen"); 12 | command.AddAlias("g"); 13 | command.Add(MinimalApiGenerator.CreateCommand()); 14 | return command; 15 | } 16 | } -------------------------------------------------------------------------------- /src/Generator/Generator.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | RendleLabs.OpenApi.Generator 9 | RendleLabs.OpenApi.Generator 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/Generator/Internal/IndentedTextWriterExtensions.cs: -------------------------------------------------------------------------------- 1 | // ReSharper disable once CheckNamespace 2 | namespace System.CodeDom.Compiler; 3 | 4 | public static class IndentedTextWriterExtensions 5 | { 6 | public static IDisposable OpenIndent(this IndentedTextWriter writer) => new Indent(writer); 7 | public static IDisposable OpenBrace(this IndentedTextWriter writer) => new Brace(writer); 8 | 9 | public static Task WriteLineNoTabsAsync(this IndentedTextWriter writer) => writer.WriteLineNoTabsAsync(string.Empty); 10 | 11 | private class Indent : IDisposable 12 | { 13 | private readonly IndentedTextWriter _writer; 14 | 15 | public Indent(IndentedTextWriter writer) 16 | { 17 | _writer = writer; 18 | _writer.Indent++; 19 | } 20 | 21 | public void Dispose() => _writer.Indent--; 22 | } 23 | 24 | private class Brace : IDisposable 25 | { 26 | private readonly IndentedTextWriter _writer; 27 | 28 | public Brace(IndentedTextWriter writer) 29 | { 30 | _writer = writer; 31 | writer.WriteLine("{"); 32 | writer.Indent++; 33 | } 34 | 35 | public void Dispose() 36 | { 37 | _writer.Indent--; 38 | _writer.WriteLine("}"); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /src/Generator/MinimalApi/MinimalApiGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.CodeDom.Compiler; 2 | using System.CommandLine; 3 | using System.Diagnostics; 4 | using System.Reflection; 5 | using System.Text; 6 | using Microsoft.OpenApi.Models; 7 | using Microsoft.OpenApi.Readers; 8 | 9 | namespace RendleLabs.OpenApi.Generator.MinimalApi; 10 | 11 | public class MinimalApiGenerator 12 | { 13 | private readonly string _openApiFile; 14 | private readonly string _output; 15 | 16 | private MinimalApiGenerator(string openApiFile, string? output) 17 | { 18 | _openApiFile = openApiFile; 19 | if (output is not { Length: > 0 }) 20 | { 21 | output = Path.GetFileNameWithoutExtension(openApiFile); 22 | } 23 | _output = Path.GetFullPath(output); 24 | } 25 | 26 | private async Task InvokeAsync() 27 | { 28 | var (document, diagnostic) = await LoadDocumentAsync(); 29 | 30 | if (diagnostic.Errors is { Count: > 0 } errors) 31 | { 32 | foreach (var error in errors) 33 | { 34 | Console.WriteLine($"{error.Message} at {error.Pointer}"); 35 | } 36 | 37 | return 1; 38 | } 39 | 40 | Directory.CreateDirectory(_output); 41 | await CreateProjectFile(); 42 | await CreateProgramFile(document); 43 | 44 | return 0; 45 | } 46 | 47 | private async Task<(OpenApiDocument, OpenApiDiagnostic)> LoadDocumentAsync() 48 | { 49 | await using var stream = File.OpenRead(_openApiFile); 50 | var result = await new OpenApiStreamReader().ReadAsync(stream); 51 | return (result.OpenApiDocument, result.OpenApiDiagnostic); 52 | } 53 | 54 | private async Task CreateProjectFile() 55 | { 56 | var name = $"{Path.GetFileNameWithoutExtension(_output)}.csproj"; 57 | var path = Path.Combine(_output, name); 58 | await using var writeStream = File.Create(path); 59 | await using var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RendleLabs.OpenApi.Generator.MinimalApi.Project.xml"); 60 | Debug.Assert(resourceStream != null); 61 | await resourceStream.CopyToAsync(writeStream); 62 | } 63 | 64 | private async Task CreateProgramFile(OpenApiDocument openApiDocument) 65 | { 66 | var path = Path.Combine("_output", "Program.cs"); 67 | await File.WriteAllTextAsync(path, GenerateProgram(openApiDocument)); 68 | } 69 | 70 | private string GenerateProgram(OpenApiDocument openApiDocument) 71 | { 72 | var builder = new StringBuilder(); 73 | using var stringWriter = new StringWriter(builder); 74 | using var writer = new IndentedTextWriter(stringWriter, " "); 75 | 76 | writer.WriteLine("var builder = WebApplication.CreateBuilder(args);"); 77 | writer.WriteLine(); 78 | writer.WriteLine("var app = builder.Build();"); 79 | writer.WriteLine(); 80 | 81 | foreach (var (pathKey, pathItem) in openApiDocument.Paths) 82 | { 83 | foreach (var (operationType, operation) in pathItem.Operations) 84 | { 85 | writer.WriteLine($"app.Map{operationType}(\"{pathKey}\", async (context) =>"); 86 | using (writer.OpenIndent()) 87 | { 88 | using (writer.OpenBrace()) 89 | { 90 | 91 | } 92 | } 93 | writer.Indent++; 94 | writer.WriteLine("{"); 95 | } 96 | } 97 | 98 | writer.WriteLine("app.Run();"); 99 | writer.Flush(); 100 | return builder.ToString(); 101 | } 102 | 103 | public static Command CreateCommand() 104 | { 105 | var command = new Command("minimal"); 106 | 107 | var openApiFileArgument = new Argument("OpenApiFile"); 108 | var outputOption = new Option(new[] { "--output", "-o" }, () => string.Empty, "Output directory"); 109 | 110 | command.SetHandler(async (context) => 111 | { 112 | var openApiFile = context.ParseResult.GetValueForArgument(openApiFileArgument); 113 | var output = context.ParseResult.GetValueForOption(outputOption); 114 | context.ExitCode = await new MinimalApiGenerator(openApiFile, output).InvokeAsync(); 115 | }); 116 | 117 | command.SetHandler( 118 | (openApiFile, output) => new MinimalApiGenerator(openApiFile, output).InvokeAsync(), 119 | openApiFileArgument, 120 | outputOption); 121 | 122 | return command; 123 | } 124 | } -------------------------------------------------------------------------------- /src/Generator/MinimalApi/Project.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/Generator/Program.cs: -------------------------------------------------------------------------------- 1 | using System.CommandLine; 2 | 3 | var rootCommand = new RootCommand(); 4 | 5 | var generateCommand = new Command("generate", "Generate an API project"); 6 | generateCommand.AddAlias("gen"); 7 | generateCommand.AddAlias("g"); 8 | var openApiFileNameArgument = new Argument("openApiFileName", "The OpenAPI definition to generate code for."); 9 | generateCommand.AddArgument(openApiFileNameArgument); 10 | var outputOption = new Option(new[]{"--output", "-o"}, "Output directory."); 11 | generateCommand.AddOption(outputOption); 12 | 13 | generateCommand.SetHandler((openApiFileName, output) => 14 | { 15 | Console.WriteLine(openApiFileName); 16 | Console.WriteLine(output); 17 | }, openApiFileNameArgument, outputOption); 18 | 19 | rootCommand.Add(generateCommand); 20 | 21 | return await rootCommand.InvokeAsync(args); 22 | -------------------------------------------------------------------------------- /src/Testing.Xunit/Testing.Xunit.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Testing.Xunit/XunitAssertExtension.cs: -------------------------------------------------------------------------------- 1 | using RendleLabs.OpenApi.Testing; 2 | 3 | namespace Testing.Xunit; 4 | 5 | public static class XunitAssertExtension 6 | { 7 | public static void RunAssertions(this OpenApiTest openApiTest) 8 | { 9 | var testResponse = openApiTest.TestResponse; 10 | var actualResponse = openApiTest.ResponseMessage; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Testing/HttpClientExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace RendleLabs.OpenApi.Testing; 4 | 5 | public static class HttpClientExtensions 6 | { 7 | public static Task ExecuteAsync(this HttpClient client, OpenApiTestRequest testRequest) 8 | { 9 | var url = testRequest.ToUri(); 10 | var message = new HttpRequestMessage(testRequest.Method, url); 11 | 12 | if (testRequest.Headers is { Count: > 0 }) 13 | { 14 | foreach (var (key, values) in testRequest.Headers) 15 | { 16 | message.Headers.TryAddWithoutValidation(key, values); 17 | } 18 | } 19 | 20 | if (testRequest.Body != null) 21 | { 22 | message.Content = new StringContent(testRequest.Body, Encoding.UTF8, testRequest.ContentType); 23 | } 24 | 25 | return client.SendAsync(message); 26 | } 27 | } -------------------------------------------------------------------------------- /src/Testing/Internal/JsonDocumentExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Buffers; 2 | using System.Text; 3 | using System.Text.Json; 4 | 5 | namespace RendleLabs.OpenApi.Testing.Internal; 6 | 7 | public static class JsonDocumentExtensions 8 | { 9 | public static string? ToUtf8String(this JsonDocument? jsonDocument) 10 | { 11 | if (jsonDocument is null) return null; 12 | var bufferWriter = new ArrayBufferWriter(); 13 | var writer = new Utf8JsonWriter(bufferWriter); 14 | jsonDocument.WriteTo(writer); 15 | writer.Flush(); 16 | return Encoding.UTF8.GetString(bufferWriter.WrittenSpan); 17 | } 18 | } -------------------------------------------------------------------------------- /src/Testing/Internal/LinqExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace RendleLabs.OpenApi.Testing.Internal; 2 | 3 | internal static class LinqExtensions 4 | { 5 | public static IEnumerable WhereNotNull(this IEnumerable source) where T : class 6 | { 7 | foreach (var item in source) 8 | { 9 | if (item is not null) 10 | { 11 | yield return item; 12 | } 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /src/Testing/Internal/OpenApiModelExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using Microsoft.OpenApi.Models; 3 | 4 | namespace RendleLabs.OpenApi.Testing.Internal; 5 | 6 | public static class OpenApiModelExtensions 7 | { 8 | public static bool TryGetParameter(this OpenApiPathItem pathItem, OperationType operationType, string name, [NotNullWhen(true)] out OpenApiParameter? parameter) 9 | { 10 | if (pathItem.Operations.TryGetValue(operationType, out var operation)) 11 | { 12 | parameter = operation.Parameters.FirstOrDefault(p => p.Name == name); 13 | if (parameter is not null) return true; 14 | } 15 | 16 | parameter = pathItem.Parameters.FirstOrDefault(p => p.Name == name); 17 | return parameter is not null; 18 | } 19 | } -------------------------------------------------------------------------------- /src/Testing/Internal/QueryString.cs: -------------------------------------------------------------------------------- 1 | namespace RendleLabs.OpenApi.Testing.Internal; 2 | 3 | internal struct QueryString 4 | { 5 | private List<(string, string)>? _values; 6 | 7 | public void Add(string key, string value) 8 | { 9 | _values ??= new List<(string, string)>(); 10 | _values.Add((key, value)); 11 | } 12 | 13 | public override string ToString() 14 | { 15 | if (_values is null) return string.Empty; 16 | return "?" + string.Join("&", _values.Select(Pair)); 17 | } 18 | 19 | private static string Pair((string, string) pair) => $"{pair.Item1}={Uri.EscapeDataString(pair.Item2)}"; 20 | } -------------------------------------------------------------------------------- /src/Testing/Internal/YamlExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using YamlDotNet.RepresentationModel; 3 | 4 | namespace RendleLabs.OpenApi.Testing.Internal; 5 | 6 | internal static class YamlExtensions 7 | { 8 | private static readonly Dictionary Keys = new(); 9 | 10 | public static bool TryGetNode(this YamlMappingNode map, string key, [NotNullWhen(true)] out YamlNode? node) 11 | { 12 | var keyNode = KeyNode(key); 13 | return map.Children.TryGetValue(keyNode, out node); 14 | } 15 | 16 | public static bool TryGetScalar(this YamlMappingNode map, string key, [NotNullWhen(true)] out YamlScalarNode? scalarNode) 17 | { 18 | var keyNode = KeyNode(key); 19 | if (map.Children.TryGetValue(keyNode, out var node) && node is YamlScalarNode x) 20 | { 21 | scalarNode = x; 22 | return true; 23 | } 24 | 25 | scalarNode = default; 26 | return false; 27 | } 28 | 29 | public static bool TryGetSequence(this YamlMappingNode map, string key, [NotNullWhen(true)] out YamlSequenceNode? sequenceNode) 30 | { 31 | var keyNode = KeyNode(key); 32 | if (map.Children.TryGetValue(keyNode, out var node) && node is YamlSequenceNode x) 33 | { 34 | sequenceNode = x; 35 | return true; 36 | } 37 | 38 | sequenceNode = default; 39 | return false; 40 | } 41 | 42 | public static IEnumerable> ChildrenOfType(this YamlMappingNode node) 43 | { 44 | foreach (var (key, value) in node.Children) 45 | { 46 | if (key is TKey tkey && value is TValue tvalue) 47 | { 48 | yield return new KeyValuePair(tkey, tvalue); 49 | } 50 | } 51 | } 52 | 53 | public static bool TryGetString(this YamlMappingNode map, string key, [NotNullWhen(true)] out string? value) 54 | { 55 | if (map.TryGetScalar(key, out var scalarNode)) 56 | { 57 | value = scalarNode.Value; 58 | return value is not null; 59 | } 60 | 61 | value = default; 62 | return false; 63 | } 64 | 65 | public static bool TryGetInt(this YamlMappingNode map, string key, [NotNullWhen(true)] out int value) 66 | { 67 | if (map.TryGetScalar(key, out var scalarNode)) 68 | { 69 | return int.TryParse(scalarNode.Value, out value); 70 | } 71 | 72 | value = default; 73 | return false; 74 | } 75 | 76 | public static bool TryGetMap(this YamlMappingNode map, string key, [NotNullWhen(true)] out YamlMappingNode? mappingNode) 77 | { 78 | var keyNode = KeyNode(key); 79 | if (map.Children.TryGetValue(keyNode, out var node) && node is YamlMappingNode x) 80 | { 81 | mappingNode = x; 82 | return true; 83 | } 84 | 85 | mappingNode = default; 86 | return false; 87 | } 88 | 89 | private static YamlScalarNode KeyNode(string key) 90 | { 91 | if (!Keys.TryGetValue(key, out var keyNode)) 92 | { 93 | Keys[key] = keyNode = new YamlScalarNode(key); 94 | } 95 | 96 | return keyNode; 97 | } 98 | } -------------------------------------------------------------------------------- /src/Testing/Internal/YamlToJson.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using YamlDotNet.Core; 3 | using YamlDotNet.RepresentationModel; 4 | 5 | namespace RendleLabs.OpenApi.Testing.Internal; 6 | 7 | internal static class YamlToJson 8 | { 9 | public static JsonDocument? ToJson(YamlMappingNode map) 10 | { 11 | using var stream = new MemoryStream(); 12 | var writer = new Utf8JsonWriter(stream); 13 | 14 | WriteMap(writer, map); 15 | 16 | writer.Flush(); 17 | 18 | stream.Position = 0; 19 | return JsonDocument.Parse(stream); 20 | } 21 | 22 | private static void WriteMap(Utf8JsonWriter writer, YamlMappingNode map) 23 | { 24 | writer.WriteStartObject(); 25 | 26 | foreach (var (k, v) in map) 27 | { 28 | if (k is not YamlScalarNode keyNode || keyNode.Value is not { Length: > 0 }) continue; 29 | 30 | writer.WritePropertyName(keyNode.Value); 31 | 32 | switch (v) 33 | { 34 | case YamlScalarNode scalarNodeValue: 35 | WriteScalarValue(writer, scalarNodeValue); 36 | break; 37 | case YamlMappingNode mapNodeValue: 38 | WriteMap(writer, mapNodeValue); 39 | break; 40 | case YamlSequenceNode sequenceNodeValue: 41 | WriteArray(writer, sequenceNodeValue); 42 | break; 43 | } 44 | } 45 | 46 | writer.WriteEndObject(); 47 | } 48 | 49 | private static void WriteArray(Utf8JsonWriter writer, YamlSequenceNode sequence) 50 | { 51 | writer.WriteStartArray(); 52 | foreach (var item in sequence) 53 | { 54 | switch (item) 55 | { 56 | case YamlScalarNode scalar: 57 | WriteScalarValue(writer, scalar); 58 | break; 59 | case YamlMappingNode map: 60 | WriteMap(writer, map); 61 | break; 62 | case YamlSequenceNode seq: 63 | WriteArray(writer, seq); 64 | break; 65 | } 66 | } 67 | writer.WriteEndArray(); 68 | } 69 | 70 | private static void WriteScalarValue(Utf8JsonWriter writer, YamlScalarNode value) 71 | { 72 | if (value.Value is null) writer.WriteNullValue(); 73 | 74 | if (value.Style == ScalarStyle.Plain) 75 | { 76 | switch (value.Value) 77 | { 78 | case "true": 79 | writer.WriteBooleanValue(true); 80 | return; 81 | case "false": 82 | writer.WriteBooleanValue(false); 83 | return; 84 | case "null": 85 | writer.WriteNullValue(); 86 | return; 87 | } 88 | 89 | if (long.TryParse(value.Value, out var longValue)) 90 | { 91 | writer.WriteNumberValue(longValue); 92 | return; 93 | } 94 | 95 | if (double.TryParse(value.Value, out var doubleValue)) 96 | { 97 | writer.WriteNumberValue(doubleValue); 98 | return; 99 | } 100 | } 101 | 102 | writer.WriteStringValue(value.Value); 103 | } 104 | } -------------------------------------------------------------------------------- /src/Testing/JsonAssert.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using FluentAssertions; 3 | 4 | namespace RendleLabs.OpenApi.Testing; 5 | 6 | public static class JsonAssert 7 | { 8 | public static void Equivalent(JsonDocument expected, JsonDocument actual) 9 | { 10 | ElementEquivalent(expected.RootElement, actual.RootElement); 11 | } 12 | 13 | private static void ElementEquivalent(JsonElement expected, JsonElement actual, string jsonPath = "") 14 | { 15 | if (expected.ValueKind != actual.ValueKind) 16 | { 17 | throw new JsonEqualException(expected.ValueKind, actual.ValueKind, $"{jsonPath}(Kind)"); 18 | } 19 | 20 | switch (expected.ValueKind) 21 | { 22 | case JsonValueKind.Object: 23 | ObjectEquivalent(expected, actual, jsonPath); 24 | break; 25 | case JsonValueKind.Array: 26 | ArrayEquivalent(expected, actual, jsonPath); 27 | break; 28 | case JsonValueKind.String: 29 | StringEquivalent(expected.GetString(), actual.GetString(), jsonPath); 30 | break; 31 | case JsonValueKind.Number: 32 | actual.ValueKind.Should().Be(JsonValueKind.Number); 33 | NumberEquivalent(expected.GetDecimal(), actual.GetDecimal(), jsonPath); 34 | break; 35 | case JsonValueKind.Undefined: 36 | case JsonValueKind.True: 37 | case JsonValueKind.False: 38 | case JsonValueKind.Null: 39 | break; 40 | default: 41 | throw new ArgumentOutOfRangeException(); 42 | } 43 | } 44 | 45 | private static void StringEquivalent(string? expected, string? actual, string jsonPath) 46 | { 47 | actual.Should().Be(expected, jsonPath); 48 | } 49 | 50 | private static void NumberEquivalent(decimal? expected, decimal? actual, string jsonPath) 51 | { 52 | actual.Should().Be(expected, jsonPath); 53 | } 54 | 55 | private static void ObjectEquivalent(JsonElement expected, JsonElement actual, string? jsonPath) 56 | { 57 | foreach (var expectedProperty in expected.EnumerateObject()) 58 | { 59 | var actualProperty = actual.GetProperty(expectedProperty.Name); 60 | ElementEquivalent(expectedProperty.Value, actualProperty, $"{jsonPath}['{expectedProperty.Name}']"); 61 | } 62 | } 63 | 64 | private static void ArrayEquivalent(JsonElement expected, JsonElement actual, string jsonPath) 65 | { 66 | var expectedArray = expected.EnumerateArray().ToArray(); 67 | var actualArray = actual.EnumerateArray().ToArray(); 68 | 69 | if (expectedArray.Length != actualArray.Length) 70 | { 71 | actualArray.Length.Should().Be(expectedArray.Length); 72 | } 73 | 74 | for (int i = 0, l = expectedArray.Length; i < l; i++) 75 | { 76 | ElementEquivalent(expectedArray[i], actualArray[i], $"{jsonPath}[{i}]"); 77 | } 78 | } 79 | } -------------------------------------------------------------------------------- /src/Testing/JsonEqualException.cs: -------------------------------------------------------------------------------- 1 | using Xunit.Sdk; 2 | 3 | namespace RendleLabs.OpenApi.Testing; 4 | 5 | public class JsonEqualException : AssertActualExpectedException 6 | { 7 | public JsonEqualException(object? expected, object? actual, string jsonPath) 8 | : base(expected, actual, CreateMessage(jsonPath), null, null) 9 | { 10 | } 11 | 12 | public JsonEqualException(object? expected, object? actual, string jsonPath, Exception? innerException) 13 | : base(expected, actual, CreateMessage(jsonPath), null, null, innerException) 14 | { 15 | } 16 | 17 | private static string CreateMessage(string jsonPath) => $"Failure: JsonEqual {jsonPath}"; 18 | } -------------------------------------------------------------------------------- /src/Testing/OpenApiTest.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using System.Text.Json; 3 | using System.Text.RegularExpressions; 4 | using FluentAssertions; 5 | 6 | namespace RendleLabs.OpenApi.Testing; 7 | 8 | public class OpenApiTest 9 | { 10 | public OpenApiTest(OpenApiTestRequest testRequest, OpenApiTestResponse testResponse) 11 | { 12 | TestRequest = testRequest; 13 | TestResponse = testResponse; 14 | } 15 | 16 | internal OpenApiTestRequest TestRequest { get; } 17 | internal OpenApiTestResponse TestResponse { get; } 18 | internal HttpRequestMessage RequestMessage { get; private set; } 19 | internal HttpResponseMessage ResponseMessage { get; private set; } 20 | 21 | public async Task ExecuteAsync(HttpClient client) 22 | { 23 | 24 | var url = TestRequest.ToUri(); 25 | RequestMessage = new HttpRequestMessage(TestRequest.Method, url); 26 | 27 | if (TestRequest.Headers is { Count: > 0 }) 28 | { 29 | foreach (var (key, values) in TestRequest.Headers) 30 | { 31 | RequestMessage.Headers.TryAddWithoutValidation(key, values); 32 | } 33 | } 34 | 35 | if (TestRequest.Body != null) 36 | { 37 | RequestMessage.Content = new StringContent(TestRequest.Body, Encoding.UTF8, TestRequest.ContentType); 38 | } 39 | 40 | ResponseMessage = await client.SendAsync(RequestMessage); 41 | } 42 | 43 | public async Task Assert() 44 | { 45 | ((int)ResponseMessage.StatusCode).Should().Be(TestResponse.Status); 46 | 47 | if (TestResponse.Headers is { Count: > 0 } expectedHeaders) 48 | { 49 | foreach (var (expectedKey, expectedValues) in expectedHeaders) 50 | { 51 | ResponseMessage.Headers.Should().ContainKey(expectedKey); 52 | var actualValues = ResponseMessage.Headers.GetValues(expectedKey)!.ToHashSet(); 53 | foreach (var expectedValue in expectedValues) 54 | { 55 | if (expectedValue.StartsWith('/') && expectedValue.EndsWith('/')) 56 | { 57 | var regex = new Regex(expectedValue.Trim('/')); 58 | actualValues.Should().Contain(s => regex.IsMatch(s)); 59 | } 60 | else 61 | { 62 | actualValues.Should().Contain(expectedValue); 63 | } 64 | } 65 | } 66 | } 67 | 68 | if (TestResponse.ContentType is { Length: > 0 } contentType) 69 | { 70 | contentType.Should().Be(ResponseMessage.Content.Headers.ContentType?.ToString()); 71 | 72 | if (TestResponse.Body is { Length: > 0 } expectedBody) 73 | { 74 | if (contentType.StartsWith("text/")) 75 | { 76 | var body = await ResponseMessage.Content.ReadAsStringAsync(); 77 | body.Trim().Should().Be(expectedBody.Trim()); 78 | } 79 | else if (contentType == "application/json") 80 | { 81 | var expectedJson = JsonDocument.Parse(expectedBody); 82 | var actualJson = await JsonDocument.ParseAsync(await ResponseMessage.Content.ReadAsStreamAsync()); 83 | JsonAssert.Equivalent(expectedJson, actualJson); 84 | } 85 | } 86 | } 87 | } 88 | } -------------------------------------------------------------------------------- /src/Testing/OpenApiTestBody.cs: -------------------------------------------------------------------------------- 1 | namespace RendleLabs.OpenApi.Testing; 2 | 3 | public class OpenApiTestBody 4 | { 5 | public OpenApiTestBody(string contentType, string requestBody) 6 | { 7 | ContentType = contentType; 8 | Content = requestBody; 9 | } 10 | 11 | public string ContentType { get; } 12 | public string Content { get; } 13 | } -------------------------------------------------------------------------------- /src/Testing/OpenApiTestDocument.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | 3 | namespace RendleLabs.OpenApi.Testing; 4 | 5 | public class OpenApiTestDocument 6 | { 7 | public OpenApiTestDocument(string? server, List tests) 8 | { 9 | Server = server; 10 | Tests = tests.ToArray(); 11 | } 12 | 13 | public string? Server { get; } 14 | 15 | public OpenApiTestElement[] Tests { get; } 16 | } -------------------------------------------------------------------------------- /src/Testing/OpenApiTestElement.cs: -------------------------------------------------------------------------------- 1 | namespace RendleLabs.OpenApi.Testing; 2 | 3 | public class OpenApiTestElement 4 | { 5 | public HttpMethod Method { get; set; } 6 | public string Uri { get; set; } 7 | public OpenApiTestBody? RequestBody { get; internal init; } 8 | public IReadOnlyDictionary Headers { get; internal init; } 9 | public OpenApiTestExpect Expect { get; internal init; } 10 | public string? OutputName { get; internal init; } 11 | } 12 | 13 | public class OpenApiTestSequence 14 | { 15 | 16 | } -------------------------------------------------------------------------------- /src/Testing/OpenApiTestExpect.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | 3 | namespace RendleLabs.OpenApi.Testing; 4 | 5 | public class OpenApiTestExpect 6 | { 7 | public OpenApiTestExpect(int status, OpenApiTestBody? responseBody, ReadOnlyDictionary headers) 8 | { 9 | Status = status; 10 | ResponseBody = responseBody; 11 | Headers = headers; 12 | } 13 | 14 | public int Status { get; } 15 | public OpenApiTestBody? ResponseBody { get; } 16 | public IReadOnlyDictionary Headers { get; } 17 | } -------------------------------------------------------------------------------- /src/Testing/OpenApiTestPath.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using Microsoft.OpenApi.Models; 3 | 4 | namespace RendleLabs.OpenApi.Testing; 5 | 6 | public class OpenApiTestPath 7 | { 8 | public OpenApiTestPath(string path, Dictionary operations) 9 | { 10 | Path = path; 11 | Operations = new ReadOnlyDictionary(operations); 12 | } 13 | 14 | public string Path { get; } 15 | 16 | public IReadOnlyDictionary Operations { get; } 17 | } -------------------------------------------------------------------------------- /src/Testing/OpenApiTestRequest.cs: -------------------------------------------------------------------------------- 1 | namespace RendleLabs.OpenApi.Testing; 2 | 3 | public class OpenApiTestRequest 4 | { 5 | public HttpMethod Method { get; init; } = null!; 6 | public string? Server { get; init; } 7 | public string Path { get; init; } = null!; 8 | public string? Body { get; init; } 9 | public string? ContentType { get; init; } 10 | public IReadOnlyDictionary? Headers { get; init; } 11 | 12 | public override string ToString() => $"{Method} {ToUri()}"; 13 | 14 | public Uri ToUri() => 15 | Server is { Length: > 0 } 16 | ? new Uri($"{Server.TrimEnd('/')}/{Path.TrimStart('/')}", UriKind.Absolute) 17 | : new Uri(Path, UriKind.Relative); 18 | } -------------------------------------------------------------------------------- /src/Testing/OpenApiTestResponse.cs: -------------------------------------------------------------------------------- 1 | namespace RendleLabs.OpenApi.Testing; 2 | 3 | public class OpenApiTestResponse 4 | { 5 | public int Status { get; set; } 6 | public string? Body { get; set; } 7 | public IReadOnlyDictionary? Headers { get; set; } 8 | public string? ContentType { get; set; } 9 | public string? OutputName { get; set; } 10 | 11 | public string? GetOutput(string path) 12 | { 13 | var parts = path.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).AsSpan(); 14 | if (parts.Length < 2) throw new InvalidOperationException(); 15 | if (parts[0].Equals("Headers")) return GetOutputHeader(parts.Slice(1)); 16 | else throw new InvalidOperationException(); 17 | } 18 | 19 | private string? GetOutputHeader(Span slice) 20 | { 21 | if (Headers is null) return null; 22 | if (Headers.TryGetValue(slice[0], out var headers) && headers?.Length > 0) return headers.FirstOrDefault(); 23 | return null; 24 | } 25 | 26 | public override string ToString() => Status.ToString(); 27 | } 28 | -------------------------------------------------------------------------------- /src/Testing/OpenApiTheoryData.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Text.RegularExpressions; 3 | using Microsoft.OpenApi.Models; 4 | using RendleLabs.OpenApi.Testing.Internal; 5 | using Xunit.Sdk; 6 | 7 | namespace RendleLabs.OpenApi.Testing; 8 | 9 | public class OpenApiTestDataAttribute : DataAttribute 10 | { 11 | public override IEnumerable GetData(MethodInfo testMethod) 12 | { 13 | throw new NotImplementedException(); 14 | } 15 | } 16 | 17 | public class OpenApiTheoryData 18 | { 19 | private readonly OpenApiTestDocument _testDocument; 20 | private readonly OpenApiDocument _apiDocument; 21 | 22 | public OpenApiTheoryData(OpenApiTestDocument testDocument, OpenApiDocument apiDocument) 23 | { 24 | _testDocument = testDocument; 25 | _apiDocument = apiDocument; 26 | } 27 | 28 | public IEnumerable Enumerate() 29 | { 30 | var server = _testDocument.Server; 31 | 32 | var list = new List<(OpenApiTestRequest, OpenApiTestResponse)>(_testDocument.Tests.Length); 33 | 34 | foreach (var test in _testDocument.Tests) 35 | { 36 | var request = OpenApiTestRequest(server, test.Uri, test.Method, test); 37 | 38 | var response = OpenApiTestResponse(test); 39 | 40 | list.Add((request, response)); 41 | } 42 | 43 | for (int i = list.Count - 1; i >= 0; i++) 44 | { 45 | var (request, response) = list[i]; 46 | if (request.Path.Contains('{')) 47 | { 48 | var variables = OutputVariables.Get(request.Path); 49 | } 50 | } 51 | 52 | throw new NotImplementedException(); 53 | } 54 | 55 | private string CreatePath(OperationType operationType, string pathTemplate, IReadOnlyDictionary parameters) 56 | { 57 | if (!_apiDocument.Paths.TryGetValue(pathTemplate, out var pathItem)) return pathTemplate; 58 | var path = pathTemplate; 59 | var queryString = new QueryString(); 60 | foreach (var (key, value) in parameters) 61 | { 62 | if (pathItem.TryGetParameter(operationType, key, out var parameter)) 63 | { 64 | switch (parameter.In) 65 | { 66 | case ParameterLocation.Path: 67 | path = path.Replace($"{{{key}}}", value); 68 | break; 69 | case ParameterLocation.Query when value is not null: 70 | queryString.Add(key, value); 71 | break; 72 | } 73 | } 74 | } 75 | 76 | return path + queryString; 77 | } 78 | 79 | private static OpenApiTestRequest OpenApiTestRequest(string? server, string path, HttpMethod method, OpenApiTestElement operationTestElement) 80 | { 81 | var request = new OpenApiTestRequest 82 | { 83 | Server = server, 84 | Path = path, 85 | Method = method, 86 | Body = operationTestElement.RequestBody?.Content, 87 | ContentType = operationTestElement.RequestBody?.ContentType, 88 | Headers = operationTestElement.Headers, 89 | }; 90 | return request; 91 | } 92 | 93 | private static OpenApiTestResponse OpenApiTestResponse(OpenApiTestElement testElement) 94 | { 95 | var response = new OpenApiTestResponse 96 | { 97 | Status = testElement.Expect.Status, 98 | ContentType = testElement.Expect.ResponseBody?.ContentType, 99 | Body = testElement.Expect.ResponseBody?.Content, 100 | Headers = testElement.Expect.Headers, 101 | OutputName = testElement.OutputName, 102 | }; 103 | return response; 104 | } 105 | 106 | private static HttpMethod GetHttpMethod(OperationType operationType) 107 | { 108 | return operationType switch 109 | { 110 | OperationType.Get => HttpMethod.Get, 111 | OperationType.Put => HttpMethod.Put, 112 | OperationType.Post => HttpMethod.Post, 113 | OperationType.Delete => HttpMethod.Delete, 114 | OperationType.Options => HttpMethod.Options, 115 | OperationType.Head => HttpMethod.Head, 116 | OperationType.Patch => HttpMethod.Patch, 117 | OperationType.Trace => HttpMethod.Trace, 118 | _ => throw new ArgumentOutOfRangeException(nameof(operationType), operationType, null) 119 | }; 120 | } 121 | } 122 | 123 | internal static class OutputVariables 124 | { 125 | private static readonly Regex TextInBraces = new Regex(@"\{\{.+?\}\}", RegexOptions.Compiled); 126 | 127 | public static OutputVariable[] Get(string input) 128 | { 129 | var matches = TextInBraces.Matches(input); 130 | return matches.Count == 0 131 | ? Array.Empty() 132 | : matches.Select(m => m.Value.TrimStart('{')).Select(s => s.TrimEnd('}')).Select(Create).ToArray(); 133 | } 134 | 135 | private static OutputVariable Create(string input) 136 | { 137 | input = input.TrimStart('{').TrimEnd('}'); 138 | var firstDot = input.IndexOf('.'); 139 | if (firstDot < 1) throw new InvalidOperationException(); 140 | var source = input.Substring(0, firstDot); 141 | 142 | if (source.Equals("header", StringComparison.OrdinalIgnoreCase)) return new HeaderOutputVariable(source, input.Substring(firstDot + 1)); 143 | 144 | throw new NotImplementedException(); 145 | } 146 | } 147 | 148 | internal abstract class OutputVariable 149 | { 150 | protected OutputVariable(string source) 151 | { 152 | Source = source; 153 | } 154 | 155 | public string Source { get; } 156 | 157 | public abstract string? Get(HttpResponseMessage response); 158 | } 159 | 160 | internal class HeaderOutputVariable : OutputVariable 161 | { 162 | public HeaderOutputVariable(string source, string name) : base(source) 163 | { 164 | Name = name; 165 | } 166 | 167 | public string Name { get; } 168 | 169 | public override string? Get(HttpResponseMessage response) 170 | { 171 | return response.Headers.TryGetValues(Name, out var values) 172 | ? values.FirstOrDefault() 173 | : null; 174 | } 175 | } -------------------------------------------------------------------------------- /src/Testing/Testing.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | RendleLabs.OpenApi.Testing 8 | RendleLabs.OpenApi.Testing 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/Web/ElementsEndpoint.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Text; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.AspNetCore.Routing; 5 | 6 | namespace RendleLabs.OpenApi.Web; 7 | 8 | internal static class ElementsEndpoint 9 | { 10 | private static byte[]? _htmlBytes; 11 | 12 | public static void Map(IEndpointRouteBuilder app, StaticOpenApiOptions options, string specPath, 13 | StaticOpenApiEndpointConventionBuilder endpointConventionBuilder) 14 | { 15 | endpointConventionBuilder.Add( 16 | app.MapGet(options.Elements.Path!, async context => 17 | { 18 | _htmlBytes ??= await LoadHtmlBytesFromAssembly(specPath); 19 | 20 | if (_htmlBytes.Length == 0) 21 | { 22 | context.Response.StatusCode = 404; 23 | return; 24 | } 25 | 26 | context.Response.StatusCode = 200; 27 | context.Response.ContentType = "text/html"; 28 | context.Response.ContentLength = _htmlBytes.Length; 29 | await context.Response.BodyWriter.WriteAsync(_htmlBytes); 30 | await context.Response.BodyWriter.FlushAsync(); 31 | })); 32 | } 33 | 34 | private static async Task LoadHtmlBytesFromAssembly(string? specPath) 35 | { 36 | var resource = $"RendleLabs.OpenApi.Web.Resources.elements.html"; 37 | await using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource); 38 | if (stream is null) 39 | { 40 | return Array.Empty(); 41 | } 42 | 43 | using var reader = new StreamReader(stream); 44 | var html = await reader.ReadToEndAsync(); 45 | html = html.Replace("{{SPEC_URL}}", specPath); 46 | return Encoding.UTF8.GetBytes(html); 47 | } 48 | } -------------------------------------------------------------------------------- /src/Web/EndpointConventionBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | 3 | namespace RendleLabs.OpenApi.Web; 4 | 5 | internal static class EndpointConventionBuilderExtensions 6 | { 7 | public static IEndpointConventionBuilder AllowAnonymous(this IEndpointConventionBuilder builder, bool allowAnonymous) 8 | { 9 | if (allowAnonymous) 10 | { 11 | builder.AllowAnonymous(); 12 | } 13 | 14 | return builder; 15 | } 16 | } -------------------------------------------------------------------------------- /src/Web/RedocEndpoint.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Text; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.AspNetCore.Routing; 5 | 6 | namespace RendleLabs.OpenApi.Web; 7 | 8 | internal static class RedocEndpoint 9 | { 10 | private static byte[]? _htmlBytes; 11 | 12 | public static void Map(IEndpointRouteBuilder app, StaticOpenApiOptions options, string specPath, 13 | StaticOpenApiEndpointConventionBuilder endpointConventionBuilder) 14 | { 15 | endpointConventionBuilder.Add( 16 | app.MapGet(options.Redoc.Path!, async context => 17 | { 18 | _htmlBytes ??= await LoadHtmlBytesFromAssembly(specPath); 19 | 20 | if (_htmlBytes.Length == 0) 21 | { 22 | context.Response.StatusCode = 404; 23 | return; 24 | } 25 | 26 | context.Response.StatusCode = 200; 27 | context.Response.ContentType = "text/html"; 28 | context.Response.ContentLength = _htmlBytes.Length; 29 | await context.Response.BodyWriter.WriteAsync(_htmlBytes); 30 | await context.Response.BodyWriter.FlushAsync(); 31 | })); 32 | } 33 | 34 | private static async Task LoadHtmlBytesFromAssembly(string? specPath) 35 | { 36 | var resource = $"RendleLabs.OpenApi.Web.Resources.redoc.html"; 37 | await using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource); 38 | if (stream is null) 39 | { 40 | return Array.Empty(); 41 | } 42 | 43 | using var reader = new StreamReader(stream); 44 | var html = await reader.ReadToEndAsync(); 45 | html = html.Replace("{{SPEC_URL}}", specPath); 46 | return Encoding.UTF8.GetBytes(html); 47 | } 48 | } -------------------------------------------------------------------------------- /src/Web/Resources/elements.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Elements in HTML 7 | 8 | 9 | 10 | 11 | 12 | 13 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/Web/Resources/redoc.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Redoc 5 | 6 | 7 | 11 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/Web/StaticOpenApiEndpointRouteBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Routing; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using Microsoft.Extensions.Logging; 8 | using Microsoft.OpenApi; 9 | using Microsoft.OpenApi.Extensions; 10 | using Microsoft.OpenApi.Models; 11 | using Microsoft.OpenApi.Readers; 12 | 13 | namespace RendleLabs.OpenApi.Web; 14 | 15 | internal class StaticOpenApi 16 | { 17 | } 18 | 19 | public static class StaticOpenApiEndpointRouteBuilderExtensions 20 | { 21 | public static IEndpointConventionBuilder UseStaticOpenApi(this IEndpointRouteBuilder app, string sourceFile, StaticOpenApiOptions options) 22 | { 23 | var document = LoadOpenApiDocumentFromContentFile(app, sourceFile); 24 | 25 | var endpointConventionBuilder = new StaticOpenApiEndpointConventionBuilder(); 26 | MapEndpoints(app, options, document, endpointConventionBuilder); 27 | 28 | return endpointConventionBuilder; 29 | } 30 | 31 | public static IEndpointConventionBuilder UseStaticOpenApi(this IEndpointRouteBuilder app, Assembly resourceAssembly, string resourcePath, 32 | StaticOpenApiOptions options) 33 | { 34 | var endpointConventionBuilder = new StaticOpenApiEndpointConventionBuilder(); 35 | var sourceStream = resourceAssembly.GetManifestResourceStream(resourcePath); 36 | if (sourceStream is null) 37 | { 38 | app.ServiceProvider.GetService>() 39 | ?.LogWarning("OpenAPI embedded resource {ResourcePath} not found.", resourcePath); 40 | return endpointConventionBuilder; 41 | } 42 | 43 | var document = LoadOpenApiDocumentFromStream(app, sourceStream); 44 | 45 | MapEndpoints(app, options, document, endpointConventionBuilder); 46 | 47 | return endpointConventionBuilder; 48 | } 49 | 50 | private static void MapEndpoints(IEndpointRouteBuilder app, StaticOpenApiOptions options, OpenApiDocument document, 51 | StaticOpenApiEndpointConventionBuilder endpointConventionBuilder) 52 | { 53 | document.Servers.Clear(); 54 | var serverUrlSet = new HashSet(StringComparer.CurrentCultureIgnoreCase); 55 | string? specPath = null; 56 | if (options.JsonPath is { Length: > 0 }) 57 | { 58 | specPath = options.JsonPath; 59 | endpointConventionBuilder.Add( 60 | app.MapGet(options.JsonPath, async context => 61 | { 62 | AddRequestServer(context.Request, document, serverUrlSet); 63 | var json = document.SerializeAsJson(options.Version == 3 ? OpenApiSpecVersion.OpenApi3_0 : OpenApiSpecVersion.OpenApi2_0); 64 | context.Response.StatusCode = 200; 65 | context.Response.ContentType = "application/json"; 66 | await context.Response.WriteAsync(json); 67 | }) 68 | ); 69 | 70 | if (options.UiPathPrefix is { Length: > 0 }) 71 | { 72 | SwaggerUiEndpoints.Map(app, options, endpointConventionBuilder); 73 | } 74 | } 75 | 76 | if (options.YamlPath is { Length: > 0 }) 77 | { 78 | specPath ??= options.YamlPath; 79 | endpointConventionBuilder.Add( 80 | app.MapGet(options.YamlPath, async context => 81 | { 82 | AddRequestServer(context.Request, document, serverUrlSet); 83 | var yaml = document.SerializeAsYaml(options.Version == 3 ? OpenApiSpecVersion.OpenApi3_0 : OpenApiSpecVersion.OpenApi2_0); 84 | context.Response.StatusCode = 200; 85 | context.Response.ContentType = "application/yaml"; 86 | await context.Response.WriteAsync(yaml); 87 | })); 88 | } 89 | 90 | if (specPath is { Length: > 0 }) 91 | { 92 | specPath = "/" + specPath.Trim('/'); 93 | if (options.Elements.Path is { Length: > 0 }) 94 | { 95 | ElementsEndpoint.Map(app, options, specPath, endpointConventionBuilder); 96 | } 97 | else if (options.Redoc.Path is { Length: > 0 }) 98 | { 99 | RedocEndpoint.Map(app, options, specPath, endpointConventionBuilder); 100 | } 101 | } 102 | } 103 | 104 | private static void AddRequestServer(HttpRequest request, OpenApiDocument document, HashSet serverUrlSet) 105 | { 106 | var host = $"{request.Scheme}://{request.Host}"; 107 | if (serverUrlSet.Add(host)) 108 | { 109 | document.Servers.Insert(0, new OpenApiServer 110 | { 111 | Url = host 112 | }); 113 | } 114 | } 115 | 116 | private static OpenApiDocument LoadOpenApiDocumentFromContentFile(IEndpointRouteBuilder app, string sourceFile) 117 | { 118 | using var sourceStream = app.ServiceProvider.GetRequiredService() 119 | .ContentRootFileProvider 120 | .GetFileInfo(sourceFile) 121 | .CreateReadStream(); 122 | 123 | return LoadOpenApiDocumentFromStream(app, sourceStream); 124 | } 125 | 126 | private static OpenApiDocument LoadOpenApiDocumentFromStream(IEndpointRouteBuilder app, Stream sourceStream) 127 | { 128 | var document = new OpenApiStreamReader().Read(sourceStream, out var diagnostic); 129 | 130 | if (diagnostic.Errors.Count > 0) 131 | { 132 | throw new StaticOpenApiLoadException(diagnostic.Errors); 133 | } 134 | 135 | if (diagnostic.Warnings.Count > 0 136 | && app.ServiceProvider.GetService()?.CreateLogger("StaticOpenApi") is { } logger) 137 | { 138 | foreach (var warning in diagnostic.Warnings) 139 | { 140 | logger.LogWarning("{Message}: {Pointer}", warning.Message, warning.Pointer); 141 | } 142 | } 143 | 144 | return document; 145 | } 146 | } 147 | 148 | internal class StaticOpenApiEndpointConventionBuilder : IEndpointConventionBuilder 149 | { 150 | private readonly List _builders = new(); 151 | 152 | public void Add(IEndpointConventionBuilder builder) => _builders.Add(builder); 153 | 154 | public void Add(Action convention) 155 | { 156 | foreach (var builder in _builders) 157 | { 158 | builder.Add(convention); 159 | } 160 | } 161 | } -------------------------------------------------------------------------------- /src/Web/StaticOpenApiLoadException.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | 3 | namespace RendleLabs.OpenApi.Web; 4 | 5 | [Serializable] 6 | public class StaticOpenApiLoadException : Exception 7 | { 8 | public StaticOpenApiLoadException(IList errors) : base("Error loading OpenApi document") 9 | { 10 | Errors = errors; 11 | } 12 | 13 | public IList Errors { get; } 14 | } -------------------------------------------------------------------------------- /src/Web/StaticOpenApiOptions.cs: -------------------------------------------------------------------------------- 1 | namespace RendleLabs.OpenApi.Web; 2 | 3 | public class StaticOpenApiOptions 4 | { 5 | public string? JsonPath { get; set; } 6 | public string? YamlPath { get; set; } 7 | public string? UiPathPrefix { get; set; } 8 | public int Version { get; set; } = 3; 9 | public RedocOptions Redoc { get; } = new(); 10 | public ElementsOptions Elements { get; } = new(); 11 | } 12 | 13 | public class RedocOptions 14 | { 15 | public bool Enabled { get; set; } 16 | public string? Path { get; set; } 17 | } 18 | 19 | public class ElementsOptions 20 | { 21 | public bool Enabled { get; set; } 22 | public string? Path { get; set; } 23 | } 24 | -------------------------------------------------------------------------------- /src/Web/SwaggerUiEndpoints.cs: -------------------------------------------------------------------------------- 1 | using System.IO.Pipelines; 2 | using System.Reflection; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.AspNetCore.Http; 5 | using Microsoft.AspNetCore.Routing; 6 | 7 | namespace RendleLabs.OpenApi.Web; 8 | 9 | internal static class SwaggerUiEndpoints 10 | { 11 | public static void Map(IEndpointRouteBuilder app, StaticOpenApiOptions options, 12 | StaticOpenApiEndpointConventionBuilder endpointConventionBuilder) 13 | { 14 | var uiPathPrefix = options.UiPathPrefix!.Trim('/'); 15 | 16 | endpointConventionBuilder.Add( 17 | app.MapGet($"{uiPathPrefix}/swagger-initializer.js", async context => 18 | { 19 | var swaggerInitializerJs = SwaggerUiInitializerTemplate 20 | .Replace("{{SWAGGER.JSON}}", $"/{options.JsonPath!.Trim('/')}") 21 | .Replace("{{OAUTH2_REDIRECT_URL}}", $"{context.Request.Scheme}://{context.Request.Host}/{uiPathPrefix}/oauth2-redirect.html"); 22 | context.Response.StatusCode = 200; 23 | await context.Response.WriteAsync(swaggerInitializerJs); 24 | })); 25 | 26 | endpointConventionBuilder.Add( 27 | app.MapGet($"{uiPathPrefix}/", async context => 28 | { 29 | context.Response.StatusCode = 301; 30 | context.Response.Headers.Location = $"{uiPathPrefix}/index.html"; 31 | await context.Response.CompleteAsync(); 32 | })); 33 | 34 | endpointConventionBuilder.Add( 35 | app.MapGet($"{uiPathPrefix}/{{*path}}", async context => 36 | { 37 | if (!context.Request.RouteValues.TryGetValue("path", out var path)) 38 | { 39 | path = "index.html"; 40 | } 41 | 42 | var resource = $"RendleLabs.OpenApi.Web.node_modules.swagger_ui_dist.{path}"; 43 | await using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource); 44 | if (stream is null) 45 | { 46 | context.Response.StatusCode = 404; 47 | await context.Response.CompleteAsync(); 48 | return; 49 | } 50 | 51 | context.Response.StatusCode = 200; 52 | await stream.CopyToAsync(context.Response.BodyWriter); 53 | })); 54 | } 55 | 56 | private const string SwaggerUiInitializerTemplate = @"window.onload = function() { 57 | // 58 | 59 | // the following lines will be replaced by docker/configurator, when it runs in a docker-container 60 | window.ui = SwaggerUIBundle({ 61 | url: ""{{SWAGGER.JSON}}"", 62 | oauth2RedirectUrl: ""{{OAUTH2_REDIRECT_URL}}"", 63 | dom_id: '#swagger-ui', 64 | deepLinking: true, 65 | presets: [ 66 | SwaggerUIBundle.presets.apis, 67 | SwaggerUIStandalonePreset 68 | ], 69 | plugins: [ 70 | SwaggerUIBundle.plugins.DownloadUrl 71 | ], 72 | layout: ""StandaloneLayout"" 73 | }); 74 | 75 | // 76 | };"; 77 | } -------------------------------------------------------------------------------- /src/Web/Web.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | RendleLabs.OpenApi.Web 8 | RendleLabs.OpenApi.Web 9 | 10 | 11 | 12 | RendleLabs.OpenApi.Web 13 | MIT 14 | https://github.com/RendleLabs/OpenApi 15 | openapi;swagger 16 | 0.1.4-beta 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /src/Web/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rendlelabs-openapi-web", 3 | "version": "1.0.0", 4 | "lockfileVersion": 2, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "rendlelabs-openapi-web", 9 | "version": "1.0.0", 10 | "license": "MIT", 11 | "dependencies": { 12 | "swagger-ui-dist": "4.14.2" 13 | } 14 | }, 15 | "node_modules/swagger-ui-dist": { 16 | "version": "4.14.2", 17 | "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-4.14.2.tgz", 18 | "integrity": "sha512-kOIU7Ts3TrXDLb3/c9jRe4qGp8O3bRT19FFJA8wJfrRFkcK/4atPn3krhtBVJ57ZkNNofworXHxuYwmaisXBdg==" 19 | } 20 | }, 21 | "dependencies": { 22 | "swagger-ui-dist": { 23 | "version": "4.14.2", 24 | "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-4.14.2.tgz", 25 | "integrity": "sha512-kOIU7Ts3TrXDLb3/c9jRe4qGp8O3bRT19FFJA8wJfrRFkcK/4atPn3krhtBVJ57ZkNNofworXHxuYwmaisXBdg==" 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Web/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rendlelabs-openapi-web", 3 | "version": "1.0.0", 4 | "description": "Libraries for working with static OpenApi files and testing OpenApi implementations", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/RendleLabs/OpenApi.git" 8 | }, 9 | "author": "Mark Rendle", 10 | "license": "MIT", 11 | "bugs": { 12 | "url": "https://github.com/RendleLabs/OpenApi/issues" 13 | }, 14 | "homepage": "https://github.com/RendleLabs/OpenApi#readme", 15 | "dependencies": { 16 | "swagger-ui-dist": "4.14.2" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /test/Analyzer.Tests/Analyzer.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | all 17 | 18 | 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | all 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /test/Analyzer.Tests/UnitTest1.cs: -------------------------------------------------------------------------------- 1 | namespace Analyzer.Tests; 2 | 3 | public class UnitTest1 4 | { 5 | [Fact] 6 | public void GetsLastTokens() 7 | { 8 | const string source = "Microsoft.AspNetCore.Mvc.ControllerBase"; 9 | var input = source.AsSpan(); 10 | 11 | var typeName = TextHelpers.GetLastToken(ref input, '.'); 12 | Assert.Equal("ControllerBase", new string(typeName)); 13 | 14 | var mvc = TextHelpers.GetLastToken(ref input, '.'); 15 | Assert.Equal("Mvc", new string(mvc)); 16 | var aspNetCore = TextHelpers.GetLastToken(ref input, '.'); 17 | Assert.Equal("AspNetCore", new string(aspNetCore)); 18 | var microsoft = TextHelpers.GetLastToken(ref input, '.'); 19 | Assert.Equal("Microsoft", new string(microsoft)); 20 | 21 | Assert.Equal(0, input.Length); 22 | } 23 | } -------------------------------------------------------------------------------- /test/Analyzer.Tests/Usings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; -------------------------------------------------------------------------------- /test/Bundle.Tests/Bundle.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | false 9 | RendleLabs.OpenApi.Bundle.Tests 10 | 11 | 12 | 13 | 14 | 15 | 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | all 18 | 19 | 20 | runtime; build; native; contentfiles; analyzers; buildtransitive 21 | all 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | Always 32 | 33 | 34 | Always 35 | 36 | 37 | Always 38 | 39 | 40 | Always 41 | 42 | 43 | Always 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /test/Bundle.Tests/FragmentFinderTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.OpenApi.Models; 2 | 3 | namespace RendleLabs.OpenApi.Bundle.Tests; 4 | 5 | public class FragmentFinderTests 6 | { 7 | [Fact] 8 | public void FindsSchema() 9 | { 10 | var yaml = @"components: 11 | schemas: 12 | foo: 13 | type: object 14 | properties: 15 | id: 16 | type: number"; 17 | 18 | var schema = FragmentFinder.Find(yaml, "components/schemas/foo"); 19 | Assert.Equal("object", schema.Type); 20 | } 21 | } -------------------------------------------------------------------------------- /test/Bundle.Tests/ReferenceWalkerTests.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Text; 3 | using Microsoft.OpenApi; 4 | using Microsoft.OpenApi.Extensions; 5 | using Microsoft.OpenApi.Models; 6 | using Microsoft.OpenApi.Readers; 7 | using Microsoft.OpenApi.Writers; 8 | 9 | namespace RendleLabs.OpenApi.Bundle.Tests; 10 | 11 | public class ReferenceWalkerTests 12 | { 13 | [Fact] 14 | public async Task FindsReferencesInYaml() 15 | { 16 | var path = GetPath("openapi.yaml"); 17 | var directory = Path.GetDirectoryName(path)!; 18 | var document = await LoadOpenApiDocument(path)!; 19 | if (document is null) throw new InvalidOperationException(); 20 | 21 | var walker = new ReferenceWalker(); 22 | var references = new ReferenceInfoCollection(); 23 | walker.Walk(document, directory, references); 24 | 25 | await new ReferenceResolver(document, references).ResolveAsync(); 26 | 27 | Assert.NotNull(document); 28 | 29 | var country = Assert.Contains("Country", document.Components.Schemas); 30 | var isoCountryCode = Assert.Contains("IsoCountryCode", document.Components.Schemas); 31 | var internalServerError = Assert.Contains("InternalServerError", document.Components.Responses); 32 | } 33 | 34 | private static async Task LoadOpenApiDocument(string openApiPath) 35 | { 36 | var stream = File.OpenRead(openApiPath); 37 | var result = await new OpenApiStreamReader().ReadAsync(stream); 38 | return result.OpenApiDocument; 39 | } 40 | 41 | private static string GetPath(string fileName) 42 | { 43 | var directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "TestData"); 44 | var openapiPath = Path.Combine(directory, fileName); 45 | return openapiPath; 46 | } 47 | 48 | private static string ToString(OpenApiDocument document) 49 | { 50 | var settings = new OpenApiWriterSettings 51 | { 52 | InlineLocalReferences = false, 53 | }; 54 | var sb = new StringBuilder(); 55 | using var sw = new StringWriter(sb); 56 | var writer = new OpenApiYamlWriter(sw, settings); 57 | document.Serialize(writer, OpenApiSpecVersion.OpenApi3_0); 58 | return sb.ToString(); 59 | } 60 | } 61 | 62 | public class SchemaLoaderTests 63 | { 64 | [Fact] 65 | public void LoadsSchema() 66 | { 67 | var directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "TestData"); 68 | var schemaPath = Path.Combine(directory, "country.schema.json"); 69 | var loader = new SchemaLoader(); 70 | var schema = loader.LoadSchema(schemaPath, out var diagnostic); 71 | Assert.NotNull(schema); 72 | } 73 | } -------------------------------------------------------------------------------- /test/Bundle.Tests/TestData/Responses/InternalServerError.yaml: -------------------------------------------------------------------------------- 1 | description: Internal Server Error 2 | content: 3 | application/json: 4 | schema: 5 | type: object 6 | properties: 7 | title: 8 | type: string 9 | detail: 10 | type: string -------------------------------------------------------------------------------- /test/Bundle.Tests/TestData/Schema/Country.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/schema", 3 | "$id": "https://newdaycards.com/contactdetails/Country.json", 4 | "description": "An ISO-recognized country", 5 | "type": "object", 6 | "properties": { 7 | "isoCode": { 8 | "$ref": "./IsoCountryCode.json" 9 | }, 10 | "englishShortName": { 11 | "type": "string" 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /test/Bundle.Tests/TestData/Schema/IsoCountryCode.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/schema", 3 | "$id": "https://newdaycards.com/contactdetails/IsoCountryCode.schema.json", 4 | "description": "Two-letter ISO 3166 Country Code", 5 | "type": "string", 6 | "enum": [ 7 | "AF", 8 | "AX", 9 | "AL", 10 | "DZ", 11 | "AS", 12 | "AD", 13 | "AO", 14 | "AI", 15 | "AQ", 16 | "AG", 17 | "AR", 18 | "AM", 19 | "AW", 20 | "AU", 21 | "AT", 22 | "AZ", 23 | "BS", 24 | "BH", 25 | "BD", 26 | "BB", 27 | "BY", 28 | "BE", 29 | "BZ", 30 | "BJ", 31 | "BM", 32 | "BT", 33 | "BO", 34 | "BQ", 35 | "BA", 36 | "BW", 37 | "BV", 38 | "BR", 39 | "IO", 40 | "BN", 41 | "BG", 42 | "BF", 43 | "BI", 44 | "CV", 45 | "KH", 46 | "CM", 47 | "CA", 48 | "KY", 49 | "CF", 50 | "TD", 51 | "CL", 52 | "CN", 53 | "CX", 54 | "CC", 55 | "CO", 56 | "KM", 57 | "CG", 58 | "CD", 59 | "CK", 60 | "CR", 61 | "CI", 62 | "HR", 63 | "CU", 64 | "CW", 65 | "CY", 66 | "CZ", 67 | "DK", 68 | "DJ", 69 | "DM", 70 | "DO", 71 | "EC", 72 | "EG", 73 | "SV", 74 | "GQ", 75 | "ER", 76 | "EE", 77 | "SZ", 78 | "ET", 79 | "FK", 80 | "FO", 81 | "FJ", 82 | "FI", 83 | "FR", 84 | "GF", 85 | "PF", 86 | "TF", 87 | "GA", 88 | "GM", 89 | "GE", 90 | "DE", 91 | "GH", 92 | "GI", 93 | "GR", 94 | "GL", 95 | "GD", 96 | "GP", 97 | "GU", 98 | "GT", 99 | "GG", 100 | "GN", 101 | "GW", 102 | "GY", 103 | "HT", 104 | "HM", 105 | "VA", 106 | "HN", 107 | "HK", 108 | "HU", 109 | "IS", 110 | "IN", 111 | "ID", 112 | "IR", 113 | "IQ", 114 | "IE", 115 | "IM", 116 | "IL", 117 | "IT", 118 | "JM", 119 | "JP", 120 | "JE", 121 | "JO", 122 | "KZ", 123 | "KE", 124 | "KI", 125 | "KP", 126 | "KR", 127 | "KW", 128 | "KG", 129 | "LA", 130 | "LV", 131 | "LB", 132 | "LS", 133 | "LR", 134 | "LY", 135 | "LI", 136 | "LT", 137 | "LU", 138 | "MO", 139 | "MG", 140 | "MW", 141 | "MY", 142 | "MV", 143 | "ML", 144 | "MT", 145 | "MH", 146 | "MQ", 147 | "MR", 148 | "MU", 149 | "YT", 150 | "MX", 151 | "FM", 152 | "MD", 153 | "MC", 154 | "MN", 155 | "ME", 156 | "MS", 157 | "MA", 158 | "MZ", 159 | "MM", 160 | "NA", 161 | "NR", 162 | "NP", 163 | "NL", 164 | "NC", 165 | "NZ", 166 | "NI", 167 | "NE", 168 | "NG", 169 | "NU", 170 | "NF", 171 | "MK", 172 | "MP", 173 | "NO", 174 | "OM", 175 | "PK", 176 | "PW", 177 | "PS", 178 | "PA", 179 | "PG", 180 | "PY", 181 | "PE", 182 | "PH", 183 | "PN", 184 | "PL", 185 | "PT", 186 | "PR", 187 | "QA", 188 | "RE", 189 | "RO", 190 | "RU", 191 | "RW", 192 | "BL", 193 | "SH", 194 | "KN", 195 | "LC", 196 | "MF", 197 | "PM", 198 | "VC", 199 | "WS", 200 | "SM", 201 | "ST", 202 | "SA", 203 | "SN", 204 | "RS", 205 | "SC", 206 | "SL", 207 | "SG", 208 | "SX", 209 | "SK", 210 | "SI", 211 | "SB", 212 | "SO", 213 | "ZA", 214 | "GS", 215 | "SS", 216 | "ES", 217 | "LK", 218 | "SD", 219 | "SR", 220 | "SJ", 221 | "SE", 222 | "CH", 223 | "SY", 224 | "TW", 225 | "TJ", 226 | "TZ", 227 | "TH", 228 | "TL", 229 | "TG", 230 | "TK", 231 | "TO", 232 | "TT", 233 | "TN", 234 | "TR", 235 | "TM", 236 | "TC", 237 | "TV", 238 | "UG", 239 | "UA", 240 | "AE", 241 | "GB", 242 | "US", 243 | "UM", 244 | "UY", 245 | "UZ", 246 | "VU", 247 | "VE", 248 | "VN", 249 | "VG", 250 | "VI", 251 | "WF", 252 | "EH", 253 | "YE", 254 | "ZM", 255 | "ZW" 256 | ] 257 | } -------------------------------------------------------------------------------- /test/Bundle.Tests/TestData/Schema/ProblemDetails.json: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /test/Bundle.Tests/TestData/openapi.json: -------------------------------------------------------------------------------- 1 | { 2 | "openapi": "3.0.2", 3 | "info": { 4 | "title": "Contact API", 5 | "version": "1.0" 6 | }, 7 | "servers": [ 8 | { 9 | "url": "https://api.server.test/v1" 10 | } 11 | ], 12 | "paths": { 13 | "/api/countries/{isoCountryCode}": { 14 | "parameters": [ 15 | { 16 | "in": "path", 17 | "required": true, 18 | "name": "isoCountryCode", 19 | "schema": { 20 | "$ref": "./IsoCountryCode.schema.json" 21 | } 22 | } 23 | ], 24 | "get": { 25 | "responses": { 26 | "200": { 27 | "description": "Country details", 28 | "content": { 29 | "application/json": { 30 | "schema": { 31 | "$ref": "./Country.schema.json" 32 | }, 33 | "example": { 34 | "isoCode": "GB", 35 | "englishShortName": "United Kingdom" 36 | } 37 | } 38 | } 39 | }, 40 | "404": { 41 | "description": "Invalid ISO country code" 42 | } 43 | } 44 | } 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /test/Bundle.Tests/TestData/openapi.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.2 2 | info: 3 | title: Contact API 4 | version: '1.0' 5 | servers: 6 | - url: https://api.server.test/v1 7 | paths: 8 | "/api/countries/{isoCountryCode}": 9 | parameters: 10 | - in: path 11 | required: true 12 | name: isoCountryCode 13 | schema: 14 | "$ref": "./Schema/IsoCountryCode.json" 15 | get: 16 | responses: 17 | 200: 18 | description: Country details 19 | content: 20 | application/json: 21 | schema: 22 | "$ref": "./Schema/Country.json" 23 | example: 24 | isoCode: GB 25 | englishShortName: United Kingdom 26 | 404: 27 | description: Invalid ISO country code 28 | 500: 29 | $ref: './Responses/InternalServerError.yaml' -------------------------------------------------------------------------------- /test/Bundle.Tests/Usings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; -------------------------------------------------------------------------------- /test/Bundle.Tests/YamlTest.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using SharpYaml.Serialization; 3 | 4 | namespace RendleLabs.OpenApi.Bundle.Tests; 5 | 6 | public class YamlTest 7 | { 8 | [Fact] 9 | public void Temp() 10 | { 11 | var root = new YamlMappingNode(); 12 | root.Children.Add(new YamlScalarNode("foo"), new YamlMappingNode(new KeyValuePair(new YamlScalarNode("bar"), new YamlScalarNode("42")))); 13 | var document = new YamlDocument(root); 14 | var stream = new YamlStream(document); 15 | var builder = new StringBuilder(); 16 | var writer = new StringWriter(builder); 17 | stream.Save(writer, true); 18 | var s = builder.ToString(); 19 | Assert.NotNull(s); 20 | } 21 | } -------------------------------------------------------------------------------- /test/Generator.Tests/ApiBaseGeneratorTests.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Text; 3 | using Microsoft.OpenApi.Models; 4 | using Microsoft.OpenApi.Readers; 5 | using RendleLabs.OpenApi.Generator.ApiFirst; 6 | 7 | namespace RendleLabs.OpenApi.Generator.Tests; 8 | 9 | public class ApiBaseGeneratorTests 10 | { 11 | private readonly OpenApiDocument _apiDocument; 12 | 13 | public ApiBaseGeneratorTests() 14 | { 15 | using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RendleLabs.OpenApi.Generator.Tests.openapi.yaml"); 16 | _apiDocument = new OpenApiStreamReader().Read(stream, out _); 17 | } 18 | 19 | [Fact] 20 | public async Task GeneratesBaseClass() 21 | { 22 | var builder = new StringBuilder(); 23 | var writer = new StringWriter(builder); 24 | var target = new ApiBaseGenerator(writer, "ApiBase", _apiDocument, new ModelGenerator(), "Books"); 25 | await target.GenerateAsync(); 26 | await writer.FlushAsync(); 27 | var actual = builder.ToString(); 28 | Assert.Equal(ExpectedBooksBase.Trim(), actual.Trim()); 29 | } 30 | 31 | private const string ExpectedBooksBase = @"using System.Diagnostics.CodeAnalysis; 32 | using Microsoft.AspNetCore.Mvc; 33 | using ApiBase.Models; 34 | 35 | namespace ApiBase.Api; 36 | 37 | [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicMethods)] 38 | public abstract partial class BooksBase 39 | { 40 | private static readonly IResult NotImplementedResult = Results.StatusCode(501); 41 | 42 | private static void __Map(WebApplication app, Func builder) where T : BooksBase 43 | { 44 | app.MapGet(""/books"", ([FromQuery] int? skip, [FromQuery] int? take, HttpContext context) => 45 | { 46 | var impl = context.RequestServices.GetService() ?? builder(context.RequestServices); 47 | return impl.GetBooks(skip, take, context); 48 | }) 49 | .WithName(""GetBooks""); 50 | 51 | app.MapPost(""/books"", ([FromBody] NewBook newBook, HttpContext context) => 52 | { 53 | var impl = context.RequestServices.GetService() ?? builder(context.RequestServices); 54 | return impl.AddBook(newBook, context); 55 | }) 56 | .WithName(""AddBook""); 57 | 58 | app.MapGet(""/books/{id}"", (int id, HttpContext context) => 59 | { 60 | var impl = context.RequestServices.GetService() ?? builder(context.RequestServices); 61 | return impl.GetBook(id, context); 62 | }) 63 | .WithName(""GetBook""); 64 | 65 | } 66 | 67 | protected static IResult Ok(IList? books = null) => Results.Ok(books); 68 | protected static IResult Ok(Book? book = null) => Results.Ok(book); 69 | protected static IResult Created(Uri uri, Book? book = null) => Results.Created(uri, book); 70 | protected static IResult NotFound() => Results.NotFound(); 71 | 72 | public static LinkProvider Links { get; } = new LinkProvider(); 73 | 74 | public readonly partial struct LinkProvider 75 | { 76 | public Uri GetBooks(int? skip = null, int? take = null) => new($""/books{GetBooksQueryString(skip, take)}"", UriKind.Relative); 77 | private static string GetBooksQueryString(int? skip = null, int? take = null) 78 | { 79 | if (skip is null && skip is null) return string.Empty; 80 | var builder = new global::System.Text.StringBuilder(); 81 | 82 | if (skip is not null) 83 | { 84 | builder.Append(builder.Length == 0 ? '?' : '&'); 85 | builder.AppendLine(""skip={skip}"");} 86 | 87 | if (take is not null) 88 | { 89 | builder.Append(builder.Length == 0 ? '?' : '&'); 90 | builder.AppendLine(""take={take}"");} 91 | 92 | return builder.ToString(); 93 | } 94 | public Uri AddBook() => new(""/books"", UriKind.Relative); 95 | public Uri GetBook(int id) => new($""/books/{id}"", UriKind.Relative); 96 | } 97 | 98 | protected virtual ValueTask GetBooks(int? skip, int? take, HttpContext context) => new(NotImplementedResult); 99 | protected virtual ValueTask AddBook(NewBook newBook, HttpContext context) => new(NotImplementedResult); 100 | protected virtual ValueTask GetBook(int id, HttpContext context) => new(NotImplementedResult); 101 | }"; 102 | } -------------------------------------------------------------------------------- /test/Generator.Tests/BaseActionMethodGeneratorTests.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Microsoft.OpenApi.Models; 3 | using Microsoft.OpenApi.Readers; 4 | using RendleLabs.OpenApi.Generator.Controllers; 5 | 6 | namespace RendleLabs.OpenApi.Generator.Tests; 7 | 8 | public class BaseActionMethodGeneratorTests 9 | { 10 | private readonly OpenApiDocument _apiDocument; 11 | 12 | public BaseActionMethodGeneratorTests() 13 | { 14 | using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RendleLabs.OpenApi.Generator.Tests.openapi.yaml"); 15 | _apiDocument = new OpenApiStreamReader().Read(stream, out _); 16 | } 17 | 18 | [Fact] 19 | public void GeneratesGetBooks() 20 | { 21 | var path = _apiDocument.Paths["/books"]; 22 | var operation = path.Operations[OperationType.Get]; 23 | var target = new BaseActionMethodGenerator("/books", OperationType.Get, operation); 24 | 25 | var writer = new Writer(); 26 | target.Generate(writer.IndentedTextWriter); 27 | var actual = writer.ToString(); 28 | Assert.Equal(Expected.GetBooks, actual); 29 | } 30 | 31 | [Fact] 32 | public void GeneratesGetBook() 33 | { 34 | var path = _apiDocument.Paths["/books/{id}"]; 35 | var operation = path.Operations[OperationType.Get]; 36 | var target = new BaseActionMethodGenerator("/books/{id}", OperationType.Get, operation); 37 | 38 | var writer = new Writer(); 39 | target.Generate(writer.IndentedTextWriter); 40 | var actual = writer.ToString(); 41 | Assert.Equal(Expected.GetBook, actual); 42 | } 43 | 44 | [Fact] 45 | public void GeneratesAddBook() 46 | { 47 | var path = _apiDocument.Paths["/books"]; 48 | var operation = path.Operations[OperationType.Post]; 49 | var target = new BaseActionMethodGenerator("/books", OperationType.Post, operation); 50 | 51 | var writer = new Writer(); 52 | target.Generate(writer.IndentedTextWriter); 53 | var actual = writer.ToString(); 54 | Assert.Equal(Expected.AddBook, actual); 55 | } 56 | 57 | private static class Expected 58 | { 59 | public const string GetBooks = 60 | """ 61 | [HttpGet("/books", Name = "GetBooks"] 62 | public Task>> GetBooks(CancellationToken cancellationToken) => Task.FromResult(StatusCode(501)); 63 | 64 | """; 65 | 66 | public const string GetBook = 67 | """ 68 | [HttpGet("/books/{id}", Name = "GetBook"] 69 | public Task> GetBook([FromRoute] int id, CancellationToken cancellationToken) => Task.FromResult(StatusCode(501)); 70 | 71 | """; 72 | 73 | public const string AddBook = 74 | """ 75 | [HttpPost("/books", Name = "AddBook"] 76 | public Task AddBook([FromBody] Models.NewBook newBook, CancellationToken cancellationToken) => Task.FromResult(StatusCode(501)); 77 | 78 | """; 79 | } 80 | } -------------------------------------------------------------------------------- /test/Generator.Tests/Generator.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | false 8 | RendleLabs.OpenApi.Generator.Tests 9 | RendleLabs.OpenApi.Generator.Tests 10 | preview 11 | 12 | 13 | 14 | 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | all 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /test/Generator.Tests/ModelFinderTests.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Microsoft.OpenApi.Models; 3 | using Microsoft.OpenApi.Readers; 4 | using RendleLabs.OpenApi.Generator.ApiFirst; 5 | 6 | namespace RendleLabs.OpenApi.Generator.Tests; 7 | 8 | public class ModelFinderTests 9 | { 10 | private readonly OpenApiDocument _apiDocument; 11 | 12 | public ModelFinderTests() 13 | { 14 | using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RendleLabs.OpenApi.Generator.Tests.openapi.yaml"); 15 | _apiDocument = new OpenApiStreamReader().Read(stream, out _); 16 | } 17 | 18 | [Fact] 19 | public void FindsModels() 20 | { 21 | var actual = ModelFinder.FindModels(_apiDocument).ToArray(); 22 | Assert.NotEmpty(actual); 23 | } 24 | } -------------------------------------------------------------------------------- /test/Generator.Tests/ModelGeneratorTests.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Text; 3 | using Microsoft.OpenApi.Models; 4 | using Microsoft.OpenApi.Readers; 5 | using RendleLabs.OpenApi.Generator.ApiFirst; 6 | 7 | namespace RendleLabs.OpenApi.Generator.Tests; 8 | 9 | public class ModelGeneratorTests 10 | { 11 | private readonly OpenApiDocument _apiDocument; 12 | 13 | public ModelGeneratorTests() 14 | { 15 | using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RendleLabs.OpenApi.Generator.Tests.openapi.yaml"); 16 | _apiDocument = new OpenApiStreamReader().Read(stream, out _); 17 | } 18 | 19 | [Fact] 20 | public async Task GeneratesOneOfEachClass() 21 | { 22 | var builder = new StringBuilder(); 23 | var writer = new StringWriter(builder); 24 | 25 | var target = new ModelGenerator(); 26 | foreach (var schema in ModelFinder.FindModels(_apiDocument)) 27 | { 28 | target.AddSchema(schema); 29 | } 30 | 31 | await target.GenerateAsync(writer); 32 | await writer.FlushAsync(); 33 | var actual = builder.ToString().Trim(); 34 | Assert.Equal(ExpectedClasses.Trim(), actual); 35 | } 36 | 37 | private const string ExpectedClasses = @" 38 | public partial class Book 39 | { 40 | [global::System.Text.Json.Serialization.JsonPropertyName(""id"")] 41 | public int? Id { get; set; } 42 | [global::System.Text.Json.Serialization.JsonPropertyName(""title"")] 43 | public string? Title { get; set; } 44 | [global::System.Text.Json.Serialization.JsonPropertyName(""author"")] 45 | public string? Author { get; set; } 46 | } 47 | 48 | public partial class NewBook 49 | { 50 | [global::System.Text.Json.Serialization.JsonPropertyName(""title"")] 51 | public string? Title { get; set; } 52 | [global::System.Text.Json.Serialization.JsonPropertyName(""author"")] 53 | public string? Author { get; set; } 54 | } 55 | "; 56 | } -------------------------------------------------------------------------------- /test/Generator.Tests/Usings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; -------------------------------------------------------------------------------- /test/Generator.Tests/Writer.cs: -------------------------------------------------------------------------------- 1 | using System.CodeDom.Compiler; 2 | using System.Text; 3 | 4 | namespace RendleLabs.OpenApi.Generator.Tests; 5 | 6 | internal class Writer 7 | { 8 | public StringBuilder Builder { get; set; } 9 | public StringWriter TextWriter { get; set; } 10 | public IndentedTextWriter IndentedTextWriter { get; set; } 11 | 12 | public Writer() 13 | { 14 | Builder = new StringBuilder(); 15 | TextWriter = new StringWriter(Builder); 16 | IndentedTextWriter = new IndentedTextWriter(TextWriter, " "); 17 | } 18 | 19 | public override string ToString() 20 | { 21 | TextWriter.Flush(); 22 | return Builder.ToString(); 23 | } 24 | } -------------------------------------------------------------------------------- /test/Generator.Tests/openapi.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.3 2 | info: 3 | title: Test API 4 | description: Test API 5 | version: 1.0.0 6 | servers: 7 | - url: 'https://localhost:5001' 8 | tags: 9 | - name: Books 10 | paths: 11 | /books: 12 | get: 13 | operationId: GetBooks 14 | parameters: 15 | - name: skip 16 | in: query 17 | schema: 18 | type: integer 19 | - name: take 20 | in: query 21 | schema: 22 | type: integer 23 | tags: 24 | - Books 25 | responses: 26 | '200': 27 | description: OK 28 | content: 29 | application/json: 30 | schema: 31 | type: array 32 | items: 33 | $ref: '#/components/schemas/Book' 34 | post: 35 | operationId: AddBook 36 | tags: 37 | - Books 38 | requestBody: 39 | content: 40 | application/json: 41 | schema: 42 | $ref: '#/components/schemas/NewBook' 43 | responses: 44 | '201': 45 | description: Created 46 | content: 47 | application/json: 48 | schema: 49 | $ref: '#/components/schemas/Book' 50 | headers: 51 | Location: 52 | description: URI of new book 53 | /books/{id}: 54 | parameters: 55 | - name: id 56 | in: path 57 | schema: 58 | type: integer 59 | required: true 60 | get: 61 | operationId: GetBook 62 | tags: 63 | - Books 64 | responses: 65 | '200': 66 | description: OK 67 | content: 68 | application/json: 69 | schema: 70 | $ref: '#/components/schemas/Book' 71 | '404': 72 | description: Not Found 73 | components: 74 | schemas: 75 | Book: 76 | type: object 77 | properties: 78 | id: 79 | type: integer 80 | title: 81 | type: string 82 | author: 83 | type: string 84 | NewBook: 85 | type: object 86 | properties: 87 | title: 88 | type: string 89 | author: 90 | type: string 91 | -------------------------------------------------------------------------------- /test/Testing.Api/Data/Book.cs: -------------------------------------------------------------------------------- 1 | namespace Testing.Api; 2 | 3 | public class Book 4 | { 5 | public Guid Id { get; set; } 6 | public string Title { get; set; } 7 | public string Author { get; set; } 8 | } -------------------------------------------------------------------------------- /test/Testing.Api/Data/BookData.cs: -------------------------------------------------------------------------------- 1 | namespace Testing.Api; 2 | 3 | public class BookData 4 | { 5 | private readonly SemaphoreSlim _semaphore = new(1); 6 | private readonly Dictionary _books = new(); 7 | 8 | public async Task AddAsync(NewBook newBook) 9 | { 10 | var book = new Book 11 | { 12 | Id = Guid.NewGuid(), 13 | Title = newBook.Title, 14 | Author = newBook.Author 15 | }; 16 | 17 | await _semaphore.WaitAsync(); 18 | 19 | try 20 | { 21 | _books.Add(book.Id, book); 22 | } 23 | finally 24 | { 25 | _semaphore.Release(); 26 | } 27 | 28 | return book; 29 | } 30 | 31 | public async Task GetAsync(Guid id) 32 | { 33 | await _semaphore.WaitAsync(); 34 | try 35 | { 36 | return _books[id]; 37 | } 38 | finally 39 | { 40 | _semaphore.Release(); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /test/Testing.Api/Data/NewBook.cs: -------------------------------------------------------------------------------- 1 | namespace Testing.Api; 2 | 3 | public class NewBook 4 | { 5 | public string Title { get; set; } 6 | public string Author { get; set; } 7 | } -------------------------------------------------------------------------------- /test/Testing.Api/Program.cs: -------------------------------------------------------------------------------- 1 | using Testing.Api; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | builder.Services.AddSingleton(); 6 | 7 | var app = builder.Build(); 8 | 9 | app.MapGet("/", () => "Hello World!"); 10 | 11 | app.MapGet("/books/{id}", async (Guid id, BookData bookData) => 12 | { 13 | try 14 | { 15 | return Results.Ok(await bookData.GetAsync(id)); 16 | } 17 | catch (IndexOutOfRangeException) 18 | { 19 | return Results.NotFound(); 20 | } 21 | }) 22 | .WithName("GetBook"); 23 | 24 | app.MapPost("/books", async (NewBook newBook, BookData bookData) => 25 | { 26 | var book = await bookData.AddAsync(newBook); 27 | return Results.CreatedAtRoute("GetBook", new { id = book.Id }); 28 | }) 29 | .WithName("AddBook"); 30 | 31 | 32 | app.Run(); -------------------------------------------------------------------------------- /test/Testing.Api/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:31990", 7 | "sslPort": 44348 8 | } 9 | }, 10 | "profiles": { 11 | "Testing.Api": { 12 | "commandName": "Project", 13 | "dotnetRunMessages": true, 14 | "launchBrowser": true, 15 | "applicationUrl": "https://localhost:7042;http://localhost:5263", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "IIS Express": { 21 | "commandName": "IISExpress", 22 | "launchBrowser": true, 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /test/Testing.Api/Testing.Api.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /test/Testing.Api/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /test/Testing.Api/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /test/Testing.Tests/Api/openapi.tests.yaml: -------------------------------------------------------------------------------- 1 | server: https://localhost:5001 2 | tests: 3 | - sequence: 4 | - POST /books: 5 | requestBody: 6 | application/json: 7 | title: Mort 8 | author: Terry Pratchett 9 | expect: 10 | status: 201 11 | headers: 12 | Location: /^\/books/.*/ 13 | output: PostBook 14 | - GET {{PostBook.Headers.Location}}: 15 | expect: 16 | status: 200 17 | response: 18 | application/json: 19 | title: Mort 20 | author: Terry Pratchett -------------------------------------------------------------------------------- /test/Testing.Tests/ApiTests.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http.Json; 2 | using System.Text.Json; 3 | using Microsoft.AspNetCore.Mvc.Testing; 4 | using Testing.Api; 5 | 6 | namespace RendleLabs.OpenApi.Testing.Tests; 7 | 8 | public class ApiTests 9 | { 10 | [Fact] 11 | public async Task AddsAndGetsBook() 12 | { 13 | await using var appFactory = new WebApplicationFactory(); 14 | using var client = appFactory.CreateClient(); 15 | 16 | var request = new HttpRequestMessage(HttpMethod.Post, "/books") 17 | { 18 | Content = JsonContent.Create(new { Title = "Mort", Author = "Terry Pratchett" }), 19 | }; 20 | var response = await client.SendAsync(request); 21 | Assert.True(response.IsSuccessStatusCode); 22 | var location = response.Headers.Location; 23 | var book = await client.GetFromJsonAsync(location); 24 | Assert.NotNull(book); 25 | Assert.Equal("Mort", book.Title); 26 | Assert.Equal("Terry Pratchett", book.Author); 27 | } 28 | 29 | public class Book 30 | { 31 | public Guid Id { get; set; } 32 | public string Title { get; set; } 33 | public string Author { get; set; } 34 | } 35 | } -------------------------------------------------------------------------------- /test/Testing.Tests/HttpBin/json/openapi.json: -------------------------------------------------------------------------------- 1 | { 2 | "openapi": "3.0.2", 3 | "info": { 4 | "title": "httpbin", 5 | "version": "1.0" 6 | }, 7 | "servers": [ 8 | { 9 | "url": "https://httpbin.org" 10 | } 11 | ], 12 | "paths": { 13 | "/base64/{value}": { 14 | "parameters": [ 15 | { 16 | "name": "value", 17 | "schema": { 18 | "type": "string" 19 | }, 20 | "required": true, 21 | "in": "path" 22 | } 23 | ], 24 | "get": { 25 | "responses": { 26 | "200": { 27 | "description": "Decoded base64 content", 28 | "content": { 29 | "text/html": { 30 | "schema": { 31 | "type": "string" 32 | } 33 | } 34 | } 35 | } 36 | } 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /test/Testing.Tests/HttpBin/json/openapi.tests.json: -------------------------------------------------------------------------------- 1 | { 2 | "server": "https://httpbin.org", 3 | "tests": { 4 | "/base64/{value}": { 5 | "get": [ 6 | { 7 | "parameters": { 8 | "value": "SGVsbG8sIHdvcmxkIQ==" 9 | }, 10 | "expect": { 11 | "status": 200, 12 | "responseBody": "Hello, world!" 13 | } 14 | } 15 | ] 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /test/Testing.Tests/HttpBin/yaml/openapi.tests.yaml: -------------------------------------------------------------------------------- 1 | server: https://httpbin.org 2 | tests: 3 | - GET /base64/SGVsbG8sIHdvcmxkIQ==: 4 | expect: 5 | status: 200 6 | responseBody: 7 | text/html: Hello, world! 8 | - POST /anything/foo: 9 | requestBody: 10 | application/json: 11 | id: bar 12 | expect: 13 | status: 200 14 | responseBody: 15 | application/json: 16 | json: 17 | id: bar 18 | url: 'https://httpbin.org/anything/foo' -------------------------------------------------------------------------------- /test/Testing.Tests/HttpBin/yaml/openapi.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.2 2 | info: 3 | title: httpbin 4 | version: '1.0' 5 | tags: 6 | - name: base64 7 | servers: 8 | - url: https://httpbin.org 9 | paths: 10 | "/base64/{value}": 11 | parameters: 12 | - name: value 13 | schema: 14 | type: string 15 | required: true 16 | in: path 17 | get: 18 | tags: 19 | - base64 20 | responses: 21 | '200': 22 | description: Decoded base64 content 23 | content: 24 | text/html: 25 | schema: 26 | type: string 27 | format: 28 | "/anything/{anything}": 29 | parameters: 30 | - name: anything 31 | schema: 32 | type: string 33 | required: true 34 | in: path 35 | post: 36 | requestBody: 37 | content: 38 | application/json: 39 | schema: 40 | type: object 41 | responses: 42 | '200': 43 | description: Info about request 44 | content: 45 | application/json: 46 | schema: 47 | type: object 48 | -------------------------------------------------------------------------------- /test/Testing.Tests/MemberDataTests.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using Microsoft.OpenApi.Readers; 3 | 4 | namespace RendleLabs.OpenApi.Testing.Tests; 5 | 6 | public class MemberDataTests 7 | { 8 | [Theory] 9 | [MemberData(nameof(Data))] 10 | public async Task Run(OpenApiTestRequest testRequest, OpenApiTestResponse expectedTestResponse) 11 | { 12 | using var client = new HttpClient(); 13 | var response = await client.ExecuteAsync(testRequest); 14 | 15 | Assert.Equal(expectedTestResponse.Status, (int)response.StatusCode); 16 | if (expectedTestResponse.ContentType is not null) 17 | { 18 | Assert.Equal(expectedTestResponse.ContentType, response.Content.Headers.ContentType?.MediaType); 19 | if (expectedTestResponse.ContentType.StartsWith("text/")) 20 | { 21 | var responseBody = await response.Content.ReadAsStringAsync(); 22 | Assert.Equal(expectedTestResponse.Body, responseBody); 23 | } 24 | else if (expectedTestResponse.ContentType == "application/json" && expectedTestResponse.Body is { Length: > 0 }) 25 | { 26 | var expectedBody = JsonDocument.Parse(expectedTestResponse.Body); 27 | var actualBody = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync()); 28 | JsonAssert.Equivalent(expectedBody, actualBody); 29 | } 30 | } 31 | } 32 | 33 | public static IEnumerable Data() 34 | { 35 | var testJson = ResourceStreams.Get("HttpBin.yaml.openapi.tests.yaml"); 36 | var apiJson = ResourceStreams.Get("HttpBin.yaml.openapi.yaml"); 37 | var testDocument = new OpenApiTestDocumentParser().Parse(testJson); 38 | var apiDocument = new OpenApiStreamReader().Read(apiJson, out _); 39 | var data = new OpenApiTheoryData(testDocument, apiDocument); 40 | return data.Enumerate(); 41 | } 42 | } -------------------------------------------------------------------------------- /test/Testing.Tests/OpenApiTestDocumentParserTests.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using Microsoft.OpenApi.Models; 3 | 4 | namespace RendleLabs.OpenApi.Testing.Tests; 5 | 6 | public class OpenApiTestDocumentParserTests 7 | { 8 | [Fact] 9 | public void ParsesYaml() 10 | { 11 | using var stream = ResourceStreams.Get("HttpBin.yaml.openapi.tests.yaml"); 12 | var actual = new OpenApiTestDocumentParser().Parse(stream); 13 | 14 | Assert.Equal("https://httpbin.org", actual.Server); 15 | Assert.NotEmpty(actual.Tests); 16 | 17 | var test = actual.Tests[0]; 18 | 19 | Assert.Equal("/base64/SGVsbG8sIHdvcmxkIQ==", test.Uri); 20 | Assert.Equal(HttpMethod.Get, test.Method); 21 | 22 | Assert.Equal(200, test.Expect.Status); 23 | Assert.Equal("Hello, world!", test.Expect.ResponseBody?.Content); 24 | 25 | test = actual.Tests[1]; 26 | 27 | Assert.Equal("/anything/foo", test.Uri); 28 | Assert.Equal(HttpMethod.Post, test.Method); 29 | Assert.Equal("application/json", test.RequestBody?.ContentType); 30 | 31 | var json = JsonDocument.Parse(test.RequestBody!.Content); 32 | Assert.True(json.RootElement.TryGetProperty("id", out var id)); 33 | Assert.Equal("bar", id.GetString()); 34 | Assert.Equal(201, test.Expect.Status); 35 | 36 | Assert.Equal("application/json", test.Expect.ResponseBody?.ContentType); 37 | json = JsonDocument.Parse(test.Expect.ResponseBody!.Content); 38 | Assert.True(json.RootElement.TryGetProperty("json", out var jsonElement)); 39 | Assert.True(jsonElement.TryGetProperty("id", out id)); 40 | Assert.Equal("bar", id.GetString()); 41 | Assert.True(json.RootElement.TryGetProperty("url", out var urlElement)); 42 | Assert.Equal("https://httpbin.org/anything/foo", urlElement.GetString()); 43 | } 44 | } -------------------------------------------------------------------------------- /test/Testing.Tests/OpenTheoryDataTests.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using Microsoft.OpenApi.Models; 3 | using Microsoft.OpenApi.Readers; 4 | 5 | namespace RendleLabs.OpenApi.Testing.Tests; 6 | 7 | 8 | public class OpenTheoryDataTests 9 | { 10 | [Fact] 11 | public void EnumerateTests() 12 | { 13 | var testYaml = ResourceStreams.Get("HttpBin.yaml.openapi.tests.yaml"); 14 | var apiYaml = ResourceStreams.Get("HttpBin.yaml.openapi.yaml"); 15 | 16 | var testDocument = new OpenApiTestDocumentParser().Parse(testYaml); 17 | var apiDocument = new OpenApiStreamReader().Read(apiYaml, out _); 18 | 19 | var target = new OpenApiTheoryData(testDocument, apiDocument); 20 | var actual = target.Enumerate().First(); 21 | Assert.Equal(2, actual.Length); 22 | var request = Assert.IsType(actual[0]); 23 | Assert.Equal("/base64/SGVsbG8sIHdvcmxkIQ==", request.Path); 24 | Assert.Equal(HttpMethod.Get, request.Method); 25 | Assert.Null(request.Body); 26 | var response = Assert.IsType(actual[1]); 27 | Assert.Equal(200, response.Status); 28 | Assert.Equal("Hello, world!", response.Body); 29 | } 30 | } -------------------------------------------------------------------------------- /test/Testing.Tests/ResourceStrings.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace RendleLabs.OpenApi.Testing.Tests; 4 | 5 | internal static class ResourceStrings 6 | { 7 | public static string Get(string name) 8 | { 9 | name = $"{typeof(MemberDataTests).Namespace}.{name}"; 10 | using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name); 11 | if (stream is null) throw new ArgumentException(); 12 | using var reader = new StreamReader(stream); 13 | return reader.ReadToEnd(); 14 | } 15 | } 16 | 17 | internal static class ResourceStreams 18 | { 19 | public static Stream Get(string name) 20 | { 21 | name = $"{typeof(MemberDataTests).Namespace}.{name}"; 22 | var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name); 23 | if (stream is null) throw new ArgumentException(); 24 | return stream; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /test/Testing.Tests/SequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using Microsoft.OpenApi.Readers; 3 | 4 | namespace RendleLabs.OpenApi.Testing.Tests; 5 | 6 | public class SequenceTests 7 | { 8 | [Theory] 9 | [MemberData(nameof(Data))] 10 | public async Task Run(OpenApiTestRequest testRequest, OpenApiTestResponse expectedTestResponse) 11 | { 12 | using var client = new HttpClient(); 13 | var response = await client.ExecuteAsync(testRequest); 14 | 15 | Assert.Equal(expectedTestResponse.Status, (int)response.StatusCode); 16 | if (expectedTestResponse.ContentType is not null) 17 | { 18 | Assert.Equal(expectedTestResponse.ContentType, response.Content.Headers.ContentType?.MediaType); 19 | if (expectedTestResponse.ContentType.StartsWith("text/")) 20 | { 21 | var responseBody = await response.Content.ReadAsStringAsync(); 22 | Assert.Equal(expectedTestResponse.Body, responseBody); 23 | } 24 | else if (expectedTestResponse.ContentType == "application/json" && expectedTestResponse.Body is { Length: > 0 }) 25 | { 26 | var expectedBody = JsonDocument.Parse(expectedTestResponse.Body); 27 | var actualBody = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync()); 28 | JsonAssert.Equivalent(expectedBody, actualBody); 29 | } 30 | } 31 | } 32 | 33 | public static IEnumerable Data() 34 | { 35 | var testJson = ResourceStreams.Get("HttpBin.yaml.openapi.tests.yaml"); 36 | var apiJson = ResourceStreams.Get("HttpBin.yaml.openapi.yaml"); 37 | var testDocument = new OpenApiTestDocumentParser().Parse(testJson); 38 | var apiDocument = new OpenApiStreamReader().Read(apiJson, out _); 39 | var data = new OpenApiTheoryData(testDocument, apiDocument); 40 | return data.Enumerate(); 41 | } 42 | } -------------------------------------------------------------------------------- /test/Testing.Tests/Testing.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | false 8 | RendleLabs.OpenApi.Testing.Tests 9 | RendleLabs.OpenApi.Testing.Tests 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | all 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /test/Testing.Tests/Usings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; -------------------------------------------------------------------------------- /test/Testing.WebApi/Controllers/WeatherForecastImpl.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace Testing.WebApi.Controllers; 4 | 5 | [ApiController] 6 | public abstract class WeatherForecastControllerBase : ControllerBase 7 | { 8 | [HttpGet("WeatherForecast", Name = "GetWeatherForecast")] 9 | public virtual ActionResult> Get() 10 | { 11 | return StatusCode(501); 12 | } 13 | } 14 | 15 | public class WeatherForecastController : WeatherForecastControllerBase 16 | { 17 | private static readonly string[] Summaries = new[] 18 | { 19 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 20 | }; 21 | 22 | private readonly ILogger _logger; 23 | 24 | public WeatherForecastController(ILogger logger) 25 | { 26 | _logger = logger; 27 | } 28 | 29 | public override ActionResult> Get() 30 | { 31 | Response.Headers.Location = Url.Action("Get", "WeatherForecast"); 32 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 33 | { 34 | Date = DateTime.Now.AddDays(index), 35 | TemperatureC = Random.Shared.Next(-20, 55), 36 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 37 | }) 38 | .ToArray(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /test/Testing.WebApi/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = WebApplication.CreateBuilder(args); 2 | 3 | // Add services to the container. 4 | 5 | builder.Services.AddControllers(); 6 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 7 | builder.Services.AddEndpointsApiExplorer(); 8 | builder.Services.AddSwaggerGen(); 9 | 10 | var app = builder.Build(); 11 | 12 | // Configure the HTTP request pipeline. 13 | if (app.Environment.IsDevelopment()) 14 | { 15 | app.UseSwagger(); 16 | app.UseSwaggerUI(); 17 | } 18 | 19 | app.UseHttpsRedirection(); 20 | 21 | app.UseAuthorization(); 22 | 23 | app.MapControllers(); 24 | 25 | app.Run(); 26 | -------------------------------------------------------------------------------- /test/Testing.WebApi/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "Testing.WebApi": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": true, 7 | "launchBrowser": true, 8 | "launchUrl": "swagger", 9 | "applicationUrl": "https://localhost:7029;http://localhost:5226", 10 | "environmentVariables": { 11 | "ASPNETCORE_ENVIRONMENT": "Development" 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /test/Testing.WebApi/Testing.WebApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /test/Testing.WebApi/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace Testing.WebApi; 2 | 3 | public class WeatherForecast 4 | { 5 | public DateTime Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } 13 | -------------------------------------------------------------------------------- /test/Testing.WebApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /test/Testing.WebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /test/Web.TestApp/Program.cs: -------------------------------------------------------------------------------- 1 | using RendleLabs.OpenApi.Web; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | var app = builder.Build(); 6 | 7 | app.UseStaticOpenApi("openapi.yaml", new StaticOpenApiOptions 8 | { 9 | Version = 3, 10 | JsonPath = "swagger/v1/openapi.json", 11 | YamlPath = "swagger/v1/openapi.yaml", 12 | UiPathPrefix = "swagger", 13 | Elements = 14 | { 15 | Path = "swagger/v1/docs" 16 | } 17 | }) 18 | .AllowAnonymous(); 19 | 20 | app.MapGet("/", () => "Hello World!"); 21 | 22 | app.Run(); -------------------------------------------------------------------------------- /test/Web.TestApp/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Web.TestApp": { 4 | "commandName": "Project", 5 | "dotnetRunMessages": true, 6 | "launchBrowser": true, 7 | "launchUrl": "swagger", 8 | "applicationUrl": "https://localhost:7046;http://localhost:5125", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development" 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /test/Web.TestApp/Web.TestApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | PreserveNewest 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /test/Web.TestApp/api.md: -------------------------------------------------------------------------------- 1 | # Contact Addresses API 2 | 3 | > Version 1.0 4 | 5 | ## Path Table 6 | 7 | | Method | Path | Description | 8 | | --- | --- | --- | 9 | | GET | [/api/{accountNumber}/addresses](#getapiaccountnumberaddresses) | | 10 | | POST | [/api/{accountNumber}/addresses](#postapiaccountnumberaddresses) | | 11 | | GET | [/api/{accountNumber}/addresses/{id}](#getapiaccountnumberaddressesid) | | 12 | | PUT | [/api/{accountNumber}/addresses/{id}](#putapiaccountnumberaddressesid) | | 13 | 14 | ## Reference Table 15 | 16 | | Name | Path | Description | 17 | | --- | --- | --- | 18 | | Address | [#/components/schemas/Address](#componentsschemasaddress) | | 19 | | IsoCountryCode | [#/components/schemas/IsoCountryCode](#componentsschemasisocountrycode) | | 20 | 21 | ## Path Details 22 | 23 | *** 24 | 25 | ### [GET]/api/{accountNumber}/addresses 26 | 27 | #### Responses 28 | 29 | - 200 Addresses for customer 30 | 31 | `application/json` 32 | 33 | ```ts 34 | { 35 | // Unique identifier 36 | id?: string 37 | // The type of address 38 | type?: string 39 | line1?: string 40 | line2?: string 41 | line3?: string 42 | city?: string 43 | region?: string 44 | isoCountry?: string 45 | postalCode?: string 46 | }[] 47 | ``` 48 | 49 | - 404 Customer not found 50 | 51 | *** 52 | 53 | ### [POST]/api/{accountNumber}/addresses 54 | 55 | - Description 56 | Create customer address 57 | 58 | #### RequestBody 59 | 60 | - application/json 61 | 62 | ```ts 63 | { 64 | // Unique identifier 65 | id?: string 66 | // The type of address 67 | type?: string 68 | line1?: string 69 | line2?: string 70 | line3?: string 71 | city?: string 72 | region?: string 73 | isoCountry?: string 74 | postalCode?: string 75 | } 76 | ``` 77 | 78 | #### Responses 79 | 80 | - 201 Address created successfully 81 | 82 | - 400 Bad request 83 | 84 | - 404 Customer account not found 85 | 86 | *** 87 | 88 | ### [GET]/api/{accountNumber}/addresses/{id} 89 | 90 | #### Responses 91 | 92 | - 200 Address for customer 93 | 94 | `application/json` 95 | 96 | ```ts 97 | { 98 | // Unique identifier 99 | id?: string 100 | // The type of address 101 | type?: string 102 | line1?: string 103 | line2?: string 104 | line3?: string 105 | city?: string 106 | region?: string 107 | isoCountry?: string 108 | postalCode?: string 109 | } 110 | ``` 111 | 112 | - 404 Address not found 113 | 114 | *** 115 | 116 | ### [PUT]/api/{accountNumber}/addresses/{id} 117 | 118 | - Description 119 | Update customer address 120 | 121 | #### RequestBody 122 | 123 | - application/json 124 | 125 | ```ts 126 | { 127 | // Unique identifier 128 | id?: string 129 | // The type of address 130 | type?: string 131 | line1?: string 132 | line2?: string 133 | line3?: string 134 | city?: string 135 | region?: string 136 | isoCountry?: string 137 | postalCode?: string 138 | } 139 | ``` 140 | 141 | #### Responses 142 | 143 | - 200 Address updated successfully 144 | 145 | - 400 Bad request 146 | 147 | - 404 Customer account not found 148 | 149 | ## References 150 | 151 | ### #/components/schemas/Address 152 | 153 | ```ts 154 | { 155 | // Unique identifier 156 | id?: string 157 | // The type of address 158 | type?: string 159 | line1?: string 160 | line2?: string 161 | line3?: string 162 | city?: string 163 | region?: string 164 | isoCountry?: string 165 | postalCode?: string 166 | } 167 | ``` 168 | 169 | ### #/components/schemas/IsoCountryCode 170 | 171 | ```ts 172 | { 173 | "type": "string", 174 | "enum": [ 175 | "AF", 176 | "AX", 177 | "AL", 178 | "DZ", 179 | "AS", 180 | "AD", 181 | "AO", 182 | "AI", 183 | "AQ", 184 | "AG", 185 | "AR", 186 | "AM", 187 | "AW", 188 | "AU", 189 | "AT", 190 | "AZ", 191 | "BS", 192 | "BH", 193 | "BD", 194 | "BB", 195 | "BY", 196 | "BE", 197 | "BZ", 198 | "BJ", 199 | "BM", 200 | "BT", 201 | "BO", 202 | "BQ", 203 | "BA", 204 | "BW", 205 | "BV", 206 | "BR", 207 | "IO", 208 | "BN", 209 | "BG", 210 | "BF", 211 | "BI", 212 | "CV", 213 | "KH", 214 | "CM", 215 | "CA", 216 | "KY", 217 | "CF", 218 | "TD", 219 | "CL", 220 | "CN", 221 | "CX", 222 | "CC", 223 | "CO", 224 | "KM", 225 | "CG", 226 | "CD", 227 | "CK", 228 | "CR", 229 | "CI", 230 | "HR", 231 | "CU", 232 | "CW", 233 | "CY", 234 | "CZ", 235 | "DK", 236 | "DJ", 237 | "DM", 238 | "DO", 239 | "EC", 240 | "EG", 241 | "SV", 242 | "GQ", 243 | "ER", 244 | "EE", 245 | "SZ", 246 | "ET", 247 | "FK", 248 | "FO", 249 | "FJ", 250 | "FI", 251 | "FR", 252 | "GF", 253 | "PF", 254 | "TF", 255 | "GA", 256 | "GM", 257 | "GE", 258 | "DE", 259 | "GH", 260 | "GI", 261 | "GR", 262 | "GL", 263 | "GD", 264 | "GP", 265 | "GU", 266 | "GT", 267 | "GG", 268 | "GN", 269 | "GW", 270 | "GY", 271 | "HT", 272 | "HM", 273 | "VA", 274 | "HN", 275 | "HK", 276 | "HU", 277 | "IS", 278 | "IN", 279 | "ID", 280 | "IR", 281 | "IQ", 282 | "IE", 283 | "IM", 284 | "IL", 285 | "IT", 286 | "JM", 287 | "JP", 288 | "JE", 289 | "JO", 290 | "KZ", 291 | "KE", 292 | "KI", 293 | "KP", 294 | "KR", 295 | "KW", 296 | "KG", 297 | "LA", 298 | "LV", 299 | "LB", 300 | "LS", 301 | "LR", 302 | "LY", 303 | "LI", 304 | "LT", 305 | "LU", 306 | "MO", 307 | "MG", 308 | "MW", 309 | "MY", 310 | "MV", 311 | "ML", 312 | "MT", 313 | "MH", 314 | "MQ", 315 | "MR", 316 | "MU", 317 | "YT", 318 | "MX", 319 | "FM", 320 | "MD", 321 | "MC", 322 | "MN", 323 | "ME", 324 | "MS", 325 | "MA", 326 | "MZ", 327 | "MM", 328 | "NA", 329 | "NR", 330 | "NP", 331 | "NL", 332 | "NC", 333 | "NZ", 334 | "NI", 335 | "NE", 336 | "NG", 337 | "NU", 338 | "NF", 339 | "MK", 340 | "MP", 341 | "NO", 342 | "OM", 343 | "PK", 344 | "PW", 345 | "PS", 346 | "PA", 347 | "PG", 348 | "PY", 349 | "PE", 350 | "PH", 351 | "PN", 352 | "PL", 353 | "PT", 354 | "PR", 355 | "QA", 356 | "RE", 357 | "RO", 358 | "RU", 359 | "RW", 360 | "BL", 361 | "SH", 362 | "KN", 363 | "LC", 364 | "MF", 365 | "PM", 366 | "VC", 367 | "WS", 368 | "SM", 369 | "ST", 370 | "SA", 371 | "SN", 372 | "RS", 373 | "SC", 374 | "SL", 375 | "SG", 376 | "SX", 377 | "SK", 378 | "SI", 379 | "SB", 380 | "SO", 381 | "ZA", 382 | "GS", 383 | "SS", 384 | "ES", 385 | "LK", 386 | "SD", 387 | "SR", 388 | "SJ", 389 | "SE", 390 | "CH", 391 | "SY", 392 | "TW", 393 | "TJ", 394 | "TZ", 395 | "TH", 396 | "TL", 397 | "TG", 398 | "TK", 399 | "TO", 400 | "TT", 401 | "TN", 402 | "TR", 403 | "TM", 404 | "TC", 405 | "TV", 406 | "UG", 407 | "UA", 408 | "AE", 409 | "GB", 410 | "US", 411 | "UM", 412 | "UY", 413 | "UZ", 414 | "VU", 415 | "VE", 416 | "VN", 417 | "VG", 418 | "VI", 419 | "WF", 420 | "EH", 421 | "YE", 422 | "ZM", 423 | "ZW" 424 | ] 425 | } 426 | ``` -------------------------------------------------------------------------------- /test/Web.TestApp/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /test/Web.TestApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /test/Web.TestApp/openapi.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.2 2 | info: 3 | title: Contact Addresses API 4 | version: "1.0" 5 | servers: 6 | - url: https://api.server.test/v1 7 | paths: 8 | "/api/{accountNumber}/addresses": 9 | parameters: 10 | - name: accountNumber 11 | in: path 12 | required: true 13 | schema: 14 | type: string 15 | get: 16 | operationId: getAddresses 17 | responses: 18 | "200": 19 | description: Addresses for customer 20 | content: 21 | application/json: 22 | schema: 23 | type: array 24 | items: 25 | $ref: '#/components/schemas/Address' 26 | "404": 27 | description: Customer not found 28 | post: 29 | operationId: createAddress 30 | description: Create customer address 31 | requestBody: 32 | content: 33 | application/json: 34 | schema: 35 | $ref: '#/components/schemas/Address' 36 | responses: 37 | "201": 38 | description: Address created successfully 39 | headers: 40 | Location: 41 | description: The absolute URI of the new address 42 | schema: 43 | type: string 44 | "400": 45 | description: Bad request 46 | "404": 47 | description: Customer account not found 48 | "/api/{accountNumber}/addresses/{id}": 49 | parameters: 50 | - name: accountNumber 51 | in: path 52 | required: true 53 | schema: 54 | type: string 55 | - name: id 56 | in: path 57 | required: true 58 | schema: 59 | type: string 60 | get: 61 | operationId: getAddressById 62 | responses: 63 | "200": 64 | description: Address for customer 65 | content: 66 | application/json: 67 | schema: 68 | $ref: '#/components/schemas/Address' 69 | "404": 70 | description: Address not found 71 | put: 72 | operationId: updateAddressById 73 | description: Update customer address 74 | requestBody: 75 | content: 76 | application/json: 77 | schema: 78 | $ref: '#/components/schemas/Address' 79 | responses: 80 | "200": 81 | description: Address updated successfully 82 | "400": 83 | description: Bad request 84 | "404": 85 | description: Customer account not found 86 | components: 87 | schemas: 88 | Address: 89 | type: object 90 | properties: 91 | id: 92 | type: string 93 | description: Unique identifier 94 | type: 95 | type: string 96 | description: The type of address 97 | line1: 98 | type: string 99 | line2: 100 | type: string 101 | line3: 102 | type: string 103 | city: 104 | type: string 105 | region: 106 | type: string 107 | isoCountry: 108 | $ref: '#/components/schemas/IsoCountryCode' 109 | postalCode: 110 | type: string 111 | IsoCountryCode: 112 | type: string 113 | enum: [ 114 | "AF", "AX", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", 115 | "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BQ", "BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "CV", "KH", "CM", 116 | "CA", "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CI", "HR", "CU", "CW", "CY", "CZ", 117 | "DK", "DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "SZ", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF", 118 | "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM", "VA", "HN", 119 | "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "KP", "KR", 120 | "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", 121 | "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "NC", "NZ", "NI", 122 | "NE", "NG", "NU", "NF", "MK", "MP", "NO", "OM", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", 123 | "QA", "RE", "RO", "RU", "RW", "BL", "SH", "KN", "LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", 124 | "SG", "SX", "SK", "SI", "SB", "SO", "ZA", "GS", "SS", "ES", "LK", "SD", "SR", "SJ", "SE", "CH", "SY", "TW", "TJ", "TZ", 125 | "TH", "TL", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY", "UZ", "VU", 126 | "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW" ] 127 | 128 | -------------------------------------------------------------------------------- /test/WebApi.TestApp/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace WebApi.TestApp.Controllers; 4 | 5 | [ApiController] 6 | [Route("[controller]")] 7 | public class WeatherForecastController : ControllerBase 8 | { 9 | private static readonly string[] Summaries = new[] 10 | { 11 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 12 | }; 13 | 14 | private readonly ILogger _logger; 15 | 16 | public WeatherForecastController(ILogger logger) 17 | { 18 | _logger = logger; 19 | } 20 | 21 | [HttpGet(Name = "GetWeatherForecast")] 22 | public IEnumerable Get() 23 | { 24 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 25 | { 26 | Date = DateTime.Now.AddDays(index), 27 | TemperatureC = Random.Shared.Next(-20, 55), 28 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 29 | }) 30 | .ToArray(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /test/WebApi.TestApp/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = WebApplication.CreateBuilder(args); 2 | 3 | // Add services to the container. 4 | 5 | builder.Services.AddControllers(); 6 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 7 | builder.Services.AddEndpointsApiExplorer(); 8 | builder.Services.AddSwaggerGen(); 9 | 10 | var app = builder.Build(); 11 | 12 | // Configure the HTTP request pipeline. 13 | if (app.Environment.IsDevelopment()) 14 | { 15 | app.UseSwagger(); 16 | app.UseSwaggerUI(); 17 | } 18 | 19 | app.UseHttpsRedirection(); 20 | 21 | app.UseAuthorization(); 22 | 23 | app.MapControllers(); 24 | 25 | app.Run(); 26 | -------------------------------------------------------------------------------- /test/WebApi.TestApp/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:44006", 8 | "sslPort": 44384 9 | } 10 | }, 11 | "profiles": { 12 | "WebApi.TestApp": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7265;http://localhost:5080", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /test/WebApi.TestApp/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace WebApi.TestApp; 2 | 3 | public class WeatherForecast 4 | { 5 | public DateTime Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } 13 | -------------------------------------------------------------------------------- /test/WebApi.TestApp/WebApi.TestApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /test/WebApi.TestApp/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /test/WebApi.TestApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /ui/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "openapi-io", 3 | "version": "1.0.0", 4 | "lockfileVersion": 2, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "openapi-io", 9 | "version": "1.0.0", 10 | "license": "ISC", 11 | "dependencies": { 12 | "swagger-ui-dist": "^4.14.2" 13 | } 14 | }, 15 | "node_modules/swagger-ui-dist": { 16 | "version": "4.14.2", 17 | "resolved": "https://fileandserve.pkgs.visualstudio.com/_packaging/FileAndServe/npm/registry/swagger-ui-dist/-/swagger-ui-dist-4.14.2.tgz", 18 | "integrity": "sha1-+8rMfvrmTJT3M1gQ1+6Pk7bGVAA=", 19 | "license": "Apache-2.0" 20 | } 21 | }, 22 | "dependencies": { 23 | "swagger-ui-dist": { 24 | "version": "4.14.2", 25 | "resolved": "https://fileandserve.pkgs.visualstudio.com/_packaging/FileAndServe/npm/registry/swagger-ui-dist/-/swagger-ui-dist-4.14.2.tgz", 26 | "integrity": "sha1-+8rMfvrmTJT3M1gQ1+6Pk7bGVAA=" 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ui/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "openapi-io", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "swagger-ui-dist": "^4.14.2" 13 | } 14 | } 15 | --------------------------------------------------------------------------------