public void U4_4056_TryAscii()
        {
            var settings    = SettingsForTests.GenerateMockSettings();
            var contentMock = Mock.Get(settings.RequestHandler);

            contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty <IChar>());
            contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false);
            SettingsForTests.ConfigureSettings(settings);

            const string input1 = "ÆØÅ and æøå and 中文测试 and  אודות האתר and größer БбДдЖж page";
            const string input2 = "ÆØÅ and æøå and größer БбДдЖж page";

            var helper = new DefaultShortStringHelper(settings).WithDefaultConfig(); // unicode

            Assert.AreEqual("æøå-and-æøå-and-中文测试-and-אודות-האתר-and-größer-ббдджж-page", helper.CleanStringForUrlSegment(input1));
            Assert.AreEqual("æøå-and-æøå-and-größer-ббдджж-page", helper.CleanStringForUrlSegment(input2));

            helper = new DefaultShortStringHelper(SettingsForTests.GetDefault())
                     .WithConfig(CleanStringType.UrlSegment, new DefaultShortStringHelper.Config
            {
                IsTerm     = (c, leading) => char.IsLetterOrDigit(c) || c == '_',
                StringType = CleanStringType.LowerCase | CleanStringType.TryAscii,     // try ascii
                Separator  = '-'
            });
            Assert.AreEqual("æøå-and-æøå-and-中文测试-and-אודות-האתר-and-größer-ббдджж-page", helper.CleanStringForUrlSegment(input1));
            Assert.AreEqual("aeoa-and-aeoa-and-grosser-bbddzhzh-page", helper.CleanStringForUrlSegment(input2));
        }
        public override void Initialize()
        {
            base.Initialize();

            //generate new mock settings and assign so we can configure in individual tests
            _umbracoSettings = SettingsForTests.GenerateMockSettings();
            SettingsForTests.ConfigureSettings(_umbracoSettings);

            var url = "/test";

            var lookup  = new Umbraco.Web.Routing.ContentFinderByNiceUrl();
            var lookups = new Umbraco.Web.Routing.IContentFinder[] { lookup };

            var t = Template.MakeNew("test", new User(0));

            var umbracoContext = GetUmbracoContext(url, t.Id);
            var urlProvider    = new UrlProvider(umbracoContext, _umbracoSettings.WebRouting, new IUrlProvider[] { new DefaultUrlProvider() });
            var routingContext = new RoutingContext(
                umbracoContext,
                lookups,
                new FakeLastChanceFinder(),
                urlProvider);

            //assign the routing context back to the umbraco context
            umbracoContext.RoutingContext = routingContext;

            ////assign the routing context back to the umbraco context
            //umbracoContext.RoutingContext = routingContext;
            Umbraco.Web.UmbracoContext.Current = routingContext.UmbracoContext;
        }
Exemple #3
0
        public override void Initialize()
        {
            base.Initialize();

            _httpContextFactory = new FakeHttpContextFactory("~/Home");
            //ensure the StateHelper is using our custom context
            StateHelper.HttpContext = _httpContextFactory.HttpContext;

            var settings    = SettingsForTests.GenerateMockSettings();
            var contentMock = Mock.Get(settings.Content);

            contentMock.Setup(x => x.UseLegacyXmlSchema).Returns(false);
            SettingsForTests.ConfigureSettings(settings);
            _xml = new XmlDocument();
            _xml.LoadXml(GetXml());
            var cache = new PublishedContentCache
            {
                GetXmlDelegate = (context, preview) => _xml
            };

            _umbracoContext = new UmbracoContext(
                _httpContextFactory.HttpContext,
                ApplicationContext,
                new PublishedCaches(cache, new PublishedMediaCache(ApplicationContext)),
                new WebSecurity(_httpContextFactory.HttpContext, ApplicationContext));

            _cache = _umbracoContext.ContentCache;
        }
        public override void Initialize()
        {
            base.Initialize();

            this.redirectUrlServiceMock  = new Mock <IRedirectUrlService>();
            this.mappingEngineMock       = new Mock <IMappingEngine>();
            this.localizeTextServiceMock = new Mock <ILocalizedTextService>();
            this.contentServiceMock      = new Mock <IContentService>();
            this.domainServiceMock       = new Mock <IDomainService>();

            SettingsForTests.ConfigureSettings(SettingsForTests.GenerateMockSettings());



            var umbracoContext = this.GetUmbracoContext("http://localhost", -1, new RouteData(), false);

            this.controller = new RedirectsApiController(umbracoContext, this.redirectUrlServiceMock.Object, this.mappingEngineMock.Object, this.Logger, this.localizeTextServiceMock.Object, this.contentServiceMock.Object, this.domainServiceMock.Object)
            {
                Request = new HttpRequestMessage
                {
                    Properties =
                    {
                        {
                            HttpPropertyKeys.HttpConfigurationKey,
                            new HttpConfiguration()
                        }
                    }
                }
            };
        }
