protected IResourceGraph BuildGraph()
        {
            var resourceGraphBuilder = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance);

            resourceGraphBuilder.Add <TestResource>("testResource");
            resourceGraphBuilder.Add <TestResourceWithList>("testResource-with-list");
            // one to one relationships
            resourceGraphBuilder.Add <OneToOnePrincipal>("oneToOnePrincipals");
            resourceGraphBuilder.Add <OneToOneDependent>("oneToOneDependents");
            resourceGraphBuilder.Add <OneToOneRequiredDependent>("oneToOneRequiredDependents");
            // one to many relationships
            resourceGraphBuilder.Add <OneToManyPrincipal>("oneToManyPrincipals");
            resourceGraphBuilder.Add <OneToManyDependent>("oneToManyDependents");
            resourceGraphBuilder.Add <OneToManyRequiredDependent>("oneToMany-requiredDependents");
            // collective relationships
            resourceGraphBuilder.Add <MultipleRelationshipsPrincipalPart>("multiPrincipals");
            resourceGraphBuilder.Add <MultipleRelationshipsDependentPart>("multiDependents");

            resourceGraphBuilder.Add <Article>();
            resourceGraphBuilder.Add <Person>();
            resourceGraphBuilder.Add <Blog>();
            resourceGraphBuilder.Add <Food>();
            resourceGraphBuilder.Add <Song>();

            return(resourceGraphBuilder.Build());
        }
        public void When_model_has_no_parameterless_contructor_it_must_fail()
        {
            // Arrange
            var graph = new ResourceGraphBuilder(new JsonApiOptions()).AddResource <ResourceWithParameters>().Build();

            var serializer = new RequestDeserializer(graph, new TargetedFields());

            var body = new
            {
                data = new
                {
                    id   = "1",
                    type = "resourceWithParameters"
                }
            };
            string content = Newtonsoft.Json.JsonConvert.SerializeObject(body);

            // Act
            Action action = () => serializer.Deserialize(content);

            // Assert
            var exception = Assert.Throws <InvalidOperationException>(action);

            Assert.Equal("Failed to create an instance of 'UnitTests.Models.ConstructionTests+ResourceWithParameters' using its default constructor.", exception.Message);
        }
예제 #3
0
        CreateTestObjects <TPrimary, TSecondary>(
            IHooksDiscovery <TPrimary> primaryDiscovery          = null,
            IHooksDiscovery <TSecondary> secondaryDiscovery      = null,
            DbContextOptions <AppDbContext> repoDbContextOptions = null
            )
            where TPrimary : class, IIdentifiable <int>
            where TSecondary : class, IIdentifiable <int>
        {
            // creates the resource definition mock and corresponding for a given set of discoverable hooks
            var primaryResource   = CreateResourceDefinition <TPrimary>();
            var secondaryResource = CreateResourceDefinition <TSecondary>();

            // mocking the genericServiceFactory and JsonApiContext and wiring them up.
            var(ufMock, constraintsMock, gpfMock, options) = CreateMocks();

            var dbContext = repoDbContextOptions != null ? new AppDbContext(repoDbContextOptions) : null;

            var resourceGraph = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance)
                                .Add <TPrimary>()
                                .Add <TSecondary>()
                                .Build();

            SetupProcessorFactoryForResourceDefinition(gpfMock, primaryResource.Object, primaryDiscovery, dbContext, resourceGraph);
            SetupProcessorFactoryForResourceDefinition(gpfMock, secondaryResource.Object, secondaryDiscovery, dbContext, resourceGraph);

            var execHelper      = new HookExecutorHelper(gpfMock.Object, ResourceGraph, options);
            var traversalHelper = new TraversalHelper(ResourceGraph, ufMock.Object);
            var hookExecutor    = new ResourceHookExecutor(execHelper, traversalHelper, ufMock.Object, constraintsMock.Object, ResourceGraph);

            return(constraintsMock, ufMock, hookExecutor, primaryResource, secondaryResource);
        }
