Exemple #1
0
        public static async Task RegisteredType_AdditionalLink(
            Guid id,
            Guid parentId,
            UnequalNonNullPair <NonEmptyString> routes,
            JsonSerializerSettings serializerSettings)
        {
            if (serializerSettings is null)
            {
                throw new ArgumentNullException(nameof(serializerSettings));
            }

            var dto = new Registered
            {
                Id       = id,
                ParentId = parentId,
            };

            var(route, parentRoute) = routes;
            var builder = new TransformationMap.Builder <Registered>(r => Const(new Uri($"https://example.invalid/registered/{r.Id}")));
            ITransformationMap <Registered> transformationMap = builder;

            _ = transformationMap.Link("up", r => Const(new Uri($"https://example.invalid/parent/{r.ParentId}")));
            var map = new Dictionary <Type, ITransformationInstructions>
            {
                [typeof(Registered)] = builder,
            };

            await using var serviceProvider = new ServiceCollection()
                                              .AddScoped <ILinkBuilder <Constant>, LinkBuilder.Constant>()
                                              .BuildServiceProvider();
            var repo = new HalRepository(map, serviceProvider);

            serializerSettings.Converters.Add(new LinkCollection.Converter());
            var sut = new HalJsonOutputFormatter(serializerSettings, ArrayPool <char> .Shared, new MvcOptions(), repo);

            using var writer = new StringWriter();
            var context = new OutputFormatterWriteContext(
                new DefaultHttpContext(),
                (_, _) => writer,
                typeof(Registered),
                dto);

            await sut.WriteResponseBodyAsync(context, new UTF8Encoding(encoderShouldEmitUTF8Identifier : false)).ConfigureAwait(false);

            var actual = JsonConvert.DeserializeObject <HollowHal>(writer.ToString(), serializerSettings);

            Assert.NotNull(actual);
            Assert.Empty(actual.Embedded);
            Assert.NotNull(actual.Links);
            Assert.Equal(2, actual.Links.Count);
            var self = Assert.Contains("self", actual.Links);

            Assert.NotNull(self);
            Assert.Equal($"https://example.invalid/registered/{id}", self.Href);
            var parent = Assert.Contains("up", actual.Links);

            Assert.NotNull(parent);
            Assert.Equal($"https://example.invalid/parent/{parentId}", parent.Href);
        }
        public static async Task RegisteredType_NullLink(
            Guid id,
            Guid parentId,
            UnequalNonNullPair <NonEmptyString> routes,
            JsonSerializerSettings serializerSettings)
        {
            // arrange
            var dto = new Registered
            {
                Id       = id,
                ParentId = parentId
            };

            var(route, parentRoute) = routes;
            var builder = new TransformationMap.Builder <Registered>(r => Const(new Uri($"https://example.invalid/registered/{r.Id}")));
            ITransformationMap <Registered> transformationMap = builder;

            transformationMap.Link("up", _ => (ILinkData)null);
            var map = new Dictionary <Type, ITransformationInstructions>
            {
                [typeof(Registered)] = builder
            };
            var serviceProvider = new ServiceCollection()
                                  .AddScoped <ILinkBuilder <Constant>, LinkBuilder.Constant>()
                                  .BuildServiceProvider();
            var repo = new HalRepository(map, serviceProvider);

            serializerSettings.Converters.Add(new LinkCollection.Converter());
            var sut     = new HalJsonOutputFormatter(serializerSettings, ArrayPool <char> .Shared, repo);
            var writer  = new StringWriter();
            var context = new OutputFormatterWriteContext(
                new DefaultHttpContext(),
                (_, __) => writer,
                typeof(Registered),
                dto);

            // act
            await sut.WriteResponseBodyAsync(context, new UTF8Encoding(encoderShouldEmitUTF8Identifier : false)).ConfigureAwait(false);

            var actual = JsonConvert.DeserializeObject <HollowHal>(writer.ToString(), serializerSettings);

            // assert
            Assert.NotNull(actual);
            Assert.Empty(actual.Embedded);
            Assert.NotNull(actual.Links);
            var(rel, link) = Assert.Single(actual.Links);
            Assert.Equal("self", rel);
            Assert.Equal($"https://example.invalid/registered/{id}", link.Href);
        }
        public async Task UsesResourceJsonConverter()
        {
            var formatter = new HalJsonOutputFormatter(
                new JsonSerializerSettings(),
                ArrayPool <char> .Shared,
                new HalOptions());

            using (var body = new MemoryStream())
            {
                var resource = new Resource <TestResource>
                {
                    Data = new TestResource
                    {
                        Content = "HAL-lo there"
                    }
                };

                var serviceProvider = new Mock <IServiceProvider>();
                serviceProvider.Setup(p => p.GetService(typeof(ILogger <HalJsonOutputFormatter>)))
                .Returns(new NullLogger <HalJsonOutputFormatter>());

                var response = new Mock <HttpResponse>();
                response.SetupGet(r => r.Body).Returns(body);
                var httpContext = new Mock <HttpContext>();
                httpContext.SetupGet(c => c.Response).Returns(response.Object);
                httpContext.SetupGet(c => c.RequestServices).Returns(serviceProvider.Object);

                var writeContext = new OutputFormatterWriteContext(
                    httpContext.Object,
                    (s, e) => new StreamWriter(s, e, 4096, true),
                    resource.GetType(),
                    resource);

                await formatter.WriteResponseBodyAsync(writeContext, Encoding.UTF8);

                string expected = "{\"Content\":\"HAL-lo there\"}";

                body.Seek(0, SeekOrigin.Begin);
                string actual = null;
                using (var reader = new StreamReader(body))
                {
                    actual = reader.ReadToEnd();
                }

                Assert.AreEqual(expected, actual);
            }
        }
        public static async Task RegisteredType_SelfLink(Guid id, JsonSerializerSettings serializerSettings)
        {
            // arrange
            var dto = new Registered
            {
                Id = id
            };
            var map = new Dictionary <Type, ITransformationInstructions>
            {
                [typeof(Registered)] = new TransformationMap.Builder <Registered>(
                    r => Const(new Uri($"https://example.invalid/registered/{r.Id}")))
            };
            var serviceProvider = new ServiceCollection()
                                  .AddScoped <ILinkBuilder <Constant>, LinkBuilder.Constant>()
                                  .BuildServiceProvider();
            var repo = new HalRepository(map, serviceProvider);

            serializerSettings.Converters.Add(new LinkCollection.Converter());
            var sut     = new HalJsonOutputFormatter(serializerSettings, ArrayPool <char> .Shared, repo);
            var writer  = new StringWriter();
            var context = new OutputFormatterWriteContext(
                new DefaultHttpContext(),
                (_, __) => writer,
                typeof(Registered),
                dto);

            // act
            await sut.WriteResponseBodyAsync(context, new UTF8Encoding(encoderShouldEmitUTF8Identifier : false)).ConfigureAwait(false);

            var actual = JsonConvert.DeserializeObject <HollowHal>(writer.ToString(), serializerSettings);

            // assert
            Assert.NotNull(actual);
            Assert.Empty(actual.Embedded);
            Assert.NotNull(actual.Links);
            Assert.Equal(1, actual.Links.Count);
            var self = Assert.Contains(Relations.Self, actual.Links);

            Assert.NotNull(self);
            Assert.Equal($"https://example.invalid/registered/{id}", self.Href);
        }
Exemple #5
0
        public static async Task UnregisteredType_NotModified(Guid id, JsonSerializerSettings serializerSettings)
        {
            var dto = new Unregistered
            {
                Id = id,
            };

            using var svc = new ServiceContainer();
            var repo = new HalRepository(ImmutableDictionary <Type, ITransformationInstructions> .Empty, svc);
            var sut  = new HalJsonOutputFormatter(serializerSettings, ArrayPool <char> .Shared, new MvcOptions(), repo);

            await using var writer = new StringWriter();
            var context = new OutputFormatterWriteContext(
                new DefaultHttpContext(),
                (_, _) => writer,
                typeof(Unregistered),
                dto);

            await sut.WriteResponseBodyAsync(context, new UTF8Encoding(encoderShouldEmitUTF8Identifier : false)).ConfigureAwait(false);

            var actual = JsonConvert.DeserializeObject <Unregistered>(writer.ToString(), serializerSettings);

            Assert.Equal(id, actual.Id);
        }