示例#1
0
        public static void SeedDatabase(CmdDbContext context)
        {
            var actorMovieCollection       = ModelMocks.GetActorMovieCollection();
            var actorsWithEmptyFilmography = ModelMocks.GetActorsWithEmptyFilmography();

            context.AddRange(actorMovieCollection);
            context.AddRange(actorsWithEmptyFilmography);

            context.SaveChanges();
        }
        public async void Search_200_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (request, umbCtx, typedContent, serviceContext, searchProvider) =>
            {
                var mockSearchResults = new Mock <ISearchResults>();
                mockSearchResults.Setup(results => results.TotalItemCount).Returns(10);
                mockSearchResults.Setup(results => results.Skip(It.IsAny <int>())).Returns(new[]
                {
                    new SearchResult()
                    {
                        Id = 789
                    },
                    new SearchResult()
                    {
                        Id = 456
                    },
                });

                var mockSearchProvider = Mock.Get(searchProvider);
                mockSearchProvider.Setup(x => x.CreateSearchCriteria()).Returns(Mock.Of <ISearchCriteria>());
                mockSearchProvider.Setup(x => x.Search(It.IsAny <ISearchCriteria>(), It.IsAny <int>()))
                .Returns(mockSearchResults.Object);

                var mockMediaService = Mock.Get(serviceContext.MediaService);
                mockMediaService.Setup(x => x.GetByIds(It.IsAny <IEnumerable <int> >()))
                .Returns(new[]
                {
                    ModelMocks.SimpleMockedMedia(789),
                    ModelMocks.SimpleMockedMedia(456)
                });
            });

            using (var server = TestServer.Create(builder => startup.Configuration(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}/search?lucene=parentID:\\-1", RouteConstants.MediaSegment)),
                    Method     = HttpMethod.Get,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            }
        }
        public AddressServiceTests()
        {
            _dbMock     = new Mock <FestispecContext>();
            _modelMocks = new ModelMocks();
            _dbMock.Setup(x => x.Customers).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Customers).Object);
            _dbMock.Setup(x => x.Addresses).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Addresses).Object);
            _dbMock.Setup(x => x.Festivals).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Festivals).Object);
            _dbMock.Setup(x => x.Employees).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Employees).Object);

            _addressService = new AddressService(_dbMock.Object);
        }
示例#4
0
        public async Task Get_Children_Is_200_With_Params_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (testServices) =>
            {
                MockServicesForAuthorizationSuccess(testServices, 123);

                var mockMediaService = Mock.Get(testServices.ServiceContext.MediaService);

                mockMediaService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedMedia());

                long total = 6;
                mockMediaService.Setup(x => x.GetPagedChildren(It.IsAny <int>(), It.IsAny <long>(), It.IsAny <int>(), out total, It.IsAny <string>(), Direction.Ascending, It.IsAny <string>()))
                .Returns(new List <IMedia>(new[]
                {
                    ModelMocks.SimpleMockedMedia(789),
                    ModelMocks.SimpleMockedMedia(456)
                }));

                mockMediaService.Setup(x => x.HasChildren(It.IsAny <int>())).Returns(true);
            });

            using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri($"http://testserver/umbraco/rest/v1/{RouteConstants.MediaSegment}/123/children?page=2&size=2"),
                    Method     = HttpMethod.Get,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

                var djson = JsonConvert.DeserializeObject <JObject>(json);

                Assert.AreEqual(6, djson["totalResults"].Value <int>());
                Assert.AreEqual(2, djson["page"].Value <int>());
                Assert.AreEqual(2, djson["pageSize"].Value <int>());
                Assert.IsNotNull(djson["_links"]["next"]);
                Assert.IsNotNull(djson["_links"]["prev"]);
            }
        }
示例#5
0
        public SicknessServiceTests()
        {
            _dbMock = new Mock <FestispecContext>();
            var modelMocks = new ModelMocks();

            _dbMock.Setup(x => x.Employees).Returns(MockHelpers.CreateDbSetMock(modelMocks.Employees).Object);
            _dbMock.Setup(x => x.Availabilities)
            .Returns(MockHelpers.CreateDbSetMock(modelMocks.Availabilities).Object);
            _dbMock.Setup(x => x.PlannedEvents).Returns(MockHelpers.CreateDbSetMock(modelMocks.PlannedEvents).Object);
            _dbMock.Setup(m => m.SaveChangesAsync()).ReturnsAsync(1);

            _sicknessService = new SicknessService(_dbMock.Object);
        }
