Enable nullable reference types for unit test project

Signed-off-by: Jon Skeet <jonskeet@google.com>
This commit is contained in:
Jon Skeet 2021-07-08 16:53:48 +01:00 committed by Jon Skeet
parent bb8f4a8d13
commit e7ebdd7c1c
30 changed files with 179 additions and 162 deletions

View File

@ -45,11 +45,11 @@ namespace CloudNative.CloudEvents.Amqp.UnitTests
Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull"), receivedCloudEvent.Source); Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull"), receivedCloudEvent.Source);
Assert.Equal("123", receivedCloudEvent.Subject); Assert.Equal("123", receivedCloudEvent.Subject);
Assert.Equal("A234-1234-1234", receivedCloudEvent.Id); Assert.Equal("A234-1234-1234", receivedCloudEvent.Id);
AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time.Value); AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time!.Value);
Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType); Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType);
Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data); Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data);
Assert.Equal("value", (string)receivedCloudEvent["comexampleextension1"]); Assert.Equal("value", (string?)receivedCloudEvent["comexampleextension1"]);
} }
[Fact] [Fact]
@ -82,11 +82,11 @@ namespace CloudNative.CloudEvents.Amqp.UnitTests
Assert.Equal("com.github.pull.create", receivedCloudEvent.Type); Assert.Equal("com.github.pull.create", receivedCloudEvent.Type);
Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source); Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source);
Assert.Equal("A234-1234-1234", receivedCloudEvent.Id); Assert.Equal("A234-1234-1234", receivedCloudEvent.Id);
AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time.Value); AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time!.Value);
Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType); Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType);
Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data); Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data);
Assert.Equal("value", (string)receivedCloudEvent["comexampleextension1"]); Assert.Equal("value", (string?)receivedCloudEvent["comexampleextension1"]);
} }
[Fact] [Fact]
@ -109,7 +109,7 @@ namespace CloudNative.CloudEvents.Amqp.UnitTests
var message1 = Message.Decode(encodedAmqpMessage); var message1 = Message.Decode(encodedAmqpMessage);
var receivedCloudEvent = message1.ToCloudEvent(new JsonEventFormatter()); var receivedCloudEvent = message1.ToCloudEvent(new JsonEventFormatter());
AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time.Value); AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time!.Value);
} }
[Fact] [Fact]

View File

@ -18,7 +18,7 @@ namespace CloudNative.CloudEvents.AspNetCore.UnitTests
{ {
public class HttpRequestExtensionsTest public class HttpRequestExtensionsTest
{ {
public static TheoryData<string, string, IDictionary<string, string>> SingleCloudEventMessages = new TheoryData<string, string, IDictionary<string, string>> public static TheoryData<string, string, IDictionary<string, string>?> SingleCloudEventMessages = new TheoryData<string, string, IDictionary<string, string>?>
{ {
{ {
"Binary", "Binary",
@ -38,7 +38,7 @@ namespace CloudNative.CloudEvents.AspNetCore.UnitTests
} }
}; };
public static TheoryData<string, string, IDictionary<string, string>> BatchMessages = new TheoryData<string, string, IDictionary<string, string>> public static TheoryData<string, string, IDictionary<string, string>?> BatchMessages = new TheoryData<string, string, IDictionary<string, string>?>
{ {
{ {
"Batch", "Batch",
@ -47,7 +47,7 @@ namespace CloudNative.CloudEvents.AspNetCore.UnitTests
} }
}; };
public static TheoryData<string, string, IDictionary<string, string>> NonCloudEventMessages = new TheoryData<string, string, IDictionary<string, string>> public static TheoryData<string, string, IDictionary<string, string>?> NonCloudEventMessages = new TheoryData<string, string, IDictionary<string, string>?>
{ {
{ {
"Plain text", "Plain text",
@ -58,7 +58,7 @@ namespace CloudNative.CloudEvents.AspNetCore.UnitTests
[Theory] [Theory]
[MemberData(nameof(SingleCloudEventMessages))] [MemberData(nameof(SingleCloudEventMessages))]
public void IsCloudEvent_True(string description, string contentType, IDictionary<string, string> headers) public void IsCloudEvent_True(string description, string contentType, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -71,7 +71,7 @@ namespace CloudNative.CloudEvents.AspNetCore.UnitTests
[Theory] [Theory]
[MemberData(nameof(BatchMessages))] [MemberData(nameof(BatchMessages))]
[MemberData(nameof(NonCloudEventMessages))] [MemberData(nameof(NonCloudEventMessages))]
public void IsCloudEvent_False(string description, string contentType, IDictionary<string, string> headers) public void IsCloudEvent_False(string description, string contentType, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -83,7 +83,7 @@ namespace CloudNative.CloudEvents.AspNetCore.UnitTests
[Theory] [Theory]
[MemberData(nameof(BatchMessages))] [MemberData(nameof(BatchMessages))]
public void IsCloudEventBatch_True(string description, string contentType, IDictionary<string, string> headers) public void IsCloudEventBatch_True(string description, string contentType, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -96,7 +96,7 @@ namespace CloudNative.CloudEvents.AspNetCore.UnitTests
[Theory] [Theory]
[MemberData(nameof(SingleCloudEventMessages))] [MemberData(nameof(SingleCloudEventMessages))]
[MemberData(nameof(NonCloudEventMessages))] [MemberData(nameof(NonCloudEventMessages))]
public void IsCloudEventBatch_False(string description, string contentType, IDictionary<string, string> headers) public void IsCloudEventBatch_False(string description, string contentType, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -138,7 +138,7 @@ namespace CloudNative.CloudEvents.AspNetCore.UnitTests
Body = BinaryDataUtilities.AsStream(content) Body = BinaryDataUtilities.AsStream(content)
}; };
private static void CopyHeaders(IDictionary<string, string> source, HttpRequest target) private static void CopyHeaders(IDictionary<string, string>? source, HttpRequest target)
{ {
if (source is null) if (source is null)
{ {

View File

@ -36,7 +36,7 @@ namespace CloudNative.CloudEvents.AspNetCore.UnitTests
Assert.Equal("1.0", response.Headers["ce-specversion"]); Assert.Equal("1.0", response.Headers["ce-specversion"]);
Assert.Equal(cloudEvent.Type, response.Headers["ce-type"]); Assert.Equal(cloudEvent.Type, response.Headers["ce-type"]);
Assert.Equal(cloudEvent.Id, response.Headers["ce-id"]); Assert.Equal(cloudEvent.Id, response.Headers["ce-id"]);
Assert.Equal(CloudEventAttributeType.UriReference.Format(cloudEvent.Source), response.Headers["ce-source"]); Assert.Equal(CloudEventAttributeType.UriReference.Format(cloudEvent.Source!), response.Headers["ce-source"]);
// There's no data content type header; the content type itself is used for that. // There's no data content type header; the content type itself is used for that.
Assert.False(response.Headers.ContainsKey("ce-datacontenttype")); Assert.False(response.Headers.ContainsKey("ce-datacontenttype"));
} }
@ -84,7 +84,7 @@ namespace CloudNative.CloudEvents.AspNetCore.UnitTests
Assert.Equal("1.0", response.Headers["ce-specversion"]); Assert.Equal("1.0", response.Headers["ce-specversion"]);
Assert.Equal(cloudEvent.Type, response.Headers["ce-type"]); Assert.Equal(cloudEvent.Type, response.Headers["ce-type"]);
Assert.Equal(cloudEvent.Id, response.Headers["ce-id"]); Assert.Equal(cloudEvent.Id, response.Headers["ce-id"]);
Assert.Equal(CloudEventAttributeType.UriReference.Format(cloudEvent.Source), response.Headers["ce-source"]); Assert.Equal(CloudEventAttributeType.UriReference.Format(cloudEvent.Source!), response.Headers["ce-source"]);
// We don't populate the data content type header // We don't populate the data content type header
Assert.False(response.Headers.ContainsKey("ce-datacontenttype")); Assert.False(response.Headers.ContainsKey("ce-datacontenttype"));
} }

View File

@ -38,7 +38,7 @@ namespace CloudNative.CloudEvents.Avro.UnitTests
Assert.Equal(cloudEvent2.Type, cloudEvent.Type); Assert.Equal(cloudEvent2.Type, cloudEvent.Type);
Assert.Equal(cloudEvent2.Source, cloudEvent.Source); Assert.Equal(cloudEvent2.Source, cloudEvent.Source);
Assert.Equal(cloudEvent2.Id, cloudEvent.Id); Assert.Equal(cloudEvent2.Id, cloudEvent.Id);
AssertTimestampsEqual(cloudEvent2.Time.Value, cloudEvent.Time.Value); AssertTimestampsEqual(cloudEvent2.Time!.Value, cloudEvent.Time!.Value);
Assert.Equal(cloudEvent2.DataContentType, cloudEvent.DataContentType); Assert.Equal(cloudEvent2.DataContentType, cloudEvent.DataContentType);
Assert.Equal(cloudEvent2.Data, cloudEvent.Data); Assert.Equal(cloudEvent2.Data, cloudEvent.Data);
} }
@ -56,11 +56,11 @@ namespace CloudNative.CloudEvents.Avro.UnitTests
Assert.Equal("com.github.pull.create", cloudEvent.Type); Assert.Equal("com.github.pull.create", cloudEvent.Type);
Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), cloudEvent.Source); Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), cloudEvent.Source);
Assert.Equal("A234-1234-1234", cloudEvent.Id); Assert.Equal("A234-1234-1234", cloudEvent.Id);
AssertTimestampsEqual("2018-04-05T17:31:00Z", cloudEvent.Time.Value); AssertTimestampsEqual("2018-04-05T17:31:00Z", cloudEvent.Time!.Value);
Assert.Equal(MediaTypeNames.Text.Xml, cloudEvent.DataContentType); Assert.Equal(MediaTypeNames.Text.Xml, cloudEvent.DataContentType);
Assert.Equal("<much wow=\"xml\"/>", cloudEvent.Data); Assert.Equal("<much wow=\"xml\"/>", cloudEvent.Data);
Assert.Equal("value", (string)cloudEvent["comexampleextension1"]); Assert.Equal("value", (string?)cloudEvent["comexampleextension1"]);
} }
[Fact] [Fact]
@ -77,7 +77,7 @@ namespace CloudNative.CloudEvents.Avro.UnitTests
Assert.Equal("com.github.pull.create", cloudEvent.Type); Assert.Equal("com.github.pull.create", cloudEvent.Type);
Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), cloudEvent.Source); Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), cloudEvent.Source);
Assert.Equal("A234-1234-1234", cloudEvent.Id); Assert.Equal("A234-1234-1234", cloudEvent.Id);
AssertTimestampsEqual("2018-04-05T17:31:00Z", cloudEvent.Time.Value); AssertTimestampsEqual("2018-04-05T17:31:00Z", cloudEvent.Time!.Value);
Assert.Equal(MediaTypeNames.Text.Xml, cloudEvent.DataContentType); Assert.Equal(MediaTypeNames.Text.Xml, cloudEvent.DataContentType);
Assert.Equal("<much wow=\"xml\"/>", cloudEvent.Data); Assert.Equal("<much wow=\"xml\"/>", cloudEvent.Data);

