public void SingleNestedTest()
        {
            (var contentType1, _) = CreateContentTypes();

            // nested single converter returns the proper value clr type TestModel, and cache level
            Assert.AreEqual(typeof(TestElementModel), contentType1.GetPropertyType("property1").ClrType);
            Assert.AreEqual(PropertyCacheLevel.Element, contentType1.GetPropertyType("property1").CacheLevel);

            var key     = Guid.NewGuid();
            var keyA    = Guid.NewGuid();
            var content = new TestPublishedContent(contentType1, key, new[]
            {
                new TestPublishedProperty(contentType1.GetPropertyType("property1"), $@"[
                    {{ ""key"": ""{keyA}"", ""propertyN1"": ""foo"", ""ncContentTypeAlias"": ""contentN1"" }}
                ]")
            }, Mock.Of <IUmbracoContextAccessor>());
            var value = content.Value("property1");

            // nested single converter returns proper TestModel value
            Assert.IsInstanceOf <TestElementModel>(value);
            var valueM = (TestElementModel)value;

            Assert.AreEqual("foo", valueM.PropValue);
            Assert.AreEqual(keyA, valueM.Key);
        }
        public void ManyNestedTest()
        {
            (_, var contentType2) = CreateContentTypes();

            // nested many converter returns the proper value clr type IEnumerable<TestModel>, and cache level
            Assert.AreEqual(typeof(IEnumerable <TestElementModel>), contentType2.GetPropertyType("property2").ClrType);
            Assert.AreEqual(PropertyCacheLevel.Element, contentType2.GetPropertyType("property2").CacheLevel);

            var key     = Guid.NewGuid();
            var keyA    = Guid.NewGuid();
            var keyB    = Guid.NewGuid();
            var content = new TestPublishedContent(contentType2, key, new[]
            {
                new TestPublishedProperty(contentType2.GetPropertyType("property2"), $@"[
                    {{ ""key"": ""{keyA}"", ""propertyN1"": ""foo"", ""ncContentTypeAlias"": ""contentN1"" }},
                    {{ ""key"": ""{keyB}"", ""propertyN1"": ""bar"", ""ncContentTypeAlias"": ""contentN1"" }}
                ]")
            },
                                                   Mock.Of <IUmbracoContextAccessor>());
            var value = content.Value("property2");

            // nested many converter returns proper IEnumerable<TestModel> value
            Assert.IsInstanceOf <IEnumerable <IPublishedElement> >(value);
            Assert.IsInstanceOf <IEnumerable <TestElementModel> >(value);
            var valueM = ((IEnumerable <TestElementModel>)value).ToArray();

            Assert.AreEqual("foo", valueM[0].PropValue);
            Assert.AreEqual(keyA, valueM[0].Key);
            Assert.AreEqual("bar", valueM[1].PropValue);
            Assert.AreEqual(keyB, valueM[1].Key);
        }
        private IPublishedContent GetContent(bool createChildren, int indexVals)
        {
            var dataTypeService = new TestObjects.TestDataTypeService(
                new DataType(new VoidEditor(Mock.Of <ILogger>()))
            {
                Id = 1
            });

            var factory          = new PublishedContentTypeFactory(Mock.Of <IPublishedModelFactory>(), new PropertyValueConverterCollection(Array.Empty <IPropertyValueConverter>()), dataTypeService);
            var contentTypeAlias = createChildren ? "Parent" : "Child";
            var d = new TestPublishedContent
            {
                CreateDate  = DateTime.Now,
                CreatorId   = 1,
                CreatorName = "Shannon",
                Id          = 3,
                SortOrder   = 4,
                TemplateId  = 5,
                UpdateDate  = DateTime.Now,
                Path        = "-1,3",
                UrlSegment  = "home-page",
                Name        = "Page" + Guid.NewGuid().ToString(),
                Version     = Guid.NewGuid(),
                WriterId    = 1,
                WriterName  = "Shannon",
                Parent      = null,
                Level       = 1,
                Children    = new List <IPublishedContent>()
            };

            d.Properties = new Collection <IPublishedProperty>(new List <IPublishedProperty>
            {
                new RawValueProperty(factory.CreatePropertyType("property1", 1), d, "value" + indexVals),
                new RawValueProperty(factory.CreatePropertyType("property2", 1), d, "value" + (indexVals + 1))
            });
            if (createChildren)
            {
                d.Children = new List <IPublishedContent>()
                {
                    GetContent(false, indexVals + 3),
                    GetContent(false, indexVals + 6),
                    GetContent(false, indexVals + 9)
                };
            }

            if (!createChildren)
            {
                //create additional columns, used to test the different columns for child nodes
                ((Collection <IPublishedProperty>)d.Properties).Add(
                    new RawValueProperty(factory.CreatePropertyType("property4", 1), d, "value" + (indexVals + 2)));
            }
            else
            {
                ((Collection <IPublishedProperty>)d.Properties).Add(
                    new RawValueProperty(factory.CreatePropertyType("property3", 1), d, "value" + (indexVals + 2)));
            }

            d.ContentType = new PublishedContentType(22, contentTypeAlias, PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            return(d);
        }
Exemplo n.º 4
0
        public void BasicPublishedContent1Test()
        {
            var appCtx = ApplicationContext.EnsureContext(
                new DatabaseContext(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), new SqlSyntaxProviders(new[] { Mock.Of <ISqlSyntaxProvider>() })),
                new ServiceContext(),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(
                    Mock.Of <ILogger>(),
                    Mock.Of <IProfiler>()), true);

            var ctx = UmbracoContext.EnsureContext(
                Mock.Of <HttpContextBase>(),
                appCtx,
                new Mock <WebSecurity>(null, null).Object,
                Mock.Of <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(), true);

            var test_name = "test";

            //create an instance of our test implemention of IPublisheContent
            var content = new TestPublishedContent()
            {
                Name = test_name
            };
            //setup a helper object which will be given to the surface controller
            var helper = new UmbracoHelper(ctx, content);
            //we use a surface controller that takes in th context and helper so that we can setup them for our needs
            var controller = new BasicTestSurfaceController(ctx, helper);
            var res        = controller.BasicPublishedContentAction();
            var model      = res.Model as string;

            Assert.AreEqual(test_name, model);
        }
        public void Get_Url_For_Culture_Variant_Non_Current_Url()
        {
            const string currentUri = "http://example.us/test";

            var globalSettings = Mock.Get(Factory.GetInstance <IGlobalSettings>()); //this will modify the IGlobalSettings instance stored in the container

            globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);

            var umbracoSettings = Current.Configs.Settings();

            var contentType      = new PublishedContentType(666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Culture);
            var publishedContent = new TestPublishedContent(contentType, 1234, Guid.NewGuid(), new Dictionary <string, object>(), false);

            var publishedContentCache = new Mock <IPublishedContentCache>();

            publishedContentCache.Setup(x => x.GetRouteById(1234, "fr-FR"))
            .Returns("9876/home/test-fr");     //prefix with the root id node with the domain assigned as per the umbraco standard
            publishedContentCache.Setup(x => x.GetById(It.IsAny <int>()))
            .Returns <int>(id => id == 1234 ? publishedContent : null);

            var domainCache = new Mock <IDomainCache>();

            domainCache.Setup(x => x.GetAssigned(It.IsAny <int>(), false))
            .Returns((int contentId, bool includeWildcards) =>
            {
                if (contentId != 9876)
                {
                    return(Enumerable.Empty <Domain>());
                }
                return(new[]
                {
                    new Domain(2, "example.us", 9876, CultureInfo.GetCultureInfo("en-US"), false),     //default
                    new Domain(3, "example.fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false)
                });
            });
            domainCache.Setup(x => x.DefaultCulture).Returns(CultureInfo.GetCultureInfo("en-US").Name);

            var snapshot = Mock.Of <IPublishedSnapshot>(x => x.Content == publishedContentCache.Object && x.Domains == domainCache.Object);

            var snapshotService = new Mock <IPublishedSnapshotService>();

            snapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>()))
            .Returns(snapshot);

            var umbracoContext = GetUmbracoContext(currentUri, umbracoSettings: umbracoSettings,
                                                   urlProviders: new[] {
                new DefaultUrlProvider(umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper())
            },
                                                   globalSettings: globalSettings.Object,
                                                   snapshotService: snapshotService.Object);


            var url = umbracoContext.UrlProvider.GetUrl(1234, "fr-FR");

            //the current uri is not the culture specific domain we want, so the result is an absolute path to the culture specific domain
            Assert.AreEqual("http://example.fr/home/test-fr/", url);
        }
        private IPublishedContent GetContent(bool createChildren, int indexVals)
        {
            var contentTypeAlias = createChildren ? "Parent" : "Child";
            var d = new TestPublishedContent
            {
                CreateDate        = DateTime.Now,
                CreatorId         = 1,
                CreatorName       = "Shannon",
                DocumentTypeAlias = contentTypeAlias,
                DocumentTypeId    = 2,
                Id         = 3,
                SortOrder  = 4,
                TemplateId = 5,
                UpdateDate = DateTime.Now,
                Path       = "-1,3",
                UrlName    = "home-page",
                Name       = "Page" + Guid.NewGuid().ToString(),
                Version    = Guid.NewGuid(),
                WriterId   = 1,
                WriterName = "Shannon",
                Parent     = null,
                Level      = 1,
                Properties = new Collection <IPublishedProperty>(
                    new List <IPublishedProperty>()
                {
                    new PropertyResult("property1", "value" + indexVals, PropertyResultType.UserProperty),
                    new PropertyResult("property2", "value" + (indexVals + 1), PropertyResultType.UserProperty)
                }),
                Children = new List <IPublishedContent>()
            };

            if (createChildren)
            {
                d.Children = new List <IPublishedContent>()
                {
                    GetContent(false, indexVals + 3),
                    GetContent(false, indexVals + 6),
                    GetContent(false, indexVals + 9)
                };
            }
            if (!createChildren)
            {
                //create additional columns, used to test the different columns for child nodes
                d.Properties.Add(new PropertyResult("property4", "value" + (indexVals + 2), PropertyResultType.UserProperty));
            }
            else
            {
                d.Properties.Add(new PropertyResult("property3", "value" + (indexVals + 2), PropertyResultType.UserProperty));
            }
            return(d);
        }
