コード例 #1
0
        public void FileUploadGeneratesScriptOncePerRequest()
        {
            // Arrange
            var    context         = GetContext();
            string expectedResult1 = _fileUploadScript
                                     + @"<div class=""file-upload"" id=""file-upload-0""><div><input name=""fileUpload"" type=""file"" /></div></div>"
                                     + @"<div class=""file-upload-buttons""><a href=""#"" onclick=""FileUploadHelper.addInputElement(0, &quot;fileUpload&quot;); return false;"">Add more files</a></div>";
            string expectedResult2 = @"<form action="""" enctype=""multipart/form-data"" method=""post""><div class=""file-upload"" id=""file-upload-1""><div><input name=""fileUpload"" type=""file"" /></div></div>"
                                     + @"<div class=""file-upload-buttons""><a href=""#"" onclick=""FileUploadHelper.addInputElement(1, &quot;fileUpload&quot;); return false;"">Add more files</a><input type=""submit"" value=""Upload"" /></div></form>";
            string expectedResult3 = @"<form action="""" enctype=""multipart/form-data"" method=""post""><div class=""file-upload"" id=""file-upload-2"">"
                                     + @"<div><input name=""fileUpload"" type=""file"" /></div></div>"
                                     + @"<div class=""file-upload-buttons""><input type=""submit"" value=""Upload"" /></div></form>";

            // Act
            var result1 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: false, addText: null, uploadText: null);
            var result2 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: true, addText: null, uploadText: null);
            var result3 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, includeFormTag: true, addText: null, uploadText: null);

            // Assert
            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult1, result1.ToString());
            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult2, result2.ToString());
            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult3, result3.ToString());
        }
コード例 #2
0
        public void BadRequestIfRequestNull()
        {
            // Target Create
            var builder = new TestDiProviderBuilder();

            builder.ServiceCollection.AddTransient <DeliveryFilesController>();
            var controller = builder.Build().GetService <DeliveryFilesController>();

            // BadRequestが返るかチェック
            var createResponse = controller.PostDeliveryFile(null, UnitTestHelper.CreateLogger());

            Assert.IsInstanceOfType(createResponse, typeof(BadRequestObjectResult));

            var updateResponse = controller.PutDeliveryFile(null, 0, UnitTestHelper.CreateLogger());

            Assert.IsInstanceOfType(updateResponse, typeof(BadRequestObjectResult));

            var updateStatusResponse = controller.PutDeliveryFileStatus(null, 0, UnitTestHelper.CreateLogger());

            Assert.IsInstanceOfType(updateStatusResponse, typeof(BadRequestObjectResult));

            // DeleteはBadRequestを返さない
        }
コード例 #3
0
ファイル: BlogAliasTests.cs プロジェクト: ghjigan/Subtext
        public void UpdateBlogAlias()
        {
            var    repository = new DatabaseObjectProvider();
            Blog   blog       = UnitTestHelper.CreateBlogAndSetupContext();
            string host1      = UnitTestHelper.GenerateUniqueString();
            string host2      = UnitTestHelper.GenerateUniqueString();

            BlogAlias alias = UnitTestHelper.CreateBlogAlias(blog, host1, "");

            repository.AddBlogAlias(alias);

            BlogAlias testAlias = repository.GetBlogAlias(alias.Id);

            testAlias.Host = host2;

            repository.UpdateBlogAlias(testAlias);

            BlogAlias testAlias2 = repository.GetBlogAlias(alias.Id);

            Assert.AreEqual(alias.Id, testAlias.Id, "Did not retrieve the correct alias.");
            Assert.AreEqual(alias.Id, testAlias2.Id, "Did not retrieve the correct alias.");
            Assert.AreEqual(host2, testAlias2.Host, "Alias was not updated");
        }
コード例 #4
0
        public void GetPostCollectionByMonthDoesNotIncludeFuturePosts()
        {
            // Arrange
            var      repository = new DatabaseObjectProvider();
            DateTime now        = DateTime.UtcNow.AddMinutes(-5);
            Entry    entryZero  = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-zero", "body-zero", null, now);
            Entry    entryOne   = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-one", "body-one", null, now.AddMinutes(1));
            Entry    entryTwo   = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-two", "body-two", null, now.AddMinutes(2));

            UnitTestHelper.Create(entryZero);
            UnitTestHelper.Create(entryOne);
            entryTwo.DatePublishedUtc = DateTime.UtcNow.AddMinutes(20);
            UnitTestHelper.Create(entryTwo);

            // Act
            ICollection <Entry> entries = repository.GetPostsByMonth(now.Month, now.Year);

            // Assert
            Assert.AreEqual(2, entries.Count, "Expected to find two entries.");

            Assert.AreEqual(entries.First().Id, entryOne.Id, "Ordering is off.");
            Assert.AreEqual(entries.ElementAt(1).Id, entryZero.Id, "Ordering is off.");
        }
コード例 #5
0
        public void CanGetPostsByMonthArchive()
        {
            UnitTestHelper.SetupBlog();
            ICollection <ArchiveCount> counts = Archives.GetPostCountByMonth();

            Assert.AreEqual(0, counts.Count);

            Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title", "body");

            UnitTestHelper.Create(entry);
            counts = Archives.GetPostCountByMonth();
            Assert.AreEqual(1, counts.Count);

            foreach (ArchiveCount archiveCount in counts)
            {
                Assert.AreEqual(1, archiveCount.Count, "Expected one post in the archive.");
                Assert.AreEqual(DateTime.Now.Date.AddDays(-1 * DateTime.Now.Date.Day + 1), archiveCount.Date,
                                "Expected date to be this month.");
                Assert.AreEqual(null, archiveCount.Title);
                Assert.AreEqual(0, archiveCount.Id);
                return;
            }
        }