View File

@ -67,11 +67,11 @@ namespace CloudNative.CloudEvents.UnitTests
[Fact] [Fact]
public void CreateExtension_NullName() => public void CreateExtension_NullName() =>
Assert.Throws<ArgumentNullException>(() => CloudEventAttribute.CreateExtension(null, CloudEventAttributeType.String)); Assert.Throws<ArgumentNullException>(() => CloudEventAttribute.CreateExtension(null!, CloudEventAttributeType.String));
[Fact] [Fact]
public void CreateExtension_NullType() => public void CreateExtension_NullType() =>
Assert.Throws<ArgumentNullException>(() => CloudEventAttribute.CreateExtension("name", null)); Assert.Throws<ArgumentNullException>(() => CloudEventAttribute.CreateExtension("name", null!));
[Fact] [Fact]
public void CreateExtension_SpecVersionName() => public void CreateExtension_SpecVersionName() =>

View File

@ -51,12 +51,12 @@ namespace CloudNative.CloudEvents.UnitTests
[Theory] [Theory]
[MemberData(nameof(AllTypes))] [MemberData(nameof(AllTypes))]
public void ParseNull(CloudEventAttributeType type) => public void ParseNull(CloudEventAttributeType type) =>
Assert.Throws<ArgumentNullException>(() => type.Parse(null)); Assert.Throws<ArgumentNullException>(() => type.Parse(null!));
[Theory] [Theory]
[MemberData(nameof(AllTypes))] [MemberData(nameof(AllTypes))]
public void FormatNull(CloudEventAttributeType type) => public void FormatNull(CloudEventAttributeType type) =>
Assert.Throws<ArgumentNullException>(() => type.Format(null)); Assert.Throws<ArgumentNullException>(() => type.Format(null!));
// None of our types can be constructed with a StringBuilder. // None of our types can be constructed with a StringBuilder.
[Theory] [Theory]

View File

@ -35,7 +35,7 @@ namespace CloudNative.CloudEvents.UnitTests
{ {
} }
[CloudEventFormatter(null)] [CloudEventFormatter(null!)]
public class NullFormatterAttribute public class NullFormatterAttribute
{ {
} }
@ -56,13 +56,13 @@ namespace CloudNative.CloudEvents.UnitTests
public class SampleCloudEventFormatter : CloudEventFormatter public class SampleCloudEventFormatter : CloudEventFormatter
{ {
public override IReadOnlyList<CloudEvent> DecodeBatchModeMessage(ReadOnlyMemory<byte> body, ContentType contentType, IEnumerable<CloudEventAttribute> extensionAttributes) => public override IReadOnlyList<CloudEvent> DecodeBatchModeMessage(ReadOnlyMemory<byte> body, ContentType? contentType, IEnumerable<CloudEventAttribute>? extensionAttributes) =>
throw new NotImplementedException(); throw new NotImplementedException();
public override void DecodeBinaryModeEventData(ReadOnlyMemory<byte> body, CloudEvent cloudEvent) => public override void DecodeBinaryModeEventData(ReadOnlyMemory<byte> body, CloudEvent cloudEvent) =>
throw new NotImplementedException(); throw new NotImplementedException();
public override CloudEvent DecodeStructuredModeMessage(ReadOnlyMemory<byte> body, ContentType contentType, IEnumerable<CloudEventAttribute> extensionAttributes) => public override CloudEvent DecodeStructuredModeMessage(ReadOnlyMemory<byte> body, ContentType? contentType, IEnumerable<CloudEventAttribute>? extensionAttributes) =>
throw new NotImplementedException(); throw new NotImplementedException();
public override ReadOnlyMemory<byte> EncodeBatchModeMessage(IEnumerable<CloudEvent> cloudEvents, out ContentType contentType) => public override ReadOnlyMemory<byte> EncodeBatchModeMessage(IEnumerable<CloudEvent> cloudEvents, out ContentType contentType) =>

View File

@ -37,7 +37,7 @@ namespace CloudNative.CloudEvents.UnitTests
Assert.Equal(MediaTypeNames.Text.Xml, cloudEvent.DataContentType); Assert.Equal(MediaTypeNames.Text.Xml, cloudEvent.DataContentType);
Assert.Equal("<much wow=\"xml\"/>", cloudEvent.Data); Assert.Equal("<much wow=\"xml\"/>", cloudEvent.Data);
Assert.Equal("value", (string)cloudEvent["comexampleextension1"]); Assert.Equal("value", (string?)cloudEvent["comexampleextension1"]);
} }
[Fact] [Fact]
@ -143,7 +143,7 @@ namespace CloudNative.CloudEvents.UnitTests
[Fact] [Fact]
public void Constructor_NullVersion() => public void Constructor_NullVersion() =>
Assert.Throws<ArgumentNullException>(() => new CloudEvent(specVersion: null)); Assert.Throws<ArgumentNullException>(() => new CloudEvent(specVersion: null!));
[Fact] [Fact]
public void Constructor_SpecVersionAndExtensionAttributes() public void Constructor_SpecVersionAndExtensionAttributes()
@ -167,7 +167,7 @@ namespace CloudNative.CloudEvents.UnitTests
[Fact] [Fact]
public void Constructor_ExtensionAttributes_NullValue() public void Constructor_ExtensionAttributes_NullValue()
{ {
var extensions = new CloudEventAttribute[] { null }; var extensions = new CloudEventAttribute[] { null! };
Assert.Throws<ArgumentException>(() => new CloudEvent(extensions)); Assert.Throws<ArgumentException>(() => new CloudEvent(extensions));
} }
@ -236,8 +236,8 @@ namespace CloudNative.CloudEvents.UnitTests
Assert.Equal("text", cloudEvent["string"]); Assert.Equal("text", cloudEvent["string"]);
Assert.Equal(10, cloudEvent["integer"]); Assert.Equal(10, cloudEvent["integer"]);
Assert.Equal(new byte[] { 77 }, cloudEvent["binary"]); Assert.Equal(new byte[] { 77 }, cloudEvent["binary"]);
Assert.True((bool) cloudEvent["boolean"]); Assert.True((bool) cloudEvent["boolean"]!);
AssertTimestampsEqual("2021-02-09T11:58:12.242Z", (DateTimeOffset) cloudEvent["timestamp"]); AssertTimestampsEqual("2021-02-09T11:58:12.242Z", (DateTimeOffset) cloudEvent["timestamp"]!);
Assert.Equal(new Uri("https://cloudevents.io"), cloudEvent["uri"]); Assert.Equal(new Uri("https://cloudevents.io"), cloudEvent["uri"]);
Assert.Equal(new Uri("//auth", UriKind.RelativeOrAbsolute), cloudEvent["urireference"]); Assert.Equal(new Uri("//auth", UriKind.RelativeOrAbsolute), cloudEvent["urireference"]);
} }
@ -256,17 +256,17 @@ namespace CloudNative.CloudEvents.UnitTests
var cloudEvent = new CloudEvent(); var cloudEvent = new CloudEvent();
cloudEvent.SetAttributeFromString("ext", "text"); cloudEvent.SetAttributeFromString("ext", "text");
Assert.Equal("text", cloudEvent["ext"]); Assert.Equal("text", cloudEvent["ext"]);
Assert.Equal(CloudEventAttributeType.String, cloudEvent.GetAttribute("ext").Type); Assert.Equal(CloudEventAttributeType.String, cloudEvent.GetAttribute("ext")!.Type);
} }
[Fact] [Fact]
public void Indexer_NullKey_Throws() public void Indexer_NullKey_Throws()
{ {
var cloudEvent = new CloudEvent(); var cloudEvent = new CloudEvent();
Assert.Throws<ArgumentNullException>(() => cloudEvent[(string)null]); Assert.Throws<ArgumentNullException>(() => cloudEvent[(string)null!]);
Assert.Throws<ArgumentNullException>(() => cloudEvent[(CloudEventAttribute)null]); Assert.Throws<ArgumentNullException>(() => cloudEvent[(CloudEventAttribute)null!]);
Assert.Throws<ArgumentNullException>(() => cloudEvent[(string)null] = "text"); Assert.Throws<ArgumentNullException>(() => cloudEvent[(string)null!] = "text");
Assert.Throws<ArgumentNullException>(() => cloudEvent[(CloudEventAttribute)null] = "text"); Assert.Throws<ArgumentNullException>(() => cloudEvent[(CloudEventAttribute)null!] = "text");
} }
[Fact] [Fact]
@ -326,7 +326,7 @@ namespace CloudNative.CloudEvents.UnitTests
{ {
var cloudEvent = new CloudEvent(); var cloudEvent = new CloudEvent();
cloudEvent["ext"] = "10"; cloudEvent["ext"] = "10";
Assert.Equal(CloudEventAttributeType.String, cloudEvent.GetAttribute("ext").Type); Assert.Equal(CloudEventAttributeType.String, cloudEvent.GetAttribute("ext")?.Type);
var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer); var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer);
// Setting the event with the attribute updates the extension registry... // Setting the event with the attribute updates the extension registry...