Exemple #5
0
        public void Setup()
        {
            var settings = SettingsForTests.GenerateMockSettings();

            SettingsForTests.ConfigureSettings(settings);

            var logger = Mock.Of <ILogger>();

            var applicationContext = ApplicationContext.EnsureContext(
                new DatabaseContext(
                    Mock.Of <IDatabaseFactory>(),
                    logger,
                    new SqlSyntaxProviders(new ISqlSyntaxProvider[0])
                    ),
                new ServiceContext(
                    contentService: Mock.Of <IContentService>() //, ...
                    ),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(logger, Mock.Of <IProfiler>()),
                true
                );

            var httpContext = Mock.Of <HttpContextBase>();

            umbracoContext = UmbracoContext.EnsureContext(
                httpContext,
                applicationContext,
                new WebSecurity(httpContext, applicationContext),
                settings,
                new List <IUrlProvider>(),
                true,
                false
                );
        }
Exemple #6
0
        public void Get_Nice_Url_Relative_Or_Absolute()
        {
            var settings    = SettingsForTests.GenerateMockSettings();
            var requestMock = Mock.Get(settings.RequestHandler);

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

            var routingContext = GetRoutingContext("http://domain1.com/test", 1111, umbracoSettings: settings);

            SettingsForTests.UseDirectoryUrls         = true;
            SettingsForTests.HideTopLevelNodeFromPath = false;

            SetDomains4();

            Assert.AreEqual("/en/1001-1-1/", routingContext.UrlProvider.GetUrl(100111));
            Assert.AreEqual("http://domain3.com/en/1003-1-1/", routingContext.UrlProvider.GetUrl(100311));

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

            Assert.AreEqual("http://domain1.com/en/1001-1-1/", routingContext.UrlProvider.GetUrl(100111));
            Assert.AreEqual("http://domain3.com/en/1003-1-1/", routingContext.UrlProvider.GetUrl(100311));

            requestMock.Setup(x => x.UseDomainPrefixes).Returns(false);
            routingContext.UrlProvider.Mode = UrlProviderMode.Absolute;

            Assert.AreEqual("http://domain1.com/en/1001-1-1/", routingContext.UrlProvider.GetUrl(100111));
            Assert.AreEqual("http://domain3.com/en/1003-1-1/", routingContext.UrlProvider.GetUrl(100311));
        }
        public void CleanStringDefaultConfig()
        {
            var settings    = SettingsForTests.GenerateMockSettings();
            var contentMock = Mock.Get(settings.RequestHandler);

            contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty <IChar>());
            contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false);
            SettingsForTests.ConfigureSettings(settings);

            var helper = new DefaultShortStringHelper(settings).WithDefaultConfig();

            const string input = "0123 中文测试 中文测试 léger ZÔRG (2) a?? *x";

            var alias    = helper.CleanStringForSafeAlias(input);
            var filename = helper.CleanStringForSafeFileName(input);
            var segment  = helper.CleanStringForUrlSegment(input);

            // umbraco-cased ascii alias, must begin with a proper letter
            Assert.AreEqual("legerZORG2AX", alias, "alias");

            // lower-cased, utf8 filename, removing illegal filename chars, using dash-separator
            Assert.AreEqual("0123-中文测试-中文测试-léger-zôrg-2-a-x", filename, "filename");

            // lower-cased, utf8 url segment, only letters and digits, using dash-separator
            Assert.AreEqual("0123-中文测试-中文测试-léger-zôrg-2-a-x", segment, "segment");
        }
        public override void Initialize()
        {
            base.Initialize();

            //generate new mock settings and assign so we can configure in individual tests
            _umbracoSettings = SettingsForTests.GenerateMockSettings();
            SettingsForTests.ConfigureSettings(_umbracoSettings);
        }
        private void SetupUmbraco()
        {
            settings = SettingsForTests.GenerateMockSettings();
            SettingsForTests.ConfigureSettings(settings);

            routingContext = GetRoutingContext("http://localhost", -1, new RouteData());
            umbracoContext = routingContext.UmbracoContext;
            umbracoContext.PublishedContentRequest = new PublishedContentRequest(new Uri("http://localhost"), routingContext,
                                                                                 settings.WebRouting, (s) => new[] { "Kunde" });
        }
Exemple #10
0
        private void SetupForLegacy()
        {
            var settings    = SettingsForTests.GenerateMockSettings();
            var contentMock = Mock.Get(settings.Content);

            contentMock.Setup(x => x.UseLegacyXmlSchema).Returns(true);
            SettingsForTests.ConfigureSettings(settings);
            _xml = new XmlDocument();
            _xml.LoadXml(GetLegacyXml());
        }