示例#6
0
        public async Task Get_Root_Result_With_Custom_Start_Nodes()
        {
            //represents the node(s) that the user will receive as their root based on their custom start node
            var rootNodes = ModelMocks.SimpleMockedContent(123, 456);

            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services,
                (testServices) =>
            {
                MockServicesForAuthorizationSuccess(testServices, 456);

                var mockContentService = Mock.Get(testServices.ServiceContext.ContentService);
                mockContentService.Setup(x => x.GetByIds(It.IsAny <int[]>())).Returns(new[]
                {
                    rootNodes
                });

                mockContentService.Setup(x => x.GetChildren(123)).Returns(new[] { ModelMocks.SimpleMockedContent(789, 123) });
                mockContentService.Setup(x => x.GetChildren(456)).Returns(new[] { ModelMocks.SimpleMockedContent(321, 456) });
            });

            var djson = await Get_Root_Result(app =>
            {
                //we are doing a custom authz for this call so need to change the startup process

                var identity = new UmbracoBackOfficeIdentity(
                    new UserData(Guid.NewGuid().ToString())
                {
                    Id    = 0,
                    Roles = new[] { "admin" },
                    AllowedApplications = new[] { "content", "media", "members" },
                    Culture             = "en-US",
                    RealName            = "Admin",
                    StartContentNodes   = new[] { 456 },
                    StartMediaNodes     = new[] { -1 },
                    Username            = "******",
                    SessionId           = Guid.NewGuid().ToString(),
                    SecurityStamp       = Guid.NewGuid().ToString()
                });

                var httpConfig = startup.UseTestWebApiConfiguration(app);
                app.AuthenticateEverything(new AuthenticateEverythingAuthenticationOptions(identity));
                app.UseUmbracoRestApi(startup.ApplicationContext);
                app.UseWebApi(httpConfig);
            }, RouteConstants.ContentSegment);

            Assert.AreEqual(1, djson["_links"]["content"].Count());
            Assert.AreEqual($"/umbraco/rest/v1/content/{123.ToGuid()}", djson["_links"]["content"]["href"].Value <string>());
            Assert.AreEqual(1, djson["_embedded"]["content"].Count());
            Assert.AreEqual(rootNodes.Key, (Guid)djson["_embedded"]["content"].First["id"]);
        }
        public async Task Get_By_Key_Result()
        {
            var guidId  = Guid.NewGuid();
            var content = ModelMocks.SimpleMockedPublishedContent(guidId, 456, 789);

            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (testServices) =>
            {
                var mockTypedContent = Mock.Get(testServices.PublishedContentQuery);
                mockTypedContent.Setup(x => x.TypedContent(It.IsAny <Guid>())).Returns(() => content);
            });

            using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri($"http://testserver/umbraco/rest/v1/{RouteConstants.ContentSegment}/{RouteConstants.PublishedSegment}/{guidId}"),
                    Method     = HttpMethod.Get,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

                Assert.AreEqual("application/hal+json", result.Content.Headers.ContentType.MediaType);
                Assert.IsAssignableFrom <StreamContent>(result.Content);

                //TODO: Need to assert more values!

                var djson = JsonConvert.DeserializeObject <JObject>(json);

                Assert.AreEqual($"/umbraco/rest/v1/content/published/{content.Key}", djson["_links"]["self"]["href"].Value <string>());
                Assert.AreEqual($"/umbraco/rest/v1/content/published/{456.ToGuid()}", djson["_links"]["parent"]["href"].Value <string>());
                Assert.AreEqual($"/umbraco/rest/v1/content/published/{content.Key}/children{{?page,size,query}}", djson["_links"]["children"]["href"].Value <string>());
                Assert.AreEqual("/umbraco/rest/v1/content/published", djson["_links"]["root"]["href"].Value <string>());

                var properties = djson["properties"].ToObject <IDictionary <string, object> >();
                Assert.AreEqual(2, properties.Count());
                Assert.IsTrue(properties.ContainsKey("TestProperty1"));
                Assert.IsTrue(properties.ContainsKey("testProperty2"));
            }
        }
        /// <summary>
        /// Sets up the services to return the correct data based on the Authorization logic for the non-published content controller
        /// </summary>
        /// <param name="testServices"></param>
        /// <param name="contentIds"></param>
        /// <remarks>
        /// Much of this is based on the call to Umbraco Core's ContentController.CheckPermissions which performs quite a few checks.
        /// Ideally we'd move this authorization logic to an interface so we can mock it instead.
        /// </remarks>
        private void MockServicesForAuthorizationSuccess(TestServices testServices, params int[] contentIds)
        {
            foreach (var contentId in contentIds)
            {
                Mock.Get(testServices.ServiceContext.ContentService)
                .Setup(x => x.GetById(contentId))
                .Returns(ModelMocks.SimpleMockedContent(contentId));

                Mock.Get(testServices.ServiceContext.UserService)
                .Setup(x => x.GetPermissionsForPath(It.IsAny <IUser>(), It.IsAny <string>()))
                .Returns(() =>
                         new EntityPermissionSet(contentId, new EntityPermissionCollection(new[]
                {
                    new EntityPermission(1, contentId, new[]
                    {
                        ActionBrowse.Instance.Letter.ToString(),
                        ActionNew.Instance.Letter.ToString(),
                        ActionUpdate.Instance.Letter.ToString(),
                        ActionPublish.Instance.Letter.ToString(),
                        ActionDelete.Instance.Letter.ToString(),
                    })
                })));

                Mock.Get(testServices.ServiceContext.UserService)
                .Setup(x => x.GetPermissions(It.IsAny <IUser>(), new[] { contentId }))
                .Returns(() =>
                         new EntityPermissionCollection(new[]
                {
                    new EntityPermission(1, contentId, new[]
                    {
                        ActionBrowse.Instance.Letter.ToString(),
                        ActionNew.Instance.Letter.ToString(),
                        ActionUpdate.Instance.Letter.ToString(),
                        ActionPublish.Instance.Letter.ToString(),
                        ActionDelete.Instance.Letter.ToString(),
                    })
                }));
            }

            Mock.Get(testServices.ServiceContext.EntityService)
            .Setup(x => x.GetAllPaths(UmbracoObjectTypes.Document, It.IsAny <int[]>()))
            .Returns((UmbracoObjectTypes objType, int[] ids) =>
            {
                return(ids.Select(i => new EntityPath
                {
                    Id = i,
                    Path = i == Constants.System.Root ? "-1" : string.Concat("-1,", i)
                }));
            });
        }