Exemplo n.º 7
0
        public void Get_Url_For_Culture_Variant_Without_Domains_Non_Current_Url()
        {
            const string currentUri = "http://example.us/test";

            var globalSettings = Mock.Get(Factory.GetInstance <IGlobalSettings>()); //this will modify the IGlobalSettings instance stored in the container

            globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true);
            globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);

            var umbracoSettings = Current.Configs.Settings();

            var requestMock = Mock.Get(umbracoSettings.RequestHandler);

            requestMock.Setup(x => x.UseDomainPrefixes).Returns(false);

            var contentType      = new PublishedContentType(666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Culture);
            var publishedContent = new TestPublishedContent(contentType, 1234, Guid.NewGuid(), new Dictionary <string, object>(), false);

            var publishedContentCache = new Mock <IPublishedContentCache>();

            publishedContentCache.Setup(x => x.GetRouteById(1234, "fr-FR"))
            .Returns("9876/home/test-fr");     //prefix with the root id node with the domain assigned as per the umbraco standard
            publishedContentCache.Setup(x => x.GetById(It.IsAny <int>()))
            .Returns <int>(id => id == 1234 ? publishedContent : null);

            var domainCache = new Mock <IDomainCache>();

            domainCache.Setup(x => x.GetAssigned(It.IsAny <int>(), false))
            .Returns((int contentId, bool includeWildcards) => Enumerable.Empty <Domain>());

            var snapshot = Mock.Of <IPublishedSnapshot>(x => x.Content == publishedContentCache.Object && x.Domains == domainCache.Object);

            var snapshotService = new Mock <IPublishedSnapshotService>();

            snapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>()))
            .Returns(snapshot);

            var umbracoContext = GetUmbracoContext(currentUri, umbracoSettings: umbracoSettings,
                                                   urlProviders: new[] {
                new DefaultUrlProvider(umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper())
            },
                                                   globalSettings: globalSettings.Object,
                                                   snapshotService: snapshotService.Object);

            //even though we are asking for a specific culture URL, there are no domains assigned so all that can be returned is a normal relative url.
            var url = umbracoContext.UrlProvider.GetUrl(1234, "fr-FR");

            Assert.AreEqual("/home/test-fr/", url);
        }
        public void HelperPublishedContent1Test()
        {
            //Setup UmbracoContext with mocks. Sets UmbracoContext.Current
            var ctx = UmbracoUnitTestHelper.GetUmbracoContext();
            //create an instance of our test implemention of IPublisheContent
            var content = new TestPublishedContent()
            {
                Name = "test"
            };
            //setup a helper object which will be given to the surface controller
            var helper = UmbracoUnitTestHelper.GetUmbracoHelper(context: ctx, content: content);
            //we use a surface controller that takes in th context and helper so that we can setup them for our needs
            var controller = new BasicTestSurfaceController(ctx, helper);
            var res        = controller.BasicPublishedContentAction();
            var model      = res.Model as string;

            Assert.AreEqual(content.Name, model);
        }
