Exemple #1
0
        public void Setup()
        {
            Current.Reset();
            var factory = Mock.Of <IFactory>();

            Current.Factory = factory;

            var serviceContext = ServiceContext.CreatePartial(
                localizedTextService: Mock.Of <ILocalizedTextService>());

            Mock.Get(factory)
            .Setup(x => x.GetInstance(It.IsAny <Type>()))
            .Returns <Type>(x =>
            {
                if (x == typeof(ServiceContext))
                {
                    return(serviceContext);
                }
                throw new Exception("oops");
            });

            var validators = new IManifestValueValidator[]
            {
                new RequiredValidator(Mock.Of <ILocalizedTextService>()),
                new RegexValidator(Mock.Of <ILocalizedTextService>(), null)
            };

            _parser = new ManifestParser(NullCacheProvider.Instance, new ManifestValueValidatorCollection(validators), Mock.Of <ILogger>());
        }
Exemple #2
0
        protected override void Compose()
        {
            base.Compose();

            Composition.Register(_ => Mock.Of <ILogger>());
            Composition.ComposeFileSystems();

            Composition.Register(_ => Mock.Of <IDataTypeService>());
            Composition.Register(_ => Mock.Of <IContentSection>());

            // all this is required so we can validate properties...
            var editor = new TextboxPropertyEditor(Mock.Of <ILogger>())
            {
                Alias = "test"
            };

            Composition.Register(_ => new DataEditorCollection(new[] { editor }));
            Composition.Register <PropertyEditorCollection>();
            var dataType = Mock.Of <IDataType>();

            Mock.Get(dataType).Setup(x => x.Configuration).Returns(() => new object());
            var dataTypeService = Mock.Of <IDataTypeService>();

            Mock.Get(dataTypeService)
            .Setup(x => x.GetDataType(It.IsAny <int>()))
            .Returns(() => dataType);

            _contentTypeService = Mock.Of <IContentTypeService>();
            var mediaTypeService  = Mock.Of <IMediaTypeService>();
            var memberTypeService = Mock.Of <IMemberTypeService>();

            Composition.Register(_ => ServiceContext.CreatePartial(dataTypeService: dataTypeService, contentTypeBaseServiceProvider: new ContentTypeBaseServiceProvider(_contentTypeService, mediaTypeService, memberTypeService)));
        }
        public void SetUp()
        {
            Current.Reset();

            // FIXME: now UrlProvider depends on EntityService for GetUrl(guid) - this is bad
            // should not depend on more than IdkMap maybe - fix this!
            var entityService = new Mock <IEntityService>();

            entityService.Setup(x => x.GetId(It.IsAny <Guid>(), It.IsAny <UmbracoObjectTypes>())).Returns(Attempt <int> .Fail());
            var serviceContext = ServiceContext.CreatePartial(entityService: entityService.Object);

            // FIXME: bad in a unit test - but Udi has a static ctor that wants it?!
            var factory = new Mock <IFactory>();

            factory.Setup(x => x.GetInstance(typeof(TypeLoader))).Returns(
                new TypeLoader(NoAppCache.Instance, IOHelper.MapPath("~/App_Data/TEMP"), new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>())));
            factory.Setup(x => x.GetInstance(typeof(ServiceContext))).Returns(serviceContext);

            var settings = SettingsForTests.GetDefaultUmbracoSettings();

            factory.Setup(x => x.GetInstance(typeof(IUmbracoSettingsSection))).Returns(settings);

            Current.Factory = factory.Object;

            Umbraco.Web.Composing.Current.UmbracoContextAccessor = new TestUmbracoContextAccessor();

            Udi.ResetUdiTypes();
        }
Exemple #4
0
        /// <summary>
        /// Gets a mocked service context built with mocked services.
        /// </summary>
        /// <returns>A ServiceContext.</returns>
        public ServiceContext GetServiceContextMock(IFactory container = null)
        {
            // FIXME: else some tests break - figure it out
            container = null;

            return(ServiceContext.CreatePartial(
                       MockService <IContentService>(container),
                       MockService <IMediaService>(container),
                       MockService <IContentTypeService>(container),
                       MockService <IMediaTypeService>(container),
                       MockService <IDataTypeService>(container),
                       MockService <IFileService>(container),
                       MockService <ILocalizationService>(container),
                       MockService <IPackagingService>(container),
                       MockService <IEntityService>(container),
                       MockService <IRelationService>(container),
                       MockService <IMemberGroupService>(container),
                       MockService <IMemberTypeService>(container),
                       MockService <IMemberService>(container),
                       MockService <IUserService>(container),
                       MockService <ITagService>(container),
                       MockService <INotificationService>(container),
                       MockService <ILocalizedTextService>(container),
                       MockService <IAuditService>(container),
                       MockService <IDomainService>(container),
                       MockService <IMacroService>(container)));
        }