View File

@ -24,7 +24,7 @@ namespace CloudNative.CloudEvents.UnitTests
{ {
var version = CloudEventsSpecVersion.FromVersionId(versionId); var version = CloudEventsSpecVersion.FromVersionId(versionId);
Assert.NotNull(version); Assert.NotNull(version);
Assert.Equal(versionId, version.VersionId); Assert.Equal(versionId, version!.VersionId);
} }
} }
} }

View File

@ -3,6 +3,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework> <TargetFramework>netcoreapp2.1</TargetFramework>
<LangVersion>8.0</LangVersion> <LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

@ -22,7 +22,7 @@ namespace CloudNative.CloudEvents.Core.UnitTests
[Fact] [Fact]
public void GetOrdinal_NullInput() => public void GetOrdinal_NullInput() =>
Assert.Throws<ArgumentNullException>(() => CloudEventAttributeTypes.GetOrdinal(null)); Assert.Throws<ArgumentNullException>(() => CloudEventAttributeTypes.GetOrdinal(null!));
[Theory] [Theory]
[MemberData(nameof(AllTypes))] [MemberData(nameof(AllTypes))]

View File

@ -22,9 +22,9 @@ namespace CloudNative.CloudEvents.Core.UnitTests
{ {
var originalContentType = new ContentType(text); var originalContentType = new ContentType(text);
var header = MimeUtilities.ToMediaTypeHeaderValue(originalContentType); var header = MimeUtilities.ToMediaTypeHeaderValue(originalContentType);
AssertEqualParts(text, header.ToString()); AssertEqualParts(text, header!.ToString());
var convertedContentType = MimeUtilities.ToContentType(header); var convertedContentType = MimeUtilities.ToContentType(header);
AssertEqualParts(originalContentType.ToString(), convertedContentType.ToString()); AssertEqualParts(originalContentType.ToString(), convertedContentType!.ToString());
// Conversions can end up reordering the parameters. In reality we're only // Conversions can end up reordering the parameters. In reality we're only
// likely to end up with a media type and charset, but our tests use more parameters. // likely to end up with a media type and charset, but our tests use more parameters.
@ -57,7 +57,7 @@ namespace CloudNative.CloudEvents.Core.UnitTests
[Fact] [Fact]
public void ContentTypeGetEncoding_NoContentType() public void ContentTypeGetEncoding_NoContentType()
{ {
ContentType contentType = null; ContentType? contentType = null;
Encoding encoding = MimeUtilities.GetEncoding(contentType); Encoding encoding = MimeUtilities.GetEncoding(contentType);
Assert.Equal(Encoding.UTF8, encoding); Assert.Equal(Encoding.UTF8, encoding);
} }
@ -75,7 +75,7 @@ namespace CloudNative.CloudEvents.Core.UnitTests
[InlineData("text/plain")] [InlineData("text/plain")]
public void CreateContentTypeOrNull_WithContentType(string text) public void CreateContentTypeOrNull_WithContentType(string text)
{ {
ContentType ct = MimeUtilities.CreateContentTypeOrNull(text); ContentType? ct = MimeUtilities.CreateContentTypeOrNull(text);
Assert.Equal(text, ct?.ToString()); Assert.Equal(text, ct?.ToString());
} }

View File

@ -94,10 +94,10 @@ namespace CloudNative.CloudEvents.UnitTests
public class GameResult public class GameResult
{ {
[JsonProperty("playerId")] [JsonProperty("playerId")]
public string PlayerId { get; set; } public string? PlayerId { get; set; }
[JsonProperty("gameId")] [JsonProperty("gameId")]
public string GameId { get; set; } public string? GameId { get; set; }
[JsonProperty("score")] [JsonProperty("score")]
public int Score { get; set; } public int Score { get; set; }
@ -137,8 +137,8 @@ namespace CloudNative.CloudEvents.UnitTests
// Sample: guide.md#DeserializeGameResult1 // Sample: guide.md#DeserializeGameResult1
CloudEventFormatter formatter = new JsonEventFormatter(); CloudEventFormatter formatter = new JsonEventFormatter();
CloudEvent cloudEvent = await request.ToCloudEventAsync(formatter); CloudEvent cloudEvent = await request.ToCloudEventAsync(formatter);
JObject dataAsJObject = (JObject) cloudEvent.Data; JObject dataAsJObject = (JObject) cloudEvent.Data!;
GameResult result = dataAsJObject.ToObject<GameResult>(); GameResult result = dataAsJObject.ToObject<GameResult>()!;
// End sample // End sample
return result; return result;
} }
@ -148,7 +148,7 @@ namespace CloudNative.CloudEvents.UnitTests
// Sample: guide.md#DeserializeGameResult2 // Sample: guide.md#DeserializeGameResult2
CloudEventFormatter formatter = new JsonEventFormatter<GameResult>(); CloudEventFormatter formatter = new JsonEventFormatter<GameResult>();
CloudEvent cloudEvent = await request.ToCloudEventAsync(formatter); CloudEvent cloudEvent = await request.ToCloudEventAsync(formatter);
GameResult result = (GameResult) cloudEvent.Data; GameResult result = (GameResult) cloudEvent.Data!;
// End sample // End sample
return result; return result;
} }

View File

