From 47685cd19c7e58391625be043b1e5d82c49eedc8 Mon Sep 17 00:00:00 2001 From: Alex Wichmann Date: Fri, 14 Jun 2024 12:35:18 +0200 Subject: [PATCH] fix: resolving wrong reference (#180) --- .../Services/AsyncApiReferenceResolver.cs | 8 +++++- .../AsyncApiReaderTests.cs | 27 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/LEGO.AsyncAPI/Services/AsyncApiReferenceResolver.cs b/src/LEGO.AsyncAPI/Services/AsyncApiReferenceResolver.cs index da6195c6..b3c693e0 100644 --- a/src/LEGO.AsyncAPI/Services/AsyncApiReferenceResolver.cs +++ b/src/LEGO.AsyncAPI/Services/AsyncApiReferenceResolver.cs @@ -218,7 +218,13 @@ private T ResolveReference(AsyncApiReference reference) try { - return this.currentDocument.ResolveReference(reference) as T; + var resolvedReference = this.currentDocument.ResolveReference(reference) as T; + if (resolvedReference == null) + { + throw new AsyncApiException($"Cannot resolve reference '{reference.Reference}' to '{typeof(T).Name}'."); + } + + return resolvedReference; } catch (AsyncApiException ex) { diff --git a/test/LEGO.AsyncAPI.Tests/AsyncApiReaderTests.cs b/test/LEGO.AsyncAPI.Tests/AsyncApiReaderTests.cs index bf19a944..8953f2cd 100644 --- a/test/LEGO.AsyncAPI.Tests/AsyncApiReaderTests.cs +++ b/test/LEGO.AsyncAPI.Tests/AsyncApiReaderTests.cs @@ -6,6 +6,7 @@ namespace LEGO.AsyncAPI.Tests using System.Collections.Generic; using System.Linq; using System.Text.Json.Nodes; + using FluentAssertions; using LEGO.AsyncAPI.Exceptions; using LEGO.AsyncAPI.Models; using LEGO.AsyncAPI.Models.Interfaces; @@ -336,6 +337,32 @@ public void Read_WithBasicPlusSecuritySchemeDeserializes() Assert.AreEqual("Provide your username and password for SASL/SCRAM authentication", scheme.Value.Description); } + [Test] + public void Read_WithWrongReference_AddsError() + { + var yaml = + """ + asyncapi: 2.3.0 + info: + title: test + version: 1.0.0 + channels: + workspace: + publish: + message: + $ref: '#/components/securitySchemes/saslScram' + components: + securitySchemes: + saslScram: + type: scramSha256 + description: Provide your username and password for SASL/SCRAM authentication + """; + var reader = new AsyncApiStringReader(); + var doc = reader.Read(yaml, out var diagnostic); + diagnostic.Errors.Should().NotBeEmpty(); + doc.Channels.Values.First().Publish.Message.First().Should().BeNull(); + } + [Test] public void Read_WithBasicPlusOAuthFlowDeserializes() {