コード例 #1
0
        public void DefaultImplementation_NoPropertyNameTable()
        {
            var formatter = new JsonEventFormatter();
            var event1    = formatter.DecodeStructuredModeMessage(CreateJsonStream(), null, null);
            var event2    = formatter.DecodeStructuredModeMessage(CreateJsonStream(), null, null);

            JObject data1 = (JObject)event1.Data !;
            JObject data2 = (JObject)event2.Data !;

            var property1 = data1.Properties().Single();
            var property2 = data2.Properties().Single();

            Assert.Equal(property1.Name, property2.Name);
            Assert.NotSame(property1.Name, property2.Name);
        }
コード例 #2
0
        public void DecodeStructuredModeMessage_AllAttributeTypes()
        {
            var obj = new JObject
            {
                // Required attributes
                ["specversion"] = "1.0",
                ["type"]        = "test-type",
                ["id"]          = "test-id",
                ["source"]      = "//source",
                // Extension attributes
                ["binary"]       = SampleBinaryDataBase64,
                ["boolean"]      = true,
                ["integer"]      = 10,
                ["string"]       = "text",
                ["timestamp"]    = SampleTimestampText,
                ["uri"]          = SampleUriText,
                ["urireference"] = SampleUriReferenceText
            };

            byte[] bytes      = Encoding.UTF8.GetBytes(obj.ToString());
            var    formatter  = new JsonEventFormatter();
            var    cloudEvent = formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, AllTypesExtensions);

            Assert.Equal(SampleBinaryData, cloudEvent["binary"]);
            Assert.True((bool)cloudEvent["boolean"]);
            Assert.Equal(10, cloudEvent["integer"]);
            Assert.Equal("text", cloudEvent["string"]);
            AssertTimestampsEqual(SampleTimestamp, (DateTimeOffset)cloudEvent["timestamp"]);
            Assert.Equal(SampleUri, cloudEvent["uri"]);
            Assert.Equal(SampleUriReference, cloudEvent["urireference"]);
        }
コード例 #3
0
        /// <summary>
        /// Convenience method to serialize a JObject to bytes, then
        /// decode it as a structured event with the default (System.Text.Json) JsonEventFormatter and no extension attributes.
        /// </summary>
        private static CloudEvent DecodeStructuredModeMessage(Newtonsoft.Json.Linq.JObject obj)
        {
            byte[] bytes     = Encoding.UTF8.GetBytes(obj.ToString());
            var    formatter = new JsonEventFormatter();

            return(formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, null));
        }
コード例 #4
0
        public void Transcode()
        {
            var jsonFormatter = new JsonEventFormatter();
            var cloudEvent1   = jsonFormatter.DecodeStructuredModeText(sampleJson);
            var jsonData      = jsonFormatter.EncodeStructuredModeMessage(cloudEvent1, out var contentType);
            var cloudEvent    = jsonFormatter.DecodeStructuredModeMessage(jsonData, contentType, Sequence.AllAttributes);

            Assert.Equal("Integer", cloudEvent[Sequence.SequenceTypeAttribute]);
            Assert.Equal("25", cloudEvent[Sequence.SequenceAttribute]);
        }
コード例 #5
0
        public void Transcode()
        {
            var jsonFormatter = new JsonEventFormatter();
            var cloudEvent1   = jsonFormatter.DecodeStructuredModeText(sampleJson);
            var jsonData      = jsonFormatter.EncodeStructuredModeMessage(cloudEvent1, out var contentType);
            var cloudEvent    = jsonFormatter.DecodeStructuredModeMessage(jsonData, contentType, null);

            Assert.Equal("abc", cloudEvent["partitionkey"]);
            Assert.Equal("abc", cloudEvent[Partitioning.PartitionKeyAttribute]);
            Assert.Equal("abc", cloudEvent.GetPartitionKey());
        }
