Creates Sitecore items in memory.
상속: IDisposable, IEnumerable
    public void DoesUserAgentMatchesTheRegularExpressionValueCondition(string userAgent, string regularExpressionValue, bool expectedResult, Db database)
    {


      SetupDb(database);


      RuleContext ruleContext = new RuleContext();

      PoorMansDeviceDetectorCondition<RuleContext> customUserAgentCondition = new PoorMansDeviceDetectorCondition<RuleContext>()
      {
        OperatorId = Constants.StringOperations.MatchesTheRegularExpression.ItemID.ToString(),
        Value = regularExpressionValue,
        UserAgent = userAgent
      };

      var ruleStack = new RuleStack();

      // act
      customUserAgentCondition.Evaluate(ruleContext, ruleStack);

      // assert
      ruleStack.Should().HaveCount(1);

      object value = ruleStack.Pop();

      value.Should().Be(expectedResult);

    }
 public void ShouldShutdownLicenseWatcher()
 {
   using (var db = new Db())
   {
     db.GetItem("/sitecore/content");
   }
 }
예제 #3
0
        public void GetProfileShouldReturnFullEditProfileModel(Db db, [Substitute] UserProfile userProfile, [RightKeys("FirstName", "LastName", "Phone", "Interest")] IDictionary<string, string> properties,
      [Frozen] IProfileSettingsService profileSettingsService, [Frozen] IUserProfileProvider userProfileProvider, [Greedy] UserProfileService userProfileService)
        {
            using (db)
              {
            var id = new ID();
            db.Add(new DbItem("Profile", id)
            {
              Fields =
              {
            new DbField("FirstName", Templates.UserProfile.Fields.FirstName),
            new DbField("LastName", Templates.UserProfile.Fields.LastName),
            new DbField("Phone", Templates.UserProfile.Fields.PhoneNumber),
            new DbField("Interest", Templates.UserProfile.Fields.Interest)
              }
            });
            profileSettingsService.GetUserDefaultProfile().Returns(db.GetItem(id));
            userProfileProvider.GetCustomProperties(Arg.Any<UserProfile>()).Returns(properties);

            var result = userProfileService.GetProfile(userProfile);
            result.FirstName.Should().Be(properties["FirstName"]);
            result.LastName.Should().Be(properties["LastName"]);
            result.PhoneNumber.Should().Be(properties["Phone"]);
            result.Interest.Should().Be(properties["Interest"]);
              }
        }
    public void RenderParallaxMediaAttributes_Video_ShouldReturnVideoType(Db db)
    {
      var homeItemId = ID.NewID;
      var mediaItemId = ID.NewID;
      db.Add(new DbItem("home", homeItemId)
      {
        new DbLinkField("BackgroundMedia", Templates.HasParallaxBackground.Fields.BackgroundMedia)
        {
          LinkType = "media",
          TargetID = mediaItemId
        }
      });

      db.Add(new DbItem("mediaItem", mediaItemId)
      {
        {
          "Mime type", "video/fake"
        }
      });
      var homeItem = db.GetItem(homeItemId);

      var htmlString = homeItem.RenderParallaxMediaAttributes();
      var attributes = htmlString.ToString().Split(' ').Select(x => x.Split('=')).ToDictionary(x => x[0], val => val.Length == 1 ? "" : val[1].Trim('\'', '"'));

      attributes["data-multibackground-layer-0-attachment"].Should().Be("static");
      attributes["data-multibackground"].Should().BeEmpty();
      attributes["data-multibackground-layer-0-type"].Should().Be("video");
      attributes["data-multibackground-layer-0-format"].Should().Be("fake");
    }
    public void GetEnumerator_Call_ReturnScoresWithKeyName(Db db, ID keyId1, ID keyId2, DbItem profileItem, IBehaviorProfileContext behaviorProfile)
    {
      //Arrange
      using (new SecurityDisabler())
      {
        profileItem.Add(new DbItem("Key1", keyId1, ProfileKeyItem.TemplateID)
        {
          {ProfileKeyItem.FieldIDs.NameField,"key1name" }
        });
        profileItem.Add(new DbItem("Key2", keyId2, ProfileKeyItem.TemplateID)
        {
          {ProfileKeyItem.FieldIDs.NameField,"key2name" }
        });

        db.Add(profileItem);

        var item = db.GetItem(profileItem.FullPath);
        var profile = new ProfileItem(item);

        var behaviorScores = new List<KeyValuePair<ID, float>>() { new KeyValuePair<ID, float>(keyId1, 10), new KeyValuePair<ID, float>(keyId2, 20) };
        behaviorProfile.Scores.Returns(behaviorScores);
        var behaviorProfileDecorator = new BehaviorProfileDecorator(profile, behaviorProfile);

        //Act
        var result = behaviorProfileDecorator.ToList();

        //Assert      
        result.Should().BeEquivalentTo(new[] { new KeyValuePair<string, float>("key1name", 10), new KeyValuePair<string, float>("key2name", 20) });
      }
    }
    public void Update_ItemPassed_ShouldReplaceLinks([Substitute] LinkDatabase linkDb, Db db)
    {
      var datasourceItemId = ID.NewID;

      db.Add(new DbItem("source")
      {
        Children =
        {
          new DbItem("_Local")
          {
            new DbItem("DatasourceItem")
          }
        },
        Fields =
        {
          "testField"
        }
      });
      ;
      db.Add(new DbItem("target")
      {
        Children =
        {
          new DbItem("_Local")
          {
            new DbItem("DatasourceItem")
          }
        },
        Fields =
        {
          "testField"
        }
      });
      ;


      var sourceItem = db.GetItem("/sitecore/content/source");
      var targetItem = db.GetItem("/sitecore/content/target");
      var datasourceItem = db.GetItem("/sitecore/content/source/_Local/DatasourceItem");
      var targetDatasourceItem = db.GetItem("/sitecore/content/target/_Local/DatasourceItem");
      var itemLinks = new[]
      {
        new ItemLink(sourceItem, FieldIDs.LayoutField, datasourceItem, string.Empty)
      };

      linkDb.GetReferences(sourceItem).Returns(itemLinks.ToArray());
      using (new LinkDatabaseSwitcher(linkDb))
      {
        using (new EditContext(targetItem))
        {
          targetItem["__Renderings"] = datasourceItem.ID.ToString();
        }
        var referenceReplacer = new UpdateLocalDatasourceReferencesService(sourceItem, targetItem);

        referenceReplacer.Update();

        var expectedValue = targetDatasourceItem.ID.ToString();
        targetItem["__Renderings"].Should().Be(expectedValue);
      }
    }