Exemple #11
0
        public void DoNotPolluteCache()
        {
            SettingsForTests.UseDirectoryUrls         = true;
            SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains

            var settings = SettingsForTests.GenerateMockSettings();
            var request  = Mock.Get(settings.RequestHandler);

            request.Setup(x => x.UseDomainPrefixes).Returns(true);

            SetDomains1();

            RoutingContext routingContext;
            string         url = "http://domain1.com/1001-1/1001-1-1";

            // get the nice url for 100111
            routingContext = GetRoutingContext(url, 9999, umbracoSettings: settings);
            Assert.AreEqual("http://domain2.com/1001-1-1/", routingContext.UrlProvider.GetUrl(100111, true));

            // check that the proper route has been cached
            var cache = routingContext.UmbracoContext.ContentCache.InnerCache as PublishedContentCache;

            if (cache == null)
            {
                throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
            }
            var cachedRoutes = cache.RoutesCache.GetCachedRoutes();

            Assert.AreEqual("10011/1001-1-1", cachedRoutes[100111]);

            // route a rogue url
            url = "http://domain1.com/1001-1/1001-1-1";
            var uri = routingContext.UmbracoContext.CleanedUmbracoUrl;             //very important to use the cleaned up umbraco url
            var pcr = new PublishedContentRequest(uri, routingContext);

            pcr.Engine.FindDomain();
            Assert.IsTrue(pcr.HasDomain);

            // check that it's been routed
            var lookup = new ContentFinderByNiceUrl();
            var result = lookup.TryFindContent(pcr);

            Assert.IsTrue(result);
            Assert.AreEqual(100111, pcr.PublishedContent.Id);

            // has the cache been polluted?
            cachedRoutes = cache.RoutesCache.GetCachedRoutes();
            Assert.AreEqual("10011/1001-1-1", cachedRoutes[100111]);             // no
            //Assert.AreEqual("1001/1001-1/1001-1-1", cachedRoutes[100111]); // yes

            // what's the nice url now?
            Assert.AreEqual("http://domain2.com/1001-1-1/", routingContext.UrlProvider.GetUrl(100111));             // good
            //Assert.AreEqual("http://domain1.com/1001-1/1001-1-1", routingContext.NiceUrlProvider.GetNiceUrl(100111, true)); // bad
        }
Exemple #12
0
        public override void TestSetup()
        {
            base.TestSetup();

            var settings    = SettingsForTests.GenerateMockSettings();
            var contentMock = Mock.Get(settings.Content);

            contentMock.Setup(x => x.ForceSafeAliases).Returns(true);
            contentMock.Setup(x => x.UmbracoLibraryCacheDuration).Returns(1800);
            SettingsForTests.ConfigureSettings(settings);
        }
        public void U4_4055_4056()
        {
            var settings    = SettingsForTests.GenerateMockSettings();
            var contentMock = Mock.Get(settings.RequestHandler);

            contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty <IChar>());
            contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false);
            SettingsForTests.ConfigureSettings(settings);

            const string input = "publishedVersion";

            Assert.AreEqual("PublishedVersion", input.ConvertCase(StringAliasCaseType.PascalCase));                                                     // obsolete, use the one below
            Assert.AreEqual("PublishedVersion", input.ToCleanString(CleanStringType.ConvertCase | CleanStringType.PascalCase | CleanStringType.Ascii)); // role, case and code
        }
        public override void Initialize()
        {
            base.Initialize();
            SettingsForTests.ConfigureSettings(SettingsForTests.GenerateMockSettings());
            this.relationService = new Mock <IRelationService>();
            this.dataTypeService = new Mock <IDataTypeService>();

            this.serviceMock = new Mock <NexuService>(
                this.ProfilingLogger,
                this.relationService.Object,
                PropertyParserResolver.Current,
                this.dataTypeService.Object)
            {
                CallBase = true
            };
            this.service = this.serviceMock.Object;
        }
        public void Uri_From_Umbraco(string sourceUrl, string expectedUrl, bool directoryUrls, bool trailingSlash)
        {
            ConfigurationManager.AppSettings.Set("umbracoUseDirectoryUrls", directoryUrls ? "true" : "false");

            var settings    = SettingsForTests.GenerateMockSettings();
            var requestMock = Mock.Get(settings.RequestHandler);

            requestMock.Setup(x => x.AddTrailingSlash).Returns(trailingSlash);
            SettingsForTests.ConfigureSettings(settings);

            UriUtility.SetAppDomainAppVirtualPath("/");

            var expectedUri = NewUri(expectedUrl);
            var sourceUri   = NewUri(sourceUrl);
            var resultUri   = UriUtility.UriFromUmbraco(sourceUri);

            Assert.AreEqual(expectedUri.ToString(), resultUri.ToString());
        }
