diff --git a/.github/workflows/runtime-csharp-testing.yml b/.github/workflows/runtime-csharp-testing.yml new file mode 100644 index 0000000000..00d06de58f --- /dev/null +++ b/.github/workflows/runtime-csharp-testing.yml @@ -0,0 +1,43 @@ +name: Runtime Testing C# Models +on: + push: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + paths: + - 'src/generators/csharp/**' + - 'test/runtime/runtime-csharp/**' + - 'test/runtime/**csharp**' + +jobs: + test: + name: Runtime Testing C# Models + if: "github.event.pull_request.draft == false &&!((github.actor == 'asyncapi-bot' && startsWith(github.event.pull_request.title, 'ci: update global workflows')) || (github.actor == 'asyncapi-bot' && startsWith(github.event.pull_request.title, 'chore(release):')) || (github.actor == 'allcontributors' && startsWith(github.event.pull_request.title, 'docs: add')))" + runs-on: ubuntu-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v3 + - name: Check package-lock version + uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master + id: lockversion + - name: Setup Node.js + uses: actions/setup-node@v3 + with: + node-version: "${{ steps.lockversion.outputs.version }}" + cache: 'npm' + cache-dependency-path: '**/package-lock.json' + - if: matrix.os != 'windows-latest' + name: Setup dotnet + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - if: matrix.os == 'windows-latest' + name: Setup csc.exe + uses: yoavain/Setup-CSC@v7 + - name: Build library + run: npm install && npm run build:prod + - name: Generate C# models + run: npm run generate:runtime:csharp + - name: Run runtime tests + run: npm run test:runtime:csharp + + diff --git a/package-lock.json b/package-lock.json index 701ed3effd..7d73d3f081 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@asyncapi/modelina", - "version": "1.8.11", + "version": "1.8.12", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@asyncapi/modelina", - "version": "1.8.11", + "version": "1.8.12", "license": "Apache-2.0", "dependencies": { "@apidevtools/json-schema-ref-parser": "^9.0.9", diff --git a/package.json b/package.json index 761e6b2ca3..c95f568a7f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@asyncapi/modelina", - "version": "1.8.11", + "version": "1.8.12", "description": "Library for generating data models based on inputs such as AsyncAPI, OpenAPI, or JSON Schema documents", "license": "Apache-2.0", "homepage": "https://www.modelina.org", @@ -110,6 +110,8 @@ "generate:runtime:php": "cross-env CI=true ts-node ./test/runtime/runtime-php.ts", "test:runtime:typescript": "cd ./test/runtime/runtime-typescript && npm i && npm run test", "generate:runtime:typescript": "cross-env CI=true ts-node ./test/runtime/runtime-typescript.ts", + "test:runtime:csharp": "cross-env CI=true jest ./test/runtime/runtime-csharp.spec.ts", + "generate:runtime:csharp": "cross-env CI=true ts-node ./test/runtime/runtime-csharp.ts", "test:watch": "jest --watch", "docs": "npm run docs:api", "docs:api": "typedoc src/index.ts --out ./modelina-website/public/docs/api/generated --name Modelina", diff --git a/src/generators/csharp/presets/JsonSerializerPreset.ts b/src/generators/csharp/presets/JsonSerializerPreset.ts index 82e6252c49..eefd5fd1df 100644 --- a/src/generators/csharp/presets/JsonSerializerPreset.ts +++ b/src/generators/csharp/presets/JsonSerializerPreset.ts @@ -50,12 +50,13 @@ if (${modelInstanceVariable} != null) { ${renderSerializeProperty('unwrappedProperty.Value', propertyModel)} } }`; - } - serializeProperties += `if(${modelInstanceVariable} != null) { + } else { + serializeProperties += `if(${modelInstanceVariable} != null) { // write property name and let the serializer serialize the value itself writer.WritePropertyName("${propertyModel.unconstrainedPropertyName}"); ${renderSerializeProperty(modelInstanceVariable, propertyModel)} }\n`; + } } } return serializeProperties; diff --git a/test/generators/csharp/presets/__snapshots__/JsonSerializerPreset.spec.ts.snap b/test/generators/csharp/presets/__snapshots__/JsonSerializerPreset.spec.ts.snap index b5f12109a8..9012503f6b 100644 --- a/test/generators/csharp/presets/__snapshots__/JsonSerializerPreset.spec.ts.snap +++ b/test/generators/csharp/presets/__snapshots__/JsonSerializerPreset.spec.ts.snap @@ -147,13 +147,8 @@ internal class TestConverter : JsonConverter writer.WritePropertyName(unwrappedProperty.Key); JsonSerializer.Serialize(writer, unwrappedProperty.Value, options); } - }if(value.AdditionalProperties != null) { - // write property name and let the serializer serialize the value itself - writer.WritePropertyName(\\"additionalProperties\\"); - JsonSerializer.Serialize(writer, value.AdditionalProperties, options); } - writer.WriteEndObject(); } @@ -292,13 +287,8 @@ internal class NestedTestConverter : JsonConverter writer.WritePropertyName(unwrappedProperty.Key); JsonSerializer.Serialize(writer, unwrappedProperty.Value, options); } - }if(value.AdditionalProperties != null) { - // write property name and let the serializer serialize the value itself - writer.WritePropertyName(\\"additionalProperties\\"); - JsonSerializer.Serialize(writer, value.AdditionalProperties, options); } - writer.WriteEndObject(); } diff --git a/test/runtime/runtime-csharp.spec.ts b/test/runtime/runtime-csharp.spec.ts new file mode 100644 index 0000000000..fdd8279c2e --- /dev/null +++ b/test/runtime/runtime-csharp.spec.ts @@ -0,0 +1,12 @@ +import { execCommand } from '../blackbox/utils/Utils'; +import path from 'path'; + +jest.setTimeout(50000); + +test('C# runtime testing', async () => { + const compileCommand = `cd ${path.resolve( + __dirname, + './runtime-csharp' + )} && dotnet test runtime-csharp`; + await execCommand(compileCommand); +}); diff --git a/test/runtime/runtime-csharp.ts b/test/runtime/runtime-csharp.ts new file mode 100644 index 0000000000..97f5c1c441 --- /dev/null +++ b/test/runtime/runtime-csharp.ts @@ -0,0 +1,17 @@ +import { CSHARP_JSON_SERIALIZER_PRESET, CSharpFileGenerator } from '../../'; +import path from 'path'; +import input from './generic-input.json'; + +const generator = new CSharpFileGenerator({ + presets: [CSHARP_JSON_SERIALIZER_PRESET] +}); + +generator.generateToFiles( + input, + path.resolve( + // eslint-disable-next-line no-undef + __dirname, + './runtime-csharp/runtime-csharp/src/models/json_serializer' + ), + { namespace: 'com.mycompany.app.generic' } +); diff --git a/test/runtime/runtime-csharp/.gitignore b/test/runtime/runtime-csharp/.gitignore new file mode 100644 index 0000000000..0fc0c43bd6 --- /dev/null +++ b/test/runtime/runtime-csharp/.gitignore @@ -0,0 +1,402 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + + +## Ignore auto-generated src code +src/ \ No newline at end of file diff --git a/test/runtime/runtime-csharp/runtime-csharp.sln b/test/runtime/runtime-csharp/runtime-csharp.sln new file mode 100644 index 0000000000..28e236a111 --- /dev/null +++ b/test/runtime/runtime-csharp/runtime-csharp.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 25.0.1703.8 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "runtime-csharp", "runtime-csharp\runtime-csharp.csproj", "{5474C3FC-151F-4CEF-AB62-49D964E86EC9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5474C3FC-151F-4CEF-AB62-49D964E86EC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5474C3FC-151F-4CEF-AB62-49D964E86EC9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5474C3FC-151F-4CEF-AB62-49D964E86EC9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5474C3FC-151F-4CEF-AB62-49D964E86EC9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5B2C6F52-B721-417A-A1DF-DBE8592A3294} + EndGlobalSection +EndGlobal diff --git a/test/runtime/runtime-csharp/runtime-csharp/README.md b/test/runtime/runtime-csharp/runtime-csharp/README.md new file mode 100644 index 0000000000..460f52fe71 --- /dev/null +++ b/test/runtime/runtime-csharp/runtime-csharp/README.md @@ -0,0 +1,8 @@ +# Modelina C# Runtime project + +This is the Modelina C# runtime project that is used to test the C#-generated code from Modelina at runtime to ensure that everything works as expected. + +Here is how it works: +- The models are first generated during the build phase of the project, by running the root npm script `npm run generate:runtime:csharp`. These models are pre-defined with the [generic input](../generic-input.json). +- The tests are manually added and changed. +- When the project is tested, it tests the generated models at runtime for semantic errors. \ No newline at end of file diff --git a/test/runtime/runtime-csharp/runtime-csharp/Usings.cs b/test/runtime/runtime-csharp/runtime-csharp/Usings.cs new file mode 100644 index 0000000000..9a28bd89e2 --- /dev/null +++ b/test/runtime/runtime-csharp/runtime-csharp/Usings.cs @@ -0,0 +1 @@ +global using NUnit.Framework; diff --git a/test/runtime/runtime-csharp/runtime-csharp/runtime-csharp.csproj b/test/runtime/runtime-csharp/runtime-csharp/runtime-csharp.csproj new file mode 100644 index 0000000000..7cb79cdc30 --- /dev/null +++ b/test/runtime/runtime-csharp/runtime-csharp/runtime-csharp.csproj @@ -0,0 +1,36 @@ + + + + net6.0 + runtime_csharp + enable + enable + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/runtime/runtime-csharp/runtime-csharp/test/models/json_serializer/Address.cs b/test/runtime/runtime-csharp/runtime-csharp/test/models/json_serializer/Address.cs new file mode 100644 index 0000000000..4275e8d7d7 --- /dev/null +++ b/test/runtime/runtime-csharp/runtime-csharp/test/models/json_serializer/Address.cs @@ -0,0 +1,31 @@ +using System.Text.Json; +using com.mycompany.app.generic; + +namespace runtime_csharp; + +public class AddressTests +{ + + [SetUp] + public void Setup() + { + } + + [Test] + public void TestSerializingFullModel() + { + Address address = new Address(); + NestedObject nestedObject = new NestedObject(); + nestedObject.Test = "test"; + address.NestedObject = nestedObject; + address.StreetName = "test"; + address.Marriage = true; + address.Members = 2; + address.HouseNumber = 1; + address.ArrayType = new dynamic[] { 1, "test" }; + string actualJsonString = JsonSerializer.Serialize(address); + string expectedJsonString = "{\"street_name\":\"test\",\"house_number\":1,\"marriage\":true,\"members\":2,\"array_type\":[1,\"test\"],\"nestedObject\":{\"test\":\"test\"}}"; + Assert.That(actualJsonString, Is.EqualTo(expectedJsonString)); + } +} +