コード例 #6
0
        public void CanDeleteEnclosure()
        {
            Blog  blog       = UnitTestHelper.CreateBlogAndSetupContext();
            var   repository = new DatabaseObjectProvider();
            Entry e          = UnitTestHelper.CreateEntryInstanceForSyndication("Simone Chiaretta", "Post for testing Enclosures",
                                                                                "Listen to my great podcast");
            int entryId = UnitTestHelper.Create(e);

            Enclosure enc = UnitTestHelper.BuildEnclosure("Nothing to see here.", "httP://blablabla.com", "audio/mp3",
                                                          entryId, 12345678, true, true);

            repository.Create(enc);

            Entry newEntry = repository.GetEntry(entryId, true, false);

            Assert.IsNotNull(newEntry.Enclosure, "Did not create enclosure.");

            repository.DeleteEnclosure(enc.Id);

            Entry newEntry1 = repository.GetEntry(entryId, true, false);

            Assert.IsNull(newEntry1.Enclosure, "Did not delete enclosure.");
        }
コード例 #7
0
        public void CanInsertNewMetaTag(string content, string name, string httpEquiv, bool withEntry, string errMsg)
        {
            blog = UnitTestHelper.CreateBlogAndSetupContext();

            int?entryId = null;

            if (withEntry)
            {
                Entry e = UnitTestHelper.CreateEntryInstanceForSyndication("Steven Harman", "My Post", "Foo Bar Zaa!");
                entryId = UnitTestHelper.Create(e);
            }

            MetaTag mt = UnitTestHelper.BuildMetaTag(content, name, httpEquiv, blog.Id, entryId, DateTime.Now);

            // make sure there are no meta-tags for this blog in the data store
            ICollection <MetaTag> tags = MetaTags.GetMetaTagsForBlog(blog, 0, 100);

            Assert.AreEqual(0, tags.Count, "Should be zero MetaTags.");

            // add the meta-tag to the data store
            int tagId = MetaTags.Create(mt);

            tags = MetaTags.GetMetaTagsForBlog(blog, 0, 100);

            Assert.AreEqual(1, tags.Count, errMsg);

            MetaTag newTag = tags.First();

            // make sure all attributes of the meta-tag were written to the data store correctly.
            Assert.AreEqual(tagId, newTag.Id, "Wrong Id");
            Assert.AreEqual(mt.Content, newTag.Content, "Wrong content");
            Assert.AreEqual(mt.Name, newTag.Name, "wrong name attribute");
            Assert.AreEqual(mt.HttpEquiv, newTag.HttpEquiv, "Wrong http-equiv attriubte");
            Assert.AreEqual(mt.BlogId, newTag.BlogId, "Wrong blogId");
            Assert.AreEqual(mt.EntryId, newTag.EntryId, "Wrong entryId");
            Assert.AreEqual(mt.DateCreated.Date, newTag.DateCreated.Date, "Wrong created date");
        }
コード例 #8
0
ファイル: DataPageTest.cs プロジェクト: sebfischer83/datatent
        public void TryAddManyContentTest()
        {
            var numberOfPages = 1;

            // generate test pages
            byte[] testArray = new byte[Constants.PAGE_SIZE_INCL_HEADER * numberOfPages];

            Memory <byte> memory = new Memory <byte>(testArray);

            // create dummy headers for the 5 pages
            for (uint i = 0; i < numberOfPages; i++)
            {
                var slice = memory.Slice((int)(Constants.PAGE_SIZE_INCL_HEADER * i));
                SpanExtensions.WriteBytes(slice, 0, UnitTestHelper.GetPageHeader(i, PageType.Data));
            }

            string testContent  = "Hello World!!!";
            var    bytesContent = Encoding.UTF8.GetBytes(testContent);

            var dataPageManager = new DataPageManager(memory);
            var page            = (DataPage)dataPageManager.GetPageById(0);

            page.Should().NotBeNull();
            var _guids = new ushort[100];

            for (int i = 0; i < 100; i++)
            {
                var res = page.TryAddContent(bytesContent, 0);
                _guids[i] = res.Id;
            }

            _guids.Should().NotBeEmpty();

            var document = page.FindById(_guids[55]);

            document.Should().NotBeNull();
        }
コード例 #9
0
        public void Setup()
        {
            var numberOfPages = 1;

            // generate test pages
            byte[] testArray = new byte[Constants.PAGE_SIZE_INCL_HEADER * numberOfPages];

            Memory <byte> memory = new Memory <byte>(testArray);

            // create dummy headers for the 5 pages
            for (uint i = 0; i < numberOfPages; i++)
            {
                var slice = memory.Slice((int)(Constants.PAGE_SIZE_INCL_HEADER * i));
                SpanExtensions.WriteBytes(slice, 0, UnitTestHelper.GetPageHeader(i, PageType.Data));
            }

            string testContent = "Hello World!!!";

            bytesContent = Encoding.UTF8.GetBytes(testContent);

            var _dataPageManager = new DataPageManager(memory);

            _page  = (DataPage)_dataPageManager.GetPageById(0);
            _guids = new ushort[100];
            for (int i = 0; i < 100; i++)
            {
                var res = _page.TryAddContent(bytesContent, 0);
                _guids[i] = res.Id;
            }

            Random random = new Random();

            for (int i = 0; i < Int16.MaxValue * 10; i++)
            {
                _indexes.Add(random.Next(0, 99));
            }
        }
