Esempio n. 1
0
        public void Can_Serialize_Complex_Types()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <TestResource>("test-resource");
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.Options).Returns(new JsonApiOptions());
            jsonApiContextMock.Setup(m => m.RequestEntity)
            .Returns(contextGraph.GetContextEntity("test-resource"));
            jsonApiContextMock.Setup(m => m.MetaBuilder).Returns(new MetaBuilder());
            jsonApiContextMock.Setup(m => m.PageManager).Returns(new PageManager());

            var documentBuilder = new DocumentBuilder(jsonApiContextMock.Object);
            var serializer      = new JsonApiSerializer(jsonApiContextMock.Object, documentBuilder);
            var resource        = new TestResource
            {
                ComplexMember = new ComplexType
                {
                    CompoundName = "testname"
                }
            };

            // act
            var result = serializer.Serialize(resource);

            // assert
            Assert.NotNull(result);
            Assert.Equal("{\"data\":{\"attributes\":{\"complex-member\":{\"compound-name\":\"testname\"}},\"type\":\"test-resource\",\"id\":\"\"}}", result);
        }
Esempio n. 2
0
        public void Immutable_Attrs_Are_Not_Included_In_AttributesToUpdate()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <TestResource>("test-resource");
            var contextGraph = contextGraphBuilder.Build();

            var attributesToUpdate = new Dictionary <AttrAttribute, object>();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(attributesToUpdate);

            var jsonApiOptions = new JsonApiOptions();

            jsonApiOptions.SerializerSettings.ContractResolver = new DasherizedResolver();
            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object);

            var content = new Document
            {
                Data = new DocumentData
                {
                    Type       = "test-resource",
                    Id         = "1",
                    Attributes = new Dictionary <string, object>
                    {
                        {
                            "complex-member", new Dictionary <string, string> {
                                { "compound-name", "testName" }
                            }
                        },
                        { "immutable", "value" }
                    }
                }
            };

            var contentString = JsonConvert.SerializeObject(content);

            // act
            var result = deserializer.Deserialize <TestResource>(contentString);

            // assert
            Assert.NotNull(result.ComplexMember);
            Assert.Single(attributesToUpdate);

            foreach (var attr in attributesToUpdate)
            {
                Assert.False(attr.Key.IsImmutable);
            }
        }
Esempio n. 3
0
        public void Can_Deserialize_Independent_Side_Of_One_To_One_Relationship_With_Relationship_Body()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <Independent>("independents");
            contextGraphBuilder.AddResource <Dependent>("dependents");
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary <AttrAttribute, object>());
            jsonApiContextMock.Setup(m => m.HasOneRelationshipPointers).Returns(new HasOneRelationshipPointers());

            var jsonApiOptions = new JsonApiOptions();

            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object);

            var property = Guid.NewGuid().ToString();
            var content  = new Document
            {
                Data = new DocumentData
                {
                    Type       = "independents",
                    Id         = "1",
                    Attributes = new Dictionary <string, object> {
                        { "property", property }
                    },
                    // a common case for this is deserialization in unit tests
                    Relationships = new Dictionary <string, RelationshipData> {
                        {
                            "dependent", new RelationshipData
                            {
                                SingleData = new ResourceIdentifierObject("dependents", "1")
                            }
                        }
                    }
                }
            };

            var contentString = JsonConvert.SerializeObject(content);

            // act
            var result = deserializer.Deserialize <Independent>(contentString);

            // assert
            Assert.NotNull(result);
            Assert.Equal(property, result.Property);
            Assert.NotNull(result.Dependent);
            Assert.Equal(1, result.Dependent.Id);
        }
Esempio n. 4
0
        public void Can_Deserialize_Object_With_HasManyRelationship()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <OneToManyIndependent>("independents");
            contextGraphBuilder.AddResource <OneToManyDependent>("dependents");
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary <AttrAttribute, object>());
            jsonApiContextMock.Setup(m => m.HasManyRelationshipPointers).Returns(new HasManyRelationshipPointers());

            var jsonApiOptions = new JsonApiOptions();

            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object);

            var contentString =
                @"{
                ""data"": {
                    ""type"": ""independents"",
                    ""id"": ""1"",
                    ""attributes"": { },
                    ""relationships"": {
                        ""dependents"": {
                            ""data"": [
                                {
                                    ""type"": ""dependents"",
                                    ""id"": ""2""
                                }
                            ]
                        }
                    }
                }
            }";

            // act
            var result = deserializer.Deserialize <OneToManyIndependent>(contentString);

            // assert
            Assert.NotNull(result);
            Assert.Equal(1, result.Id);
            Assert.NotNull(result.Dependents);
            Assert.NotEmpty(result.Dependents);
            Assert.Single(result.Dependents);

            var dependent = result.Dependents[0];

            Assert.Equal(2, dependent.Id);
        }