コード例 #6
0
        public void Transcode()
        {
            var jsonFormatter = new JsonEventFormatter();
            var cloudEvent1   = jsonFormatter.DecodeStructuredModeText(sampleJson);
            var jsonData      = jsonFormatter.EncodeStructuredModeMessage(cloudEvent1, out var contentType);
            var cloudEvent    = jsonFormatter.DecodeStructuredModeMessage(jsonData, contentType, DistributedTracing.AllAttributes);

            Assert.Equal(SampleParent, cloudEvent[DistributedTracing.TraceParentAttribute]);
            Assert.Equal(SampleParent, cloudEvent.GetTraceParent());
            Assert.Equal(SampleState, cloudEvent[DistributedTracing.TraceStateAttribute]);
            Assert.Equal(SampleState, cloudEvent.GetTraceState());
        }
コード例 #7
0
    public void CloudEventToKafkaMessage_CloudEventFormatJson_VerifyIdIsCorrectlyStored()
    {
        var publisher       = GetKafkaPublisher <byte[]>(CloudEventFormat.Json);
        var inputCloudEvent = MotorCloudEvent.CreateTestCloudEvent(Array.Empty <byte>());
        var cloudFormatter  = new JsonEventFormatter();

        var kafkaMessage = publisher.CloudEventToKafkaMessage(inputCloudEvent);

        var cloudEvent = cloudFormatter.DecodeStructuredModeMessage(kafkaMessage.Value, null, null);

        Assert.Equal(inputCloudEvent.Id, cloudEvent.Id);
    }
コード例 #8
0
        public void SamplingJsonTranscode()
        {
            var jsonFormatter = new JsonEventFormatter();
            var cloudEvent1   = jsonFormatter.DecodeStructuredModeText(sampleJson);

            // Note that the value is just a string here, as we don't know the attribute type.
            Assert.Equal("1", cloudEvent1["sampledrate"]);

            var jsonData   = jsonFormatter.EncodeStructuredModeMessage(cloudEvent1, out var contentType);
            var cloudEvent = jsonFormatter.DecodeStructuredModeMessage(jsonData, contentType, Sampling.AllAttributes);

            // When parsing with the attributes in place, the value is propagated as an integer.
            Assert.Equal(1, cloudEvent["sampledrate"]);
            Assert.Equal(1, cloudEvent.GetSampledRate());
        }
コード例 #9
0
        private static List<CloudEvent> DeserializeRequest(Request request)
        {
            var content = request.Content;
            var stream = new MemoryStream();
            content.WriteTo(stream, CancellationToken.None);
            stream.Position = 0;
            JsonDocument requestDocument = JsonDocument.Parse(stream);
            var cloudEvents = new List<CloudEvent>();

            foreach (JsonElement property in requestDocument.RootElement.EnumerateArray())
            {
                var bytes = JsonSerializer.SerializeToUtf8Bytes(property, typeof(JsonElement));
                cloudEvents.Add(s_eventFormatter.DecodeStructuredModeMessage(bytes, new ContentType("application/json"), null));
            }

            return cloudEvents;
        }
コード例 #10
0
        public void DecodeStructuredModeMessage_IncorrectExtensionTypeWithValidValue()
        {
            var obj = new JObject
            {
                ["specversion"] = "1.0",
                ["type"]        = "test-type",
                ["id"]          = "test-id",
                ["source"]      = "//source",
                // Incorrect type, but is a valid value for the extension
                ["integer"] = "10",
            };

            // Decode the event, providing the extension with the correct type.
            byte[] bytes      = Encoding.UTF8.GetBytes(obj.ToString());
            var    formatter  = new JsonEventFormatter();
            var    cloudEvent = formatter.DecodeStructuredModeMessage(bytes, s_jsonCloudEventContentType, AllTypesExtensions);

            // The value will have been decoded according to the extension.
            Assert.Equal(10, cloudEvent["integer"]);
        }