예제 #4
0
        protected HooksDummyData()
        {
            ResourceGraph = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance).Add <TodoItem>().Add <Person>().Add <Passport>()
                            .Add <Article>().Add <IdentifiableArticleTag>().Add <Tag>().Build();

            // @formatter:wrap_chained_method_calls chop_always
            // @formatter:keep_existing_linebreaks true

            TodoFaker = new Faker <TodoItem>()
                        .RuleFor(todoItem => todoItem.Id, faker => faker.UniqueIndex + 1);

            PersonFaker = new Faker <Person>()
                          .RuleFor(person => person.Id, faker => faker.UniqueIndex + 1);

            ArticleFaker = new Faker <Article>()
                           .RuleFor(article => article.Id, faker => faker.UniqueIndex + 1);

            TagFaker = new Faker <Tag>()
                       .RuleFor(tag => tag.Id, faker => faker.UniqueIndex + 1);

            ArticleTagFaker = new Faker <ArticleTag>();

            _identifiableArticleTagFaker = new Faker <IdentifiableArticleTag>()
                                           .RuleFor(identifiableArticleTag => identifiableArticleTag.Id, faker => faker.UniqueIndex + 1);

            PassportFaker = new Faker <Passport>()
                            .RuleFor(passport => passport.Id, faker => faker.UniqueIndex + 1);

            // @formatter:wrap_chained_method_calls restore
            // @formatter:keep_existing_linebreaks restore
        }
        protected BaseParseTests()
        {
            Options = new JsonApiOptions();

            // @formatter:wrap_chained_method_calls chop_always
            // @formatter:keep_existing_linebreaks true

            ResourceGraph = new ResourceGraphBuilder(Options, NullLoggerFactory.Instance)
                            .Add <Blog>()
                            .Add <BlogPost>()
                            .Add <Label>()
                            .Add <Comment>()
                            .Add <WebAccount>()
                            .Add <AccountPreferences>()
                            .Build();

            // @formatter:wrap_chained_method_calls restore
            // @formatter:keep_existing_linebreaks restore

            Request = new JsonApiRequest
            {
                PrimaryResource = ResourceGraph.GetResourceContext <Blog>(),
                IsCollection    = true
            };
        }
예제 #6
0
        public static IResourceGraph CreateResourceGraph(IJsonApiOptions options)
        {
            ResourceGraphBuilder builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);

            builder.Add <BenchmarkResource>(BenchmarkResourcePublicNames.Type);
            return(builder.Build());
        }
예제 #7
0
        protected IResourceGraph BuildGraph()
        {
            var resourceGraphBuilder = new ResourceGraphBuilder();

            resourceGraphBuilder.AddResource <TestResource>("testResource");
            resourceGraphBuilder.AddResource <TestResourceWithList>("testResource-with-list");
            // one to one relationships
            resourceGraphBuilder.AddResource <OneToOnePrincipal>("oneToOnePrincipals");
            resourceGraphBuilder.AddResource <OneToOneDependent>("oneToOneDependents");
            resourceGraphBuilder.AddResource <OneToOneRequiredDependent>("oneToOneRequiredDependents");
            // one to many relationships
            resourceGraphBuilder.AddResource <OneToManyPrincipal>("oneToManyPrincipals");
            resourceGraphBuilder.AddResource <OneToManyDependent>("oneToManyDependents");
            resourceGraphBuilder.AddResource <OneToManyRequiredDependent>("oneToMany-requiredDependents");
            // collective relationships
            resourceGraphBuilder.AddResource <MultipleRelationshipsPrincipalPart>("multiPrincipals");
            resourceGraphBuilder.AddResource <MultipleRelationshipsDependentPart>("multiDependents");

            resourceGraphBuilder.AddResource <Article>();
            resourceGraphBuilder.AddResource <Person>();
            resourceGraphBuilder.AddResource <Blog>();
            resourceGraphBuilder.AddResource <Food>();
            resourceGraphBuilder.AddResource <Song>();

            return(resourceGraphBuilder.Build());
        }