@ -23,7 +23,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
{ {
public class HttpClientExtensionsTest : HttpTestBase public class HttpClientExtensionsTest : HttpTestBase
{ {
public static TheoryData<string, HttpContent, IDictionary<string, string>> SingleCloudEventMessages => new TheoryData<string, HttpContent, IDictionary<string, string>> public static TheoryData<string, HttpContent, IDictionary<string, string>?> SingleCloudEventMessages => new TheoryData<string, HttpContent, IDictionary<string, string>?>
{ {
{ {
"Binary", "Binary",
@ -43,7 +43,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
} }
}; };
public static TheoryData<string, HttpContent, IDictionary<string, string>> BatchMessages => new TheoryData<string, HttpContent, IDictionary<string, string>> public static TheoryData<string, HttpContent, IDictionary<string, string>?> BatchMessages => new TheoryData<string, HttpContent, IDictionary<string, string>?>
{ {
{ {
"Batch", "Batch",
@ -52,7 +52,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
} }
}; };
public static TheoryData<string, HttpContent, IDictionary<string, string>> NonCloudEventMessages => new TheoryData<string, HttpContent, IDictionary<string, string>> public static TheoryData<string, HttpContent, IDictionary<string, string>?> NonCloudEventMessages => new TheoryData<string, HttpContent, IDictionary<string, string>?>
{ {
{ {
"Plain text", "Plain text",
@ -63,7 +63,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
[Theory] [Theory]
[MemberData(nameof(SingleCloudEventMessages))] [MemberData(nameof(SingleCloudEventMessages))]
public void IsCloudEvent_True(string description, HttpContent content, IDictionary<string, string> headers) public void IsCloudEvent_True(string description, HttpContent content, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -80,7 +80,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
[Theory] [Theory]
[MemberData(nameof(BatchMessages))] [MemberData(nameof(BatchMessages))]
[MemberData(nameof(NonCloudEventMessages))] [MemberData(nameof(NonCloudEventMessages))]
public void IsCloudEvent_False(string description, HttpContent content, IDictionary<string, string> headers) public void IsCloudEvent_False(string description, HttpContent content, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -96,7 +96,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
[Theory] [Theory]
[MemberData(nameof(BatchMessages))] [MemberData(nameof(BatchMessages))]
public void IsCloudEventBatch_True(string description, HttpContent content, IDictionary<string, string> headers) public void IsCloudEventBatch_True(string description, HttpContent content, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -113,7 +113,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
[Theory] [Theory]
[MemberData(nameof(SingleCloudEventMessages))] [MemberData(nameof(SingleCloudEventMessages))]
[MemberData(nameof(NonCloudEventMessages))] [MemberData(nameof(NonCloudEventMessages))]
public void IsCloudEventBatch_False(string description, HttpContent content, IDictionary<string, string> headers) public void IsCloudEventBatch_False(string description, HttpContent content, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -222,7 +222,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
Assert.Equal("com.github.pull.create", receivedCloudEvent.Type); Assert.Equal("com.github.pull.create", receivedCloudEvent.Type);
Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source); Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source);
Assert.Equal("A234-1234-1234", receivedCloudEvent.Id); Assert.Equal("A234-1234-1234", receivedCloudEvent.Id);
AssertTimestampsEqual(SampleTimestamp, receivedCloudEvent.Time.Value); AssertTimestampsEqual(SampleTimestamp, receivedCloudEvent.Time!.Value);
Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType); Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType);
Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data); Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data);
@ -316,7 +316,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
Assert.Equal("com.github.pull.create", receivedCloudEvent.Type); Assert.Equal("com.github.pull.create", receivedCloudEvent.Type);
Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source); Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source);
Assert.Equal("A234-1234-1234", receivedCloudEvent.Id); Assert.Equal("A234-1234-1234", receivedCloudEvent.Id);
AssertTimestampsEqual(SampleTimestamp, receivedCloudEvent.Time.Value); AssertTimestampsEqual(SampleTimestamp, receivedCloudEvent.Time!.Value);
Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType); Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType);
Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data); Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data);
@ -426,7 +426,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
AssertBatchesEqual(batch, parsedBatch); AssertBatchesEqual(batch, parsedBatch);
} }
internal static void CopyHeaders(IDictionary<string, string> source, HttpHeaders target) internal static void CopyHeaders(IDictionary<string, string>? source, HttpHeaders target)
{ {
if (source is null) if (source is null)
{ {

View File

@ -21,7 +21,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
{ {
[Theory] [Theory]
[MemberData(nameof(HttpClientExtensionsTest.SingleCloudEventMessages), MemberType = typeof(HttpClientExtensionsTest))] [MemberData(nameof(HttpClientExtensionsTest.SingleCloudEventMessages), MemberType = typeof(HttpClientExtensionsTest))]
public async Task IsCloudEvent_True(string description, HttpContent content, IDictionary<string, string> headers) public async Task IsCloudEvent_True(string description, HttpContent content, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -35,7 +35,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
[Theory] [Theory]
[MemberData(nameof(HttpClientExtensionsTest.BatchMessages), MemberType = typeof(HttpClientExtensionsTest))] [MemberData(nameof(HttpClientExtensionsTest.BatchMessages), MemberType = typeof(HttpClientExtensionsTest))]
[MemberData(nameof(HttpClientExtensionsTest.NonCloudEventMessages), MemberType = typeof(HttpClientExtensionsTest))] [MemberData(nameof(HttpClientExtensionsTest.NonCloudEventMessages), MemberType = typeof(HttpClientExtensionsTest))]
public async Task IsCloudEvent_False(string description, HttpContent content, IDictionary<string, string> headers) public async Task IsCloudEvent_False(string description, HttpContent content, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -48,7 +48,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
[Theory] [Theory]
[MemberData(nameof(HttpClientExtensionsTest.BatchMessages), MemberType = typeof(HttpClientExtensionsTest))] [MemberData(nameof(HttpClientExtensionsTest.BatchMessages), MemberType = typeof(HttpClientExtensionsTest))]
public async Task IsCloudEventBatch_True(string description, HttpContent content, IDictionary<string, string> headers) public async Task IsCloudEventBatch_True(string description, HttpContent content, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -62,7 +62,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
[Theory] [Theory]
[MemberData(nameof(HttpClientExtensionsTest.SingleCloudEventMessages), MemberType = typeof(HttpClientExtensionsTest))] [MemberData(nameof(HttpClientExtensionsTest.SingleCloudEventMessages), MemberType = typeof(HttpClientExtensionsTest))]
[MemberData(nameof(HttpClientExtensionsTest.NonCloudEventMessages), MemberType = typeof(HttpClientExtensionsTest))] [MemberData(nameof(HttpClientExtensionsTest.NonCloudEventMessages), MemberType = typeof(HttpClientExtensionsTest))]
public async Task IsCloudEventBatch_False(string description, HttpContent content, IDictionary<string, string> headers) public async Task IsCloudEventBatch_False(string description, HttpContent content, IDictionary<string, string>? headers)
{ {
// Really only present for display purposes. // Really only present for display purposes.
Assert.NotNull(description); Assert.NotNull(description);
@ -201,7 +201,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
Assert.Equal("1.0", response.Headers.GetValues("ce-specversion").Single()); Assert.Equal("1.0", response.Headers.GetValues("ce-specversion").Single());
Assert.Equal(cloudEvent.Type, response.Headers.GetValues("ce-type").Single()); Assert.Equal(cloudEvent.Type, response.Headers.GetValues("ce-type").Single());
Assert.Equal(cloudEvent.Id, response.Headers.GetValues("ce-id").Single()); Assert.Equal(cloudEvent.Id, response.Headers.GetValues("ce-id").Single());
Assert.Equal(CloudEventAttributeType.UriReference.Format(cloudEvent.Source), response.Headers.GetValues("ce-source").Single()); Assert.Equal(CloudEventAttributeType.UriReference.Format(cloudEvent.Source!), response.Headers.GetValues("ce-source").Single());
// There's no data content type header; the content type itself is used for that. // There's no data content type header; the content type itself is used for that.
Assert.False(response.Headers.Contains("ce-datacontenttype")); Assert.False(response.Headers.Contains("ce-datacontenttype"));
} }
@ -251,7 +251,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
Assert.Equal("1.0", response.Headers.GetValues("ce-specversion").Single()); Assert.Equal("1.0", response.Headers.GetValues("ce-specversion").Single());
Assert.Equal(cloudEvent.Type, response.Headers.GetValues("ce-type").Single()); Assert.Equal(cloudEvent.Type, response.Headers.GetValues("ce-type").Single());
Assert.Equal(cloudEvent.Id, response.Headers.GetValues("ce-id").Single()); Assert.Equal(cloudEvent.Id, response.Headers.GetValues("ce-id").Single());
Assert.Equal(CloudEventAttributeType.UriReference.Format(cloudEvent.Source), response.Headers.GetValues("ce-source").Single()); Assert.Equal(CloudEventAttributeType.UriReference.Format(cloudEvent.Source!), response.Headers.GetValues("ce-source").Single());
// We don't populate the data content type header // We don't populate the data content type header
Assert.False(response.Headers.Contains("ce-datacontenttype")); Assert.False(response.Headers.Contains("ce-datacontenttype"));
} }
@ -299,7 +299,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
Assert.True(response.IsSuccessStatusCode, content); Assert.True(response.IsSuccessStatusCode, content);
Assert.True(executed); Assert.True(executed);
return result; return result!;
} }
/// <summary> /// <summary>

View File

@ -150,7 +150,7 @@ namespace CloudNative.CloudEvents.Http.UnitTests
using var response = (HttpWebResponse) await request.GetResponseAsync(); using var response = (HttpWebResponse) await request.GetResponseAsync();
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Assert.True(executed); Assert.True(executed);
return result; return result!;
} }
} }
} }

View File