Exemplo n.º 9
0
        public void SimpleConverter2Test()
        {
            var cacheMock    = new Mock <IPublishedContentCache>();
            var cacheContent = new Dictionary <int, IPublishedContent>();

            cacheMock.Setup(x => x.GetById(It.IsAny <int>())).Returns <int>(id => cacheContent.TryGetValue(id, out IPublishedContent content) ? content : null);
            var publishedSnapshotMock = new Mock <IPublishedSnapshot>();

            publishedSnapshotMock.Setup(x => x.Content).Returns(cacheMock.Object);
            var publishedSnapshotAccessorMock = new Mock <IPublishedSnapshotAccessor>();

            publishedSnapshotAccessorMock.Setup(x => x.PublishedSnapshot).Returns(publishedSnapshotMock.Object);
            var publishedSnapshotAccessor = publishedSnapshotAccessorMock.Object;

            var converters = new PropertyValueConverterCollection(new IPropertyValueConverter[]
            {
                new SimpleConverter2(publishedSnapshotAccessor),
            });

            var dataTypeService = new TestObjects.TestDataTypeService(
                new DataType(new VoidEditor(Mock.Of <ILogger>()))
            {
                Id = 1
            });

            var contentTypeFactory = new PublishedContentTypeFactory(Mock.Of <IPublishedModelFactory>(), converters, dataTypeService);

            var elementType1 = contentTypeFactory.CreateContentType(1000, "element1", new[]
            {
                contentTypeFactory.CreatePropertyType("prop1", 1),
            });

            var element1 = new PublishedElement(elementType1, Guid.NewGuid(), new Dictionary <string, object> {
                { "prop1", "1234" }
            }, false);

            var cntType1 = contentTypeFactory.CreateContentType(1001, "cnt1", Array.Empty <PublishedPropertyType>());
            var cnt1     = new TestPublishedContent(cntType1, 1234, Guid.NewGuid(), new Dictionary <string, object>(), false);

            cacheContent[cnt1.Id] = cnt1;

            Assert.AreSame(cnt1, element1.Value("prop1"));
        }
        public void HelperCurrentPageTest()
        {
            //Setup UmbracoContext with mocks. Sets UmbracoContext.Current
            var ctx = UmbracoUnitTestHelper.GetUmbracoContext();

            var content = new TestPublishedContent()
            {
                Name = "test"
            };

            var controller = new BasicTestSurfaceController();

            //Setting the controller context will provide the route data, route def, publushed content request, and current page to the surface controller
            controller.ControllerContext = UmbracoUnitTestHelper.GetControllerContext(ctx, controller, UmbracoUnitTestHelper.GetPublishedContentRequest(ctx, currentContent: content));

            var res   = controller.BasicCurrentPageAction();
            var model = res.Model as string;

            Assert.AreEqual(content.Name, model);
        }
		private IPublishedContent GetContent(bool createChildren, int indexVals)
		{
		    var contentTypeAlias = createChildren ? "Parent" : "Child";
			var d = new TestPublishedContent
				{
					CreateDate = DateTime.Now,
					CreatorId = 1,
					CreatorName = "Shannon",
                    DocumentTypeAlias = contentTypeAlias,
					DocumentTypeId = 2,
					Id = 3,
					SortOrder = 4,
					TemplateId = 5,
					UpdateDate = DateTime.Now,
					Path = "-1,3",
					UrlName = "home-page",
					Name = "Page" + Guid.NewGuid().ToString(),
					Version = Guid.NewGuid(),
					WriterId = 1,
					WriterName = "Shannon",
					Parent = null,
					Level = 1,
					Properties = new Collection<IPublishedProperty>(
						new List<IPublishedProperty>()
							{
								new PropertyResult("property1", "value" + indexVals, Guid.NewGuid(), PropertyResultType.UserProperty),
								new PropertyResult("property2", "value" + (indexVals + 1), Guid.NewGuid(), PropertyResultType.UserProperty)
							}),
					Children = new List<IPublishedContent>()
				};
			if (createChildren)
			{
				d.Children = new List<IPublishedContent>()
					{
						GetContent(false, indexVals + 3),
						GetContent(false, indexVals + 6),
						GetContent(false, indexVals + 9)
					};
			}
			if (!createChildren)
			{
				//create additional columns, used to test the different columns for child nodes
				d.Properties.Add(new PropertyResult("property4", "value" + (indexVals + 2), Guid.NewGuid(), PropertyResultType.UserProperty));
			}
			else
			{
				d.Properties.Add(new PropertyResult("property3", "value" + (indexVals + 2), Guid.NewGuid(), PropertyResultType.UserProperty));
			}
			return d;
		}