예제 #8
0
        protected TestObjectsC <TPrimary, TFirstSecondary, TSecondSecondary> CreateTestObjectsC <TPrimary, TFirstSecondary, TSecondSecondary>(
            IHooksDiscovery <TPrimary> primaryDiscovery = null, IHooksDiscovery <TFirstSecondary> firstSecondaryDiscovery            = null,
            IHooksDiscovery <TSecondSecondary> secondSecondaryDiscovery = null, DbContextOptions <AppDbContext> repoDbContextOptions = null)
            where TPrimary : class, IIdentifiable <int>
            where TFirstSecondary : class, IIdentifiable <int>
            where TSecondSecondary : class, IIdentifiable <int>
        {
            // creates the resource definition mock and corresponding for a given set of discoverable hooks
            Mock <IResourceHookContainer <TPrimary> >         primaryResource         = CreateResourceDefinition <TPrimary>();
            Mock <IResourceHookContainer <TFirstSecondary> >  firstSecondaryResource  = CreateResourceDefinition <TFirstSecondary>();
            Mock <IResourceHookContainer <TSecondSecondary> > secondSecondaryResource = CreateResourceDefinition <TSecondSecondary>();

            // mocking the genericServiceFactory and JsonApiContext and wiring them up.
            (Mock <ITargetedFields> ufMock, Mock <IEnumerable <IQueryConstraintProvider> > constraintsMock, Mock <IGenericServiceFactory> gpfMock,
             IJsonApiOptions options) = CreateMocks();

            AppDbContext dbContext = repoDbContextOptions != null ? new AppDbContext(repoDbContextOptions) : null;

            IResourceGraph resourceGraph = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance).Add <TPrimary>().Add <TFirstSecondary>()
                                           .Add <TSecondSecondary>().Build();

            SetupProcessorFactoryForResourceDefinition(gpfMock, primaryResource.Object, primaryDiscovery, dbContext, resourceGraph);
            SetupProcessorFactoryForResourceDefinition(gpfMock, firstSecondaryResource.Object, firstSecondaryDiscovery, dbContext, resourceGraph);
            SetupProcessorFactoryForResourceDefinition(gpfMock, secondSecondaryResource.Object, secondSecondaryDiscovery, dbContext, resourceGraph);

            var execHelper      = new HookContainerProvider(gpfMock.Object, ResourceGraph, options);
            var traversalHelper = new NodeNavigator(ResourceGraph, ufMock.Object);
            var hookExecutor    = new ResourceHookExecutor(execHelper, traversalHelper, ufMock.Object, constraintsMock.Object, ResourceGraph);

            return(new TestObjectsC <TPrimary, TFirstSecondary, TSecondSecondary>(constraintsMock, hookExecutor, primaryResource, firstSecondaryResource,
                                                                                  secondSecondaryResource));
        }
        public void When_resource_has_constructor_with_injectable_parameter_it_must_succeed()
        {
            // Arrange
            var graph = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance)
                        .AddResource <ResourceWithDbContextConstructor>()
                        .Build();

            var appDbContext = new AppDbContext(new DbContextOptionsBuilder <AppDbContext>().Options, new FrozenSystemClock());

            var serviceContainer = new ServiceContainer();

            serviceContainer.AddService(typeof(AppDbContext), appDbContext);

            var serializer = new RequestDeserializer(graph, new DefaultResourceFactory(serviceContainer), new TargetedFields());

            var body = new
            {
                data = new
                {
                    id   = "1",
                    type = "resourceWithDbContextConstructors"
                }
            };

            string content = JsonConvert.SerializeObject(body);

            // Act
            object result = serializer.Deserialize(content);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(typeof(ResourceWithDbContextConstructor), result.GetType());
            Assert.Equal(appDbContext, ((ResourceWithDbContextConstructor)result).AppDbContext);
        }
        public static IResourceGraph CreateResourceGraph()
        {
            IResourceGraphBuilder builder = new ResourceGraphBuilder();

            builder.AddResource <BenchmarkResource>(BenchmarkResourcePublicNames.Type);
            return(builder.Build());
        }
        public void When_resource_has_default_constructor_it_must_succeed()
        {
            // Arrange
            var graph = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance)
                        .AddResource <ResourceWithoutConstructor>()
                        .Build();

            var serializer = new RequestDeserializer(graph, new DefaultResourceFactory(new ServiceContainer()), new TargetedFields());

            var body = new
            {
                data = new
                {
                    id   = "1",
                    type = "resourceWithoutConstructors"
                }
            };

            string content = JsonConvert.SerializeObject(body);

            // Act
            object result = serializer.Deserialize(content);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(typeof(ResourceWithoutConstructor), result.GetType());
        }
        public void When_resource_has_default_constructor_that_throws_it_must_fail()
        {
            // Arrange
            var graph = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance)
                        .AddResource <ResourceWithThrowingConstructor>()
                        .Build();

            var serializer = new RequestDeserializer(graph, new DefaultResourceFactory(new ServiceContainer()), new TargetedFields());

            var body = new
            {
                data = new
                {
                    id   = "1",
                    type = "resourceWithThrowingConstructors"
                }
            };

            string content = JsonConvert.SerializeObject(body);

            // Act
            Action action = () => serializer.Deserialize(content);

            // Assert
            var exception = Assert.Throws <InvalidOperationException>(action);

            Assert.Equal(
                "Failed to create an instance of 'UnitTests.Models.ResourceWithThrowingConstructor' using its default constructor.",
                exception.Message);
        }