예제 #7
0
 public void GetActive_ShouldReturnLanguageModelForContextLanguage(Db db, [Content] DbItem item)
 {
   var contextItem = db.GetItem(item.ID);
   Context.Item = contextItem;
   var activeLanguage = LanguageRepository.GetActive();
   activeLanguage.TwoLetterCode.Should().BeEquivalentTo(Context.Language.Name);
 }
예제 #8
0
    public void GetKeywords_ContextItem_ShouldReturnKeywordsModel(Db db, string contextItemName, string keyword1ItemName, string keyword2ItemName)
    {
      var contextItemId = ID.NewID;
      var keyword1Id = ID.NewID;
      var keyword2Id = ID.NewID;
      db.Add(new DbItem(contextItemName, contextItemId, Templates.PageMetadata.ID)
             {
               new DbField(Templates.PageMetadata.Fields.Keywords)
               {
                 {"en", $"{keyword1Id}|{keyword2Id}"}
               }
             });
      db.Add(new DbItem(keyword1ItemName, keyword1Id, Templates.Keyword.ID)
             {
               new DbField(Templates.Keyword.Fields.Keyword)
               {
                 {"en", keyword1ItemName}
               }
             });
      db.Add(new DbItem(keyword2ItemName, keyword2Id, Templates.Keyword.ID)
             {
               new DbField(Templates.Keyword.Fields.Keyword)
               {
                 {"en", keyword2ItemName}
               }
             });

      var contextItem = db.GetItem(contextItemId);
      var keywordsModel = MetadataRepository.GetKeywords(contextItem);
      keywordsModel.Should().BeOfType<MetaKeywordsModel>();
      keywordsModel.Keywords.Count().Should().Be(2);
    }
예제 #9
0
    public void GetSupportedLanguages_NoneSelected_ShouldReturnEmptyList(Db db, [Content] DbTemplate template, DbItem item, string rootName)
    {
      template.BaseIDs = new[]
      {
        Templates.Site.ID, Feature.Language.Templates.LanguageSettings.ID
      };

      var languageItem = new DbItem("en");
      db.Add(languageItem);

      var siteRootItem = new DbItem(rootName, ID.NewID, template.ID)
      {
        new DbField(Feature.Language.Templates.LanguageSettings.Fields.SupportedLanguages)
        {
          {
            "en", ""
          }
        }
      };

      siteRootItem.Add(item);
      db.Add(siteRootItem);
      var contextItem = db.GetItem(item.ID);
      Context.Item = contextItem;
      var supportedLanguages = LanguageRepository.GetSupportedLanguages();
      supportedLanguages.Count().Should().Be(0);
    }