コード例 #10
0
        public void GetBlogPostsReturnsAllPostsIfPostConfigNoneSpecified()
        {
            //Create some entries.
            Entry entryZero = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-zero", "body-zero");

            entryZero.IsActive = true;
            Entry entryOne = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-one", "body-one");

            entryOne.IsActive = true;
            Entry entryTwo = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-two", "body-two");

            entryTwo.IsActive = false;
            Entry entryThree = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-three", "body-zero");

            entryThree.IsActive       = true;
            entryThree.DateCreated    = DateTime.Now.AddDays(10);
            entryThree.DateSyndicated = DateTime.Now.AddDays(10);

            //Persist entries.
            UnitTestHelper.Create(entryZero);
            Thread.Sleep(500);
            UnitTestHelper.Create(entryOne);
            Thread.Sleep(500);
            UnitTestHelper.Create(entryTwo);
            Thread.Sleep(500);
            UnitTestHelper.Create(entryThree);

            Assert.IsTrue(entryThree.DateSyndicated > DateTime.Now);

            //Get EntryDay
            ICollection <EntryDay> entryList = ObjectProvider.Instance().GetBlogPostsForHomePage(10, PostConfig.None).ToList();

            //Test outcome
            Assert.AreEqual(2, entryList.Count, "Expected to find two entry days.");
            Assert.AreEqual(1, entryList.First().Count, "Expected to find one entry in the first day.");
            Assert.AreEqual(3, entryList.ElementAt(1).Count, "Expected to find three entries in the second day.");
        }
コード例 #11
0
        public void NormarizeTest(
            string SettingKey1, string SettingValue1,
            string SettingKey2, string SettingValue2,
            int nowMonth,
            string expectedGetterName)
        {
            // 設定値
            var diBuilder = new TestDiProviderBuilder();

            diBuilder.AddConfigure(SettingKey1, SettingValue1);
            diBuilder.AddConfigure(SettingKey2, SettingValue2);

            // DI設定
            diBuilder.ServiceCollection.AddTransient <ITimeProvider>(x => UnitTestHelper.CreateTimeProvider(new DateTime(2020, nowMonth, 1)));
            diBuilder.ServiceCollection.AddSingleton <IPrimaryRepository, PrimaryRepositoryMock>();
            diBuilder.ServiceCollection.AddSingleton <IDtDeviceFileRepository, DtDeviceFileRepositoryMock>();
            var provider = diBuilder.Build();

            // テスト対象実行
            var target = provider.GetService <ICleanBlobService>();

            target.Clean();

            var expected = GetExpected(expectedGetterName);

            // 結果確認のため、状態を持つリポジトリを取得する。このために上記の設定でシングルトンにしている。
            var primaryRepository      = provider.GetService <IPrimaryRepository>() as PrimaryRepositoryMock;
            var dtDeviceFileRepository = provider.GetService <IDtDeviceFileRepository>() as DtDeviceFileRepositoryMock;

            Assert.AreEqual(
                expected.Item1.ToStringJson(),
                dtDeviceFileRepository.files.ToStringJson());
            Assert.AreEqual(
                expected.Item2.ToStringJson(),
                primaryRepository.ArchiveFiles.ToStringJson());
        }
コード例 #12
0
        public async Task ReaderService_UpdateAsync_UpdateModel()
        {
            //arrange
            var reader = new ReaderModel()
            {
                Id      = 10,
                Name    = "Test_Updating",
                Email   = "*****@*****.**",
                Phone   = "159487263",
                Address = "test address"
            };
            var mockUnitOfWork = new Mock <IUnitOfWork>();

            mockUnitOfWork.Setup(m => m.ReaderRepository.Update(It.IsAny <Reader>()));
            IReaderService readerService = new ReaderService(mockUnitOfWork.Object, UnitTestHelper.CreateMapperProfile());

            //act
            await readerService.UpdateAsync(reader);

            //assert
            mockUnitOfWork.Verify(x => x.ReaderRepository.Update(
                                      It.Is <Reader>(r => r.Id == reader.Id && r.Name == reader.Name && r.Email == reader.Email)), Times.Once);
            mockUnitOfWork.Verify(x => x.SaveAsync(), Times.Once);
        }
コード例 #13
0
        public void GetRecentEntries_WithFuturePosts_OnlyReturnsPastPosts()
        {
            // Arrange
            var      repository = new DatabaseObjectProvider();
            DateTime utcNow     = DateTime.UtcNow.AddDays(-2);
            var      blog1      = UnitTestHelper.CreateBlogAndSetupContext(null, "subfolder1");
            var      entryOne   = UnitTestHelper.CreateAndSaveEntryForSyndication("me", "blog1-entry-one", "body-zero", null, utcNow, utcNow);
            var      entryTwo   = UnitTestHelper.CreateAndSaveEntryForSyndication("me", "blog1-entry-two", "body-zero", null, utcNow, utcNow.AddDays(10));
            var      entryThree = UnitTestHelper.CreateAndSaveEntryForSyndication("me", "blog1-entry-three", "body-zero", null, utcNow, utcNow);
            var      blog2      = UnitTestHelper.CreateBlogAndSetupContext(blog1.Host, "subfolder2");
            var      entryFour  = UnitTestHelper.CreateAndSaveEntryForSyndication("me", "blog2-entry-four", "body-zero", null, utcNow, utcNow.AddDays(10));
            var      entryFive  = UnitTestHelper.CreateAndSaveEntryForSyndication("me", "blog2-entry-five", "body-zero", null, utcNow, utcNow);

            UnitTestHelper.WriteTableToOutput("subtext_Config");
            UnitTestHelper.WriteTableToOutput("subtext_Content");
            // Act
            ICollection <Entry> entries = repository.GetRecentEntries(null, null, 10);

            // Assert (reverse ordering)
            Assert.AreEqual(3, entries.Count);
            Assert.AreEqual(entries.First().Id, entryFive.Id);
            Assert.AreEqual(entries.ElementAt(1).Id, entryThree.Id);
            Assert.AreEqual(entries.ElementAt(2).Id, entryOne.Id);
        }