示例#9
0
        public AvailabilityServiceTests()
        {
            // Setup database mocks
            _dbMock     = new Mock <FestispecContext>();
            _modelMocks = new ModelMocks();

            _dbMock.Setup(x => x.Employees).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Employees).Object);

            _dbMock.Setup(x => x.Availabilities).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Availabilities).Object);

            _dbMock.Setup(x => x.PlannedEvents).Returns(MockHelpers.CreateDbSetMock(_modelMocks.PlannedEvents).Object);

            _dbMock.Setup(m => m.SaveChangesAsync()).ReturnsAsync(1);

            _availabilityService = new AvailabilityService(_dbMock.Object);
        }
        public EmployeeServiceTests()
        {
            _dbMock     = new Mock <FestispecContext>();
            _modelMocks = new ModelMocks();
            _dbMock.Setup(x => x.Employees).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Employees).Object);
            _dbMock.Setup(x => x.Accounts).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Accounts).Object);
            _dbMock.Setup(x => x.Certificates).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Certificates).Object);
            _dbMock.Setup(x => x.Addresses).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Addresses).Object);
            _dbMock.Setup(x => x.Festivals).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Festivals).Object);
            _dbMock.Setup(x => x.Customers).Returns(MockHelpers.CreateDbSetMock(_modelMocks.Customers).Object);

            _employeeService = new EmployeeService(_dbMock.Object,
                                                   new Mock <AuthenticationService>(_dbMock.Object, new JsonSyncService <Account>(_dbMock.Object)).Object,
                                                   new JsonSyncService <Employee>(_dbMock.Object),
                                                   new AddressService(_dbMock.Object));
        }
        public async void Get_Root_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services,
                (request, umbCtx, typedContent, serviceContext, searchProvider) =>
            {
                var mockMediaService = Mock.Get(serviceContext.MediaService);
                mockMediaService.Setup(x => x.GetRootMedia()).Returns(new[]
                {
                    ModelMocks.SimpleMockedMedia(123, -1),
                    ModelMocks.SimpleMockedMedia(456, -1)
                });

                mockMediaService.Setup(x => x.GetChildren(123)).Returns(new[] { ModelMocks.SimpleMockedMedia(789, 123) });
                mockMediaService.Setup(x => x.GetChildren(456)).Returns(new[] { ModelMocks.SimpleMockedMedia(321, 456) });
            });

            using (var server = TestServer.Create(builder => startup.Configuration(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}", RouteConstants.MediaSegment)),
                    Method     = HttpMethod.Get,
                };
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));
                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

                var asdf = GlobalConfiguration.Configuration;

                var djson = JsonConvert.DeserializeObject <JObject>(json);

                Assert.AreEqual("/umbraco/rest/v1/media", djson["_links"]["root"]["href"].Value <string>());
                Assert.AreEqual(2, djson["totalResults"].Value <int>());
                Assert.AreEqual(2, djson["_links"]["content"].Count());
                Assert.AreEqual(2, djson["_embedded"]["content"].Count());
            }
        }