예제 #10
0
    public void ReplaceItemReferences_ItemPassed_ShouldReplaceContentPath(ItemReferenceReplacer referenceReplacer, Db db, [Content] Item source, [Content] Item target)
    {
      var initialValue = source.Paths.ContentPath;
      var expectedValue = target.Paths.ContentPath;

      ReplaceItemReferences_ItemPassed_ShouldReplaceValue(referenceReplacer, db, source, target, initialValue, expectedValue);
    }
        public void Execute_CreatesInferredType()
        {
            //Arrange  
            using (Db database = new Db
            {
                new DbTemplate(new ID(StubInferred.TemplateId)),
                new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(StubInferred.TemplateId))
            })
            {
                var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
                var path = "/sitecore/content/Target";

                context.Load(new AttributeTypeLoader(typeof(StubInferred)));


                var typeContext = new SitecoreTypeCreationContext();
                var args = new ConfigurationResolverArgs(context, typeContext, null, null);
                var task = new TemplateInferredTypeTask();
                typeContext.InferType = true;
                typeContext.Item = database.GetItem(path);
                typeContext.RequestedType = typeof(IBase);
                args.RequestedType = typeof(IBase);



                //Act
                task.Execute(args);


                //Assert
                Assert.IsNotNull(args.Result);
                Assert.AreEqual(typeof(StubInferred), args.Result.Type);
            }
        }
예제 #12
0
        public void EnableRSS(bool enabled)
        {
            var blogTemplateId = ID.NewID;

            var settings = Mock.Of<IWeBlogSettings>(x =>
                x.ContentRootPath == "/sitecore/content" &&
                x.BlogTemplateIds == new[] { ID.NewID, blogTemplateId, ID.NewID }
            );

            var manager = new BlogManager(settings);

            using (var db = new Db
            {
                new DbItem("blog", ID.NewID, blogTemplateId)
                {
                    { "Enable RSS", enabled ? "1" : string.Empty }
                }
            })
            {
                var item = db.GetItem("/sitecore/content/blog");
                var result = manager.EnableRSS(item);

                if(enabled)
                    Assert.That(result, Is.True);
                else
                {
                    Assert.That(result, Is.False);
                }
            }
        }
예제 #13
0
    public void ReplaceItemReferences_ItemPassed_ShouldReplaceID(ItemReferenceReplacer referenceReplacer, Db db, [Content] Item source, [Content] Item target)
    {
      var initialValue = source.ID.ToString();
      var expectedValue = target.ID.ToString();

      ReplaceItemReferences_ItemPassed_ShouldReplaceValue(referenceReplacer, db, source, target, initialValue, expectedValue);
    }
예제 #14
0
        public void Test(string input, string expected, int limit, bool stripTags)
        {
            var procesor = new AutoGenerate
            {
                FieldName = "Text",
                StripTags = stripTags,
                MaximumCharacterCount = limit
            };

            using (var db = new Db
            {
                new DbItem("item")
                {
                    new DbField("text")
                    {
                        Value = input
                    }
                }
            })
            {
                var args = new GetSummaryArgs
                {
                    Entry = db.GetItem("/sitecore/content/item")
                };

                procesor.Process(args);

                Assert.That(args.Summary, Is.EqualTo(expected));
            }
        }
