mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-21 17:16:16 +08:00
9b034f8291
# Description Nullable reference types are now enabled once, in `common.props`, and every project in the repository builds warning-clean with them. **Configuration** - `<Nullable>enable</Nullable>` lives in `common.props`. All per-project `<Nullable>` settings are removed: 178 project files (enable, annotations, and the `disable` in the three Aot test projects). - 419 per-file `#nullable enable`/`restore` directives and the 4 `#nullable disable` directives are removed. - Kept on purpose: - The 5 `<auto-generated>` schema files (`UANodeSet.cs`, `UA Type Dictionary.cs`, `OPCBinarySchema.cs`, `SecuredApplication.cs`, `PInvokeHelper.cs`) keep `#nullable enable`. The compiler ignores the project setting in generated code, so the directive is required there. - `tests/Opc.Ua.Interop.LegacyPeer` keeps `disable`. It builds against the 1.5.378 packages and does not import the repository props. - `docs/DeveloperGuide.md` and `.github/copilot-instructions.md` now describe the central setting. **Migration** (the 43 unset and 13 annotations-only projects, roughly 10k diagnostics) - **Production code: annotated at the declarations.** Covers `tools/Opc.Ua.SourceGeneration.Core`, `src/Opc.Ua.Lds.Server` and the LDS sample. - Members, parameters and returns are nullable where null actually flows. - Null-check helpers carry `[NotNullWhen]` (`IsNull`, `IsValidXmlName`, `IsMethodTypeDesign`). - `CoreUtils.Format`, `Utils.Format`, `ITemplateWriter.WriteLine` take `params object?[]`. `Template.AddReplacement` takes `string?` (rendering already skips null replacements). - `IRegisteredServerStore.RegisterAsync` returns `Task<RegistrationEntry?>`: it returns null when a registration is removed. - Dereferences backed by an invariant (for example, the validated model) use `!`, so runtime behaviour is unchanged. - **Behavioural changes in production code** (small, deliberate): - `NodeSetToModelDesign` throws `InvalidOperationException` when the file is not a NodeSet. Before, it threw a NullReferenceException on the next line. - `ModelDesignValidator` starts its lookup tables empty instead of null. A redundant `if (m_nodes == null) return;` guard is gone. - **Test code: minimal annotations.** - `?` on values that can be null, `!` where the test asserts non-null. - `= null!` for fixture members assigned in SetUp. - `TryGetStructure<T>(out T? x)` where the inferred `T?` broke the `IEncodeable` constraint. - A few redundant `== null` checks on structs (`NodeId`, `ArrayOf<T>`) folded into the adjacent `IsNull`/`Count` checks. **Notes for reviewers** - The diff is large (~1,500 files) but almost entirely mechanical: `?`, `!` and directive removal. The non-annotation changes are listed above. - Known follow-up, not done here: `IModelDesign.Namespaces/TargetNamespace/NamespaceUris` stay non-nullable even though the validator returns null before it loads a dictionary. Making them nullable would ripple through every generator call site. ## Related Issues - Fixes #4439 ## Checklist - [ ] I have signed the [CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf) and read the [CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md) doc. - [ ] I have added tests that prove my fix is effective or that my feature works and increased code coverage. - [x] I have added all necessary documentation. - [x] I have verified that my changes do not introduce (new) build or analyzer warnings. - [ ] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. - [ ] I have addressed **all** PR feedback received. The "no new warnings" box covers net10.0 and net48: full non-incremental builds of `UA.slnx`, `tools/SourceGeneration.slnx`, `tools/MigrationAnalyzer.slnx` and the Aot test projects finished with 0 warnings and 0 errors under the repository's warnings-as-errors settings. net9.0 and net8.0 also had no nullable diagnostics, but they were not rebuilt after the final fixes. Tests have not been run locally yet. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
393 lines
16 KiB
C#
393 lines
16 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
|
|
*
|
|
* OPC Foundation MIT License 1.00
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person
|
|
* obtaining a copy of this software and associated documentation
|
|
* files (the "Software"), to deal in the Software without
|
|
* restriction, including without limitation the rights to use,
|
|
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the
|
|
* Software is furnished to do so, subject to the following
|
|
* conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be
|
|
* included in all copies or substantial portions of the Software.
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
* OTHER DEALINGS IN THE SOFTWARE.
|
|
*
|
|
* The complete license agreement can be found here:
|
|
* http://opcfoundation.org/License/MIT/1.00/
|
|
* ======================================================================*/
|
|
|
|
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Bindings;
|
|
using Opc.Ua.Tests;
|
|
|
|
namespace Opc.Ua.Core.Tests.Stack.WebApi
|
|
{
|
|
/// <summary>
|
|
/// Unit tests for the <see cref="WebApiBodyCodec"/> — envelope-less
|
|
/// OPC UA JSON encode / decode used by the HTTPS REST binding
|
|
/// (Part 6 §G.3 "OpenAPI Mapping").
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Category("WebApiBodyCodec")]
|
|
[SetCulture("en-us")]
|
|
[SetUICulture("en-us")]
|
|
[Parallelizable]
|
|
public class WebApiBodyCodecTests
|
|
{
|
|
[Test]
|
|
public void EncodeReadRequestProducesEnvelopeLessRoot()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
ReadRequest request = BuildReadRequest();
|
|
|
|
byte[] payload = WebApiBodyCodec.EncodeBody(request, context, JsonEncoderOptions.Compact);
|
|
|
|
using var document = JsonDocument.Parse(payload);
|
|
JsonElement root = document.RootElement;
|
|
|
|
Assert.That(root.ValueKind, Is.EqualTo(JsonValueKind.Object));
|
|
Assert.That(
|
|
root.TryGetProperty("UaTypeId", out _),
|
|
Is.False,
|
|
"REST body must not carry the {UaTypeId, UaBody} envelope written by JsonEncoder.EncodeMessage");
|
|
Assert.That(
|
|
root.TryGetProperty("UaBody", out _),
|
|
Is.False,
|
|
"REST body must not carry the {UaTypeId, UaBody} envelope written by JsonEncoder.EncodeMessage");
|
|
Assert.That(
|
|
root.TryGetProperty("RequestHeader", out _),
|
|
Is.True,
|
|
"REST body root object should expose the request's own fields directly");
|
|
}
|
|
|
|
[Test]
|
|
public void EncodeAndDecodeRoundTripsReadRequestInCompact()
|
|
{
|
|
AssertReadRequestRoundTrip(JsonEncoderOptions.Compact);
|
|
}
|
|
|
|
[Test]
|
|
public void EncodeAndDecodeRoundTripsReadRequestInVerbose()
|
|
{
|
|
AssertReadRequestRoundTrip(JsonEncoderOptions.Verbose);
|
|
}
|
|
|
|
[Test]
|
|
public async Task DecodeBodyAsyncReadsFromStream()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
ReadRequest original = BuildReadRequest();
|
|
|
|
byte[] payload = WebApiBodyCodec.EncodeBody(
|
|
original, context, JsonEncoderOptions.Compact);
|
|
|
|
using var stream = new MemoryStream(payload);
|
|
ReadRequest decoded = await WebApiBodyCodec
|
|
.DecodeBodyAsync<ReadRequest>(stream, context)
|
|
.ConfigureAwait(false);
|
|
|
|
Assert.That(decoded, Is.Not.Null);
|
|
Assert.That(decoded.RequestHeader.RequestHandle, Is.EqualTo(original.RequestHeader.RequestHandle));
|
|
Assert.That(decoded.NodesToRead, Has.Count.EqualTo(original.NodesToRead.Count));
|
|
}
|
|
|
|
[Test]
|
|
public async Task EncodeBodyAsyncWritesToStream()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
ReadRequest original = BuildReadRequest();
|
|
|
|
using var destination = new MemoryStream();
|
|
await WebApiBodyCodec
|
|
.EncodeBodyAsync(original, destination, context, JsonEncoderOptions.Compact)
|
|
.ConfigureAwait(false);
|
|
|
|
destination.Position = 0;
|
|
ReadRequest decoded = await WebApiBodyCodec
|
|
.DecodeBodyAsync<ReadRequest>(destination, context)
|
|
.ConfigureAwait(false);
|
|
|
|
Assert.That(decoded.RequestHeader.RequestHandle, Is.EqualTo(original.RequestHeader.RequestHandle));
|
|
}
|
|
|
|
[Test]
|
|
public void EncodeAndDecodeRoundTripsReadResponseWithVariantPayloads()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
|
|
DateTimeUtc sourceTimestamp = DateTimeUtc.Now;
|
|
var original = new ReadResponse
|
|
{
|
|
ResponseHeader = new ResponseHeader
|
|
{
|
|
Timestamp = DateTime.UtcNow,
|
|
RequestHandle = 1000,
|
|
ServiceResult = StatusCodes.Good
|
|
},
|
|
Results = new ArrayOf<DataValue>(new DataValue[]
|
|
{
|
|
new(
|
|
new Variant(42),
|
|
StatusCodes.Good,
|
|
sourceTimestamp),
|
|
new(
|
|
new Variant("hello"),
|
|
StatusCodes.GoodEntryInserted)
|
|
}.AsMemory())
|
|
};
|
|
|
|
byte[] payload = WebApiBodyCodec.EncodeBody(
|
|
original, context, JsonEncoderOptions.Compact);
|
|
|
|
ReadResponse decoded = WebApiBodyCodec.DecodeBody<ReadResponse>(payload, context);
|
|
|
|
Assert.That(decoded.ResponseHeader.RequestHandle, Is.EqualTo(1000u));
|
|
Assert.That(decoded.Results, Has.Count.EqualTo(2));
|
|
Assert.That(decoded.Results[0].WrappedValue.TryGetValue(out int intValue), Is.True);
|
|
Assert.That(intValue, Is.EqualTo(42));
|
|
Assert.That(decoded.Results[1].WrappedValue.TryGetValue(out string? stringValue), Is.True);
|
|
Assert.That(stringValue, Is.EqualTo("hello"));
|
|
}
|
|
|
|
[Test]
|
|
public void DecodeBodyThrowsBadDecodingErrorOnMalformedJson()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
byte[] payload = Encoding.UTF8.GetBytes("not a json document");
|
|
|
|
ServiceResultException ex = Assert.Throws<ServiceResultException>(
|
|
() => WebApiBodyCodec.DecodeBody<ReadRequest>(payload, context))!;
|
|
Assert.That(ex.StatusCode, Is.EqualTo((uint)StatusCodes.BadDecodingError));
|
|
}
|
|
|
|
[Test]
|
|
public void DecodeBodyThrowsBadEncodingLimitsExceededWhenPayloadTooLarge()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
context.MaxMessageSize = 16;
|
|
|
|
byte[] payload = Encoding.UTF8.GetBytes("{\"NodesToRead\": []}");
|
|
Assert.That(payload, Has.Length.GreaterThan(context.MaxMessageSize));
|
|
|
|
ServiceResultException ex = Assert.Throws<ServiceResultException>(
|
|
() => WebApiBodyCodec.DecodeBody<ReadRequest>(payload, context))!;
|
|
Assert.That(ex.StatusCode, Is.EqualTo((uint)StatusCodes.BadEncodingLimitsExceeded));
|
|
}
|
|
|
|
[Test]
|
|
public void DecodeBodyAcceptsEmptyJsonObject()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
byte[] payload = Encoding.UTF8.GetBytes("{}");
|
|
|
|
ReadRequest decoded = WebApiBodyCodec.DecodeBody<ReadRequest>(payload, context);
|
|
|
|
Assert.That(decoded, Is.Not.Null);
|
|
Assert.That(decoded.NodesToRead, Has.Count.Zero);
|
|
}
|
|
|
|
[Test]
|
|
public void EncodeBodyNullValueThrowsArgumentNullException()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
|
|
Assert.Throws<ArgumentNullException>(
|
|
() => WebApiBodyCodec.EncodeBody<ReadRequest>(null!, context));
|
|
}
|
|
|
|
[Test]
|
|
public void EncodeBodyNullContextThrowsArgumentNullException()
|
|
{
|
|
ReadRequest request = BuildReadRequest();
|
|
|
|
Assert.Throws<ArgumentNullException>(
|
|
() => WebApiBodyCodec.EncodeBody(request, null!));
|
|
}
|
|
|
|
[Test]
|
|
public void DecodeBodyNullPayloadThrowsArgumentNullException()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
|
|
Assert.Throws<ArgumentNullException>(
|
|
() => WebApiBodyCodec.DecodeBody<ReadRequest>(null!, context));
|
|
}
|
|
|
|
[Test]
|
|
public void DecodeBodyAsyncNullStreamThrowsArgumentNullException()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
|
|
Assert.ThrowsAsync<ArgumentNullException>(async () =>
|
|
await WebApiBodyCodec
|
|
.DecodeBodyAsync<ReadRequest>(null!, context, ct: CancellationToken.None)
|
|
.ConfigureAwait(false));
|
|
}
|
|
|
|
[Test]
|
|
public void EncodeBodyCompactOmitsDefaultValuesPerSpec()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
|
|
var request = new ReadRequest
|
|
{
|
|
RequestHeader = new RequestHeader(),
|
|
NodesToRead = new ArrayOf<ReadValueId>()
|
|
};
|
|
|
|
byte[] compactBytes = WebApiBodyCodec.EncodeBody(request, context, JsonEncoderOptions.Compact);
|
|
byte[] verboseBytes = WebApiBodyCodec.EncodeBody(request, context, JsonEncoderOptions.Verbose);
|
|
|
|
Assert.That(
|
|
compactBytes,
|
|
Has.Length.LessThan(verboseBytes.Length),
|
|
"Compact must omit default values per Part 6 §5.4.9");
|
|
}
|
|
|
|
private static ReadRequest BuildReadRequest()
|
|
{
|
|
return new ReadRequest
|
|
{
|
|
RequestHeader = new RequestHeader
|
|
{
|
|
Timestamp = DateTime.UtcNow,
|
|
RequestHandle = 12345,
|
|
TimeoutHint = 1000,
|
|
AuthenticationToken = new NodeId(Guid.NewGuid(), 0)
|
|
},
|
|
MaxAge = 250,
|
|
TimestampsToReturn = TimestampsToReturn.Both,
|
|
NodesToRead = new ArrayOf<ReadValueId>(new ReadValueId[]
|
|
{
|
|
new() {
|
|
NodeId = new NodeId("Var1", 2),
|
|
AttributeId = Attributes.Value
|
|
},
|
|
new() {
|
|
NodeId = new NodeId(42u, 0),
|
|
AttributeId = Attributes.DisplayName
|
|
}
|
|
}.AsMemory())
|
|
};
|
|
}
|
|
|
|
private static void AssertReadRequestRoundTrip(JsonEncoderOptions options)
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
ReadRequest original = BuildReadRequest();
|
|
|
|
byte[] payload = WebApiBodyCodec.EncodeBody(original, context, options);
|
|
ReadRequest decoded = WebApiBodyCodec.DecodeBody<ReadRequest>(payload, context);
|
|
|
|
Assert.That(decoded, Is.Not.Null);
|
|
Assert.That(decoded.RequestHeader.RequestHandle, Is.EqualTo(12345u));
|
|
Assert.That(decoded.RequestHeader.TimeoutHint, Is.EqualTo(1000u));
|
|
Assert.That(decoded.MaxAge, Is.EqualTo(250d));
|
|
Assert.That(decoded.TimestampsToReturn, Is.EqualTo(TimestampsToReturn.Both));
|
|
Assert.That(decoded.NodesToRead, Has.Count.EqualTo(2));
|
|
Assert.That(decoded.NodesToRead[0].NodeId, Is.EqualTo(original.NodesToRead[0].NodeId));
|
|
Assert.That(decoded.NodesToRead[0].AttributeId, Is.EqualTo(Attributes.Value));
|
|
Assert.That(decoded.NodesToRead[1].NodeId, Is.EqualTo(original.NodesToRead[1].NodeId));
|
|
Assert.That(decoded.NodesToRead[1].AttributeId, Is.EqualTo(Attributes.DisplayName));
|
|
}
|
|
|
|
[Test]
|
|
public void DecodeBodyNonGenericReturnsConcreteType()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
ReadRequest original = BuildReadRequest();
|
|
byte[] payload = WebApiBodyCodec.EncodeBody(original, context, JsonEncoderOptions.Compact);
|
|
|
|
#pragma warning disable CA2263 // Prefer generic overload when type is known
|
|
IEncodeable decoded = WebApiBodyCodec.DecodeBody(typeof(ReadRequest), payload, context);
|
|
#pragma warning restore CA2263 // Prefer generic overload when type is known
|
|
|
|
Assert.That(decoded, Is.InstanceOf<ReadRequest>());
|
|
var typed = (ReadRequest)decoded;
|
|
Assert.That(typed.NodesToRead, Has.Count.EqualTo(2));
|
|
Assert.That(typed.MaxAge, Is.EqualTo(250d));
|
|
}
|
|
|
|
[Test]
|
|
public async Task DecodeBodyAsyncNonGenericRoundTripsResponse()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
|
|
var original = new ReadResponse
|
|
{
|
|
ResponseHeader = new ResponseHeader { RequestHandle = 99 },
|
|
Results = new ArrayOf<DataValue>(new[]
|
|
{
|
|
new DataValue(new Variant(42), StatusCodes.Good, DateTime.UtcNow)
|
|
}.AsMemory())
|
|
};
|
|
byte[] payload = WebApiBodyCodec.EncodeBody(original, context, JsonEncoderOptions.Compact);
|
|
using var stream = new MemoryStream(payload);
|
|
|
|
IEncodeable decoded = await WebApiBodyCodec
|
|
.DecodeBodyAsync(typeof(ReadResponse), stream, context)
|
|
.ConfigureAwait(false);
|
|
|
|
Assert.That(decoded, Is.InstanceOf<ReadResponse>());
|
|
var typed = (ReadResponse)decoded;
|
|
Assert.That(typed.ResponseHeader.RequestHandle, Is.EqualTo(99u));
|
|
Assert.That(typed.Results, Has.Count.EqualTo(1));
|
|
Assert.That(typed.Results[0].WrappedValue.TryGetValue(out int v), Is.True);
|
|
Assert.That(v, Is.EqualTo(42));
|
|
}
|
|
|
|
[Test]
|
|
public void DecodeBodyNonGenericRejectsNonEncodeableType()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
byte[] payload = Encoding.UTF8.GetBytes("{}");
|
|
|
|
ArgumentException ex = Assert.Throws<ArgumentException>(
|
|
() => WebApiBodyCodec.DecodeBody(typeof(string), payload, context))!;
|
|
Assert.That(ex.Message, Does.Contain("IEncodeable"));
|
|
}
|
|
|
|
[Test]
|
|
public void DecodeBodyNonGenericRejectsNullBodyType()
|
|
{
|
|
var context = ServiceMessageContext.Create(
|
|
NUnitTelemetryContext.Create());
|
|
|
|
Assert.Throws<ArgumentNullException>(
|
|
() => WebApiBodyCodec.DecodeBody(null!, [], context));
|
|
}
|
|
}
|
|
}
|