Exemple #5
0
 public TestSurfaceController(UmbracoContext ctx, UmbracoHelper helper = null)
     : base(ctx, null, ServiceContext.CreatePartial(), Mock.Of <CacheHelper>(), null, null)
 {
     if (helper != null)
     {
         Umbraco = helper;
     }
 }
Exemple #6
0
 internal static PublishedRouter CreatePublishedRouter(IWebRoutingSection webRoutingSection, IFactory container = null, ContentFinderCollection contentFinders = null)
 {
     return(new PublishedRouter(
                webRoutingSection,
                contentFinders ?? new ContentFinderCollection(Enumerable.Empty <IContentFinder>()),
                new TestLastChanceFinder(),
                new TestVariationContextAccessor(),
                container?.TryGetInstance <ServiceContext>() ?? ServiceContext.CreatePartial(),
                new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>())));
 }
        public virtual void Setup()
        {
            SetupHttpContext();
            SetupCultureDictionaries();
            SetupPublishedContentQuerying();
            SetupMembership();

            ServiceContext = ServiceContext.CreatePartial(memberService: MemberService.Object);
            UmbracoHelper  = new UmbracoHelper(Mock.Of <IPublishedContent>(), Mock.Of <ITagQuery>(), CultureDictionaryFactory.Object, Mock.Of <IUmbracoComponentRenderer>(), PublishedContentQuery.Object, MembershipHelper);
            UmbracoMapper  = new UmbracoMapper(new MapDefinitionCollection(new List <IMapDefinition>()), Mock.Of <IScopeProvider>());
        }
Exemple #8
0
        public virtual void SetUp()
        {
            this.SetupHttpContext();
            this.SetupCultureDictionaries();
            this.SetupPublishedContentQuerying();
            this.SetupMembership();

            this.ServiceContext = ServiceContext.CreatePartial();
            this.UmbracoHelper  = new Umbraco.Web.UmbracoHelper(Mock.Of <IPublishedContent>(), Mock.Of <ITagQuery>(), this.CultureDictionaryFactory.Object, Mock.Of <IUmbracoComponentRenderer>(), this.PublishedContentQuery.Object, this.MembershipHelper);
            this.UmbracoMapper  = new UmbracoMapper(new MapDefinitionCollection(new List <IMapDefinition>()));
        }
        public void Setup()
        {
            Mock <Core.Composing.IFactory> factory = new Mock <Core.Composing.IFactory>();

            LocalizationService      = new Mock <ILocalizationService>();
            CultureDictionaryFactory = new Mock <ICultureDictionaryFactory>();

            factory
            .Setup(x => x.GetInstance(typeof(ServiceContext)))
            .Returns(ServiceContext.CreatePartial(localizationService: LocalizationService.Object));

            factory
            .Setup(x => x.GetInstance(typeof(ICultureDictionaryFactory)))
            .Returns(CultureDictionaryFactory.Object);

            Core.Composing.Current.Factory = factory.Object;
        }
Exemple #10
0
        public void Can_Lookup_Content()
        {
            var publishedSnapshot = new Mock <IPublishedSnapshot>();

            publishedSnapshot.Setup(x => x.Members).Returns(Mock.Of <IPublishedMemberCache>());
            var contentCache = new Mock <IPublishedContentCache>();
            var content      = new Mock <IPublishedContent>();

            content.Setup(x => x.Id).Returns(2);
            contentCache.Setup(x => x.GetById(It.IsAny <int>())).Returns(content.Object);
            var mediaCache = new Mock <IPublishedMediaCache>();

            publishedSnapshot.Setup(x => x.Content).Returns(contentCache.Object);
            publishedSnapshot.Setup(x => x.Media).Returns(mediaCache.Object);
            var publishedSnapshotService = new Mock <IPublishedSnapshotService>();

            publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(publishedSnapshot.Object);
            var globalSettings = TestObjects.GetGlobalSettings();

            var umbracoContext = UmbracoContext.EnsureContext(
                Current.UmbracoContextAccessor,
                new Mock <HttpContextBase>().Object,
                publishedSnapshotService.Object,
                new Mock <WebSecurity>(null, null, globalSettings).Object,
                Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "AutoLegacy")),
                Enumerable.Empty <IUrlProvider>(),
                globalSettings,
                new TestVariationContextAccessor(),
                true);

            var helper = new UmbracoHelper(
                umbracoContext,
                Mock.Of <IPublishedContent>(),
                Mock.Of <ITagQuery>(),
                Mock.Of <ICultureDictionary>(),
                Mock.Of <IUmbracoComponentRenderer>(),
                new MembershipHelper(new TestUmbracoContextAccessor(umbracoContext), Mock.Of <MembershipProvider>(), Mock.Of <RoleProvider>(), Mock.Of <IMemberService>(), Mock.Of <IMemberTypeService>(), Mock.Of <IUserService>(), Mock.Of <IPublicAccessService>(), null, Mock.Of <CacheHelper>(), Mock.Of <ILogger>()),
                ServiceContext.CreatePartial());

            var ctrl   = new TestSurfaceController(umbracoContext, helper);
            var result = ctrl.GetContent(2) as PublishedContentResult;

            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Content.Id);
        }