示例#12
0
        private void SetupMocksForPost(ServiceContext serviceContext)
        {
            var mockRelationService = Mock.Get(serviceContext.RelationService);

            mockRelationService.Setup(x => x.GetRelationTypeByAlias(It.IsAny <string>())).Returns(() => ModelMocks.SimpleMockedRelationType());
            mockRelationService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedRelation(1234, 567, 8910));
            mockRelationService.Setup(x => x.Relate(It.IsAny <IUmbracoEntity>(), It.IsAny <IUmbracoEntity>(), It.IsAny <IRelationType>()))
            .Returns(() => ModelMocks.SimpleMockedRelation(1234, 567, 8910));

            var mockServiceProvider = new Mock <IServiceProvider>();

            mockServiceProvider.Setup(x => x.GetService(It.IsAny <Type>())).Returns(new ModelMocks.SimplePropertyEditor());

            Func <IEnumerable <Type> > producerList = Enumerable.Empty <Type>;
            var mockPropertyEditorResolver          = new Mock <PropertyEditorResolver>(
                Mock.Of <IServiceProvider>(),
                Mock.Of <ILogger>(),
                producerList);
        }
示例#13
0
        public async Task Get_Root_With_OPTIONS()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services,
                (testServices) =>
            {
                var mockMediaService = Mock.Get(testServices.ServiceContext.MediaService);
                mockMediaService.Setup(x => x.GetRootMedia()).Returns(new[]
                {
                    ModelMocks.SimpleMockedMedia(123, -1),
                    ModelMocks.SimpleMockedMedia(456, -1)
                });

                mockMediaService.Setup(x => x.GetChildren(123)).Returns(new[] { ModelMocks.SimpleMockedMedia(789, 123) });
                mockMediaService.Setup(x => x.GetChildren(456)).Returns(new[] { ModelMocks.SimpleMockedMedia(321, 456) });
            });

            await Get_Root_With_OPTIONS(startup.UseDefaultTestSetup, RouteConstants.MediaSegment);
        }
        public async void Get_Root_With_OPTIONS()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services,
                (request, umbCtx, typedContent, serviceContext, searchProvider) =>
            {
                var mockMediaService = Mock.Get(serviceContext.MediaService);
                mockMediaService.Setup(x => x.GetRootMedia()).Returns(new[]
                {
                    ModelMocks.SimpleMockedMedia(123, -1),
                    ModelMocks.SimpleMockedMedia(456, -1)
                });

                mockMediaService.Setup(x => x.GetChildren(123)).Returns(new[] { ModelMocks.SimpleMockedMedia(789, 123) });
                mockMediaService.Setup(x => x.GetChildren(456)).Returns(new[] { ModelMocks.SimpleMockedMedia(321, 456) });
            });

            using (var server = TestServer.Create(builder => startup.Configuration(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}", RouteConstants.MediaSegment)),
                    Method     = HttpMethod.Options,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));
                request.Headers.Add("Access-Control-Request-Headers", "accept, authorization");
                request.Headers.Add("Access-Control-Request-Method", "GET");
                request.Headers.Add("Origin", "http://localhost:12061");
                request.Headers.Add("Referer", "http://localhost:12061/browser.html");

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            }
        }