@ -25,7 +25,7 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
[InlineData("CE_SPECVERSION", "1.0", false)] [InlineData("CE_SPECVERSION", "1.0", false)]
public void IsCloudEvent(string headerName, string headerValue, bool expectedResult) public void IsCloudEvent(string headerName, string headerValue, bool expectedResult)
{ {
var message = new Message<string, byte[]> var message = new Message<string?, byte[]>
{ {
Headers = new Headers { { headerName, Encoding.UTF8.GetBytes(headerValue) } } Headers = new Headers { { headerName, Encoding.UTF8.GetBytes(headerValue) } }
}; };
@ -34,7 +34,7 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
[Fact] [Fact]
public void IsCloudEvent_NoHeaders() => public void IsCloudEvent_NoHeaders() =>
Assert.False(new Message<string, byte[]>().IsCloudEvent()); Assert.False(new Message<string?, byte[]>().IsCloudEvent());
[Fact] [Fact]
public void KafkaStructuredMessageTest() public void KafkaStructuredMessageTest()
@ -64,7 +64,7 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
// using serialization to create fully independent copy thus simulating message transport // using serialization to create fully independent copy thus simulating message transport
// real transport will work in a similar way // real transport will work in a similar way
var serialized = JsonConvert.SerializeObject(message, new HeaderConverter()); var serialized = JsonConvert.SerializeObject(message, new HeaderConverter());
var messageCopy = JsonConvert.DeserializeObject<Message<string, byte[]>>(serialized, new HeadersConverter(), new HeaderConverter()); var messageCopy = JsonConvert.DeserializeObject<Message<string?, byte[]>>(serialized, new HeadersConverter(), new HeaderConverter())!;
Assert.True(messageCopy.IsCloudEvent()); Assert.True(messageCopy.IsCloudEvent());
var receivedCloudEvent = messageCopy.ToCloudEvent(jsonEventFormatter); var receivedCloudEvent = messageCopy.ToCloudEvent(jsonEventFormatter);
@ -74,11 +74,11 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull"), receivedCloudEvent.Source); Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull"), receivedCloudEvent.Source);
Assert.Equal("123", receivedCloudEvent.Subject); Assert.Equal("123", receivedCloudEvent.Subject);
Assert.Equal("A234-1234-1234", receivedCloudEvent.Id); Assert.Equal("A234-1234-1234", receivedCloudEvent.Id);
AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time.Value); AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time!.Value);
Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType); Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType);
Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data); Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data);
Assert.Equal("value", (string)receivedCloudEvent["comexampleextension1"]); Assert.Equal("value", (string?)receivedCloudEvent["comexampleextension1"]);
} }
[Fact] [Fact]
@ -111,7 +111,7 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
{ {
Converters = { new HeadersConverter(), new HeaderConverter() } Converters = { new HeadersConverter(), new HeaderConverter() }
}; };
var messageCopy = JsonConvert.DeserializeObject<Message<string, byte[]>>(serialized, settings); var messageCopy = JsonConvert.DeserializeObject<Message<string?, byte[]>>(serialized, settings)!;
Assert.True(messageCopy.IsCloudEvent()); Assert.True(messageCopy.IsCloudEvent());
var receivedCloudEvent = messageCopy.ToCloudEvent(jsonEventFormatter, Partitioning.AllAttributes); var receivedCloudEvent = messageCopy.ToCloudEvent(jsonEventFormatter, Partitioning.AllAttributes);
@ -120,12 +120,12 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
Assert.Equal("com.github.pull.create", receivedCloudEvent.Type); Assert.Equal("com.github.pull.create", receivedCloudEvent.Type);
Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source); Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source);
Assert.Equal("A234-1234-1234", receivedCloudEvent.Id); Assert.Equal("A234-1234-1234", receivedCloudEvent.Id);
AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time.Value); AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time!.Value);
Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType); Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType);
Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data); Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data);
Assert.Equal("hello much wow", (string) receivedCloudEvent[Partitioning.PartitionKeyAttribute]); Assert.Equal("hello much wow", (string?) receivedCloudEvent[Partitioning.PartitionKeyAttribute]);
Assert.Equal("value", (string)receivedCloudEvent["comexampleextension1"]); Assert.Equal("value", (string?)receivedCloudEvent["comexampleextension1"]);
} }
private class HeadersConverter : JsonConverter private class HeadersConverter : JsonConverter
@ -135,7 +135,7 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
return objectType == typeof(Headers); return objectType == typeof(Headers);
} }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{ {
if (reader.TokenType == JsonToken.Null) if (reader.TokenType == JsonToken.Null)
{ {
@ -143,7 +143,7 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
} }
else else
{ {
var surrogate = serializer.Deserialize<List<Header>>(reader); var surrogate = serializer.Deserialize<List<Header>>(reader)!;
var headers = new Headers(); var headers = new Headers();
foreach(var header in surrogate) foreach(var header in surrogate)
@ -154,7 +154,7 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
} }
} }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@ -164,8 +164,8 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
{ {
private class HeaderContainer private class HeaderContainer
{ {
public string Key { get; set; } public string? Key { get; set; }
public byte[] Value { get; set; } public byte[]? Value { get; set; }
} }
public override bool CanConvert(Type objectType) public override bool CanConvert(Type objectType)
@ -173,15 +173,15 @@ namespace CloudNative.CloudEvents.Kafka.UnitTests
return objectType == typeof(Header) || objectType == typeof(IHeader); return objectType == typeof(Header) || objectType == typeof(IHeader);
} }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{ {
var headerContainer = serializer.Deserialize<HeaderContainer>(reader); var headerContainer = serializer.Deserialize<HeaderContainer>(reader)!;
return new Header(headerContainer.Key, headerContainer.Value); return new Header(headerContainer.Key, headerContainer.Value);
} }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{ {
var header = (IHeader)value; var header = (IHeader)value!;
var container = new HeaderContainer { Key = header.Key, Value = header.GetValueBytes() }; var container = new HeaderContainer { Key = header.Key, Value = header.GetValueBytes() };
serializer.Serialize(writer, container); serializer.Serialize(writer, container);
} }

View File

@ -72,11 +72,11 @@ namespace CloudNative.CloudEvents.Mqtt.UnitTests
Assert.Equal("com.github.pull.create", receivedCloudEvent.Type); Assert.Equal("com.github.pull.create", receivedCloudEvent.Type);
Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source); Assert.Equal(new Uri("https://github.com/cloudevents/spec/pull/123"), receivedCloudEvent.Source);
Assert.Equal("A234-1234-1234", receivedCloudEvent.Id); Assert.Equal("A234-1234-1234", receivedCloudEvent.Id);
AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time.Value); AssertTimestampsEqual("2018-04-05T17:31:00Z", receivedCloudEvent.Time!.Value);
Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType); Assert.Equal(MediaTypeNames.Text.Xml, receivedCloudEvent.DataContentType);
Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data); Assert.Equal("<much wow=\"xml\"/>", receivedCloudEvent.Data);
Assert.Equal("value", (string)receivedCloudEvent["comexampleextension1"]); Assert.Equal("value", (string?)receivedCloudEvent["comexampleextension1"]);
} }
} }
} }

View File

@ -12,6 +12,6 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
public const string JsonPropertyName = "customattribute"; public const string JsonPropertyName = "customattribute";
[JsonProperty(JsonPropertyName)] [JsonProperty(JsonPropertyName)]
public string AttributedProperty { get; set; } public string? AttributedProperty { get; set; }
} }
} }

View File

@ -23,10 +23,10 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
obj["data"] = new JObject { [AttributedModel.JsonPropertyName] = "test" }; obj["data"] = new JObject { [AttributedModel.JsonPropertyName] = "test" };
byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString());
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, null, null); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, null, null);
var model = (AttributedModel) cloudEvent.Data; var model = (AttributedModel)cloudEvent.Data!;
Assert.Equal("test", model.AttributedProperty); Assert.Equal("test", model.AttributedProperty);
} }
@ -37,10 +37,10 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
obj["data"] = new JObject { [AttributedModel.JsonPropertyName] = "test" }; obj["data"] = new JObject { [AttributedModel.JsonPropertyName] = "test" };
byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString());
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, new ContentType("text/plain"), null); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, new ContentType("text/plain"), null);
var model = (AttributedModel)cloudEvent.Data; var model = (AttributedModel)cloudEvent.Data!;
Assert.Equal("test", model.AttributedProperty); Assert.Equal("test", model.AttributedProperty);
} }
@ -50,7 +50,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
var obj = JsonEventFormatterTest.CreateMinimalValidJObject(); var obj = JsonEventFormatterTest.CreateMinimalValidJObject();
byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString());
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, null, null); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, null, null);
Assert.Null(cloudEvent.Data); Assert.Null(cloudEvent.Data);
} }
@ -62,7 +62,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
obj["data_base64"] = Convert.ToBase64String(Encoding.UTF8.GetBytes("{}")); obj["data_base64"] = Convert.ToBase64String(Encoding.UTF8.GetBytes("{}"));
byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString());
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
Assert.Throws<ArgumentException>(() => formatter.DecodeStructuredModeMessage(bytes, null, null)); Assert.Throws<ArgumentException>(() => formatter.DecodeStructuredModeMessage(bytes, null, null));
} }
@ -72,18 +72,18 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
var obj = new JObject { [AttributedModel.JsonPropertyName] = "test" }; var obj = new JObject { [AttributedModel.JsonPropertyName] = "test" };
byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString());
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var cloudEvent = new CloudEvent(); var cloudEvent = new CloudEvent();
formatter.DecodeBinaryModeEventData(bytes, cloudEvent); formatter.DecodeBinaryModeEventData(bytes, cloudEvent);
var model = (AttributedModel)cloudEvent.Data; var model = (AttributedModel)cloudEvent.Data!;
Assert.Equal("test", model.AttributedProperty); Assert.Equal("test", model.AttributedProperty);
} }
[Fact] [Fact]
public void DecodeBinaryEventModeData_NoData() public void DecodeBinaryEventModeData_NoData()
{ {
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var cloudEvent = new CloudEvent { Data = "original" }; var cloudEvent = new CloudEvent { Data = "original" };
formatter.DecodeBinaryModeEventData(new byte[0], cloudEvent); formatter.DecodeBinaryModeEventData(new byte[0], cloudEvent);
Assert.Null(cloudEvent.Data); Assert.Null(cloudEvent.Data);
@ -94,11 +94,11 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
cloudEvent.Data = new AttributedModel { AttributedProperty = "test" }; cloudEvent.Data = new AttributedModel { AttributedProperty = "test" };
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var body = formatter.EncodeStructuredModeMessage(cloudEvent, out _); var body = formatter.EncodeStructuredModeMessage(cloudEvent, out _);
var jobject = JsonEventFormatterTest.ParseJson(body); var jobject = JsonEventFormatterTest.ParseJson(body);
Assert.False(jobject.ContainsKey("data_base64")); Assert.False(jobject.ContainsKey("data_base64"));
var data = (JObject)jobject["data"]; var data = (JObject)jobject["data"]!;
new JTokenAsserter new JTokenAsserter
{ {
@ -111,7 +111,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var body = formatter.EncodeStructuredModeMessage(cloudEvent, out _); var body = formatter.EncodeStructuredModeMessage(cloudEvent, out _);
var jobject = JsonEventFormatterTest.ParseJson(body); var jobject = JsonEventFormatterTest.ParseJson(body);
Assert.False(jobject.ContainsKey("data")); Assert.False(jobject.ContainsKey("data"));
@ -123,7 +123,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
cloudEvent.Data = new OtherModelClass { Text = "Wrong type" }; cloudEvent.Data = new OtherModelClass { Text = "Wrong type" };
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
Assert.Throws<InvalidCastException>(() => formatter.EncodeStructuredModeMessage(cloudEvent, out _)); Assert.Throws<InvalidCastException>(() => formatter.EncodeStructuredModeMessage(cloudEvent, out _));
} }
@ -132,7 +132,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
cloudEvent.Data = new AttributedModel { AttributedProperty = "test" }; cloudEvent.Data = new AttributedModel { AttributedProperty = "test" };
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var body = formatter.EncodeBinaryModeEventData(cloudEvent); var body = formatter.EncodeBinaryModeEventData(cloudEvent);
var jobject = JsonEventFormatterTest.ParseJson(body); var jobject = JsonEventFormatterTest.ParseJson(body);
@ -146,7 +146,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
public void EncodeBinaryModeEventData_NoData() public void EncodeBinaryModeEventData_NoData()
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var bytes = formatter.EncodeBinaryModeEventData(cloudEvent); var bytes = formatter.EncodeBinaryModeEventData(cloudEvent);
Assert.True(bytes.IsEmpty); Assert.True(bytes.IsEmpty);
} }
@ -156,13 +156,20 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
cloudEvent.Data = new OtherModelClass { Text = "Wrong type" }; cloudEvent.Data = new OtherModelClass { Text = "Wrong type" };
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
Assert.Throws<InvalidCastException>(() => formatter.EncodeBinaryModeEventData(cloudEvent)); Assert.Throws<InvalidCastException>(() => formatter.EncodeBinaryModeEventData(cloudEvent));
} }
private static CloudEventFormatter CreateFormatter<T>()
{
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(T));
Assert.NotNull(formatter);
return formatter!;
}
private class OtherModelClass private class OtherModelClass
{ {
public string Text { get; set; } public string? Text { get; set; }
} }
} }
} }