コード例 #11
0
        public void DecodeStructuredModeMessage_Minimal(string charset)
        {
            var obj = new JObject
            {
                ["specversion"] = "1.0",
                ["type"]        = "test-type",
                ["id"]          = "test-id",
                ["source"]      = SampleUriText,
                ["text"]        = NonAsciiValue
            };

            byte[] bytes      = Encoding.GetEncoding(charset).GetBytes(obj.ToString());
            var    stream     = new MemoryStream(bytes);
            var    formatter  = new JsonEventFormatter();
            var    cloudEvent = formatter.DecodeStructuredModeMessage(stream, new ContentType($"application/cloudevents+json; charset={charset}"), null);

            Assert.Equal("test-type", cloudEvent.Type);
            Assert.Equal("test-id", cloudEvent.Id);
            Assert.Equal(SampleUri, cloudEvent.Source);
        }
コード例 #12
0
    public async void PublishMessageAsJsonFormat()
    {
        const string expectedMessage = "testMessage";
        var topicName = _randomizerString.Generate();
        var queueName = _randomizerString.Generate();

        var publisherOptions = GetNATSBaseOptions(topicName);
        var publisher = GetPublisher(MSOptions.Create(publisherOptions), CloudEventFormat.Json);

        var consumerOptions = GetNATSConsumerOptions(topicName, queueName);

        var consumer = GetConsumer<string>(MSOptions.Create(consumerOptions));
        var rawConsumedNatsMessage =
            await RawConsumedNatsMessageWithNatsPublisherPublishedMessage(consumer, publisher, expectedMessage);

        Assert.NotNull(rawConsumedNatsMessage);
        var jsonEventFormatter = new JsonEventFormatter();
        var cloudEvent = jsonEventFormatter.DecodeStructuredModeMessage(rawConsumedNatsMessage, null, null);
        Assert.Equal(expectedMessage, Encoding.UTF8.GetString(cloudEvent.Data as byte[] ?? Array.Empty<byte>()));

    }
コード例 #13
0
        public void GivenDynamicType_WhenWhen_ThenThen()
        {
            // Given
            var p           = new Faker().Person;
            var userCreated = new UserCreatedRecordDataContract
            {
                BirthDate = p.DateOfBirth,
                FirstName = p.FirstName,
                LastName  = p.LastName,
                Id        = p.Random.Guid()
            };

            var resolver = new InMemoryTypeResolver();

            resolver.RegisterType <UserCreatedRecordDataContract>();

            // serialize
            CloudEvent expected  = new CloudEvent <UserCreatedRecordDataContract>(userCreated);
            var        formatter = new JsonEventFormatter();
            var        bytes     = formatter.EncodeStructuredModeMessage(expected, out var ct);
            var        json      = Encoding.Default.GetString(bytes.ToArray());

            // When
            var e = formatter.DecodeStructuredModeMessage(bytes, ct, new CloudEventAttribute[0]);
コード例 #14
0
        public void GivenASingleEventSerialized_WhenDeserialize_ThenResultIsEquivalentToSource()
        {
            // Given
            var p = new Faker().Person;
            var userCreatedDataContract = new UserCreatedRecordDataContract
            {
                BirthDate = p.DateOfBirth,
                FirstName = p.FirstName,
                LastName  = p.LastName,
                Id        = p.Random.Guid()
            };

            var expected = new CloudEventBuilder <UserCreatedRecordDataContract>().WithData(userCreatedDataContract)
                           .Build();
            var formatter = new JsonEventFormatter <UserCreatedRecordDataContract>();
            var bytes     = formatter.EncodeStructuredModeMessage(expected, out var ct);

            // When
            var e = formatter.DecodeStructuredModeMessage(bytes, ct, new List <CloudEventAttribute>());
            CloudEvent <UserCreatedRecordDataContract> actual = e;

            // Then
            actual.Should().BeEquivalentTo(expected);
        }
コード例 #15
0
        public void DecodeStructuredModeMessage_NotJson()
        {
            var formatter = new JsonEventFormatter();

            Assert.ThrowsAny <JsonException>(() => formatter.DecodeStructuredModeMessage(new byte[10], new ContentType("application/json"), null));
        }