コード例 #14
0
        public void ReaderService_GetAll_ReturnsReaderModels()
        {
            //arrange
            var expected       = GetTestReaderModels().ToList();
            var mockUnitOfWork = new Mock <IUnitOfWork>();

            mockUnitOfWork
            .Setup(m => m.ReaderRepository.GetAllWithDetails())
            .Returns(GetTestReaderEntities().AsQueryable());
            IReaderService readerService = new ReaderService(mockUnitOfWork.Object, UnitTestHelper.CreateMapperProfile());

            //act
            var actual = readerService.GetAll().ToList();

            //assert
            Assert.IsInstanceOf <IEnumerable <ReaderModel> >(actual);
            Assert.AreEqual(expected.Count, actual.Count);
            for (int i = 0; i < expected.Count; i++)
            {
                var expectedReaderModel = expected[i];
                var actualReaderModel   = actual[i];
                Assert.IsTrue(_readerModelComparer.Equals(expectedReaderModel, actualReaderModel));
            }
        }
コード例 #15
0
        public async void DeletingTask_SetsSubtasksParentProjectTaskIdToNull()
        {
            var db = UnitTestHelper.CreateInMemoryDb(); //ensure that we have same db in the scope of the test

            await using (var context = db.CreateContext())
            {
                //arrange
                var projectService = new ProjectService(context, UnitTestHelper.Mapper);
                await projectService.Add(DataSeeder.NewProject(3));

                var taskService = new TaskService(context, UnitTestHelper.Mapper);
                await taskService.Add(DataSeeder.NewTask(3, 3));

                await taskService.Add(DataSeeder.NewTask(33, 3, 3));

                await taskService.Add(DataSeeder.NewTask(333, 3, 3));

                //act
                var task = DataSeeder.NewTask(3, 3);
                await taskService.DeleteOrThrow(task.Id);
            }

            //assert
            await using (var context = db.CreateContext())
            {
                var tasksService = new TaskService(context, UnitTestHelper.Mapper);

                var task = await tasksService.Get(33);

                task.ParentTaskId.Should().BeNull();

                task = await tasksService.Get(333);

                task.ParentTaskId.Should().BeNull();
            }
        }
コード例 #16
0
        public void ProcessRequest_WithoutEntryIdInRouteData_SendsErrorResponse()
        {
            //arrange
            UnitTestHelper.SetupBlog();
            var  repository = new DatabaseObjectProvider();
            Blog blog       = Config.CurrentBlog;

            blog.TrackbacksEnabled = true;
            var          subtextContext = new Mock <ISubtextContext>();
            StringWriter writer         = subtextContext.FakeSubtextContextRequest(blog, "/trackbackhandler", "/", string.Empty);

            subtextContext.Setup(c => c.Repository).Returns(repository);
            Mock <BlogUrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper);

            urlHelper.Setup(u => u.TrackbacksUrl(It.IsAny <int>())).Returns("/whatever/trackback");
            subtextContext.SetupBlog(blog);
            var handler = new TrackBackHandler(subtextContext.Object);

            //act
            handler.ProcessRequest();

            //assert
            Assert.IsTrue(writer.ToString().Contains("EntryId is invalid or missing"));
        }
コード例 #17
0
        public void TestDefaultCtor()
        {
            // set up
            var track = UnitTestHelper.GetDefaultTrack();

            track.CalculateStatistics();

            // run
            var viewModel = new TrackStatisticsViewModel(track);

            // check
            Assert.IsTrue(viewModel.NumTrackPoints > 0, "there must be some track points");
            Assert.IsTrue(viewModel.Distance.Any(), "distance must contain value");
            Assert.IsTrue(viewModel.Duration.Any(), "duration must contain value");

            Assert.IsTrue(viewModel.HeightGain.Any(), "height gain must contain value");
            Assert.IsTrue(viewModel.HeightLoss.Any(), "height loss must contain value");
            Assert.IsTrue(viewModel.MaxHeight.Any(), "max. height must contain value");
            Assert.IsTrue(viewModel.MinHeight.Any(), "min. height must contain value");
            Assert.IsTrue(viewModel.MaxClimbRate.Any(), "max. climb rate must contain value");
            Assert.IsTrue(viewModel.MaxSinkRate.Any(), "max. sink rate must contain value");
            Assert.IsTrue(viewModel.MaxSpeed.Any(), "max. speed must contain value");
            Assert.IsTrue(viewModel.AverageSpeed.Any(), "average speed must contain value");
        }
コード例 #18
0
        public void GetStatCounterAnalyticsEscapesCorrectly()
        {
            string account  = "My_\"stat_account";
            string actual   = Analytics.GetStatCounterHtml(2, account).ToString();
            string expected = "<script type=\"text/javascript\">\n" +
                              "var sc_project=2;\n" +
                              "var sc_invisible=1;\n" +
                              "var sc_security=\"My_\\\"stat_account\";\n" +
                              "var sc_text=2;\n" +
                              "var sc_https=1;\n" +
                              "var scJsHost = ((\"https:\" == document.location.protocol) ? \"https://secure.\" : \"http://www.\");\n" +
                              "document.write(\"<sc\" + \"ript type='text/javascript' src='\" + " +
                              "scJsHost + \"statcounter.com/counter/counter_xhtml.js'></\" + \"script>\");\n" +
                              "</script>\n\n" +
                              "<noscript>" +
                              "<div class=\"statcounter\">" +
                              "<a title=\"tumblrstatistics\" class=\"statcounter\" href=\"http://www.statcounter.com/tumblr/\">" +
                              "<img class=\"statcounter\" src=\"https://c.statcounter.com/2/0/My_&quot;stat_account/1/\" alt=\"tumblr statistics\"/>" +
                              "</a>" +
                              "</div>" +
                              "</noscript>";

            UnitTestHelper.AssertEqualsIgnoreWhitespace(expected, actual);
        }