Exemple #11
0
        public void Can_Mock_Umbraco_Helper()
        {
            var umbracoContext = TestObjects.GetUmbracoContextMock();

            // unless we can inject them in MembershipHelper, we need need this
            Composition.Register(_ => Mock.Of <IMemberService>());
            Composition.Register(_ => Mock.Of <IMemberTypeService>());
            Composition.Register(_ => Mock.Of <IUserService>());
            Composition.Register(_ => CacheHelper.Disabled);
            Composition.Register <ServiceContext>();

            // ReSharper disable once UnusedVariable
            var helper = new UmbracoHelper(umbracoContext,
                                           Mock.Of <IPublishedContent>(),
                                           Mock.Of <ITagQuery>(),
                                           Mock.Of <ICultureDictionary>(),
                                           Mock.Of <IUmbracoComponentRenderer>(),
                                           new MembershipHelper(new TestUmbracoContextAccessor(umbracoContext), Mock.Of <MembershipProvider>(), Mock.Of <RoleProvider>(), Mock.Of <IMemberService>(), Mock.Of <IMemberTypeService>(), Mock.Of <IUserService>(), Mock.Of <IPublicAccessService>(), null, Mock.Of <CacheHelper>(), Mock.Of <ILogger>()),
                                           ServiceContext.CreatePartial());

            Assert.Pass();
        }
Exemple #12
0
        public void Can_Mock_UmbracoApiController_Dependencies_With_Injected_UmbracoMapper()
        {
            var umbracoContext = TestObjects.GetUmbracoContextMock();

            var membershipHelper = new MembershipHelper(umbracoContext.HttpContext, Mock.Of <IPublishedMemberCache>(), Mock.Of <MembershipProvider>(), Mock.Of <RoleProvider>(), Mock.Of <IMemberService>(), Mock.Of <IMemberTypeService>(), Mock.Of <IUserService>(), Mock.Of <IPublicAccessService>(), Mock.Of <AppCaches>(), Mock.Of <ILogger>());
            var umbracoHelper    = new UmbracoHelper(Mock.Of <IPublishedContent>(), Mock.Of <ITagQuery>(), Mock.Of <ICultureDictionaryFactory>(), Mock.Of <IUmbracoComponentRenderer>(), Mock.Of <IPublishedContentQuery>(), membershipHelper);
            var umbracoMapper    = new UmbracoMapper(new MapDefinitionCollection(new[] { Mock.Of <IMapDefinition>() }));

            // ReSharper disable once UnusedVariable
            var umbracoApiController = new FakeUmbracoApiController(Mock.Of <IGlobalSettings>(), Mock.Of <IUmbracoContextAccessor>(), Mock.Of <ISqlContext>(), ServiceContext.CreatePartial(), AppCaches.NoCache, Mock.Of <IProfilingLogger>(), Mock.Of <IRuntimeState>(), umbracoHelper, umbracoMapper);

            Assert.Pass();
        }