View File

@ -13,7 +13,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
internal class JTokenAsserter : IEnumerable internal class JTokenAsserter : IEnumerable
{ {
private readonly List<(string name, JTokenType type, object value)> expectations = new List<(string, JTokenType, object)>(); private readonly List<(string name, JTokenType type, object? value)> expectations = new List<(string, JTokenType, object?)>();
// Just for collection initializers // Just for collection initializers
public IEnumerator GetEnumerator() => throw new NotImplementedException(); public IEnumerator GetEnumerator() => throw new NotImplementedException();
@ -21,14 +21,15 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
public void Add<T>(string name, JTokenType type, T value) => public void Add<T>(string name, JTokenType type, T value) =>
expectations.Add((name, type, value)); expectations.Add((name, type, value));
public void AssertProperties(JObject obj, bool assertCount) public void AssertProperties(JObject? obj, bool assertCount)
{ {
Assert.NotNull(obj);
foreach (var expectation in expectations) foreach (var expectation in expectations)
{ {
Assert.True( Assert.True(
obj.TryGetValue(expectation.name, out var token), obj!.TryGetValue(expectation.name, out var token),
$"Expected property '{expectation.name}' to be present"); $"Expected property '{expectation.name}' to be present");
Assert.Equal(expectation.type, token.Type); Assert.Equal(expectation.type, token!.Type);
// No need to check null values, as they'll have a null token type. // No need to check null values, as they'll have a null token type.
if (expectation.value is object) if (expectation.value is object)
{ {
@ -37,7 +38,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
} }
if (assertCount) if (assertCount)
{ {
Assert.Equal(expectations.Count, obj.Count); Assert.Equal(expectations.Count, obj!.Count);
} }
} }
} }

View File

@ -97,7 +97,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
cloudEvent.Data = new { Text = "simple text" }; cloudEvent.Data = new { Text = "simple text" };
cloudEvent.DataContentType = "application/json"; cloudEvent.DataContentType = "application/json";
JObject obj = EncodeAndParseStructured(cloudEvent); JObject obj = EncodeAndParseStructured(cloudEvent);
JObject dataProperty = (JObject) obj["data"]; JObject dataProperty = (JObject) obj["data"]!;
var asserter = new JTokenAsserter var asserter = new JTokenAsserter
{ {
{ "Text", JTokenType.String, "simple text" } { "Text", JTokenType.String, "simple text" }
@ -119,7 +119,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
var formatter = new JsonEventFormatter(serializer); var formatter = new JsonEventFormatter(serializer);
var encoded = formatter.EncodeStructuredModeMessage(cloudEvent, out _); var encoded = formatter.EncodeStructuredModeMessage(cloudEvent, out _);
JObject obj = ParseJson(encoded); JObject obj = ParseJson(encoded);
JObject dataProperty = (JObject) obj["data"]; JObject dataProperty = (JObject) obj["data"]!;
var asserter = new JTokenAsserter var asserter = new JTokenAsserter
{ {
{ "DateValue", JTokenType.String, "2021-02-19" } { "DateValue", JTokenType.String, "2021-02-19" }
@ -134,7 +134,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
cloudEvent.Data = new AttributedModel { AttributedProperty = "simple text" }; cloudEvent.Data = new AttributedModel { AttributedProperty = "simple text" };
cloudEvent.DataContentType = "application/json"; cloudEvent.DataContentType = "application/json";
JObject obj = EncodeAndParseStructured(cloudEvent); JObject obj = EncodeAndParseStructured(cloudEvent);
JObject dataProperty = (JObject) obj["data"]; JObject dataProperty = (JObject) obj["data"]!;
var asserter = new JTokenAsserter var asserter = new JTokenAsserter
{ {
{ AttributedModel.JsonPropertyName, JTokenType.String, "simple text" } { AttributedModel.JsonPropertyName, JTokenType.String, "simple text" }
@ -149,7 +149,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
cloudEvent.Data = new JValue(100); cloudEvent.Data = new JValue(100);
cloudEvent.DataContentType = "application/json"; cloudEvent.DataContentType = "application/json";
JObject obj = EncodeAndParseStructured(cloudEvent); JObject obj = EncodeAndParseStructured(cloudEvent);
JToken data = obj["data"]; JToken data = obj["data"]!;
Assert.Equal(JTokenType.Integer, data.Type); Assert.Equal(JTokenType.Integer, data.Type);
Assert.Equal(100, (int) data); Assert.Equal(100, (int) data);
} }
@ -171,9 +171,9 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
cloudEvent.Data = "some text"; cloudEvent.Data = "some text";
cloudEvent.DataContentType = "text/anything"; cloudEvent.DataContentType = "text/anything";
JObject obj = EncodeAndParseStructured(cloudEvent); JObject obj = EncodeAndParseStructured(cloudEvent);
var dataProperty = obj["data"]; var dataProperty = obj["data"]!;
Assert.Equal(JTokenType.String, dataProperty.Type); Assert.Equal(JTokenType.String, dataProperty.Type);
Assert.Equal("some text", (string) dataProperty); Assert.Equal("some text", (string?) dataProperty);
} }
// A text content type with bytes as data is serialized like any other bytes. // A text content type with bytes as data is serialized like any other bytes.
@ -185,9 +185,9 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
cloudEvent.DataContentType = "text/anything"; cloudEvent.DataContentType = "text/anything";
JObject obj = EncodeAndParseStructured(cloudEvent); JObject obj = EncodeAndParseStructured(cloudEvent);
Assert.False(obj.ContainsKey("data")); Assert.False(obj.ContainsKey("data"));
var dataBase64 = obj["data_base64"]; var dataBase64 = obj["data_base64"]!;
Assert.Equal(JTokenType.String, dataBase64.Type); Assert.Equal(JTokenType.String, dataBase64.Type);
Assert.Equal(SampleBinaryDataBase64, (string) dataBase64); Assert.Equal(SampleBinaryDataBase64, (string?) dataBase64);
} }
[Fact] [Fact]
@ -208,9 +208,9 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
cloudEvent.DataContentType = "not_text/or_json"; cloudEvent.DataContentType = "not_text/or_json";
JObject obj = EncodeAndParseStructured(cloudEvent); JObject obj = EncodeAndParseStructured(cloudEvent);
Assert.False(obj.ContainsKey("data")); Assert.False(obj.ContainsKey("data"));
var dataBase64 = obj["data_base64"]; var dataBase64 = obj["data_base64"]!;
Assert.Equal(JTokenType.String, dataBase64.Type); Assert.Equal(JTokenType.String, dataBase64.Type);
Assert.Equal(SampleBinaryDataBase64, (string) dataBase64); Assert.Equal(SampleBinaryDataBase64, (string?) dataBase64);
} }
[Fact] [Fact]
@ -407,7 +407,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
// Invalid CloudEvent // Invalid CloudEvent
Assert.Throws<ArgumentException>(() => formatter.EncodeBatchModeMessage(new[] { new CloudEvent() }, out _)); Assert.Throws<ArgumentException>(() => formatter.EncodeBatchModeMessage(new[] { new CloudEvent() }, out _));
// Null argument // Null argument
Assert.Throws<ArgumentNullException>(() => formatter.EncodeBatchModeMessage(null, out _)); Assert.Throws<ArgumentNullException>(() => formatter.EncodeBatchModeMessage(null!, out _));
// Null value within the argument. Arguably this should throw ArgumentException instead of // Null value within the argument. Arguably this should throw ArgumentException instead of
// ArgumentNullException, but it's unlikely to cause confusion. // ArgumentNullException, but it's unlikely to cause confusion.
Assert.Throws<ArgumentNullException>(() => formatter.EncodeBatchModeMessage(new CloudEvent[1], out _)); Assert.Throws<ArgumentNullException>(() => formatter.EncodeBatchModeMessage(new CloudEvent[1], out _));
@ -570,10 +570,10 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
var formatter = new JsonEventFormatter(); var formatter = new JsonEventFormatter();
var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, AllTypesExtensions); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, AllTypesExtensions);
Assert.Equal(SampleBinaryData, cloudEvent["binary"]); Assert.Equal(SampleBinaryData, cloudEvent["binary"]);
Assert.True((bool) cloudEvent["boolean"]); Assert.True((bool) cloudEvent["boolean"]!);
Assert.Equal(10, cloudEvent["integer"]); Assert.Equal(10, cloudEvent["integer"]);
Assert.Equal("text", cloudEvent["string"]); Assert.Equal("text", cloudEvent["string"]);
AssertTimestampsEqual(SampleTimestamp, (DateTimeOffset) cloudEvent["timestamp"]); AssertTimestampsEqual(SampleTimestamp, (DateTimeOffset) cloudEvent["timestamp"]!);
Assert.Equal(SampleUri, cloudEvent["uri"]); Assert.Equal(SampleUri, cloudEvent["uri"]);
Assert.Equal(SampleUriReference, cloudEvent["urireference"]); Assert.Equal(SampleUriReference, cloudEvent["urireference"]);
} }
@ -694,8 +694,8 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
} }
obj["data"] = 10; obj["data"] = 10;
var cloudEvent = DecodeStructuredModeMessage(obj); var cloudEvent = DecodeStructuredModeMessage(obj);
var token = (JToken) cloudEvent.Data; var token = (JToken) cloudEvent.Data!;
Assert.Equal(JTokenType.Integer, token.Type); Assert.Equal(JTokenType.Integer, token!.Type);
Assert.Equal(10, (int) token); Assert.Equal(10, (int) token);
} }
@ -876,7 +876,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
Assert.Null(event2.DataContentType); Assert.Null(event2.DataContentType);
} }
private static object DecodeBinaryModeEventData(byte[] bytes, string contentType) private static object? DecodeBinaryModeEventData(byte[] bytes, string contentType)
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
cloudEvent.DataContentType = contentType; cloudEvent.DataContentType = contentType;
@ -912,7 +912,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
{ {
DateParseHandling = DateParseHandling.None DateParseHandling = DateParseHandling.None
}; };
return serializer.Deserialize<T>(new JsonTextReader(new StringReader(text))); return serializer.Deserialize<T>(new JsonTextReader(new StringReader(text)))!;
} }