コード例 #19
0
ファイル: DocumentTest.cs プロジェクト: fossabot/datatent
        public void GetNextDocumentSliceAndAdjustOffsetTest()
        {
            var array = new byte[Constants.PAGE_SIZE_INCL_HEADER + 200];

            UnitTestHelper.FillArray(ref array, 0x00);
            string testString = "This is a test! This is a test! This is a test! This is a test! This is a test! This is a test! This is a test! This is a test!";

            byte[] testContent = Encoding.UTF8.GetBytes(testString);

            Memory <byte> documentSlice = new Memory <byte>(array, 0, (int)Constants.PAGE_SIZE);

            ushort id1 = 1;
            ushort id2 = 2;

            Core.Document.Document document = new Core.Document.Document(documentSlice, id1);
            document.Update(testContent);
            document = new Core.Document.Document(documentSlice.Slice((int)(testContent.Length + Constants.DOCUMENT_HEADER_SIZE)), id2);
            document.Update(testContent);


            documentSlice = new Memory <byte>(array, 0, (int)Constants.PAGE_SIZE);
            var tuple = Core.Document.Document.GetNextDocumentSliceAndAdjustOffset(ref documentSlice);

            tuple.DocumentId.Should().Be(id1);
            tuple.DocumentSlice.HasValue.Should().BeTrue();
            tuple.DocumentSlice.Value.Length.Should()
            .Be((int)(testContent.Length + Constants.DOCUMENT_HEADER_SIZE));
            tuple = Core.Document.Document.GetNextDocumentSliceAndAdjustOffset(ref documentSlice);
            tuple.DocumentId.Should().Be(id2);
            tuple.DocumentSlice.HasValue.Should().BeTrue();
            tuple.DocumentSlice.Value.Length.Should()
            .Be((int)(testContent.Length + Constants.DOCUMENT_HEADER_SIZE));
            tuple = Core.Document.Document.GetNextDocumentSliceAndAdjustOffset(ref documentSlice);
            tuple.DocumentId.Should().Be(0);
            tuple.DocumentSlice.HasValue.Should().BeFalse();
        }
コード例 #20
0
        public void GetPreviousAndNextEntriesReturnsNextWhenNoPreviousExists()
        {
            string hostname = UnitTestHelper.GenerateUniqueString();

            Config.CreateBlog("", "username", "password", hostname, string.Empty);
            UnitTestHelper.SetHttpContextWithBlogRequest(hostname, string.Empty);
            BlogRequest.Current.Blog = Config.GetBlog(hostname, string.Empty);

            Entry currentEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body",
                                                                                  UnitTestHelper.GenerateUniqueString(),
                                                                                  DateTime.Now.AddDays(-1));
            Entry nextEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body",
                                                                               UnitTestHelper.GenerateUniqueString(),
                                                                               DateTime.Now);

            int currentId = UnitTestHelper.Create(currentEntry);
            int nextId    = UnitTestHelper.Create(nextEntry);

            var entries = ObjectProvider.Instance().GetPreviousAndNextEntries(currentId,
                                                                              PostType.BlogPost);

            Assert.AreEqual(1, entries.Count, "Since there is no previous entry, should return only next");
            Assert.AreEqual(nextId, entries.First().Id, "The next entry does not match expectations.");
        }
コード例 #21
0
        public void FilterBeforePersistDoesNotAllowTooManyCommentsWithinCommentDelay()
        {
            //arrange
            var subtextContext = new Mock <ISubtextContext>();
            var cache          = new TestCache();

            cache["COMMENT FILTER:127.0.0.1"] = new FeedbackItem(FeedbackType.Comment);
            subtextContext.Setup(c => c.Cache).Returns(cache);
            subtextContext.Setup(c => c.User.IsInRole("Admins")).Returns(false); // change to true.
            subtextContext.Setup(c => c.Blog).Returns(new Blog {
                CommentDelayInMinutes = 100
            });
            var commentSpamFilter = new Mock <ICommentSpamService>();
            var commentFilter     = new CommentFilter(subtextContext.Object, commentSpamFilter.Object);

            //act, assert (no throw)
            UnitTestHelper.AssertThrows <CommentFrequencyException>(() =>
                                                                    commentFilter.FilterBeforePersist(
                                                                        new FeedbackItem(FeedbackType.Comment)
            {
                IpAddress = IPAddress.Parse("127.0.0.1")
            })
                                                                    );
        }