예제 #15
0
		public void ParseFields_ReturnsExpectedValues(string fieldValue, string standardValue, string expected)
		{
			using (var db = new Db())
			{
				var testFieldId = ID.NewID;

				var template = new DbTemplate("Test Template") { { testFieldId, standardValue } };

				db.Add(template);

				var testItem = ItemManager.CreateItem("Test", db.GetItem(ItemIDs.ContentRoot), template.ID);

				if (expected != null)
				{
					using (new EditContext(testItem))
					{
						testItem[testFieldId] = expected;
					}
				}

				var sut = new FieldReader();

				testItem.Fields.ReadAll();

				var result = sut.ParseFields(testItem, FieldReader.FieldReadType.Versioned).FirstOrDefault(f => f.FieldId == testFieldId.Guid);

				
				if (expected == null) result.Should().BeNull();
				else result.Value.Should().Be(expected);
			}
		}
    public void Process_LocalDatasourceNotExist_ShouldCreateDatasourceRoot(GetLocalDatasourceLocation processor, Db db, [Content] Item contextItem, [Content] DbTemplate template)
    {
      //arrange
      db.Add(new DbItem("rendering")
      {
        {
          Templates.RenderingOptions.Fields.SupportsLocalDatasource, "1"
        }
      });

      var renderingItem = db.GetItem("/sitecore/content/rendering");
      var getRenderingDatasourceArgs = new GetRenderingDatasourceArgs(renderingItem)
      {
        ContextItemPath = contextItem.Paths.FullPath
      };

      //act
      using (new SettingsSwitcher("Foundation.LocalDatasource.LocalDatasourceFolderTemplate", template.ID.ToString()))
      {
        processor.Process(getRenderingDatasourceArgs);
      }
      //assert
      var datasourceFolder = contextItem.GetChildren().First();
      getRenderingDatasourceArgs.DatasourceRoots.First().ID.Should().Be(datasourceFolder.ID);
      datasourceFolder.TemplateID.Should().Be(template.ID);
    }
예제 #17
0
        public void Test(string input, string expected, string xpath)
        {
            var procesor = new FirstContentBlock
            {
                FieldName = "Text",
                XPath = xpath
            };

            using (var db = new Db
            {
                new DbItem("item")
                {
                    new DbField("text")
                    {
                        Value = input
                    }
                }
            })
            {
                var args = new GetSummaryArgs
                {
                    Entry = db.GetItem("/sitecore/content/item")
                };

                procesor.Process(args);

                Assert.That(args.Summary, Is.EqualTo(expected));
            }
        }
예제 #18
0
 public void DemoContent_RenderingContextItemInitialized_ShouldReturnDemoContentView(Db db, [Greedy] DemoController sut, [Content] DemoContentItem item)
 {
     using (RenderingContext.EnterContext(new Rendering(), db.GetItem(item.ID)))
     {
         sut.DemoContent().As<ViewResult>().Model.Should().BeOfType<DemoContent>();
     }
 }
예제 #19
0
 public void Create_ShouldCreateLanguageModel(Db db, [Content] DbItem item)
 {
   var contentItem = db.GetItem(item.ID);
   Context.Item = contentItem;
   var language = LanguageFactory.Create(Context.Language);
   language.Should().NotBeNull();
   language.TwoLetterCode.Should().BeEquivalentTo(Context.Language.Name);
 }
		public void ConsumeChallenge_ShouldReturnTrue_IfTokenIsValid(Db db)
		{
			var store = CreateTestStore(db);

			store.AddChallenge("FAKE", 1000);

			store.ConsumeChallenge("FAKE").Should().BeTrue();
		}
예제 #21
0
 public void GetAll_ShouldReturnAllLanguages(Db db, [Content] DbItem item)
 {
   var contextItem = db.GetItem(item.ID);
   Context.Item = contextItem;
   var languages = LanguageRepository.GetAll();
   languages.Should().BeAssignableTo<IEnumerable<Language>>();
   languages.Count().Should().Be(db.Database.GetLanguages().Count);
 }
		public void ConsumeChallenge_ShouldNotAllowReusingTokens(Db db)
		{
			var store = CreateTestStore(db);

			store.AddChallenge("FAKE", 1000);

			store.ConsumeChallenge("FAKE").Should().BeTrue();
			store.ConsumeChallenge("FAKE").Should().BeFalse();
		}
예제 #23
0
    public void Get_ContextItemIsMatchingTemplate_ShouldReturnSelf(Db db, string contextItemName)
    {
      var contextItemId = ID.NewID;

      db.Add(new DbItem(contextItemName, contextItemId, Templates.SiteMetadata.ID));

      var contextItem = db.GetItem(contextItemId);
      var keywordsModel = MetadataRepository.Get(contextItem);
      keywordsModel.ID.Should().Be(contextItemId);
    }