示例#15
0
        /// <summary>
        /// Sets up the services to return the correct data based on the Authorization logic for the non-published content controller
        /// </summary>
        /// <param name="testServices"></param>
        /// <param name="contentIds"></param>
        /// <remarks>
        /// Much of this is based on the call to Umbraco Core's ContentController.CheckPermissions which performs quite a few checks.
        /// Ideally we'd move this authorization logic to an interface so we can mock it instead.
        /// </remarks>
        private void MockServicesForAuthorizationSuccess(TestServices testServices, params int[] contentIds)
        {
            foreach (var contentId in contentIds)
            {
                Mock.Get(testServices.ServiceContext.MediaService)
                .Setup(x => x.GetById(contentId))
                .Returns(ModelMocks.SimpleMockedMedia(contentId));
            }

            Mock.Get(testServices.ServiceContext.EntityService)
            .Setup(x => x.GetAllPaths(UmbracoObjectTypes.Media, It.IsAny <int[]>()))
            .Returns((UmbracoObjectTypes objType, int[] ids) =>
            {
                return(ids.Select(i => new EntityPath
                {
                    Id = i,
                    Path = i == Constants.System.Root ? "-1" : string.Concat("-1,", i)
                }));
            });
        }
        public async Task Get_Root_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services,
                (testServices) =>
            {
                var mockTypedContent = Mock.Get(testServices.PublishedContentQuery);
                mockTypedContent.Setup(x => x.TypedContentAtRoot()).Returns(new[]
                {
                    ModelMocks.SimpleMockedPublishedContent(123, -1, 789),
                    ModelMocks.SimpleMockedPublishedContent(456, -1, 321)
                });
            });

            using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}/{1}", RouteConstants.ContentSegment, RouteConstants.PublishedSegment)),
                    Method     = HttpMethod.Get,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

                var djson = JsonConvert.DeserializeObject <JObject>(json);

                Assert.AreEqual("/umbraco/rest/v1/content/published", djson["_links"]["root"]["href"].Value <string>());
                Assert.AreEqual(2, djson["_links"]["content"].Count());
                Assert.AreEqual(2, djson["_embedded"]["content"].Count());
            }
        }
        public async Task Get_Root_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services,
                (testServices) =>
            {
                var mockMemberService = Mock.Get(testServices.ServiceContext.MemberService);
                var mockedOut         = 0;
                mockMemberService.Setup(x => x.GetAll(It.IsAny <int>(), 100, out mockedOut)).Returns(new[]
                {
                    ModelMocks.SimpleMockedMember(123, -1),
                    ModelMocks.SimpleMockedMember(456, -1)
                });
            });

            using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri($"http://testserver/umbraco/rest/v1/{RouteConstants.MembersSegment}"),
                    Method     = HttpMethod.Get,
                };
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));
                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

                var asdf = GlobalConfiguration.Configuration;

                var djson = JsonConvert.DeserializeObject <JObject>(json);

                Assert.AreEqual("/umbraco/rest/v1/members{?page,size,query,orderBy,direction,memberTypeAlias}", djson["_links"]["root"]["href"].Value <string>());
                Assert.AreEqual(0, djson["totalResults"].Value <int>());
            }
        }