コード例 #22
0
        public async Task HandleAsync_should_only_call_ExecuteCommand_on_commandExecutors_that_can_execute()
        {
            var fakeLogger           = new Mock <ILogger <TelegramTextMessageHandler> >();
            var fakeCommandExecutor1 = new Mock <IExecuteTelegramCommand>();
            var fakeCommandExecutor2 = new Mock <IExecuteTelegramCommand>();
            var fakeCommandExecutor3 = new Mock <IExecuteTelegramCommand>();

            fakeCommandExecutor1.Setup(x => x.CanExecute(It.IsAny <TelegramCommand>())).Returns(true);
            fakeCommandExecutor2.Setup(x => x.CanExecute(It.IsAny <TelegramCommand>())).Returns(true);
            fakeCommandExecutor3.Setup(x => x.CanExecute(It.IsAny <TelegramCommand>())).Returns(false);

            var textMessage = UnitTestHelper.CreateTelegramTextMessage("/test");

            var handler = new TelegramTextMessageHandler(fakeLogger.Object, new[]
            {
                fakeCommandExecutor1.Object, fakeCommandExecutor2.Object, fakeCommandExecutor3.Object
            });

            await handler.HandleAsync(textMessage);

            fakeCommandExecutor1.Verify(x => x.ExecuteCommand(It.IsAny <TelegramCommand>()), Times.Once);
            fakeCommandExecutor2.Verify(x => x.ExecuteCommand(It.IsAny <TelegramCommand>()), Times.Once);
            fakeCommandExecutor3.Verify(x => x.ExecuteCommand(It.IsAny <TelegramCommand>()), Times.Never);
        }
コード例 #23
0
        public void CodeGen_Attribute_DisplayAttribute_Fail_Private_ResourceType()
        {
            UnitTestHelper.EnsureEnglish();
            var logger        = new ConsoleLogger();
            var generatedCode = TestHelper.GenerateCode("C#", typeof(Mock_CG_DisplayAttr_Entity_Private_ResourceType), logger);

            var expectedExceptionMessage = "Cannot retrieve property 'Name' because localization failed.  Type 'Luma.SimpleEntity.Tests.Mock_CG_DisplayAttr_Private_ResourceType' is not public or does not contain a public static string property with the name 'Resource2'.";

            var expectedException = new AttributeBuilderException(
                new InvalidOperationException(expectedExceptionMessage),
                typeof(DisplayAttribute),
                "Name");

            string expectedBuildWarning = string.Format(
                CultureInfo.CurrentCulture,
                Resource.ClientCodeGen_Attribute_ThrewException_CodeTypeMember,
                expectedException.Message,
                "TheResourcedProperty",
                typeof(Mock_CG_DisplayAttr_Entity_Private_ResourceType).Name,
                expectedException.InnerException.Message);

            TestHelper.AssertGeneratedCodeContains(generatedCode, expectedException.Message);
            TestHelper.AssertContainsWarnings(logger, expectedBuildWarning);
        }
コード例 #24
0
        public void WorkId1BaseTest()
        {
            var helper = new UnitTestHelper(Amount, 1, 3);
            var values = helper.PrepareData <string>();

            var distributor = new Distributor();

            distributor.AddWorkerCell(new StringToEntityWorker());
            distributor.AddWorkerCell(new EntityToEntityWorker());
            distributor.AddWorkerCell(new EntityToModelWorker());

            distributor.Start();

            distributor.AddData(values, new ModelConsumer(helper.SetResult), 1);
            distributor.AddData(values, new ModelConsumer(helper.SetResult), 1);
            distributor.AddData(values, new ModelConsumer(helper.SetResult), 1);

            helper.AwaitTest();
            distributor.Stop();

            PrintTestResults(helper.Results);

            Assert.Equal(helper.ResultAmount(), helper.Results.Count);
        }
コード例 #25
0
        public async Task BookRepository_Update_UpdatesEntity()
        {
            await using var context = new LibraryDbContext(UnitTestHelper.GetUnitTestDbOptions());

            var historyRepository = new HistoryRepository(context);

            var history = new History
            {
                BookId     = 2,
                CardId     = 2,
                Id         = 1,
                TakeDate   = new DateTime(2020, 7, 20),
                ReturnDate = new DateTime(2020, 7, 21)
            };

            historyRepository.Update(history);
            await context.SaveChangesAsync();

            Assert.That(history, Is.EqualTo(
                            new History {
                BookId = 2, CardId = 2, Id = 1, TakeDate = new DateTime(2020, 7, 20), ReturnDate = new DateTime(2020, 7, 21)
            })
                        .Using(new HistoryEqualityComparer()));
        }
コード例 #26
0
        public void CanUpdateEnclosure(string title, string url, string mimetype, long size, bool addToFeed,
                                       bool showWithPost)
        {
            // Arrange
            UnitTestHelper.SetupBlog(string.Empty);
            var   repository = new DatabaseObjectProvider();
            Entry e          = UnitTestHelper.CreateEntryInstanceForSyndication("Simone Chiaretta", "Post for testing Enclosures",
                                                                                "Listen to my great podcast");
            int       entryId = UnitTestHelper.Create(e);
            Enclosure enc     = UnitTestHelper.BuildEnclosure(title, url, mimetype, entryId, size, addToFeed, showWithPost);

            repository.Create(enc);

            string randomStr = UnitTestHelper.GenerateUniqueString().Left(20);

            enc.Url = url + randomStr;

            if (!string.IsNullOrEmpty(title))
            {
                enc.Title = title + randomStr;
            }

            enc.MimeType = mimetype + randomStr;

            int randomSize = new Random().Next(10, 100);

            enc.Size = size + randomSize;

            // Act
            repository.Update(enc);

            // Assert
            Entry newEntry = repository.GetEntry(entryId, true, false);

            UnitTestHelper.AssertEnclosures(enc, newEntry.Enclosure);
        }