Exemple #13
0
        IHttpController IHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            // default
            if (!typeof(UmbracoApiControllerBase).IsAssignableFrom(controllerType))
            {
                return(base.Create(request, controllerDescriptor, controllerType));
            }

            var owinContext = request.TryGetOwinContext().Result;

            var mockedUserService        = Mock.Of <IUserService>();
            var mockedContentService     = Mock.Of <IContentService>();
            var mockedMediaService       = Mock.Of <IMediaService>();
            var mockedEntityService      = Mock.Of <IEntityService>();
            var mockedMemberService      = Mock.Of <IMemberService>();
            var mockedMemberTypeService  = Mock.Of <IMemberTypeService>();
            var mockedDataTypeService    = Mock.Of <IDataTypeService>();
            var mockedContentTypeService = Mock.Of <IContentTypeService>();

            var serviceContext = ServiceContext.CreatePartial(
                userService: mockedUserService,
                contentService: mockedContentService,
                mediaService: mockedMediaService,
                entityService: mockedEntityService,
                memberService: mockedMemberService,
                memberTypeService: mockedMemberTypeService,
                dataTypeService: mockedDataTypeService,
                contentTypeService: mockedContentTypeService,
                localizedTextService: Mock.Of <ILocalizedTextService>());

            var globalSettings = SettingsForTests.GenerateMockGlobalSettings();

            // FIXME: v8?
            ////new app context
            //var dbCtx = new Mock<DatabaseContext>(Mock.Of<IDatabaseFactory>(), Mock.Of<ILogger>(), Mock.Of<ISqlSyntaxProvider>(), "test");
            ////ensure these are set so that the appctx is 'Configured'
            //dbCtx.Setup(x => x.CanConnect).Returns(true);
            //dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(true);
            //var appCtx = ApplicationContext.EnsureContext(
            //    dbCtx.Object,
            //    //pass in mocked services
            //    serviceContext,
            //    CacheHelper.CreateDisabledCacheHelper(),
            //    new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()),
            //    true);

            var httpContextItems = new Dictionary <string, object>
            {
                //add the special owin environment to the httpcontext items, this is how the GetOwinContext works
                ["owin.Environment"] = new Dictionary <string, object>()
            };

            //httpcontext with an auth'd user
            var httpContext = Mock.Of <HttpContextBase>(
                http => http.User == owinContext.Authentication.User
                //ensure the request exists with a cookies collection
                && http.Request == Mock.Of <HttpRequestBase>(r => r.Cookies == new HttpCookieCollection() &&
                                                             r.RequestContext == new System.Web.Routing.RequestContext
            {
                RouteData = new System.Web.Routing.RouteData()
            })
                //ensure the request exists with an items collection
                && http.Items == httpContextItems);

            //chuck it into the props since this is what MS does when hosted and it's needed there
            request.Properties["MS_HttpContext"] = httpContext;

            var backofficeIdentity = (UmbracoBackOfficeIdentity)owinContext.Authentication.User.Identity;

            var webSecurity = new Mock <WebSecurity>(null, null, globalSettings);

            //mock CurrentUser
            var groups = new List <ReadOnlyUserGroup>();

            for (var index = 0; index < backofficeIdentity.Roles.Length; index++)
            {
                var role = backofficeIdentity.Roles[index];
                groups.Add(new ReadOnlyUserGroup(index + 1, role, "icon-user", null, null, role, new string[0], new string[0]));
            }
            webSecurity.Setup(x => x.CurrentUser)
            .Returns(Mock.Of <IUser>(u => u.IsApproved == true &&
                                     u.IsLockedOut == false &&
                                     u.AllowedSections == backofficeIdentity.AllowedApplications &&
                                     u.Groups == groups &&
                                     u.Email == "*****@*****.**" &&
                                     u.Id == (int)backofficeIdentity.Id &&
                                     u.Language == "en" &&
                                     u.Name == backofficeIdentity.RealName &&
                                     u.StartContentIds == backofficeIdentity.StartContentNodes &&
                                     u.StartMediaIds == backofficeIdentity.StartMediaNodes &&
                                     u.Username == backofficeIdentity.Username));

            //mock Validate
            webSecurity.Setup(x => x.ValidateCurrentUser())
            .Returns(() => true);
            webSecurity.Setup(x => x.UserHasSectionAccess(It.IsAny <string>(), It.IsAny <IUser>()))
            .Returns(() => true);

            var publishedSnapshot = new Mock <IPublishedSnapshot>();

            publishedSnapshot.Setup(x => x.Members).Returns(Mock.Of <IPublishedMemberCache>());
            var publishedSnapshotService = new Mock <IPublishedSnapshotService>();

            publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(publishedSnapshot.Object);

            var umbracoContextAccessor = Umbraco.Web.Composing.Current.UmbracoContextAccessor;

            var umbCtx = new UmbracoContext(httpContext,
                                            publishedSnapshotService.Object,
                                            webSecurity.Object,
                                            Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "Auto")),
                                            Enumerable.Empty <IUrlProvider>(),
                                            Enumerable.Empty <IMediaUrlProvider>(),
                                            globalSettings,
                                            new TestVariationContextAccessor());

            //replace it
            umbracoContextAccessor.UmbracoContext = umbCtx;

            var urlHelper = new Mock <IUrlProvider>();

            urlHelper.Setup(provider => provider.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <IPublishedContent>(), It.IsAny <UrlProviderMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns(UrlInfo.Url("/hello/world/1234"));

            var membershipHelper = new MembershipHelper(umbCtx.HttpContext, Mock.Of <IPublishedMemberCache>(), Mock.Of <MembershipProvider>(), Mock.Of <RoleProvider>(), Mock.Of <IMemberService>(), Mock.Of <IMemberTypeService>(), Mock.Of <IUserService>(), Mock.Of <IPublicAccessService>(), Mock.Of <AppCaches>(), Mock.Of <ILogger>());

            var umbHelper = new UmbracoHelper(Mock.Of <IPublishedContent>(),
                                              Mock.Of <ITagQuery>(),
                                              Mock.Of <ICultureDictionaryFactory>(),
                                              Mock.Of <IUmbracoComponentRenderer>(),
                                              Mock.Of <IPublishedContentQuery>(),
                                              membershipHelper);

            return(CreateController(controllerType, request, umbracoContextAccessor, umbHelper));
        }
        public void StandaloneVariations()
        {
            // this test implements a full standalone NuCache (based upon a test IDataSource, does not
            // use any local db files, does not rely on any database) - and tests variations

            Current.Reset();
            Current.UnlockConfigs();
            Current.Configs.Add(SettingsForTests.GenerateMockUmbracoSettings);
            Current.Configs.Add <IGlobalSettings>(() => new GlobalSettings());
            var globalSettings = Current.Configs.Global();

            // create a content node kit
            var kit = new ContentNodeKit
            {
                ContentTypeId = 2,
                Node          = new ContentNode(1, Guid.NewGuid(), 0, "-1,1", 0, -1, DateTime.Now, 0),
                DraftData     = new ContentData {
                    Name       = "It Works2!", Published = false, TemplateId = 0, VersionId = 2, VersionDate = DateTime.Now, WriterId = 0,
                    Properties = new Dictionary <string, PropertyData[]> {
                        { "prop", new[]
                          {
                              new PropertyData {
                                  Culture = "", Segment = "", Value = "val2"
                              },
                              new PropertyData {
                                  Culture = "fr-FR", Segment = "", Value = "val-fr2"
                              },
                              new PropertyData {
                                  Culture = "en-UK", Segment = "", Value = "val-uk2"
                              }
                          } }
                    },
                    CultureInfos = new Dictionary <string, CultureVariation>
                    {
                        { "fr-FR", new CultureVariation {
                              Name = "name-fr2", Date = new DateTime(2018, 01, 03, 01, 00, 00)
                          } },
                        { "en-UK", new CultureVariation {
                              Name = "name-uk2", Date = new DateTime(2018, 01, 04, 01, 00, 00)
                          } }
                    }
                },
                PublishedData = new ContentData {
                    Name       = "It Works1!", Published = true, TemplateId = 0, VersionId = 1, VersionDate = DateTime.Now, WriterId = 0,
                    Properties = new Dictionary <string, PropertyData[]> {
                        { "prop", new[]
                          {
                              new PropertyData {
                                  Culture = "", Segment = "", Value = "val1"
                              },
                              new PropertyData {
                                  Culture = "fr-FR", Segment = "", Value = "val-fr1"
                              },
                              new PropertyData {
                                  Culture = "en-UK", Segment = "", Value = "val-uk1"
                              }
                          } }
                    },
                    CultureInfos = new Dictionary <string, CultureVariation>
                    {
                        { "fr-FR", new CultureVariation {
                              Name = "name-fr1", Date = new DateTime(2018, 01, 01, 01, 00, 00)
                          } },
                        { "en-UK", new CultureVariation {
                              Name = "name-uk1", Date = new DateTime(2018, 01, 02, 01, 00, 00)
                          } }
                    }
                }
            };

            // create a data source for NuCache
            var dataSource = new TestDataSource(kit);

            var runtime = Mock.Of <IRuntimeState>();

            Mock.Get(runtime).Setup(x => x.Level).Returns(RuntimeLevel.Run);

            // create data types, property types and content types
            var dataType = new DataType(new VoidEditor("Editor", Mock.Of <ILogger>()))
            {
                Id = 3
            };

            var dataTypes = new[]
            {
                dataType
            };

            var propertyType = new PropertyType("Umbraco.Void.Editor", ValueStorageType.Nvarchar)
            {
                Alias = "prop", DataTypeId = 3, Variations = ContentVariation.Culture
            };
            var contentType = new ContentType(-1)
            {
                Id = 2, Alias = "alias-ct", Variations = ContentVariation.Culture
            };

            contentType.AddPropertyType(propertyType);

            var contentTypes = new[]
            {
                contentType
            };

            var contentTypeService = Mock.Of <IContentTypeService>();

            Mock.Get(contentTypeService).Setup(x => x.GetAll()).Returns(contentTypes);
            Mock.Get(contentTypeService).Setup(x => x.GetAll(It.IsAny <int[]>())).Returns(contentTypes);

            var dataTypeService = Mock.Of <IDataTypeService>();

            Mock.Get(dataTypeService).Setup(x => x.GetAll()).Returns(dataTypes);

            // create a service context
            var serviceContext = ServiceContext.CreatePartial(
                dataTypeService: dataTypeService,
                memberTypeService: Mock.Of <IMemberTypeService>(),
                memberService: Mock.Of <IMemberService>(),
                contentTypeService: contentTypeService,
                localizationService: Mock.Of <ILocalizationService>()
                );

            // create a scope provider
            var scopeProvider = Mock.Of <IScopeProvider>();

            Mock.Get(scopeProvider)
            .Setup(x => x.CreateScope(
                       It.IsAny <IsolationLevel>(),
                       It.IsAny <RepositoryCacheMode>(),
                       It.IsAny <IEventDispatcher>(),
                       It.IsAny <bool?>(),
                       It.IsAny <bool>(),
                       It.IsAny <bool>()))
            .Returns(Mock.Of <IScope>);

            // create a published content type factory
            var contentTypeFactory = new PublishedContentTypeFactory(
                Mock.Of <IPublishedModelFactory>(),
                new PropertyValueConverterCollection(Array.Empty <IPropertyValueConverter>()),
                dataTypeService);

            // create a variation accessor
            var variationAccessor = new TestVariationContextAccessor();

            // at last, create the complete NuCache snapshot service!
            var options = new PublishedSnapshotService.Options {
                IgnoreLocalDb = true
            };
            var snapshotService = new PublishedSnapshotService(options,
                                                               null,
                                                               runtime,
                                                               serviceContext,
                                                               contentTypeFactory,
                                                               null,
                                                               new TestPublishedSnapshotAccessor(),
                                                               variationAccessor,
                                                               Mock.Of <ILogger>(),
                                                               scopeProvider,
                                                               Mock.Of <IDocumentRepository>(),
                                                               Mock.Of <IMediaRepository>(),
                                                               Mock.Of <IMemberRepository>(),
                                                               new TestDefaultCultureAccessor(),
                                                               dataSource,
                                                               globalSettings,
                                                               new SiteDomainHelper());

            // get a snapshot, get a published content
            var snapshot         = snapshotService.CreatePublishedSnapshot(previewToken: null);
            var publishedContent = snapshot.Content.GetById(1);

            // invariant is the current default
            variationAccessor.VariationContext = new VariationContext();

            Assert.IsNotNull(publishedContent);
            Assert.AreEqual("It Works1!", publishedContent.Name);
            Assert.AreEqual("val1", publishedContent.Value <string>("prop"));
            Assert.AreEqual("val-fr1", publishedContent.Value <string>("prop", "fr-FR"));
            Assert.AreEqual("val-uk1", publishedContent.Value <string>("prop", "en-UK"));

            Assert.AreEqual("name-fr1", publishedContent.GetCulture("fr-FR").Name);
            Assert.AreEqual("name-uk1", publishedContent.GetCulture("en-UK").Name);

            var draftContent = snapshot.Content.GetById(true, 1);

            Assert.AreEqual("It Works2!", draftContent.Name);
            Assert.AreEqual("val2", draftContent.Value <string>("prop"));
            Assert.AreEqual("val-fr2", draftContent.Value <string>("prop", "fr-FR"));
            Assert.AreEqual("val-uk2", draftContent.Value <string>("prop", "en-UK"));

            Assert.AreEqual("name-fr2", draftContent.GetCulture("fr-FR").Name);
            Assert.AreEqual("name-uk2", draftContent.GetCulture("en-UK").Name);

            // now french is default
            variationAccessor.VariationContext = new VariationContext("fr-FR");
            Assert.AreEqual("val-fr1", publishedContent.Value <string>("prop"));
            Assert.AreEqual("name-fr1", publishedContent.GetCulture().Name);
            Assert.AreEqual("name-fr1", publishedContent.Name);
            Assert.AreEqual(new DateTime(2018, 01, 01, 01, 00, 00), publishedContent.GetCulture().Date);

            // now uk is default
            variationAccessor.VariationContext = new VariationContext("en-UK");
            Assert.AreEqual("val-uk1", publishedContent.Value <string>("prop"));
            Assert.AreEqual("name-uk1", publishedContent.GetCulture().Name);
            Assert.AreEqual("name-uk1", publishedContent.Name);
            Assert.AreEqual(new DateTime(2018, 01, 02, 01, 00, 00), publishedContent.GetCulture().Date);

            // invariant needs to be retrieved explicitely, when it's not default
            Assert.AreEqual("val1", publishedContent.Value <string>("prop", culture: ""));

            // but,
            // if the content type / property type does not vary, then it's all invariant again
            // modify the content type and property type, notify the snapshot service
            contentType.Variations  = ContentVariation.Nothing;
            propertyType.Variations = ContentVariation.Nothing;
            snapshotService.Notify(new[] { new ContentTypeCacheRefresher.JsonPayload("IContentType", publishedContent.ContentType.Id, ContentTypeChangeTypes.RefreshMain) });

            // get a new snapshot (nothing changed in the old one), get the published content again
            var anotherSnapshot = snapshotService.CreatePublishedSnapshot(previewToken: null);
            var againContent    = anotherSnapshot.Content.GetById(1);

            Assert.AreEqual(ContentVariation.Nothing, againContent.ContentType.Variations);
            Assert.AreEqual(ContentVariation.Nothing, againContent.ContentType.GetPropertyType("prop").Variations);

            // now, "no culture" means "invariant"
            Assert.AreEqual("It Works1!", againContent.Name);
            Assert.AreEqual("val1", againContent.Value <string>("prop"));
        }
 public TestSurfaceController(
     IUmbracoContextAccessor umbracoContextAccessor,
     IPublishedContentQuery publishedContentQuery,
     IPublishedUrlProvider publishedUrlProvider)
     : base(umbracoContextAccessor, null, ServiceContext.CreatePartial(), AppCaches.Disabled, null, publishedUrlProvider) =>