예제 #13
0
        public void When_resource_has_default_constructor_it_must_succeed()
        {
            // Arrange
            var options = new JsonApiOptions();

            IResourceGraph graph = new ResourceGraphBuilder(options, NullLoggerFactory.Instance).Add <ResourceWithoutConstructor>().Build();

            var serviceContainer = new ServiceContainer();

            serviceContainer.AddService(typeof(IResourceDefinitionAccessor), new NeverResourceDefinitionAccessor());

            var serializer = new RequestDeserializer(graph, new ResourceFactory(serviceContainer), new TargetedFields(), _mockHttpContextAccessor.Object,
                                                     _requestMock.Object, options);

            var body = new
            {
                data = new
                {
                    id   = "1",
                    type = "resourceWithoutConstructors"
                }
            };

            string content = JsonConvert.SerializeObject(body);

            // Act
            object result = serializer.Deserialize(content);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(typeof(ResourceWithoutConstructor), result.GetType());
        }
예제 #14
0
        public void When_resource_has_constructor_with_string_parameter_it_must_fail()
        {
            // Arrange
            var options = new JsonApiOptions();

            IResourceGraph graph = new ResourceGraphBuilder(options, NullLoggerFactory.Instance).Add <ResourceWithStringConstructor>().Build();

            var serviceContainer = new ServiceContainer();

            serviceContainer.AddService(typeof(IResourceDefinitionAccessor), new NeverResourceDefinitionAccessor());

            var serializer = new RequestDeserializer(graph, new ResourceFactory(serviceContainer), new TargetedFields(), _mockHttpContextAccessor.Object,
                                                     _requestMock.Object, options);

            var body = new
            {
                data = new
                {
                    id   = "1",
                    type = "resourceWithStringConstructors"
                }
            };

            string content = JsonConvert.SerializeObject(body);

            // Act
            Action action = () => serializer.Deserialize(content);

            // Assert
            var exception = Assert.Throws <InvalidOperationException>(action);

            Assert.Equal("Failed to create an instance of 'UnitTests.Models.ResourceWithStringConstructor' using injected constructor parameters.",
                         exception.Message);
        }
예제 #15
0
        public ServiceDiscoveryFacadeTests()
        {
            var options = new JsonApiOptions();

            var dbResolverMock = new Mock <IDbContextResolver>();

            dbResolverMock.Setup(m => m.GetContext()).Returns(new Mock <DbContext>().Object);
            TestModelRepository._dbContextResolver = dbResolverMock.Object;

            _services.AddSingleton <IJsonApiOptions>(options);
            _services.AddSingleton <ILoggerFactory>(new LoggerFactory());
            _services.AddScoped(_ => new Mock <ILinkBuilder>().Object);
            _services.AddScoped(_ => new Mock <IJsonApiRequest>().Object);
            _services.AddScoped(_ => new Mock <ITargetedFields>().Object);
            _services.AddScoped(_ => new Mock <IResourceGraph>().Object);
            _services.AddScoped(_ => new Mock <IGenericServiceFactory>().Object);
            _services.AddScoped(_ => new Mock <IResourceContextProvider>().Object);
            _services.AddScoped(typeof(IResourceChangeTracker <>), typeof(ResourceChangeTracker <>));
            _services.AddScoped(_ => new Mock <IResourceFactory>().Object);
            _services.AddScoped(_ => new Mock <IPaginationContext>().Object);
            _services.AddScoped(_ => new Mock <IQueryLayerComposer>().Object);
            _services.AddTransient(_ => new Mock <IResourceDefinitionProvider>().Object);

            _resourceGraphBuilder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
        }