View File

@ -118,9 +118,10 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
Assert.Equal("some text", cloudEvent.Data); Assert.Equal("some text", cloudEvent.Data);
} }
private static void AssertToken(JTokenType expectedType, object expectedValue, JToken token) private static void AssertToken(JTokenType expectedType, object expectedValue, JToken? token)
{ {
Assert.Equal(expectedType, token.Type); Assert.NotNull(token);
Assert.Equal(expectedType, token!.Type);
Assert.Equal(expectedValue, token.ToObject(expectedValue.GetType())); Assert.Equal(expectedValue, token.ToObject(expectedValue.GetType()));
} }
@ -157,7 +158,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
{ {
if (cloudEvent.DataContentType == TextBinaryContentType && dataBase64Token.Type == JTokenType.String) if (cloudEvent.DataContentType == TextBinaryContentType && dataBase64Token.Type == JTokenType.String)
{ {
cloudEvent.Data = Encoding.UTF8.GetString(Convert.FromBase64String((string)dataBase64Token)); cloudEvent.Data = Encoding.UTF8.GetString(Convert.FromBase64String((string)dataBase64Token!));
} }
else else
{ {
@ -169,7 +170,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
{ {
if (cloudEvent.DataContentType == GuidContentType && dataToken.Type == JTokenType.String) if (cloudEvent.DataContentType == GuidContentType && dataToken.Type == JTokenType.String)
{ {
string text = (string)dataToken; string text = (string)dataToken!;
if (!text.StartsWith(GuidPrefix)) if (!text.StartsWith(GuidPrefix))
{ {
throw new ArgumentException("Invalid GUID text data"); throw new ArgumentException("Invalid GUID text data");

View File

@ -35,8 +35,8 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
var event1 = formatter.DecodeStructuredModeMessage(CreateJsonStream(), null, null); var event1 = formatter.DecodeStructuredModeMessage(CreateJsonStream(), null, null);
var event2 = formatter.DecodeStructuredModeMessage(CreateJsonStream(), null, null); var event2 = formatter.DecodeStructuredModeMessage(CreateJsonStream(), null, null);
JObject data1 = (JObject)event1.Data; JObject data1 = (JObject)event1.Data!;
JObject data2 = (JObject)event2.Data; JObject data2 = (JObject)event2.Data!;
var property1 = data1.Properties().Single(); var property1 = data1.Properties().Single();
var property2 = data2.Properties().Single(); var property2 = data2.Properties().Single();
@ -51,8 +51,8 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
var event1 = formatter.DecodeStructuredModeMessage(CreateJsonStream(), null, null); var event1 = formatter.DecodeStructuredModeMessage(CreateJsonStream(), null, null);
var event2 = formatter.DecodeStructuredModeMessage(CreateJsonStream(), null, null); var event2 = formatter.DecodeStructuredModeMessage(CreateJsonStream(), null, null);
JObject data1 = (JObject)event1.Data; JObject data1 = (JObject)event1.Data!;
JObject data2 = (JObject)event2.Data; JObject data2 = (JObject)event2.Data!;
var property1 = data1.Properties().Single(); var property1 = data1.Properties().Single();
var property2 = data2.Properties().Single(); var property2 = data2.Properties().Single();
@ -72,7 +72,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
private class CreateJsonReaderExposingFormatter : JsonEventFormatter private class CreateJsonReaderExposingFormatter : JsonEventFormatter
{ {
public JsonReader CreateJsonReaderPublic(Stream stream, Encoding encoding) => public JsonReader CreateJsonReaderPublic(Stream stream, Encoding? encoding) =>
base.CreateJsonReader(stream, encoding); base.CreateJsonReader(stream, encoding);
} }
@ -87,7 +87,7 @@ namespace CloudNative.CloudEvents.NewtonsoftJson.UnitTests
table.Add("DataName"); table.Add("DataName");
} }
protected override JsonReader CreateJsonReader(Stream stream, Encoding encoding) protected override JsonReader CreateJsonReader(Stream stream, Encoding? encoding)
{ {
var reader = (JsonTextReader) base.CreateJsonReader(stream, encoding); var reader = (JsonTextReader) base.CreateJsonReader(stream, encoding);
reader.PropertyNameTable = table; reader.PropertyNameTable = table;

View File

@ -12,6 +12,6 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
public const string JsonPropertyName = "customattribute"; public const string JsonPropertyName = "customattribute";
[JsonPropertyName(JsonPropertyName)] [JsonPropertyName(JsonPropertyName)]
public string AttributedProperty { get; set; } public string? AttributedProperty { get; set; }
} }
} }

View File

@ -24,10 +24,10 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
obj["data"] = new JObject { [AttributedModel.JsonPropertyName] = "test" }; obj["data"] = new JObject { [AttributedModel.JsonPropertyName] = "test" };
byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString());
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, null, null); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, null, null);
var model = (AttributedModel)cloudEvent.Data; var model = (AttributedModel)cloudEvent.Data!;
Assert.Equal("test", model.AttributedProperty); Assert.Equal("test", model.AttributedProperty);
} }
@ -38,10 +38,10 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
obj["data"] = new JObject { [AttributedModel.JsonPropertyName] = "test" }; obj["data"] = new JObject { [AttributedModel.JsonPropertyName] = "test" };
byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString());
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, new ContentType("text/plain"), null); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, new ContentType("text/plain"), null);
var model = (AttributedModel)cloudEvent.Data; var model = (AttributedModel)cloudEvent.Data!;
Assert.Equal("test", model.AttributedProperty); Assert.Equal("test", model.AttributedProperty);
} }
@ -51,7 +51,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
var obj = JsonEventFormatterTest.CreateMinimalValidJObject(); var obj = JsonEventFormatterTest.CreateMinimalValidJObject();
byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString());
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, null, null); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, null, null);
Assert.Null(cloudEvent.Data); Assert.Null(cloudEvent.Data);
} }
@ -63,7 +63,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
obj["data_base64"] = Convert.ToBase64String(Encoding.UTF8.GetBytes("{}")); obj["data_base64"] = Convert.ToBase64String(Encoding.UTF8.GetBytes("{}"));
byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString());
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
Assert.Throws<ArgumentException>(() => formatter.DecodeStructuredModeMessage(bytes, null, null)); Assert.Throws<ArgumentException>(() => formatter.DecodeStructuredModeMessage(bytes, null, null));
} }
@ -73,18 +73,18 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
var obj = new JObject { [AttributedModel.JsonPropertyName] = "test" }; var obj = new JObject { [AttributedModel.JsonPropertyName] = "test" };
byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString()); byte[] bytes = Encoding.UTF8.GetBytes(obj.ToString());
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var cloudEvent = new CloudEvent(); var cloudEvent = new CloudEvent();
formatter.DecodeBinaryModeEventData(bytes, cloudEvent); formatter.DecodeBinaryModeEventData(bytes, cloudEvent);
var model = (AttributedModel)cloudEvent.Data; var model = (AttributedModel)cloudEvent.Data!;
Assert.Equal("test", model.AttributedProperty); Assert.Equal("test", model.AttributedProperty);
} }
[Fact] [Fact]
public void DecodeBinaryEventModeData_NoData() public void DecodeBinaryEventModeData_NoData()
{ {
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var cloudEvent = new CloudEvent { Data = "original" }; var cloudEvent = new CloudEvent { Data = "original" };
formatter.DecodeBinaryModeEventData(new byte[0], cloudEvent); formatter.DecodeBinaryModeEventData(new byte[0], cloudEvent);
Assert.Null(cloudEvent.Data); Assert.Null(cloudEvent.Data);
@ -95,7 +95,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
cloudEvent.Data = new AttributedModel { AttributedProperty = "test" }; cloudEvent.Data = new AttributedModel { AttributedProperty = "test" };
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var body = formatter.EncodeStructuredModeMessage(cloudEvent, out _); var body = formatter.EncodeStructuredModeMessage(cloudEvent, out _);
var element = JsonEventFormatterTest.ParseJson(body); var element = JsonEventFormatterTest.ParseJson(body);
Assert.False(element.TryGetProperty("data_base64", out _)); Assert.False(element.TryGetProperty("data_base64", out _));
@ -112,7 +112,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var body = formatter.EncodeStructuredModeMessage(cloudEvent, out _); var body = formatter.EncodeStructuredModeMessage(cloudEvent, out _);
var element = JsonEventFormatterTest.ParseJson(body); var element = JsonEventFormatterTest.ParseJson(body);
Assert.False(element.TryGetProperty("data", out _)); Assert.False(element.TryGetProperty("data", out _));
@ -124,7 +124,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
cloudEvent.Data = new OtherModelClass { Text = "Wrong type" }; cloudEvent.Data = new OtherModelClass { Text = "Wrong type" };
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
Assert.Throws<InvalidCastException>(() => formatter.EncodeStructuredModeMessage(cloudEvent, out _)); Assert.Throws<InvalidCastException>(() => formatter.EncodeStructuredModeMessage(cloudEvent, out _));
} }
@ -133,7 +133,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
cloudEvent.Data = new AttributedModel { AttributedProperty = "test" }; cloudEvent.Data = new AttributedModel { AttributedProperty = "test" };
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
var body = formatter.EncodeBinaryModeEventData(cloudEvent); var body = formatter.EncodeBinaryModeEventData(cloudEvent);
var jobject = JsonEventFormatterTest.ParseJson(body); var jobject = JsonEventFormatterTest.ParseJson(body);
@ -147,7 +147,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
public void EncodeBinaryModeEventData_NoData() public void EncodeBinaryModeEventData_NoData()
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
Assert.True(formatter.EncodeBinaryModeEventData(cloudEvent).IsEmpty); Assert.True(formatter.EncodeBinaryModeEventData(cloudEvent).IsEmpty);
} }
@ -156,13 +156,20 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
{ {
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
cloudEvent.Data = new OtherModelClass { Text = "Wrong type" }; cloudEvent.Data = new OtherModelClass { Text = "Wrong type" };
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(AttributedModel)); var formatter = CreateFormatter<AttributedModel>();
Assert.Throws<InvalidCastException>(() => formatter.EncodeBinaryModeEventData(cloudEvent)); Assert.Throws<InvalidCastException>(() => formatter.EncodeBinaryModeEventData(cloudEvent));
} }
private static CloudEventFormatter CreateFormatter<T>()
{
var formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(T));
Assert.NotNull(formatter);
return formatter!;
}
private class OtherModelClass private class OtherModelClass
{ {
public string Text { get; set; } public string? Text { get; set; }
} }
} }
} }