Exemple #16
0
 public TestSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper = null)
     : base(umbracoContextAccessor, null, ServiceContext.CreatePartial(), AppCaches.Disabled, null, null, helper)
 {
 }
        public void SetUp()
        {
            // annoying, but content type wants short string helper ;(
            SettingsForTests.Reset();

            // well, this is also annoying, but...
            // validating a value is performed by its data editor,
            // based upon the configuration in the data type, so we
            // need to be able to retrieve them all...

            Current.Reset();

            var configs = new Configs();

            configs.Add(SettingsForTests.GetDefaultGlobalSettings);
            configs.Add(SettingsForTests.GetDefaultUmbracoSettings);

            var factory = Mock.Of <IFactory>();

            Current.Factory = factory;

            var dataEditors = new DataEditorCollection(new IDataEditor[]
            {
                new DataEditor(Mock.Of <ILogger>())
                {
                    Alias = "editor", ExplicitValueEditor = new DataValueEditor("view")
                }
            });
            var propertyEditors = new PropertyEditorCollection(dataEditors);

            var dataType = Mock.Of <IDataType>();

            Mock.Get(dataType)
            .Setup(x => x.Configuration)
            .Returns(null);

            var dataTypeService = Mock.Of <IDataTypeService>();

            Mock.Get(dataTypeService)
            .Setup(x => x.GetDataType(It.IsAny <int>()))
            .Returns <int>(x => dataType);

            var serviceContext = ServiceContext.CreatePartial(
                dataTypeService: dataTypeService,
                localizedTextService: Mock.Of <ILocalizedTextService>());

            Mock.Get(factory)
            .Setup(x => x.GetInstance(It.IsAny <Type>()))
            .Returns <Type>(x =>
            {
                if (x == typeof(Configs))
                {
                    return(configs);
                }
                if (x == typeof(PropertyEditorCollection))
                {
                    return(propertyEditors);
                }
                if (x == typeof(ServiceContext))
                {
                    return(serviceContext);
                }
                if (x == typeof(ILocalizedTextService))
                {
                    return(serviceContext.LocalizationService);
                }
                throw new NotSupportedException(x.FullName);
            });
        }