Exemple #16
0
        public override void Initialize()
        {
            base.Initialize();

            this.nexuServiceMock    = new Mock <INexuService>();
            this.mappingEngineMock  = new Mock <IMappingEngine>();
            this.contentServiceMock = new Mock <IContentService>();
            this.mediaServiceMock   = new Mock <IMediaService>();

            // Mocked settings are now necessary
            SettingsForTests.ConfigureSettings(SettingsForTests.GenerateMockSettings());

            // Routing context necessary for published content request
            this.RouteData = new RouteData();
            var routingContext = this.GetRoutingContext(
                "http://localhost",
                -1,
                this.RouteData,
                true,
                UmbracoConfig.For.UmbracoSettings());

            // setup umbraco context
            this.UmbracoContext = routingContext.UmbracoContext;

            this.controller = new NexuApiController(
                this.UmbracoContext,
                this.nexuServiceMock.Object,
                this.mappingEngineMock.Object,
                this.contentServiceMock.Object,
                this.mediaServiceMock.Object)
            {
                Request = new HttpRequestMessage
                {
                    Properties =
                    {
                        {
                            HttpPropertyKeys.HttpConfigurationKey,
                            new HttpConfiguration()
                        }
                    }
                }
            };
        }
Exemple #17
0
        public void Get_Nice_Url_NestedDomains(int nodeId, string currentUrl, bool absolute, string expected)
        {
            var settings = SettingsForTests.GenerateMockSettings();
            var request  = Mock.Get(settings.RequestHandler);

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

            var routingContext = GetRoutingContext("/test", 1111, umbracoSettings: settings);

            SettingsForTests.UseDirectoryUrls         = true;
            SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains

            SetDomains4();

            var currentUri = new Uri(currentUrl);
            var result     = routingContext.UrlProvider.GetUrl(nodeId, currentUri, absolute);

            Assert.AreEqual(expected, result);
        }