示例#18
0
        public InspectionServiceTests()
        {
            // Setup database mock
            _dbMock     = new Mock <FestispecContext>();
            _modelMocks = new ModelMocks();
            // Setup add mock
            _dbMock.Setup(x => x.PlannedInspections.Add(It.IsAny <PlannedInspection>()))
            .Returns((PlannedInspection u) => u);

            // Mock accounts
            _dbMock.Setup(x => x.PlannedInspections)
            .Returns(MockHelpers.CreateDbSetMock(new ModelMocks().PlannedInspections).Object);
            _dbMock.Setup(x => x.Festivals).Returns(MockHelpers.CreateDbSetMock(new ModelMocks().Festivals).Object);
            _dbMock.Setup(x => x.Questionnaires)
            .Returns(MockHelpers.CreateDbSetMock(new ModelMocks().Questionnaires).Object);
            _dbMock.Setup(x => x.Employees).Returns(MockHelpers.CreateDbSetMock(new ModelMocks().Employees).Object);

            // Create InspectionService
            _inspectionService =
                new InspectionService(_dbMock.Object, new JsonSyncService <PlannedInspection>(_dbMock.Object));
        }
        public async Task Search_200_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (testServices) =>
            {
                var mockTypedContent = Mock.Get(testServices.PublishedContentQuery);
                mockTypedContent.Setup(x => x.TypedSearch(It.IsAny <ISearchCriteria>(), It.IsAny <BaseSearchProvider>()))
                .Returns(new[]
                {
                    ModelMocks.SimpleMockedPublishedContent(123, -1, 789),
                    ModelMocks.SimpleMockedPublishedContent(456, -1, 321)
                });

                var mockSearchProvider = Mock.Get(testServices.SearchProvider);
                mockSearchProvider.Setup(x => x.CreateSearchCriteria()).Returns(Mock.Of <ISearchCriteria>());
            });

            using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}/{1}/search?query=parentID:\\-1", RouteConstants.ContentSegment, RouteConstants.PublishedSegment)),
                    Method     = HttpMethod.Get,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            }
        }
        public async Task Get_Root_With_OPTIONS()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services,
                (testServices) =>
            {
                var mockTypedContent = Mock.Get(testServices.PublishedContentQuery);
                mockTypedContent.Setup(x => x.TypedContentAtRoot()).Returns(new[]
                {
                    ModelMocks.SimpleMockedPublishedContent(123, -1, 789),
                    ModelMocks.SimpleMockedPublishedContent(456, -1, 321)
                });
            });

            using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri($"http://testserver/umbraco/rest/v1/{RouteConstants.ContentSegment}/{RouteConstants.PublishedSegment}"),
                    Method     = HttpMethod.Get,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));
                request.Headers.Add("Access-Control-Request-Headers", "accept, authorization");
                request.Headers.Add("Access-Control-Request-Method", "GET");
                request.Headers.Add("Origin", "http://localhost:12061");
                request.Headers.Add("Referer", "http://localhost:12061/browser.html");

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            }
        }
        public async Task Get_Children_With_Filter_By_Permissions()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (testServices) =>
            {
                MockServicesForAuthorizationSuccess(testServices, 456);

                long totalRecs;
                Mock.Get(testServices.ServiceContext.ContentService)
                .Setup(x => x.GetPagedChildren(456, It.IsAny <long>(), It.IsAny <int>(), out totalRecs, It.IsAny <string>(), It.IsAny <Direction>(), It.IsAny <string>()))
                .Returns(new []
                {
                    ModelMocks.SimpleMockedContent(10),
                    ModelMocks.SimpleMockedContent(11),
                    ModelMocks.SimpleMockedContent(12),
                    ModelMocks.SimpleMockedContent(13),
                });

                Mock.Get(testServices.ServiceContext.UserService)
                .Setup(x => x.GetPermissions(It.IsAny <IUser>(), It.IsAny <int[]>()))
                .Returns(() =>
                         new EntityPermissionCollection(new[]
                {
                    new EntityPermission(1, 10, new[] { ActionBrowse.Instance.Letter.ToString() }),
                    new EntityPermission(1, 11, new[] { ActionSort.Instance.Letter.ToString() }),
                    new EntityPermission(1, 12, new[] { ActionBrowse.Instance.Letter.ToString() }),
                    new EntityPermission(1, 13, new[] { ActionSort.Instance.Letter.ToString() }),
                }));
            });

            var djson = await GetResult(startup.UseDefaultTestSetup, new Uri($"http://testserver/umbraco/rest/v1/{RouteConstants.ContentSegment}/456/children"), HttpStatusCode.OK);

            Assert.AreEqual(2, djson["_links"]["content"].Count());
            Assert.AreEqual(2, djson["_embedded"]["content"].Count());
            Assert.AreEqual(10, djson["_embedded"]["content"].First["id"].Value <int>());
            Assert.AreEqual(12, djson["_embedded"]["content"].Last["id"].Value <int>());
        }
示例#22
0
        public async Task Search_200_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (testServices) =>
            {
                MockServicesForAuthorizationSuccess(testServices);

                var mockSearchResults = new Mock <ISearchResults>();
                mockSearchResults.Setup(results => results.TotalItemCount).Returns(10);
                mockSearchResults.Setup(results => results.Skip(It.IsAny <int>())).Returns(new[]
                {
                    new SearchResult()
                    {
                        Id = 789
                    },
                    new SearchResult()
                    {
                        Id = 456
                    },
                });

                var mockSearchProvider = Mock.Get(testServices.SearchProvider);
                mockSearchProvider.Setup(x => x.CreateSearchCriteria()).Returns(Mock.Of <ISearchCriteria>());
                mockSearchProvider.Setup(x => x.Search(It.IsAny <ISearchCriteria>(), It.IsAny <int>()))
                .Returns(mockSearchResults.Object);

                var mockMediaService = Mock.Get(testServices.ServiceContext.MediaService);
                mockMediaService.Setup(x => x.GetByIds(It.IsAny <IEnumerable <int> >()))
                .Returns(new[]
                {
                    ModelMocks.SimpleMockedMedia(789),
                    ModelMocks.SimpleMockedMedia(456)
                });
            });

            await Search_200_Result(startup.UseDefaultTestSetup, RouteConstants.MediaSegment);
        }