예제 #16
0
        public IResponseDeserializer GetDeserializer()
        {
            var options = GetService <IJsonApiOptions>();

            var resourceGraph = new ResourceGraphBuilder(options).AddResource <TodoItem>("todoItems").Build();

            return(new ResponseDeserializer(resourceGraph));
        }
        public void Can_Deserialize_Object_With_HasManyRelationship()
        {
            // arrange
            var resourceGraphBuilder = new ResourceGraphBuilder();

            resourceGraphBuilder.AddResource <OneToManyIndependent>("independents");
            resourceGraphBuilder.AddResource <OneToManyDependent>("dependents");
            var resourceGraph = resourceGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ResourceGraph).Returns(resourceGraph);
            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());

            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);
        }
예제 #18
0
        private (DefaultResourceRepository <TodoItem> Repository, Mock <ITargetedFields> TargetedFields) Setup(AppDbContext context)
        {
            var contextResolverMock = new Mock <IDbContextResolver>();

            contextResolverMock.Setup(m => m.GetContext()).Returns(context);
            var resourceGraph  = new ResourceGraphBuilder().AddResource <TodoItem>().Build();
            var targetedFields = new Mock <ITargetedFields>();
            var repository     = new DefaultResourceRepository <TodoItem>(targetedFields.Object, contextResolverMock.Object, resourceGraph, null);

            return(repository, targetedFields);
        }
        public void Can_Deserialize_Independent_Side_Of_One_To_One_Relationship_With_Relationship_Body()
        {
            // arrange
            var resourceGraphBuilder = new ResourceGraphBuilder();

            resourceGraphBuilder.AddResource <Independent>("independents");
            resourceGraphBuilder.AddResource <Dependent>("dependents");
            var resourceGraph = resourceGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ResourceGraph).Returns(resourceGraph);
            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 ResourceObject {
                    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);
        }
        public void Immutable_Attrs_Are_Not_Included_In_AttributesToUpdate()
        {
            // arrange
            var resourceGraphBuilder = new ResourceGraphBuilder();

            resourceGraphBuilder.AddResource <TestResource>("test-resource");
            var resourceGraph = resourceGraphBuilder.Build();

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

            var jsonApiContextMock = new Mock <IJsonApiContext>();

            jsonApiContextMock.SetupAllProperties();
            jsonApiContextMock.Setup(m => m.ResourceGraph).Returns(resourceGraph);
            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 ResourceObject {
                    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);
            }
        }
예제 #21
0
        public QueryParametersUnitTestCollection()
        {
            var builder = new ResourceGraphBuilder();

            builder.AddResource <Article>();
            builder.AddResource <Person>();
            builder.AddResource <Blog>();
            builder.AddResource <Food>();
            builder.AddResource <Song>();
            _resourceGraph          = builder.Build();
            _articleResourceContext = _resourceGraph.GetResourceContext <Article>();
        }
예제 #22
0
        public void AddDbContext_Does_Not_Throw_If_Context_Contains_Members_That_DoNot_Implement_IIdentifiable()
        {
            // Arrange
            var resourceGraphBuilder = new ResourceGraphBuilder();

            // Act
            resourceGraphBuilder.AddDbContext <TestContext>();
            var resourceGraph = resourceGraphBuilder.Build() as ResourceGraph;

            // Assert
            Assert.Empty(resourceGraph.GetResourceContexts());
        }