View File

@ -13,7 +13,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
{ {
internal class JsonElementAsserter : IEnumerable internal class JsonElementAsserter : IEnumerable
{ {
private readonly List<(string name, JsonValueKind type, object value)> expectations = new List<(string, JsonValueKind, object)>(); private readonly List<(string name, JsonValueKind type, object? value)> expectations = new List<(string, JsonValueKind, object?)>();
// Just for collection initializers // Just for collection initializers
public IEnumerator GetEnumerator() => throw new NotImplementedException(); public IEnumerator GetEnumerator() => throw new NotImplementedException();
@ -38,7 +38,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
JsonValueKind.False => false, JsonValueKind.False => false,
JsonValueKind.String => property.GetString(), JsonValueKind.String => property.GetString(),
JsonValueKind.Number => property.GetInt32(), JsonValueKind.Number => property.GetInt32(),
JsonValueKind.Null => (object) null, JsonValueKind.Null => (object?) null,
_ => throw new Exception($"Unhandled value kind: {property.ValueKind}") _ => throw new Exception($"Unhandled value kind: {property.ValueKind}")
}; };

View File

@ -417,7 +417,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
// Invalid CloudEvent // Invalid CloudEvent
Assert.Throws<ArgumentException>(() => formatter.EncodeBatchModeMessage(new[] { new CloudEvent() }, out _)); Assert.Throws<ArgumentException>(() => formatter.EncodeBatchModeMessage(new[] { new CloudEvent() }, out _));
// Null argument // Null argument
Assert.Throws<ArgumentNullException>(() => formatter.EncodeBatchModeMessage(null, out _)); Assert.Throws<ArgumentNullException>(() => formatter.EncodeBatchModeMessage(null!, out _));
// Null value within the argument. Arguably this should throw ArgumentException instead of // Null value within the argument. Arguably this should throw ArgumentException instead of
// ArgumentNullException, but it's unlikely to cause confusion. // ArgumentNullException, but it's unlikely to cause confusion.
Assert.Throws<ArgumentNullException>(() => formatter.EncodeBatchModeMessage(new CloudEvent[1], out _)); Assert.Throws<ArgumentNullException>(() => formatter.EncodeBatchModeMessage(new CloudEvent[1], out _));
@ -591,10 +591,10 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
var formatter = new JsonEventFormatter(); var formatter = new JsonEventFormatter();
var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, AllTypesExtensions); var cloudEvent = formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, AllTypesExtensions);
Assert.Equal(SampleBinaryData, cloudEvent["binary"]); Assert.Equal(SampleBinaryData, cloudEvent["binary"]);
Assert.True((bool)cloudEvent["boolean"]); Assert.True((bool)cloudEvent["boolean"]!);
Assert.Equal(10, cloudEvent["integer"]); Assert.Equal(10, cloudEvent["integer"]);
Assert.Equal("text", cloudEvent["string"]); Assert.Equal("text", cloudEvent["string"]);
AssertTimestampsEqual(SampleTimestamp, (DateTimeOffset)cloudEvent["timestamp"]); AssertTimestampsEqual(SampleTimestamp, (DateTimeOffset)cloudEvent["timestamp"]!);
Assert.Equal(SampleUri, cloudEvent["uri"]); Assert.Equal(SampleUri, cloudEvent["uri"]);
Assert.Equal(SampleUriReference, cloudEvent["urireference"]); Assert.Equal(SampleUriReference, cloudEvent["urireference"]);
} }
@ -715,7 +715,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
} }
obj["data"] = 10; obj["data"] = 10;
var cloudEvent = DecodeStructuredModeMessage(obj); var cloudEvent = DecodeStructuredModeMessage(obj);
var element = (JsonElement) cloudEvent.Data; var element = (JsonElement) cloudEvent.Data!;
Assert.Equal(JsonValueKind.Number, element.ValueKind); Assert.Equal(JsonValueKind.Number, element.ValueKind);
Assert.Equal(10, element.GetInt32()); Assert.Equal(10, element.GetInt32());
} }
@ -915,7 +915,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
cloudEvent.DataContentType = contentType; cloudEvent.DataContentType = contentType;
new JsonEventFormatter().DecodeBinaryModeEventData(bytes, cloudEvent); new JsonEventFormatter().DecodeBinaryModeEventData(bytes, cloudEvent);
return cloudEvent.Data; return cloudEvent.Data!;
} }
internal static JObject CreateMinimalValidJObject() => internal static JObject CreateMinimalValidJObject() =>

View File

@ -170,7 +170,7 @@ namespace CloudNative.CloudEvents.SystemTextJson.UnitTests
{ {
if (cloudEvent.DataContentType == GuidContentType && dataElement.ValueKind == JsonValueKind.String) if (cloudEvent.DataContentType == GuidContentType && dataElement.ValueKind == JsonValueKind.String)
{ {
string text = dataElement.GetString(); string text = dataElement.GetString()!;
if (!text.StartsWith(GuidPrefix)) if (!text.StartsWith(GuidPrefix))
{ {
throw new ArgumentException("Invalid GUID text data"); throw new ArgumentException("Invalid GUID text data");

View File

@ -150,7 +150,7 @@ namespace CloudNative.CloudEvents.UnitTests
{ {
Assert.True(false, "Expected both values to be null, or neither to be null"); Assert.True(false, "Expected both values to be null, or neither to be null");
} }
AssertTimestampsEqual(expected.Value, actual.Value); AssertTimestampsEqual(expected!.Value, actual!.Value);
} }
// TODO: Use this more widely // TODO: Use this more widely