示例#23
0
        public async Task Get_Root_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services,
                (testServices) =>
            {
                MockServicesForAuthorizationSuccess(testServices, 123, 456);

                var mockMediaService = Mock.Get(testServices.ServiceContext.MediaService);
                mockMediaService.Setup(x => x.GetRootMedia()).Returns(new[]
                {
                    ModelMocks.SimpleMockedMedia(123, -1),
                    ModelMocks.SimpleMockedMedia(456, -1)
                });

                mockMediaService.Setup(x => x.GetChildren(123)).Returns(new[] { ModelMocks.SimpleMockedMedia(789, 123) });
                mockMediaService.Setup(x => x.GetChildren(456)).Returns(new[] { ModelMocks.SimpleMockedMedia(321, 456) });
            });

            var djson = await Get_Root_Result(startup.UseDefaultTestSetup, RouteConstants.MediaSegment);

            Assert.AreEqual(2, djson["_links"]["content"].Count());
            Assert.AreEqual(2, djson["_embedded"]["content"].Count());
        }
        public async Task Get_Id_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (testServices) =>
            {
                var mockMemberService = Mock.Get(testServices.ServiceContext.MemberService);
                mockMemberService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedMember());
            });

            using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri($"http://testserver/umbraco/rest/v1/{RouteConstants.MembersSegment}/123"),
                    Method     = HttpMethod.Get,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

                var djson = JsonConvert.DeserializeObject <JObject>(json);

                Assert.AreEqual($"/umbraco/rest/v1/members/{123.ToGuid()}", djson["_links"]["self"]["href"].Value <string>());
                Assert.AreEqual("/umbraco/rest/v1/members{?page,size,query,orderBy,direction,memberTypeAlias}", djson["_links"]["root"]["href"].Value <string>());

                var properties = djson["properties"].ToObject <IDictionary <string, object> >();
                Assert.AreEqual(2, properties.Count());
                Assert.IsTrue(properties.ContainsKey("TestProperty1"));
                Assert.IsTrue(properties.ContainsKey("testProperty2"));
            }
        }
        public async void Get_Children_Is_200_Response()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (request, umbCtx, typedContent, serviceContext, searchProvider) =>
            {
                var mockMediaService = Mock.Get(serviceContext.MediaService);

                mockMediaService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedMedia());

                mockMediaService.Setup(x => x.GetChildren(It.IsAny <int>())).Returns(new List <IMedia>(new[] { ModelMocks.SimpleMockedMedia(789) }));

                mockMediaService.Setup(x => x.HasChildren(It.IsAny <int>())).Returns(true);
            });

            using (var server = TestServer.Create(builder => startup.Configuration(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}/123/children", RouteConstants.MediaSegment)),
                    Method     = HttpMethod.Get,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            }
        }