Exemple #18
0
        public void Get_Nice_Url_Alternate()
        {
            var settings       = SettingsForTests.GenerateMockSettings();
            var routingContext = GetRoutingContext("http://domain1.com/en/test", 1111, umbracoSettings: settings);

            SettingsForTests.UseDirectoryUrls         = true;
            SettingsForTests.HideTopLevelNodeFromPath = false;

            SetDomains5();

            var url = routingContext.UrlProvider.GetUrl(100111, true);

            Assert.AreEqual("http://domain1.com/en/1001-1-1/", url);

            var result = routingContext.UrlProvider.GetOtherUrls(100111).ToArray();

            Assert.AreEqual(2, result.Count());
            Assert.IsTrue(result.Contains("http://domain1a.com/en/1001-1-1/"));
            Assert.IsTrue(result.Contains("http://domain1b.com/en/1001-1-1/"));
        }
        public void Convert_From_Standard_Xml()
        {
            var config = SettingsForTests.GenerateMockSettings();

            var contentMock = Mock.Get(config.Content);

            contentMock.Setup(x => x.UseLegacyXmlSchema).Returns(true);

            SettingsForTests.ConfigureSettings(config);

            var nodeId = 2112;

            var xml  = XElement.Parse(@"<Image id=""2112"" version=""5b3e46ab-3e37-4cfa-ab70-014234b5bd39"" parentID=""2222"" level=""3"" writerID=""0"" nodeType=""1032"" template=""0"" sortOrder=""1"" createDate=""2010-05-19T17:32:46"" updateDate=""2010-05-19T17:32:46"" nodeName=""Sam's Umbraco Image"" urlName=""acnestressscrub"" writerName=""Administrator"" nodeTypeAlias=""Image"" path=""-1,1111,2222,2112"" isDoc="""">
				<umbracoFile><![CDATA[/media/1234/blah.pdf]]></umbracoFile>
				<umbracoWidth>115</umbracoWidth>
				<umbracoHeight>268</umbracoHeight>
				<umbracoBytes>10726</umbracoBytes>
				<umbracoExtension>jpg</umbracoExtension>
				<Image id=""3113"" version=""5b3e46ab-3e37-4cfa-ab70-014234b5bd33"" parentID=""2112"" level=""4"" writerID=""0"" nodeType=""1032"" template=""0"" sortOrder=""2"" createDate=""2010-05-19T17:32:46"" updateDate=""2010-05-19T17:32:46"" nodeName=""Another Umbraco Image"" urlName=""acnestressscrub"" writerName=""Administrator"" nodeTypeAlias=""Image"" path=""-1,1111,2222,2112,3113"" isDoc="""">
					<umbracoFile><![CDATA[/media/1234/blah.pdf]]></umbracoFile>
					<umbracoWidth>115</umbracoWidth>
					<umbracoHeight>268</umbracoHeight>
					<umbracoBytes>10726</umbracoBytes>
					<umbracoExtension>jpg</umbracoExtension>
				</Image>
			</Image>"            );
            var node = xml.DescendantsAndSelf("Image").Single(x => (int)x.Attribute("id") == nodeId);

            var publishedMedia = new PublishedMediaCache(ApplicationContext);

            var nav = node.CreateNavigator();

            var converted = publishedMedia.CreateFromCacheValues(
                publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/Image"), nodeId));

            Assert.AreEqual(nodeId, converted.Id);
            Assert.AreEqual(3, converted.Level);
            Assert.AreEqual(1, converted.SortOrder);
            Assert.AreEqual("Sam's Umbraco Image", converted.Name);
            Assert.AreEqual("-1,1111,2222,2112", converted.Path);
        }
        public void TestNoScope()
        {
            content.TestingUpdateSitemapProvider = false;

            var settings    = SettingsForTests.GenerateMockSettings();
            var contentMock = Mock.Get(settings.Content);

            contentMock.Setup(x => x.XmlCacheEnabled).Returns(false);
            SettingsForTests.ConfigureSettings(settings);

            var contentType = new ContentType(-1)
            {
                Alias = "contenttype", Name = "test"
            };

            ApplicationContext.Services.ContentTypeService.Save(contentType);

            _cacheHandler = new CacheRefresherEventHandler(true);
            _cacheHandler.OnApplicationStarted(null, ApplicationContext);

            var xml = content.Instance.XmlContent;

            Assert.IsNotNull(xml);
            var beforeXml = xml.OuterXml;
            var item      = new Content("name", -1, contentType);

            ApplicationContext.Services.ContentService.SaveAndPublishWithStatus(item);

            Console.WriteLine("Xml Before:");
            Console.WriteLine(xml.OuterXml);
            Assert.AreEqual(beforeXml, xml.OuterXml);

            xml = content.Instance.XmlContent;
            Assert.IsNotNull(xml);
            Console.WriteLine("Xml After:");
            Console.WriteLine(xml.OuterXml);
            var node = xml.GetElementById(item.Id.ToString());

            Assert.IsNotNull(node);
        }
        public override void Initialize()
        {
            // required so we can access property.Value
            //PropertyValueConvertersResolver.Current = new PropertyValueConvertersResolver();

            base.Initialize();

            //generate new mock settings and assign so we can configure in individual tests
            _umbracoSettings = SettingsForTests.GenerateMockSettings();
            SettingsForTests.ConfigureSettings(_umbracoSettings);

            var scriptingMock = Mock.Get(_umbracoSettings.Scripting);

            scriptingMock.Setup(x => x.DataTypeModelStaticMappings).Returns(new List <IRazorStaticMapping>());

            // need to specify a custom callback for unit tests
            // AutoPublishedContentTypes generates properties automatically
            // when they are requested, but we must declare those that we
            // explicitely want to be here...

            var propertyTypes = new[]
            {
                // AutoPublishedContentType will auto-generate other properties
                new PublishedPropertyType("umbracoNaviHide", 0, "?"),
                new PublishedPropertyType("selectedNodes", 0, "?"),
                new PublishedPropertyType("umbracoUrlAlias", 0, "?"),
                new PublishedPropertyType("content", 0, Constants.PropertyEditors.TinyMCEAlias),
                new PublishedPropertyType("testRecursive", 0, "?"),
                new PublishedPropertyType("siteTitle", 0, "?"),
                new PublishedPropertyType("creatorName", 0, "?"),
                new PublishedPropertyType("blah", 0, "?"),     // ugly error when that one is missing...
            };
            var type = new AutoPublishedContentType(0, "anything", propertyTypes);

            PublishedContentType.GetPublishedContentTypeCallback = (alias) => type;
        }
        public void TestScope(bool complete)
        {
            content.TestingUpdateSitemapProvider = false;

            var httpContextItems = new Hashtable();

            content.HttpContextItemsGetter = () => httpContextItems;

            var settings    = SettingsForTests.GenerateMockSettings();
            var contentMock = Mock.Get(settings.Content);

            contentMock.Setup(x => x.XmlCacheEnabled).Returns(false);
            SettingsForTests.ConfigureSettings(settings);

            var contentType = new ContentType(-1)
            {
                Alias = "contenttype", Name = "test"
            };

            ApplicationContext.Services.ContentTypeService.Save(contentType);

            _cacheHandler = new CacheRefresherEventHandler(true);
            _cacheHandler.OnApplicationStarted(null, ApplicationContext);

            var xml = content.Instance.XmlContent;

            Assert.IsNotNull(xml);
            Assert.AreSame(xml, httpContextItems[content.XmlContextContentItemKey]);
            var beforeXml      = xml;
            var beforeOuterXml = beforeXml.OuterXml;
            var item           = new Content("name", -1, contentType);

            Console.WriteLine("Xml Before:");
            Console.WriteLine(xml.OuterXml);

            var evented = 0;

            _onPublishedAssertAction = () =>
            {
                evented++;
                xml = content.Instance.XmlContent;
                Assert.IsNotNull(xml);
                Assert.AreNotSame(beforeXml, xml);
                Console.WriteLine("Xml Event:");
                Console.WriteLine(xml.OuterXml);
                var node = xml.GetElementById(item.Id.ToString());
                Assert.IsNotNull(node);
            };

            ContentService.Published += OnPublishedAssert;

            using (var scope = ApplicationContext.Current.ScopeProvider.CreateScope())
            {
                ApplicationContext.Services.ContentService.SaveAndPublishWithStatus(item); // should create an xml clone
                item.Name = "changed";
                ApplicationContext.Services.ContentService.SaveAndPublishWithStatus(item); // should re-use the xml clone

                // this should never change
                Assert.AreEqual(beforeOuterXml, beforeXml.OuterXml);

                // this does not change, other thread don't see the changes
                xml = content.Instance.XmlContentInternal;
                Assert.IsNotNull(xml);
                Assert.AreSame(beforeXml, xml);
                Console.WriteLine("XmlInternal During:");
                Console.WriteLine(xml.OuterXml);
                Assert.AreEqual(beforeOuterXml, xml.OuterXml);

                // this does not change during the scope (only in events)
                // because it is the events that trigger the changes
                xml = content.Instance.XmlContent;
                Assert.IsNotNull(xml);
                Assert.AreSame(beforeXml, xml);

                // note
                // this means that, as long as ppl don't create scopes, they'll see their
                // changes right after SaveAndPublishWithStatus, but if they create scopes,
                // they will have to wail until the scope is completed, ie wait until the
                // events trigger, to use eg GetUrl etc

                if (complete)
                {
                    scope.Complete();
                }
            }

            //The reason why there is only 1 event occuring is because we are publishing twice for the same event for the same
            //object and the scope deduplicates the events (uses the latest)
            Assert.AreEqual(complete ? 1 : 0, evented);

            // this should never change
            Assert.AreEqual(beforeOuterXml, beforeXml.OuterXml);

            xml = content.Instance.XmlContent;
            Assert.IsNotNull(xml);
            Console.WriteLine("Xml After:");
            Console.WriteLine(xml.OuterXml);
            if (complete)
            {
                var node = xml.GetElementById(item.Id.ToString());
                Assert.IsNotNull(node);
            }
            else
            {
                Assert.AreSame(beforeXml, xml);
                Assert.AreEqual(beforeOuterXml, xml.OuterXml); // nothing has changed!
            }
        }
 private void InitializeSettings()
 {
     // Stub up all the settings in Umbraco so we don't need a big app.config file.
     settings = SettingsForTests.GenerateMockSettings();
     SettingsForTests.ConfigureSettings(settings);
 }
        public override void Initialize()
        {
            base.Initialize();

            //we need to use our own custom IDatabaseFactory for the DatabaseContext because we MUST ensure that
            //a Database instance is created per thread, whereas the default implementation which will work in an HttpContext
            //threading environment, or a single apartment threading environment will not work for this test because
            //it is multi-threaded.
            _dbFactory = new PerThreadDatabaseFactory(Logger);
            //overwrite the local object
            ApplicationContext.DatabaseContext = new DatabaseContext(_dbFactory, Logger, new SqlCeSyntaxProvider(), "System.Data.SqlServerCe.4.0");

            //disable cache
            var cacheHelper = CacheHelper.CreateDisabledCacheHelper();

            //here we are going to override the ServiceContext because normally with our test cases we use a
            //global Database object but this is NOT how it should work in the web world or in any multi threaded scenario.
            //we need a new Database object for each thread.
            var repositoryFactory = new RepositoryFactory(cacheHelper, Logger, SqlSyntax, SettingsForTests.GenerateMockSettings());

            _uowProvider = new PerThreadPetaPocoUnitOfWorkProvider(_dbFactory);
            var evtMsgs = new TransientMessagesFactory();

            ApplicationContext.Services = new ServiceContext(
                repositoryFactory,
                _uowProvider,
                new FileUnitOfWorkProvider(),
                new PublishingStrategy(evtMsgs, Logger),
                cacheHelper,
                Logger,
                evtMsgs);

            CreateTestData();
        }
Exemple #25
0
 public override void Initialize()
 {
     base.Initialize();
     SettingsForTests.ConfigureSettings(SettingsForTests.GenerateMockSettings());
 }
        public override void Initialize()
        {
            base.Initialize();

            var routeData = new RouteData();

            routeData.Values["controller"] = "DummyTestController";
            routeData.Values["action"]     = "Index";

            settings = SettingsForTests.GenerateMockSettings();

            routingContext = GetRoutingContext("http://localhost", -1, routeData, umbracoSettings: settings);
            umbracoContext = routingContext.UmbracoContext;

            httpContext = umbracoContext.HttpContext;
            var httpContextMock = Mock.Get(httpContext);

            httpContextMock.Setup(x => x.Items).Returns(
                new ListDictionary()
            {
                { HttpContextExtensions.HttpContextItemName, umbracoContext }
            }
                );

            response     = httpContext.Response;
            responseMock = Mock.Get(response);
            responseMock.Setup(r => r.ContentType).Returns("text/html");
            responseMock.SetupProperty(r => r.Filter, Stream.Null);

            var experimentsPipeline = new ExperimentsPipeline();

            experimentsPipeline.OnApplicationStarted(null, ApplicationContext);

            var originalMock = new Mock <IPublishedContent>();

            originalMock.Setup(c => c.Properties).Returns(new List <IPublishedProperty>());
            experimentMock = new Mock <IExperiment>();
            experimentMock.Setup(e => e.Id).Returns("TESTPERIMENT");

            publishedContentVariationMock = new Mock <IPublishedContentVariation>();
            publishedContentVariationMock.SetupAllProperties();
            publishedContentVariationMock.SetupProperty(p => p.Content, originalMock.Object);

            variedContent = new VariedContent(originalMock.Object, new [] { publishedContentVariationMock.Object });

            var docRequest = new PublishedContentRequest(
                new Uri("/", UriKind.Relative),
                routingContext,
                settings.WebRouting,
                s => Enumerable.Empty <string>())
            {
                PublishedContent = variedContent
            };

            umbracoContext.PublishedContentRequest = docRequest;

            var viewContext = new Mock <ViewContext>();

            viewContext.Setup(c => c.HttpContext).Returns(httpContext);

            actionExecutedMock = new Mock <ActionExecutedContext>(MockBehavior.Strict);
            actionExecutedMock.Setup(f => f.IsChildAction).Returns(false);
            actionExecutedMock.Setup(f => f.HttpContext).Returns(httpContext);

            resultExecutedMock = new Mock <ResultExecutedContext>(MockBehavior.Strict);
            resultExecutedMock.Setup(f => f.HttpContext).Returns(httpContext);

            htmlHelper = new HtmlHelper(viewContext.Object, Mock.Of <IViewDataContainer>());
        }
        public void TestScopeMany(bool complete)
        {
            content.TestingUpdateSitemapProvider = false;

            var settings    = SettingsForTests.GenerateMockSettings();
            var contentMock = Mock.Get(settings.Content);

            contentMock.Setup(x => x.XmlCacheEnabled).Returns(false);
            SettingsForTests.ConfigureSettings(settings);

            var contentType = new ContentType(-1)
            {
                Alias = "contenttype", Name = "test"
            };

            ApplicationContext.Services.ContentTypeService.Save(contentType);

            _cacheHandler = new CacheRefresherEventHandler(true);
            _cacheHandler.OnApplicationStarted(null, ApplicationContext);

            var xml = content.Instance.XmlContent;

            Assert.IsNotNull(xml);
            var       beforeXml      = xml;
            var       beforeOuterXml = beforeXml.OuterXml;
            var       item           = new Content("name", -1, contentType);
            const int count          = 10;
            var       ids            = new int[count];
            var       clones         = 0;

            SafeXmlReaderWriter.Cloning = () => { clones++; };

            Console.WriteLine("Xml Before:");
            Console.WriteLine(xml.OuterXml);

            using (var scope = ApplicationContext.Current.ScopeProvider.CreateScope())
            {
                ApplicationContext.Services.ContentService.SaveAndPublishWithStatus(item);

                for (var i = 0; i < count; i++)
                {
                    var temp = new Content("content_" + i, -1, contentType);
                    ApplicationContext.Services.ContentService.SaveAndPublishWithStatus(temp);
                    ids[i] = temp.Id;
                }

                // this should never change
                Assert.AreEqual(beforeOuterXml, beforeXml.OuterXml);

                xml = content.Instance.XmlContent;
                Assert.IsNotNull(xml);
                Console.WriteLine("Xml InScope (before complete):");
                Console.WriteLine(xml.OuterXml);
                Assert.AreEqual(beforeOuterXml, xml.OuterXml);

                if (complete)
                {
                    scope.Complete();
                }

                xml = content.Instance.XmlContent;
                Assert.IsNotNull(xml);
                Console.WriteLine("Xml InScope (after complete):");
                Console.WriteLine(xml.OuterXml);
                Assert.AreEqual(beforeOuterXml, xml.OuterXml);
            }

            var scopeProvider = ApplicationContext.Current.ScopeProvider as IScopeProviderInternal;

            Assert.IsNotNull(scopeProvider);
            // ambient scope may be null, or maybe not, depending on whether the code that
            // was called did proper scoped work, or some direct (NoScope) use of the database
            Assert.IsNull(scopeProvider.AmbientContext);

            // limited number of clones!
            Assert.AreEqual(complete ? 1 : 0, clones);

            // this should never change
            Assert.AreEqual(beforeOuterXml, beforeXml.OuterXml);

            xml = content.Instance.XmlContent;
            Assert.IsNotNull(xml);
            Console.WriteLine("Xml After:");
            Console.WriteLine(xml.OuterXml);
            if (complete)
            {
                var node = xml.GetElementById(item.Id.ToString());
                Assert.IsNotNull(node);

                for (var i = 0; i < 10; i++)
                {
                    node = xml.GetElementById(ids[i].ToString());
                    Assert.IsNotNull(node);
                }
            }
            else
            {
                Assert.AreEqual(beforeOuterXml, xml.OuterXml); // nothing has changed!
            }
        }
Exemple #28
0
        public void Get_Nice_Url_DomainsAndCache()
        {
            var settings = SettingsForTests.GenerateMockSettings();
            var request  = Mock.Get(settings.RequestHandler);

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

            var routingContext = GetRoutingContext("/test", 1111, umbracoSettings: settings);

            SettingsForTests.UseDirectoryUrls         = true;
            SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains

            SetDomains4();

            string ignore;

            ignore = routingContext.UrlProvider.GetUrl(1001, new Uri("http://domain1.com"), false);
            ignore = routingContext.UrlProvider.GetUrl(10011, new Uri("http://domain1.com"), false);
            ignore = routingContext.UrlProvider.GetUrl(100111, new Uri("http://domain1.com"), false);
            ignore = routingContext.UrlProvider.GetUrl(10012, new Uri("http://domain1.com"), false);
            ignore = routingContext.UrlProvider.GetUrl(100121, new Uri("http://domain1.com"), false);
            ignore = routingContext.UrlProvider.GetUrl(10013, new Uri("http://domain1.com"), false);
            ignore = routingContext.UrlProvider.GetUrl(1002, new Uri("http://domain1.com"), false);
            ignore = routingContext.UrlProvider.GetUrl(1001, new Uri("http://domain2.com"), false);
            ignore = routingContext.UrlProvider.GetUrl(10011, new Uri("http://domain2.com"), false);
            ignore = routingContext.UrlProvider.GetUrl(100111, new Uri("http://domain2.com"), false);
            ignore = routingContext.UrlProvider.GetUrl(1002, new Uri("http://domain2.com"), false);

            var cache = routingContext.UmbracoContext.ContentCache.InnerCache as PublishedContentCache;

            if (cache == null)
            {
                throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
            }
            var cachedRoutes = cache.RoutesCache.GetCachedRoutes();

            Assert.AreEqual(7, cachedRoutes.Count);

            var cachedIds = cache.RoutesCache.GetCachedIds();

            Assert.AreEqual(7, cachedIds.Count);

            CheckRoute(cachedRoutes, cachedIds, 1001, "1001/");
            CheckRoute(cachedRoutes, cachedIds, 10011, "10011/");
            CheckRoute(cachedRoutes, cachedIds, 100111, "10011/1001-1-1");
            CheckRoute(cachedRoutes, cachedIds, 10012, "10012/");
            CheckRoute(cachedRoutes, cachedIds, 100121, "10012/1001-2-1");
            CheckRoute(cachedRoutes, cachedIds, 10013, "1001/1001-3");
            CheckRoute(cachedRoutes, cachedIds, 1002, "/1002");

            // use the cache
            Assert.AreEqual("/", routingContext.UrlProvider.GetUrl(1001, new Uri("http://domain1.com"), false));
            Assert.AreEqual("/en/", routingContext.UrlProvider.GetUrl(10011, new Uri("http://domain1.com"), false));
            Assert.AreEqual("/en/1001-1-1/", routingContext.UrlProvider.GetUrl(100111, new Uri("http://domain1.com"), false));
            Assert.AreEqual("/fr/", routingContext.UrlProvider.GetUrl(10012, new Uri("http://domain1.com"), false));
            Assert.AreEqual("/fr/1001-2-1/", routingContext.UrlProvider.GetUrl(100121, new Uri("http://domain1.com"), false));
            Assert.AreEqual("/1001-3/", routingContext.UrlProvider.GetUrl(10013, new Uri("http://domain1.com"), false));
            Assert.AreEqual("/1002/", routingContext.UrlProvider.GetUrl(1002, new Uri("http://domain1.com"), false));

            Assert.AreEqual("http://domain1.com/fr/1001-2-1/", routingContext.UrlProvider.GetUrl(100121, new Uri("http://domain2.com"), false));
        }
        public virtual void Initialize()
        {
            _logger = new Logger(new FileInfo(TestHelper.MapPathForTest("~/unit-test-log4net.config")));

            TestHelper.InitializeContentDirectories();

            string path = TestHelper.CurrentAssemblyDirectory;

            AppDomain.CurrentDomain.SetData("DataDirectory", path);

            //disable cache
            var cacheHelper = CacheHelper.CreateDisabledCacheHelper();

            var dbFactory     = new DefaultDatabaseFactory(Constants.System.UmbracoConnectionName, _logger);
            var scopeProvider = new ScopeProvider(dbFactory);
            var dbContext     = new DatabaseContext(
                scopeProvider,
                _logger, SqlSyntaxProvider, Constants.DatabaseProviders.SqlCe);

            var repositoryFactory = new RepositoryFactory(cacheHelper, _logger, SqlSyntaxProvider, SettingsForTests.GenerateMockSettings());

            var evtMsgs = new TransientMessagesFactory();

            ApplicationContext.Current = new ApplicationContext(
                //assign the db context
                dbContext,
                //assign the service context
                new ServiceContext(repositoryFactory, new PetaPocoUnitOfWorkProvider(scopeProvider), cacheHelper, _logger, evtMsgs),
                cacheHelper,
                new ProfilingLogger(_logger, Mock.Of <IProfiler>()))
            {
                IsReady = true
            };

            Resolution.Freeze();
        }