コード例 #27
0
        public void FileUploadUsesNamePropertyInJavascript()
        {
            // Arrange
            var    context        = GetContext();
            string name           = "foobar";
            string expectedResult =
                _fileUploadScript
                + @"<form action="""" enctype=""multipart/form-data"" method=""post""><div class=""file-upload"" id=""file-upload-0""><div><input name=""foobar"" type=""file"" /></div></div>"
                + @"<div class=""file-upload-buttons""><a href=""#"" onclick=""FileUploadHelper.addInputElement(0, &quot;foobar&quot;); return false;"">Add more files</a><input type=""submit"" value=""Upload"" /></div></form>";

            // Act
            var result = FileUpload._GetHtml(
                context,
                name: name,
                initialNumberOfFiles: 1,
                allowMoreFilesToBeAdded: true,
                includeFormTag: true,
                addText: null,
                uploadText: null
                );

            // Assert
            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, result.ToString());
        }
コード例 #28
0
        public void AzureSqlDatabaseServerV2Tests()
        {
            // This test uses the https endpoint, setup the certificates.
            MockHttpServer.SetupCertificates();

            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
            {
                // Setup the subscription used for the test
                AzureSubscription subscription =
                    UnitTestHelper.SetupUnitTestSubscription(powershell);

                // Create a new V2 server
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.AzureSqlDatabaseServerV2Tests");
                ServerTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsTrue(
                        actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                        "Missing proper UserAgent string.");
                });

                powershell.Runspace.SessionStateProxy.SetVariable("login", "mylogin");
                powershell.Runspace.SessionStateProxy.SetVariable("password", "Pa$$w0rd!");
                powershell.Runspace.SessionStateProxy.SetVariable("location", "East Asia");
                Collection <PSObject> newServerResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"New-AzureSqlDatabaseServer" +
                               @" -AdministratorLogin $login" +
                               @" -AdministratorLoginPassword $password" +
                               @" -Location $location" +
                               @" -Version 2"));
                });

                Collection <PSObject> getServerResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable("server", newServerResult);
                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabaseServer $server.ServerName"));
                });

                Collection <PSObject> removeServerResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable("server", newServerResult);
                    powershell.InvokeBatchScript(
                        @"$server | Remove-AzureSqlDatabaseServer" +
                        @" -Force");

                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabaseServer"));
                });

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Unexpected Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Unexpected Warnings during run!");

                // Validate New-AzureSqlDatabaseServer results
                SqlDatabaseServerContext server =
                    newServerResult.Single().BaseObject as SqlDatabaseServerContext;
                Assert.IsNotNull(server, "Expecting a SqlDatabaseServerContext object");
                VerifyServer(
                    server,
                    (string)powershell.Runspace.SessionStateProxy.GetVariable("login"),
                    (string)powershell.Runspace.SessionStateProxy.GetVariable("location"),
                    ServerVersion2,
                    "Ready");


                // Validate Get-AzureSqlDatabaseServer results
                server = getServerResult.Single().BaseObject as SqlDatabaseServerContext;
                Assert.IsNotNull(server, "Expecting a SqlDatabaseServerContext object");
                VerifyServer(
                    server,
                    (string)powershell.Runspace.SessionStateProxy.GetVariable("login"),
                    (string)powershell.Runspace.SessionStateProxy.GetVariable("location"),
                    ServerVersion2,
                    "Ready");

                powershell.Streams.ClearStreams();
            }
        }
コード例 #29
0
        public void AzureSqlDatabaseServerTests()
        {
            // This test uses the https endpoint, setup the certificates.
            MockHttpServer.SetupCertificates();

            SqlTestPsHost host = new SqlTestPsHost();
            SqlCustomPsHostUserInterface ui = host.UI as SqlCustomPsHostUserInterface;

            using (Runspace space = RunspaceFactory.CreateRunspace(host))
            {
                space.Open();

                using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
                {
                    powershell.Runspace = space;

                    // Setup the subscription used for the test
                    AzureSubscription subscription =
                        UnitTestHelper.SetupUnitTestSubscription(powershell);

                    // Create a new server
                    HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                        "UnitTest.AzureSqlDatabaseServerTests");
                    ServerTestHelper.SetDefaultTestSessionSettings(testSession);
                    testSession.RequestValidator =
                        new Action <HttpMessage, HttpMessage.Request>(
                            (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.IsTrue(
                            actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                            "Missing proper UserAgent string.");
                    });

                    powershell.Runspace.SessionStateProxy.SetVariable("login", "mylogin");
                    powershell.Runspace.SessionStateProxy.SetVariable("password", "Pa$$w0rd!");
                    powershell.Runspace.SessionStateProxy.SetVariable("location", "East Asia");
                    Collection <PSObject> newServerResult = MockServerHelper.ExecuteWithMock(
                        testSession,
                        MockHttpServer.DefaultHttpsServerPrefixUri,
                        () =>
                    {
                        return(powershell.InvokeBatchScript(
                                   @"New-AzureSqlDatabaseServer" +
                                   @" -AdministratorLogin $login" +
                                   @" -AdministratorLoginPassword $password" +
                                   @" -Location $location"));
                    });

                    ui.PromptInputs = new PSObject[] { "mylogin", "Pa$$w0rd", "East Asia" };
                    Collection <PSObject> newServerResult2 = MockServerHelper.ExecuteWithMock(
                        testSession,
                        MockHttpServer.DefaultHttpsServerPrefixUri,
                        () =>
                    {
                        return(powershell.InvokeBatchScript(@"New-AzureSqlDatabaseServer"));
                    });
                    ui.PromptInputs = null;

                    Collection <PSObject> getServerResult = MockServerHelper.ExecuteWithMock(
                        testSession,
                        MockHttpServer.DefaultHttpsServerPrefixUri,
                        () =>
                    {
                        powershell.Runspace.SessionStateProxy.SetVariable("server", newServerResult);
                        return(powershell.InvokeBatchScript(
                                   @"Get-AzureSqlDatabaseServer $server.ServerName"));
                    });

                    Collection <PSObject> setServerResult = MockServerHelper.ExecuteWithMock(
                        testSession,
                        MockHttpServer.DefaultHttpsServerPrefixUri,
                        () =>
                    {
                        powershell.Runspace.SessionStateProxy.SetVariable("server", newServerResult);
                        powershell.Runspace.SessionStateProxy.SetVariable("password", "Pa$$w0rd2");
                        powershell.InvokeBatchScript(
                            @"$server | Set-AzureSqlDatabaseServer" +
                            @" -AdminPassword $password" +
                            @" -Force");
                        return(powershell.InvokeBatchScript(
                                   @"$server | Get-AzureSqlDatabaseServer"));
                    });

                    ui.PromptInputs = new PSObject[] { "Pa$$w0rd2" };
                    Collection <PSObject> setServerResult2 = MockServerHelper.ExecuteWithMock(
                        testSession,
                        MockHttpServer.DefaultHttpsServerPrefixUri,
                        () =>
                    {
                        powershell.Runspace.SessionStateProxy.SetVariable("server", newServerResult2);
                        powershell.InvokeBatchScript(@"$server | Set-AzureSqlDatabaseServer");
                        return(powershell.InvokeBatchScript(@"$server | Get-AzureSqlDatabaseServer"));
                    });
                    ui.PromptInputs = null;

                    Collection <PSObject> removeServerResult = MockServerHelper.ExecuteWithMock(
                        testSession,
                        MockHttpServer.DefaultHttpsServerPrefixUri,
                        () =>
                    {
                        powershell.Runspace.SessionStateProxy.SetVariable("server", newServerResult);
                        powershell.InvokeBatchScript(
                            @"$server | Remove-AzureSqlDatabaseServer" +
                            @" -Force");

                        return(powershell.InvokeBatchScript(
                                   @"Get-AzureSqlDatabaseServer"));
                    });

                    ui.PromptInputs = new PSObject[] { ((SqlDatabaseServerContext)newServerResult2[0].BaseObject).ServerName };
                    ui.PromptForChoiceInputIndex = 0;   //answer yes to delete database prompt
                    Collection <PSObject> removeServerResult2 = MockServerHelper.ExecuteWithMock(
                        testSession,
                        MockHttpServer.DefaultHttpsServerPrefixUri,
                        () =>
                    {
                        powershell.InvokeBatchScript(@"Remove-AzureSqlDatabaseServer");

                        return(powershell.InvokeBatchScript(
                                   @"Get-AzureSqlDatabaseServer"));
                    });
                    ui.PromptForChoiceInputIndex = -1;
                    ui.PromptInputs = null;

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Unexpected Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Unexpected Warnings during run!");

                    // Validate New-AzureSqlDatabaseServer results
                    SqlDatabaseServerContext server =
                        newServerResult.Single().BaseObject as SqlDatabaseServerContext;
                    Assert.IsNotNull(server, "Expecting a SqlDatabaseServerContext object");
                    VerifyServer(
                        server,
                        (string)powershell.Runspace.SessionStateProxy.GetVariable("login"),
                        (string)powershell.Runspace.SessionStateProxy.GetVariable("location"),
                        ServerVersion12,
                        "Ready");

                    SqlDatabaseServerContext server2 = newServerResult2.Single().BaseObject as SqlDatabaseServerContext;
                    Assert.IsNotNull(server2, "Expecting a SqlDatabaseServerContext object");
                    VerifyServer(
                        server,
                        (string)powershell.Runspace.SessionStateProxy.GetVariable("login"),
                        (string)powershell.Runspace.SessionStateProxy.GetVariable("location"),
                        ServerVersion12,
                        "Ready");

                    // Validate Get-AzureSqlDatabaseServer results
                    server = getServerResult.Single().BaseObject as SqlDatabaseServerContext;
                    Assert.IsNotNull(server, "Expecting a SqlDatabaseServerContext object");
                    VerifyServer(
                        server,
                        (string)powershell.Runspace.SessionStateProxy.GetVariable("login"),
                        (string)powershell.Runspace.SessionStateProxy.GetVariable("location"),
                        ServerVersion12,
                        "Ready");

                    server = setServerResult.Single().BaseObject as SqlDatabaseServerContext;
                    Assert.IsNotNull(server, "Expecting a SqlDatabaseServerContext object");
                    VerifyServer(
                        server,
                        (string)powershell.Runspace.SessionStateProxy.GetVariable("login"),
                        (string)powershell.Runspace.SessionStateProxy.GetVariable("location"),
                        ServerVersion12,
                        "Ready");

                    server2 = setServerResult2.Single().BaseObject as SqlDatabaseServerContext;
                    Assert.IsNotNull(server, "Expecting a SqlDatabaseServerContext object");
                    VerifyServer(
                        server2,
                        (string)powershell.Runspace.SessionStateProxy.GetVariable("login"),
                        (string)powershell.Runspace.SessionStateProxy.GetVariable("location"),
                        ServerVersion12,
                        "Ready");

                    // Validate Remove-AzureSqlDatabaseServer results
                    Assert.IsFalse(
                        removeServerResult.Any((o) => o.GetVariableValue <string>("ServerName") == server.ServerName),
                        "Server should have been removed.");

                    Assert.IsFalse(
                        removeServerResult2.Any((o) => o.GetVariableValue <string>("ServerName") == server2.ServerName),
                        "Server 2 should have been removed.");

                    powershell.Streams.ClearStreams();
                }

                space.Close();
            }
        }
コード例 #30
0
        public void CanSetAndGetSimpleProperties()
        {
            var group = new BlogGroup();

            UnitTestHelper.AssertSimpleProperties(group);
        }