示例#26
0
        public async void Get_Id_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (request, umbCtx, typedContent, serviceContext, searchProvider) =>
            {
                var mockRelationService = Mock.Get(serviceContext.RelationService);
                mockRelationService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedRelation(123, 4567, 8910));
            });

            using (var server = TestServer.Create(builder => startup.Configuration(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}/123", RouteConstants.RelationsSegment)),
                    Method     = HttpMethod.Get,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

                var djson = JsonConvert.DeserializeObject <JObject>(json);

                Assert.AreEqual("/umbraco/rest/v1/relations/123", djson["_links"]["self"]["href"].Value <string>());
                Assert.AreEqual("/umbraco/rest/v1/relations", djson["_links"]["root"]["href"].Value <string>());
            }
        }
        public async Task Get_Id_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (testServices) =>
            {
                var mockRelationService = Mock.Get(testServices.ServiceContext.RelationService);
                mockRelationService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedRelation(123, 4567, 8910, ModelMocks.SimpleMockedRelationType()));
            });

            var djson = await Get_Id_Result(startup.UseDefaultTestSetup, RouteConstants.RelationsSegment);

            Assert.AreEqual("/umbraco/rest/v1/relations/123", djson["_links"]["self"]["href"].Value <string>());
            Assert.AreEqual("/umbraco/rest/v1/relations", djson["_links"]["root"]["href"].Value <string>());
            Assert.AreEqual("/umbraco/rest/v1/relations/relationtype/testType", djson["_links"]["relationtype"]["href"].Value <string>());
            Assert.AreEqual("/umbraco/rest/v1/content/published/{id}", djson["_links"]["content"]["href"].Value <string>());
        }
        public async Task Get_Metadata_Is_200()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (testServices) =>
            {
                var mockMemberService = Mock.Get(testServices.ServiceContext.MemberService);

                mockMemberService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedMember());
                var mockTextService = Mock.Get(testServices.ServiceContext.TextService);

                mockTextService.Setup(x => x.Localize(It.IsAny <string>(), It.IsAny <CultureInfo>(), It.IsAny <IDictionary <string, string> >()))
                .Returns((string input, CultureInfo culture, IDictionary <string, string> tokens) => input);
            });

            using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder)))
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}/123/meta", RouteConstants.MembersSegment)),
                    Method     = HttpMethod.Get,
                };

                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));

                Console.WriteLine(request);
                var result = await server.HttpClient.SendAsync(request);

                Console.WriteLine(result);

                var json = await((StreamContent)result.Content).ReadAsStringAsync();
                Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented));

                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);

                //TODO: Assert values!
            }
        }
示例#29
0
        public async Task Get_Id_Result()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (testServices) =>
            {
                MockServicesForAuthorizationSuccess(testServices, 123);

                var mockMediaService = Mock.Get(testServices.ServiceContext.MediaService);

                mockMediaService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedMedia());

                mockMediaService.Setup(x => x.GetChildren(It.IsAny <int>())).Returns(new List <IMedia>(new[] { ModelMocks.SimpleMockedMedia(789) }));

                mockMediaService.Setup(x => x.HasChildren(It.IsAny <int>())).Returns(true);
            });

            var djson = await Get_Id_Result(startup.UseDefaultTestSetup, RouteConstants.MediaSegment);

            Assert.AreEqual($"/umbraco/rest/v1/{RouteConstants.MediaSegment}/123", djson["_links"]["self"]["href"].Value <string>());
            Assert.AreEqual($"/umbraco/rest/v1/{RouteConstants.MediaSegment}/456", djson["_links"]["parent"]["href"].Value <string>());
            Assert.AreEqual($"/umbraco/rest/v1/{RouteConstants.MediaSegment}/123/children{{?page,size,query}}", djson["_links"]["children"]["href"].Value <string>());
            Assert.AreEqual($"/umbraco/rest/v1/{RouteConstants.MediaSegment}", djson["_links"]["root"]["href"].Value <string>());

            var properties = djson["properties"].ToObject <IDictionary <string, object> >();

            Assert.AreEqual(2, properties.Count);
            Assert.IsTrue(properties.ContainsKey("TestProperty1"));
            Assert.IsTrue(properties.ContainsKey("testProperty2"));
        }
示例#30
0
        public async Task Get_Metadata_Is_200()
        {
            var startup = new TestStartup(
                //This will be invoked before the controller is created so we can modify these mocked services
                (testServices) =>
            {
                MockServicesForAuthorizationSuccess(testServices, 123);

                var mockMediaService = Mock.Get(testServices.ServiceContext.MediaService);

                mockMediaService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedMedia());
                mockMediaService.Setup(x => x.GetChildren(It.IsAny <int>())).Returns(new List <IMedia>(new[] { ModelMocks.SimpleMockedMedia(789) }));
                mockMediaService.Setup(x => x.HasChildren(It.IsAny <int>())).Returns(true);

                var mockTextService = Mock.Get(testServices.ServiceContext.TextService);

                mockTextService.Setup(x => x.Localize(It.IsAny <string>(), It.IsAny <CultureInfo>(), It.IsAny <IDictionary <string, string> >()))
                .Returns((string input, CultureInfo culture, IDictionary <string, string> tokens) => input);
            });

            await Get_Metadata_Is_200(startup.UseDefaultTestSetup, RouteConstants.MediaSegment);
        }