Esempio n. 5
0
        public void Sets_The_DocumentMeta_Property_In_JsonApiContext()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <Independent>("independents");
            contextGraphBuilder.AddResource <Dependent>("dependents");
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary <AttrAttribute, object>());

            var jsonApiOptions = new JsonApiOptions();

            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var genericProcessorFactoryMock = new Mock <IGenericProcessorFactory>();

            var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object, genericProcessorFactoryMock.Object);

            var property = Guid.NewGuid().ToString();

            var content = new Document
            {
                Meta = new Dictionary <string, object>()
                {
                    { "foo", "bar" }
                },
                Data = new DocumentData
                {
                    Type       = "independents",
                    Id         = "1",
                    Attributes = new Dictionary <string, object> {
                        { "property", property }
                    },
                    // a common case for this is deserialization in unit tests
                    Relationships = new Dictionary <string, RelationshipData> {
                        { "dependent", new RelationshipData {
                          } }
                    }
                }
            };

            var contentString = JsonConvert.SerializeObject(content);

            // act
            var result = deserializer.Deserialize <Independent>(contentString);

            // assert
            jsonApiContextMock.VerifySet(mock => mock.DocumentMeta = content.Meta);
        }
Esempio n. 6
0
        public void BuildContextGraph <TContext>(Action <IContextGraphBuilder> builder)
            where TContext : DbContext
        {
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddDbContext <TContext>();

            builder?.Invoke(contextGraphBuilder);

            ContextGraph = contextGraphBuilder.Build();
        }
        public void AddDbContext_Does_Not_Throw_If_Context_Contains_Members_That_DoNot_Implement_IIdentifiable()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            // act
            contextGraphBuilder.AddDbContext <TestContext>();
            var contextGraph = contextGraphBuilder.Build() as ContextGraph;

            // assert
            Assert.Empty(contextGraph.Entities);
        }
Esempio n. 8
0
        public void BuildContextGraph(Action <IContextGraphBuilder> builder)
        {
            if (builder == null)
            {
                throw new ArgumentException("Cannot build non-EF context graph without an IContextGraphBuilder action", nameof(builder));
            }

            var contextGraphBuilder = new ContextGraphBuilder();

            builder(contextGraphBuilder);

            ContextGraph = contextGraphBuilder.Build();
        }
        public void Adding_DbContext_Members_That_DoNot_Implement_IIdentifiable_Creates_Warning()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            // act
            contextGraphBuilder.AddDbContext <TestContext>();
            var contextGraph = contextGraphBuilder.Build() as ContextGraph;

            // assert
            Assert.Equal(1, contextGraph.ValidationResults.Count);
            Assert.Contains(contextGraph.ValidationResults, v => v.LogLevel == LogLevel.Warning);
        }