예제 #24
0
    public void Get_ContextItemParentIsMatchingTemplate_ShouldReturnParent(Db db)
    {
      var contextItemId = ID.NewID;

      db.Add(new DbItem("context", contextItemId, Templates.SiteMetadata.ID));
      var contextItem = db.GetItem(contextItemId);
      var keywordsModel = MetadataRepository.Get(contextItem.Add("child", new TemplateID(ID.NewID)));

      keywordsModel.ID.Should().Be(contextItemId);
    }
		public void ConsumeChallenge_ShouldReturnFalseIfChallengeIsTooOld(Db db)
		{
			var store = CreateTestStore(db);

			store.AddChallenge("FAKE", 500);

			Thread.Sleep(550);

			store.ConsumeChallenge("FAKE").Should().BeFalse();
		}
		private IChallengeStore CreateTestStore(Db db)
		{
			// fakedb doesn't like it when we create our own template with the item API. So we'll prep that in advance.
			db.Add(new DbTemplate("Authentication Challenge")
			{
				new DbField("Expires")
			});

			return new TestSitecoreDatabaseChallengeStore();
		}
예제 #27
0
        public void CustomFields()
        {
            using (var db = new Db
            {
                new DbTemplate(Settings.CommentTemplateID)
                {
                    new DbField("Name"),
                    new DbField("Email"),
                    new DbField("Comment"),
                    new DbField("Website"),
                    new DbField("IP Address"),
                    new DbField("field1"),
                    new DbField("field2")
                },
                new DbItem("blog")
                {
                    new DbItem("entry")
                }
            })
            {
                var blog = db.GetItem("/sitecore/content/blog");
                var entry = db.GetItem("/sitecore/content/blog/entry");

                var blogManager = Mock.Of<IBlogManager>(x =>
                    x.GetCurrentBlog(entry) == new BlogHomeItem(blog)
                    );
                var processor = new CreateCommentItem(blogManager);

                var args = new CreateCommentArgs
                {
                    Database = entry.Database,
                    Comment = new Comment
                    {
                        AuthorName = "commenter",
                        AuthorEmail = "*****@*****.**",
                        Text = "the comment",
                        Fields =
                        {
                            { "field1", "value1" },
                            { "field2", "value2" },
                        }
                    },
                    EntryID = entry.ID,
                    Language = Language.Parse("da")
                };

                processor.Process(args);

                Assert.That(args.CommentItem, Is.Not.Null);
                Assert.That(args.CommentItem.InnerItem.Axes.IsDescendantOf(entry), Is.True);
                Assert.That(args.CommentItem["field1"], Is.EqualTo("value1"));
                Assert.That(args.CommentItem["field2"], Is.EqualTo("value2"));
            }
        }
예제 #28
0
    public void DemoContent_RenderingContextItemInitialized_ShouldReturnDemoContentView(
      Db db,
      [Greedy] DemoController sut,
      [Modest] RenderingContext context,
      [Content] DemoContentItem item)
    {
      context.ContextItem = db.GetItem(item.ID);
      ContextService.Get().Push(context);

      sut.DemoContent().As<ViewResult>().Model.Should().BeOfType<DemoContent>();
    }
예제 #29
0
    public void Execute_OutcomeID_RegisterOutcome(Db db, ID outcomeId, [Frozen] ITrackerService trackerService, [Greedy] RegisterOutcome registerOutcome)
    {
      //Arrange
      db.Add(new DbItem("WrongOutcome", outcomeId, Templates.Outcome.ID));
      registerOutcome.Outcome = outcomeId.ToString();

      //Act
      registerOutcome.Execute(ID.Null, null);

      //Assert
      trackerService.Received().TrackOutcome(outcomeId);
    }
    public void GetUserDefaultProfileShoulReturnListOfInterests(Db db, ID profileId, ID interestFolderId, ProfileSettingsService profileSettingsService, IEnumerable<string> interests)
    {
      var coreDb = new Db("core");
      var siteContext = this.BuildSiteContext(db, coreDb, profileId, interestFolderId, interests);

      using (new SiteContextSwitcher(siteContext))
      using (coreDb)
      {
        var interestsResult = profileSettingsService.GetInterests();
        interestsResult.Should().BeEquivalentTo(interests);
      }
    }
        public void HowToCreateItemOnSpecificTemplate()
        {
            Sitecore.Data.ID templateId = Sitecore.Data.ID.NewID;

            using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db
            {
                new DbTemplate("products", templateId)
                {
                    "Name"
                },
                new DbItem("Apple")
                {
                    TemplateID = templateId
                }
            })
            {
                Sitecore.Data.Items.Item item =
                    db.GetItem("/sitecore/content/apple");

                Xunit.Assert.Equal(templateId, item.TemplateID);
                Xunit.Assert.NotNull(item.Fields["Name"]);
            }
        }