예제 #23
0
        public QueryParametersUnitTestCollection()
        {
            var builder = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance);

            builder.AddResource <Article>();
            builder.AddResource <Person>();
            builder.AddResource <Blog>();
            builder.AddResource <Food>();
            builder.AddResource <Song>();
            _resourceGraph          = builder.Build();
            _articleResourceContext = _resourceGraph.GetResourceContext <Article>();
        }
        public void AddDbContext_Does_Not_Throw_If_Context_Contains_Members_That_Do_Not_Implement_IIdentifiable()
        {
            // Arrange
            var resourceGraphBuilder = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance);

            // Act
            resourceGraphBuilder.AddResource(typeof(TestContext));
            var resourceGraph = (ResourceGraph)resourceGraphBuilder.Build();

            // Assert
            Assert.Empty(resourceGraph.GetResourceContexts());
        }
        public void Sets_The_DocumentMeta_Property_In_JsonApiContext()
        {
            // arrange
            var resourceGraphBuilder = new ResourceGraphBuilder();

            resourceGraphBuilder.AddResource <Independent>("independents");
            resourceGraphBuilder.AddResource <Dependent>("dependents");
            var resourceGraph = resourceGraphBuilder.Build();

            var jsonApiContextMock = new Mock <IJsonApiContext>();

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

            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
            {
                Meta = new Dictionary <string, object>()
                {
                    { "foo", "bar" }
                },
                Data = new ResourceObject {
                    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);
        }
        private (DefaultResourceRepository <TodoItem> Repository, Mock <ITargetedFields> TargetedFields) Setup(AppDbContext context)
        {
            var serviceProvider     = ((IInfrastructure <IServiceProvider>)context).Instance;
            var resourceFactory     = new DefaultResourceFactory(serviceProvider);
            var contextResolverMock = new Mock <IDbContextResolver>();

            contextResolverMock.Setup(m => m.GetContext()).Returns(context);
            var resourceGraph  = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance).AddResource <TodoItem>().Build();
            var targetedFields = new Mock <ITargetedFields>();
            var repository     = new DefaultResourceRepository <TodoItem>(targetedFields.Object, contextResolverMock.Object, resourceGraph, null, resourceFactory, NullLoggerFactory.Instance);

            return(repository, targetedFields);
        }
예제 #27
0
        public void Adding_DbContext_Members_That_DoNot_Implement_IIdentifiable_Creates_Warning()
        {
            // Arrange
            var resourceGraphBuilder = new ResourceGraphBuilder();

            // Act
            resourceGraphBuilder.AddDbContext <TestContext>();
            var resourceGraph = resourceGraphBuilder.Build() as ResourceGraph;

            // Assert
            Assert.Single(resourceGraph.ValidationResults);
            Assert.Contains(resourceGraph.ValidationResults, v => v.LogLevel == LogLevel.Warning);
        }
예제 #28
0
        public async Task CreateResource_EntityTypeMismatch_IsConflict()
        {
            // Arrange
            var serializer    = GetSerializer <TodoItemCollection>(e => new { }, e => new { e.Owner });
            var resourceGraph = new ResourceGraphBuilder().AddResource <TodoItemClient>("todoItems").AddResource <Person>().AddResource <TodoItemCollectionClient, Guid>().Build();
            var _deserializer = new ResponseDeserializer(resourceGraph);
            var content       = serializer.Serialize(_todoItemFaker.Generate()).Replace("todoItems", "people");

            // Act
            var(body, response) = await Post("/api/v1/todoItems", content);

            // Assert
            AssertEqualStatusCode(HttpStatusCode.Conflict, response);
        }
        private (EntityFrameworkCoreRepository <TodoItem> Repository, Mock <ITargetedFields> TargetedFields, IResourceGraph resourceGraph) Setup(AppDbContext context)
        {
            var serviceProvider     = ((IInfrastructure <IServiceProvider>)context).Instance;
            var resourceFactory     = new ResourceFactory(serviceProvider);
            var contextResolverMock = new Mock <IDbContextResolver>();

            contextResolverMock.Setup(m => m.GetContext()).Returns(context);
            var resourceGraph  = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance).Add <TodoItem>().Build();
            var targetedFields = new Mock <ITargetedFields>();
            var serviceFactory = new Mock <IGenericServiceFactory>().Object;
            var repository     = new EntityFrameworkCoreRepository <TodoItem>(targetedFields.Object, contextResolverMock.Object, resourceGraph, serviceFactory, resourceFactory, new List <IQueryConstraintProvider>(), NullLoggerFactory.Instance);

            return(repository, targetedFields, resourceGraph);
        }
        public void GetResourceContext_Yields_Right_Type_For_Identifiable()
        {
            // Arrange
            var resourceGraphBuilder = new ResourceGraphBuilder(new JsonApiOptions(), NullLoggerFactory.Instance);

            resourceGraphBuilder.AddResource <Bar>();
            var resourceGraph = (ResourceGraph)resourceGraphBuilder.Build();

            // Act
            var result = resourceGraph.GetResourceContext(typeof(Bar));

            // Assert
            Assert.Equal(typeof(Bar), result.ResourceType);
        }