Esempio n. 10
0
        public void Can_Serialize_Complex_Types()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <TestResource>("test-resource");

            var serializer = GetSerializer(contextGraphBuilder);

            var resource = new TestResource
            {
                ComplexMember = new ComplexType
                {
                    CompoundName = "testname"
                }
            };

            // act
            var result = serializer.Serialize(resource);

            // assert
            Assert.NotNull(result);

            var expectedFormatted =
                @"{
                ""data"": {
                    ""attributes"": {
                        ""complex-member"": {
                            ""compound-name"": ""testname""
                        }
                    },
                    ""relationships"": {
                        ""children"": {
                            ""links"": {
                                ""self"": ""/test-resource//relationships/children"",
                                ""related"": ""/test-resource//children""
                            }
                        }
                    },
                    ""type"": ""test-resource"",
                    ""id"": """"
                }
            }";
            var expected = Regex.Replace(expectedFormatted, @"\s+", "");

            Assert.Equal(expected, result);
        }
        public static void AddJsonApiInternals <TContext>(this IServiceCollection services, JsonApiOptions jsonApiOptions)
            where TContext : DbContext
        {
            var contextGraphBuilder = new ContextGraphBuilder <TContext>();
            var contextGraph        = contextGraphBuilder.Build();

            services.AddScoped(typeof(DbContext), typeof(TContext));
            services.AddScoped(typeof(IEntityRepository <>), typeof(DefaultEntityRepository <>));
            services.AddScoped(typeof(IEntityRepository <,>), typeof(DefaultEntityRepository <,>));

            services.AddSingleton <JsonApiOptions>(jsonApiOptions);
            services.AddSingleton <IContextGraph>(contextGraph);
            services.AddScoped <IJsonApiContext, JsonApiContext>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddScoped <JsonApiRouteHandler>();
        }
Esempio n. 12
0
        public void Can_Deserialize_Complex_List_Types()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <TestResourceWithList>("test-resource");
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary <AttrAttribute, object>());
            jsonApiContextMock.Setup(m => m.Options).Returns(new JsonApiOptions
            {
                JsonContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            var genericProcessorFactoryMock = new Mock <IGenericProcessorFactory>();

            var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object, genericProcessorFactoryMock.Object);

            var content = new Document
            {
                Data = new DocumentData
                {
                    Type       = "test-resource",
                    Id         = "1",
                    Attributes = new Dictionary <string, object> {
                        {
                            "complex-members", new [] {
                                new { compoundName = "testName" }
                            }
                        }
                    }
                }
            };

            // act
            var result = deserializer.Deserialize <TestResourceWithList>(JsonConvert.SerializeObject(content));

            // assert
            Assert.NotNull(result.ComplexMembers);
            Assert.NotEmpty(result.ComplexMembers);
            Assert.Equal("testName", result.ComplexMembers[0].CompoundName);
        }
Esempio n. 13
0
        public void Can_Deserialize_Complex_Types_With_Dasherized_Attrs()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <TestResource>("test-resource");
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary <AttrAttribute, object>());

            var jsonApiOptions = new JsonApiOptions();

            jsonApiOptions.SerializerSettings.ContractResolver = new DasherizedResolver(); // <--
            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var genericProcessorFactoryMock = new Mock <IGenericProcessorFactory>();

            var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object, genericProcessorFactoryMock.Object);

            var content = new Document
            {
                Data = new DocumentData
                {
                    Type       = "test-resource",
                    Id         = "1",
                    Attributes = new Dictionary <string, object> {
                        {
                            "complex-member", new Dictionary <string, string> {
                                { "compound-name", "testName" }
                            }
                        }
                    }
                }
            };

            // act
            var result = deserializer.Deserialize <TestResource>(JsonConvert.SerializeObject(content));

            // assert
            Assert.NotNull(result.ComplexMember);
            Assert.Equal("testName", result.ComplexMember.CompoundName);
        }
Esempio n. 14
0
        public void Can_Deserialize_Independent_Side_Of_One_To_One_Relationship()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <Independent>("independents");
            contextGraphBuilder.AddResource <Dependent>("dependents");
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary <AttrAttribute, object>());

            var jsonApiOptions = new JsonApiOptions();

            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var genericProcessorFactoryMock = new Mock <IGenericProcessorFactory>();

            var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object, genericProcessorFactoryMock.Object);

            var property = Guid.NewGuid().ToString();
            var content  = new Document
            {
                Data = new DocumentData
                {
                    Type       = "independents",
                    Id         = "1",
                    Attributes = new Dictionary <string, object> {
                        { "property", property }
                    }
                }
            };

            var contentString = JsonConvert.SerializeObject(content);

            // act
            var result = deserializer.Deserialize <Independent>(contentString);

            // assert
            Assert.NotNull(result);
            Assert.Equal(property, result.Property);
        }
Esempio n. 15
0
        public async Task ProcessAsync_Deserializes_And_Creates()
        {
            // arrange
            var testResource = new TestResource {
                Name = "some-name"
            };

            var data = new DocumentData {
                Type       = "test-resources",
                Attributes = new Dictionary <string, object> {
                    { "name", testResource.Name }
                }
            };

            var operation = new Operation {
                Data = data,
            };

            var contextGraph = new ContextGraphBuilder()
                               .AddResource <TestResource>("test-resources")
                               .Build();

            _deserializerMock.Setup(m => m.DocumentToObject(It.IsAny <DocumentData>()))
            .Returns(testResource);

            var opProcessor = new CreateOpProcessor <TestResource>(
                _createServiceMock.Object,
                _deserializerMock.Object,
                _documentBuilderMock.Object,
                contextGraph
                );

            _documentBuilderMock.Setup(m => m.GetData(It.IsAny <ContextEntity>(), It.IsAny <TestResource>()))
            .Returns(data);

            // act
            var result = await opProcessor.ProcessAsync(operation);

            // assert
            Assert.Equal(OperationCode.add, result.Op);
            Assert.NotNull(result.Data);
            Assert.Equal(testResource.Name, result.DataObject.Attributes["name"]);
            _createServiceMock.Verify(m => m.CreateAsync(It.IsAny <TestResource>()));
        }
Esempio n. 16
0
        private JsonApiSerializer GetSerializer(
            ContextGraphBuilder contextGraphBuilder,
            List <string> included = null)
        {
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.Options).Returns(new JsonApiOptions());
            jsonApiContextMock.Setup(m => m.RequestEntity).Returns(contextGraph.GetContextEntity("test-resource"));
            // jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary<AttrAttribute, object>());
            // jsonApiContextMock.Setup(m => m.RelationshipsToUpdate).Returns(new Dictionary<RelationshipAttribute, object>());
            // jsonApiContextMock.Setup(m => m.HasManyRelationshipPointers).Returns(new HasManyRelationshipPointers());
            // jsonApiContextMock.Setup(m => m.HasOneRelationshipPointers).Returns(new HasOneRelationshipPointers());
            jsonApiContextMock.Setup(m => m.MetaBuilder).Returns(new MetaBuilder());
            jsonApiContextMock.Setup(m => m.PageManager).Returns(new PageManager());

            if (included != null)
            {
                jsonApiContextMock.Setup(m => m.IncludedRelationships).Returns(included);
            }

            var jsonApiOptions = new JsonApiOptions();

            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var services = new ServiceCollection();

            var mvcBuilder = services.AddMvcCore();

            services
            .AddJsonApiInternals(jsonApiOptions);

            var provider = services.BuildServiceProvider();
            var scoped   = new TestScopedServiceProvider(provider);

            var documentBuilder = new DocumentBuilder(jsonApiContextMock.Object, scopedServiceProvider: scoped);
            var serializer      = new JsonApiSerializer(jsonApiContextMock.Object, documentBuilder);

            return(serializer);
        }
        private JsonApiDeSerializer GetDeserializer(ContextGraphBuilder contextGraphBuilder)
        {
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary <AttrAttribute, object>());
            jsonApiContextMock.Setup(m => m.RelationshipsToUpdate).Returns(new Dictionary <RelationshipAttribute, object>());
            jsonApiContextMock.Setup(m => m.HasManyRelationshipPointers).Returns(new HasManyRelationshipPointers());
            jsonApiContextMock.Setup(m => m.HasOneRelationshipPointers).Returns(new HasOneRelationshipPointers());

            var jsonApiOptions = new JsonApiOptions();

            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object);

            return(deserializer);
        }
        public void Build_Will_Use_Instance_Specific_Resource_If_Defined_For_Single_Document()
        {
            var entity       = new User();
            var contextGraph = new ContextGraphBuilder()
                               .AddResource <User>("user")
                               .Build();

            _jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);

            var scopedServiceProvider = new TestScopedServiceProvider(
                new ServiceCollection()
                .AddScoped <ResourceDefinition <User>, InstanceSpecificUserResource>()
                .BuildServiceProvider());

            var documentBuilder = new DocumentBuilder(_jsonApiContextMock.Object, scopedServiceProvider: scopedServiceProvider);

            var documents = documentBuilder.Build(entity);

            Assert.False(documents.Data.Attributes.ContainsKey("password"));
            Assert.True(documents.Data.Attributes.ContainsKey("username"));
        }
Esempio n. 19
0
        public JsonApiDeserializer_Benchmarks()
        {
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <SimpleType>(TYPE_NAME);
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary <AttrAttribute, object>());

            var jsonApiOptions = new JsonApiOptions();

            jsonApiOptions.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var genericProcessorFactoryMock = new Mock <IGenericProcessorFactory>();

            _jsonApiDeSerializer = new JsonApiDeSerializer(jsonApiContextMock.Object, genericProcessorFactoryMock.Object);
        }
Esempio n. 20
0
        public SerializerShowdown()
        {
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <IdentifiableEwok>("Ewok");
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary <AttrAttribute, object>());

            var jsonApiOptions = new JsonApiOptions();

            jsonApiOptions.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var documentBuilder = new DocumentBuilder(jsonApiContextMock.Object);

            _json_api_dotnet_serializer = new JsonApiSerializer(jsonApiContextMock.Object, documentBuilder);
            _saule     = new JsonApiSerializer <EwokResource>();
            _partytime = new Serializer();
        }
Esempio n. 21
0
        public void Sets_Attribute_Values_On_Included_HasOne_Relationships()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <OneToManyIndependent>("independents");
            contextGraphBuilder.AddResource <OneToManyDependent>("dependents");
            var contextGraph = contextGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
            jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary <AttrAttribute, object>());
            jsonApiContextMock.Setup(m => m.RelationshipsToUpdate).Returns(new Dictionary <RelationshipAttribute, object>());
            jsonApiContextMock.Setup(m => m.HasManyRelationshipPointers).Returns(new HasManyRelationshipPointers());
            jsonApiContextMock.Setup(m => m.HasOneRelationshipPointers).Returns(new HasOneRelationshipPointers());

            var jsonApiOptions = new JsonApiOptions();

            jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

            var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object);

            var expectedName  = "John Doe";
            var contentString =
                @"{
                ""data"": {
                    ""type"": ""dependents"",
                    ""id"": ""1"",
                    ""attributes"": { },
                    ""relationships"": {
                        ""independent"": {
                            ""data"": {
                                ""type"": ""independents"",
                                ""id"": ""2""
                            }
                        }
                    }
                },
                ""included"": [
                    {
                        ""type"": ""independents"",
                        ""id"": ""2"",
                        ""attributes"": {
                            ""name"": """ + expectedName + @"""
                        }
                    }
                ]
            }";

            // act
            var result = deserializer.Deserialize <OneToManyDependent>(contentString);

            // assert
            Assert.NotNull(result);
            Assert.Equal(1, result.Id);
            Assert.NotNull(result.Independent);
            Assert.Equal(2, result.Independent.Id);
            Assert.Equal(expectedName, result.Independent.Name);
        }
        public void Can_Deserialize_Nested_Included_HasMany_Relationships()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <OneToManyIndependent>("independents");
            contextGraphBuilder.AddResource <OneToManyDependent>("dependents");
            contextGraphBuilder.AddResource <ManyToManyNested>("many-to-manys");

            var deserializer = GetDeserializer(contextGraphBuilder);

            var contentString =
                @"{
                ""data"": {
                    ""type"": ""independents"",
                    ""id"": ""1"",
                    ""attributes"": { },
                    ""relationships"": {
                        ""many-to-manys"": {
                           ""data"": [{
                                ""type"": ""many-to-manys"",
                                ""id"": ""2""
                            }, {
                                ""type"": ""many-to-manys"",
                                ""id"": ""3""
                            }]
                        }
                    }
                },
                ""included"": [
                    {
                        ""type"": ""many-to-manys"",
                        ""id"": ""2"",
                        ""attributes"": {},
                        ""relationships"": {
                            ""dependent"": {
                                ""data"": {
                                    ""type"": ""dependents"",
                                    ""id"": ""4""
                                }
                            },
                            ""independent"": {
                                ""data"": {
                                    ""type"": ""independents"",
                                    ""id"": ""5""
                                }
                            }
                        }
                    },
                    {
                        ""type"": ""many-to-manys"",
                        ""id"": ""3"",
                        ""attributes"": {},
                        ""relationships"": {
                            ""dependent"": {
                                ""data"": {
                                    ""type"": ""dependents"",
                                    ""id"": ""4""
                                }
                            },
                            ""independent"": {
                                ""data"": {
                                    ""type"": ""independents"",
                                    ""id"": ""6""
                                }
                            }
                        }
                    },
                    {
                        ""type"": ""dependents"",
                        ""id"": ""4"",
                        ""attributes"": {},
                        ""relationships"": {
                            ""many-to-manys"": {
                                ""data"": [{
                                    ""type"": ""many-to-manys"",
                                    ""id"": ""2""
                                }, {
                                    ""type"": ""many-to-manys"",
                                    ""id"": ""3""
                                }]
                            }
                        }
                    }
                    ,
                    {
                        ""type"": ""independents"",
                        ""id"": ""5"",
                        ""attributes"": {},
                        ""relationships"": {
                            ""many-to-manys"": {
                                ""data"": [{
                                    ""type"": ""many-to-manys"",
                                    ""id"": ""2""
                                }]
                            }
                        }
                    }
                    ,
                    {
                        ""type"": ""independents"",
                        ""id"": ""6"",
                        ""attributes"": {},
                        ""relationships"": {
                            ""many-to-manys"": {
                                ""data"": [{
                                    ""type"": ""many-to-manys"",
                                    ""id"": ""3""
                                }]
                            }
                        }
                    }
                ]
            }";

            // act
            var result = deserializer.Deserialize <OneToManyIndependent>(contentString);

            // assert
            Assert.NotNull(result);
            Assert.Equal(1, result.Id);
            Assert.NotNull(result.ManyToManys);
            Assert.Equal(2, result.ManyToManys.Count);

            // TODO: not sure if this should be a thing that works?
            //       could this cause cycles in the graph?
            // Assert.NotNull(result.ManyToManys[0].Dependent);
            // Assert.NotNull(result.ManyToManys[0].Independent);
            // Assert.NotNull(result.ManyToManys[1].Dependent);
            // Assert.NotNull(result.ManyToManys[1].Independent);

            // Assert.Equal(result.ManyToManys[0].Dependent, result.ManyToManys[1].Dependent);
            // Assert.NotEqual(result.ManyToManys[0].Independent, result.ManyToManys[1].Independent);
        }
Esempio n. 23
0
        public void Can_Serialize_Deeply_Nested_Relationships()
        {
            // arrange
            var contextGraphBuilder = new ContextGraphBuilder();

            contextGraphBuilder.AddResource <TestResource>("test-resource");
            contextGraphBuilder.AddResource <ChildResource>("children");
            contextGraphBuilder.AddResource <InfectionResource>("infections");

            var serializer = GetSerializer(
                contextGraphBuilder,
                included: new List <string> {
                "children.infections"
            }
                );

            var resource = new TestResource
            {
                Id       = 1,
                Children = new List <ChildResource> {
                    new ChildResource {
                        Id         = 2,
                        Infections = new List <InfectionResource> {
                            new InfectionResource {
                                Id = 4
                            },
                            new InfectionResource {
                                Id = 5
                            },
                        }
                    },
                    new ChildResource {
                        Id = 3
                    }
                }
            };

            // act
            var result = serializer.Serialize(resource);

            // assert
            Assert.NotNull(result);

            var expectedFormatted =
                @"{
                ""data"": {
                    ""attributes"": {
                        ""complex-member"": null
                    },
                    ""relationships"": {
                        ""children"": {
                            ""links"": {
                                ""self"": ""/test-resource/1/relationships/children"",
                                ""related"": ""/test-resource/1/children""
                            },
                            ""data"": [{
                                ""type"": ""children"",
                                ""id"": ""2""
                            }, {
                                ""type"": ""children"",
                                ""id"": ""3""
                            }]
                        }
                    },
                    ""type"": ""test-resource"",
                    ""id"": ""1""
                },
                ""included"": [
                    {
                        ""attributes"": {},
                        ""relationships"": {
                            ""infections"": {
                                ""links"": {
                                    ""self"": ""/children/2/relationships/infections"",
                                    ""related"": ""/children/2/infections""
                                },
                                ""data"": [{
                                    ""type"": ""infections"",
                                    ""id"": ""4""
                                }, {
                                    ""type"": ""infections"",
                                    ""id"": ""5""
                                }]
                            },
                            ""parent"": {
                                ""links"": {
                                    ""self"": ""/children/2/relationships/parent"",
                                    ""related"": ""/children/2/parent""
                                }
                            }
                        },
                        ""type"": ""children"",
                        ""id"": ""2""
                    },
                    {
                        ""attributes"": {},
                        ""relationships"": {
                            ""infected"": {
                                ""links"": {
                                    ""self"": ""/infections/4/relationships/infected"",
                                    ""related"": ""/infections/4/infected""
                                }
                            }
                        },
                        ""type"": ""infections"",
                        ""id"": ""4""
                    },
                    {
                        ""attributes"": {},
                        ""relationships"": {
                            ""infected"": {
                                ""links"": {
                                    ""self"": ""/infections/5/relationships/infected"",
                                    ""related"": ""/infections/5/infected""
                                }
                            }
                        },
                        ""type"": ""infections"",
                        ""id"": ""5""
                    },
                    {
                        ""attributes"": {},
                        ""relationships"": {
                            ""infections"": {
                                ""links"": {
                                    ""self"": ""/children/3/relationships/infections"",
                                    ""related"": ""/children/3/infections""
                                }
                            },
                            ""parent"": {
                                ""links"": {
                                    ""self"": ""/children/3/relationships/parent"",
                                    ""related"": ""/children/3/parent""
                                }
                            }
                        },
                        ""type"": ""children"",
                        ""id"": ""3""
                    }
                ]
            }";
            var expected = Regex.Replace(expectedFormatted, @"\s+", "");

            Assert.Equal(expected, result);
        }