Exemplo n.º 12
0
        public void SimpleConverter3Test()
        {
            Current.Reset();
            var register = RegisterFactory.Create();

            var composition = new Composition(register, new TypeLoader(), Mock.Of <IProfilingLogger>(), ComponentTests.MockRuntimeState(RuntimeLevel.Run));

            composition.WithCollectionBuilder <PropertyValueConverterCollectionBuilder>()
            .Append <SimpleConverter3A>()
            .Append <SimpleConverter3B>();

            IPublishedModelFactory factory = new PublishedModelFactory(new[]
            {
                typeof(PublishedSnapshotTestObjects.TestElementModel1), typeof(PublishedSnapshotTestObjects.TestElementModel2),
                typeof(PublishedSnapshotTestObjects.TestContentModel1), typeof(PublishedSnapshotTestObjects.TestContentModel2),
            });

            register.Register(f => factory);

            Current.Factory = composition.CreateFactory();

            var cacheMock    = new Mock <IPublishedContentCache>();
            var cacheContent = new Dictionary <int, IPublishedContent>();

            cacheMock.Setup(x => x.GetById(It.IsAny <int>())).Returns <int>(id => cacheContent.TryGetValue(id, out IPublishedContent content) ? content : null);
            var publishedSnapshotMock = new Mock <IPublishedSnapshot>();

            publishedSnapshotMock.Setup(x => x.Content).Returns(cacheMock.Object);
            var publishedSnapshotAccessorMock = new Mock <IPublishedSnapshotAccessor>();

            publishedSnapshotAccessorMock.Setup(x => x.PublishedSnapshot).Returns(publishedSnapshotMock.Object);
            register.Register(f => publishedSnapshotAccessorMock.Object);

            var converters = Current.Factory.GetInstance <PropertyValueConverterCollection>();

            var dataTypeService = new TestObjects.TestDataTypeService(
                new DataType(new VoidEditor(Mock.Of <ILogger>()))
            {
                Id = 1
            },
                new DataType(new VoidEditor("2", Mock.Of <ILogger>()))
            {
                Id = 2
            });

            var contentTypeFactory = new PublishedContentTypeFactory(factory, converters, dataTypeService);

            var elementType1 = contentTypeFactory.CreateContentType(1000, "element1", new[]
            {
                contentTypeFactory.CreatePropertyType("prop1", 1),
            });

            var elementType2 = contentTypeFactory.CreateContentType(1001, "element2", new[]
            {
                contentTypeFactory.CreatePropertyType("prop2", 2),
            });

            var contentType1 = contentTypeFactory.CreateContentType(1002, "content1", new[]
            {
                contentTypeFactory.CreatePropertyType("prop1", 1),
            });

            var contentType2 = contentTypeFactory.CreateContentType(1003, "content2", new[]
            {
                contentTypeFactory.CreatePropertyType("prop2", 2),
            });

            var element1 = new PublishedElement(elementType1, Guid.NewGuid(), new Dictionary <string, object> {
                { "prop1", "val1" }
            }, false);
            var element2 = new PublishedElement(elementType2, Guid.NewGuid(), new Dictionary <string, object> {
                { "prop2", "1003" }
            }, false);
            var cnt1 = new TestPublishedContent(contentType1, 1003, Guid.NewGuid(), new Dictionary <string, object> {
                { "prop1", "val1" }
            }, false);
            var cnt2 = new TestPublishedContent(contentType2, 1004, Guid.NewGuid(), new Dictionary <string, object> {
                { "prop2", "1003" }
            }, false);

            cacheContent[cnt1.Id] = cnt1.CreateModel();
            cacheContent[cnt2.Id] = cnt2.CreateModel();

            // can get the actual property Clr type
            // ie ModelType gets properly mapped by IPublishedContentModelFactory
            // must test ModelClrType with special equals 'cos they are not ref-equals
            Assert.IsTrue(ModelType.Equals(typeof(IEnumerable <>).MakeGenericType(ModelType.For("content1")), contentType2.GetPropertyType("prop2").ModelClrType));
            Assert.AreEqual(typeof(IEnumerable <PublishedSnapshotTestObjects.TestContentModel1>), contentType2.GetPropertyType("prop2").ClrType);

            // can create a model for an element
            var model1 = factory.CreateModel(element1);

            Assert.IsInstanceOf <PublishedSnapshotTestObjects.TestElementModel1>(model1);
            Assert.AreEqual("val1", ((PublishedSnapshotTestObjects.TestElementModel1)model1).Prop1);

            // can create a model for a published content
            var model2 = factory.CreateModel(element2);

            Assert.IsInstanceOf <PublishedSnapshotTestObjects.TestElementModel2>(model2);
            var mmodel2 = (PublishedSnapshotTestObjects.TestElementModel2)model2;

            // and get direct property
            Assert.IsInstanceOf <PublishedSnapshotTestObjects.TestContentModel1[]>(model2.Value("prop2"));
            Assert.AreEqual(1, ((PublishedSnapshotTestObjects.TestContentModel1[])model2.Value("prop2")).Length);

            // and get model property
            Assert.IsInstanceOf <IEnumerable <PublishedSnapshotTestObjects.TestContentModel1> >(mmodel2.Prop2);
            Assert.IsInstanceOf <PublishedSnapshotTestObjects.TestContentModel1[]>(mmodel2.Prop2);
            var mmodel1 = mmodel2.Prop2.First();

            // and we get what we want
            Assert.AreSame(cacheContent[mmodel1.Id], mmodel1);
        }