Exemple #18
0
        private void Init()
        {
            Current.Reset();

            var factory = Mock.Of <IFactory>();

            Current.Factory = factory;

            var configs = new Configs();

            Mock.Get(factory).Setup(x => x.GetInstance(typeof(Configs))).Returns(configs);
            var globalSettings = new GlobalSettings();

            configs.Add(SettingsForTests.GenerateMockUmbracoSettings);
            configs.Add <IGlobalSettings>(() => globalSettings);

            var publishedModelFactory = new NoopPublishedModelFactory();

            Mock.Get(factory).Setup(x => x.GetInstance(typeof(IPublishedModelFactory))).Returns(publishedModelFactory);

            // create a content node kit
            var kit = new ContentNodeKit
            {
                ContentTypeId = 2,
                Node          = new ContentNode(1, Guid.NewGuid(), 0, "-1,1", 0, -1, DateTime.Now, 0),
                DraftData     = new ContentData
                {
                    Name        = "It Works2!",
                    Published   = false,
                    TemplateId  = 0,
                    VersionId   = 2,
                    VersionDate = DateTime.Now,
                    WriterId    = 0,
                    Properties  = new Dictionary <string, PropertyData[]> {
                        { "prop", new[]
                          {
                              new PropertyData {
                                  Culture = "", Segment = "", Value = "val2"
                              },
                              new PropertyData {
                                  Culture = "fr-FR", Segment = "", Value = "val-fr2"
                              },
                              new PropertyData {
                                  Culture = "en-UK", Segment = "", Value = "val-uk2"
                              },
                              new PropertyData {
                                  Culture = "dk-DA", Segment = "", Value = "val-da2"
                              },
                              new PropertyData {
                                  Culture = "de-DE", Segment = "", Value = "val-de2"
                              }
                          } }
                    },
                    CultureInfos = new Dictionary <string, CultureVariation>
                    {
                        // draft data = everything, and IsDraft indicates what's edited
                        { "fr-FR", new CultureVariation {
                              Name = "name-fr2", IsDraft = true, Date = new DateTime(2018, 01, 03, 01, 00, 00)
                          } },
                        { "en-UK", new CultureVariation {
                              Name = "name-uk2", IsDraft = true, Date = new DateTime(2018, 01, 04, 01, 00, 00)
                          } },
                        { "dk-DA", new CultureVariation {
                              Name = "name-da2", IsDraft = true, Date = new DateTime(2018, 01, 05, 01, 00, 00)
                          } },
                        { "de-DE", new CultureVariation {
                              Name = "name-de1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00)
                          } }
                    }
                },
                PublishedData = new ContentData
                {
                    Name        = "It Works1!",
                    Published   = true,
                    TemplateId  = 0,
                    VersionId   = 1,
                    VersionDate = DateTime.Now,
                    WriterId    = 0,
                    Properties  = new Dictionary <string, PropertyData[]> {
                        { "prop", new[]
                          {
                              new PropertyData {
                                  Culture = "", Segment = "", Value = "val1"
                              },
                              new PropertyData {
                                  Culture = "fr-FR", Segment = "", Value = "val-fr1"
                              },
                              new PropertyData {
                                  Culture = "en-UK", Segment = "", Value = "val-uk1"
                              }
                          } }
                    },
                    CultureInfos = new Dictionary <string, CultureVariation>
                    {
                        // published data = only what's actually published, and IsDraft has to be false
                        { "fr-FR", new CultureVariation {
                              Name = "name-fr1", IsDraft = false, Date = new DateTime(2018, 01, 01, 01, 00, 00)
                          } },
                        { "en-UK", new CultureVariation {
                              Name = "name-uk1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00)
                          } },
                        { "de-DE", new CultureVariation {
                              Name = "name-de1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00)
                          } }
                    }
                }
            };

            // create a data source for NuCache
            var dataSource = new TestDataSource(kit);

            var runtime = Mock.Of <IRuntimeState>();

            Mock.Get(runtime).Setup(x => x.Level).Returns(RuntimeLevel.Run);

            // create data types, property types and content types
            var dataType = new DataType(new VoidEditor("Editor", Mock.Of <ILogger>()))
            {
                Id = 3
            };

            var dataTypes = new[]
            {
                dataType
            };

            _propertyType = new PropertyType("Umbraco.Void.Editor", ValueStorageType.Nvarchar)
            {
                Alias = "prop", DataTypeId = 3, Variations = ContentVariation.Culture
            };
            _contentType = new ContentType(-1)
            {
                Id = 2, Alias = "alias-ct", Variations = ContentVariation.Culture
            };
            _contentType.AddPropertyType(_propertyType);

            var contentTypes = new[]
            {
                _contentType
            };

            var contentTypeService = new Mock <IContentTypeService>();

            contentTypeService.Setup(x => x.GetAll()).Returns(contentTypes);
            contentTypeService.Setup(x => x.GetAll(It.IsAny <int[]>())).Returns(contentTypes);

            var mediaTypeService = new Mock <IMediaTypeService>();

            mediaTypeService.Setup(x => x.GetAll()).Returns(Enumerable.Empty <IMediaType>());
            mediaTypeService.Setup(x => x.GetAll(It.IsAny <int[]>())).Returns(Enumerable.Empty <IMediaType>());

            var contentTypeServiceBaseFactory = new Mock <IContentTypeBaseServiceProvider>();

            contentTypeServiceBaseFactory.Setup(x => x.For(It.IsAny <IContentBase>())).Returns(contentTypeService.Object);

            var dataTypeService = Mock.Of <IDataTypeService>();

            Mock.Get(dataTypeService).Setup(x => x.GetAll()).Returns(dataTypes);

            // create a service context
            var serviceContext = ServiceContext.CreatePartial(
                dataTypeService: dataTypeService,
                memberTypeService: Mock.Of <IMemberTypeService>(),
                memberService: Mock.Of <IMemberService>(),
                contentTypeService: contentTypeService.Object,
                mediaTypeService: mediaTypeService.Object,
                localizationService: Mock.Of <ILocalizationService>(),
                domainService: Mock.Of <IDomainService>()
                );

            // create a scope provider
            var scopeProvider = Mock.Of <IScopeProvider>();

            Mock.Get(scopeProvider)
            .Setup(x => x.CreateScope(
                       It.IsAny <IsolationLevel>(),
                       It.IsAny <RepositoryCacheMode>(),
                       It.IsAny <IEventDispatcher>(),
                       It.IsAny <bool?>(),
                       It.IsAny <bool>(),
                       It.IsAny <bool>()))
            .Returns(Mock.Of <IScope>);

            // create a published content type factory
            var contentTypeFactory = new PublishedContentTypeFactory(
                Mock.Of <IPublishedModelFactory>(),
                new PropertyValueConverterCollection(Array.Empty <IPropertyValueConverter>()),
                dataTypeService);

            // create a variation accessor
            _variationAccesor = new TestVariationContextAccessor();

            // at last, create the complete NuCache snapshot service!
            var options = new PublishedSnapshotServiceOptions {
                IgnoreLocalDb = true
            };

            _snapshotService = new PublishedSnapshotService(options,
                                                            null,
                                                            runtime,
                                                            serviceContext,
                                                            contentTypeFactory,
                                                            null,
                                                            new TestPublishedSnapshotAccessor(),
                                                            _variationAccesor,
                                                            Mock.Of <IProfilingLogger>(),
                                                            scopeProvider,
                                                            Mock.Of <IDocumentRepository>(),
                                                            Mock.Of <IMediaRepository>(),
                                                            Mock.Of <IMemberRepository>(),
                                                            new TestDefaultCultureAccessor(),
                                                            dataSource,
                                                            globalSettings,
                                                            Mock.Of <IEntityXmlSerializer>(),
                                                            Mock.Of <IPublishedModelFactory>(),
                                                            new UrlSegmentProviderCollection(new[] { new DefaultUrlSegmentProvider() }));

            // invariant is the current default
            _variationAccesor.VariationContext = new VariationContext();

            Mock.Get(factory).Setup(x => x.GetInstance(typeof(IVariationContextAccessor))).Returns(_variationAccesor);
        }