public void CopySettingsStorageProviderData()
        {
            var mocks = new MockRepository();

            var source                = mocks.StrictMock <ISettingsStorageProviderV30>();
            var destination           = mocks.StrictMock <ISettingsStorageProviderV30>();
            var sourceAclManager      = mocks.StrictMock <IAclManager>();
            var destinationAclManager = mocks.StrictMock <IAclManager>();

            // Setup SOURCE ---------------------

            // Settings
            var settings = new Dictionary <string, string>
            {
                { "Set1", "Value1" },
                { "Set2", "Value2" }
            };

            Expect.Call(source.GetAllSettings()).Return(settings);

            // Meta-data (global)
            Expect.Call(source.GetMetaDataItem(MetaDataItem.AccountActivationMessage, null)).Return("AAM");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.PasswordResetProcedureMessage, null)).Return("PRM");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.LoginNotice, null)).Return("");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.PageChangeMessage, null)).Return("PCM");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.DiscussionChangeMessage, null)).Return("DCM");

            // Meta-data (root)
            Expect.Call(source.GetMetaDataItem(MetaDataItem.EditNotice, null)).Return("");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.Footer, null)).Return("FOOT");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.Header, null)).Return("HEADER");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.HtmlHead, null)).Return("HTML");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.PageFooter, null)).Return("P_FOOT");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.PageHeader, null)).Return("P_HEADER");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.Sidebar, null)).Return("SIDEBAR");

            // Meta-data ("NS" namespace)
            Expect.Call(source.GetMetaDataItem(MetaDataItem.EditNotice, "NS")).Return("NS_EDIT");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.Footer, "NS")).Return("NS_FOOT");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.Header, "NS")).Return("NS_HEADER");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.HtmlHead, "NS")).Return("NS_HTML");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.PageFooter, "NS")).Return("NS_P_FOOT");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.PageHeader, "NS")).Return("NS_P_HEADER");
            Expect.Call(source.GetMetaDataItem(MetaDataItem.Sidebar, "NS")).Return("NS_SIDEBAR");

            // Plugin assemblies
            byte[] asm1 = { 1, 2, 3, 4, 5 };
            byte[] asm2 = { 6, 7, 8, 9, 10, 11, 12 };
            Expect.Call(source.ListPluginAssemblies()).Return(new[] { "Plugins1.dll", "Plugins2.dll" });
            Expect.Call(source.RetrievePluginAssembly("Plugins1.dll")).Return(asm1);
            Expect.Call(source.RetrievePluginAssembly("Plugins2.dll")).Return(asm2);

            // Plugin status
            Expect.Call(source.GetPluginStatus("Test1.Plugin1")).Return(true);
            Expect.Call(source.GetPluginStatus("Test2.Plugin2")).Return(false);

            // Plugin config
            Expect.Call(source.GetPluginConfiguration("Test1.Plugin1")).Return("Config1");
            Expect.Call(source.GetPluginConfiguration("Test2.Plugin2")).Return("");

            // Outgoing links
            var outgoingLinks = new Dictionary <string, string[]>
            {
                { "Page1", new[] { "Page2", "Page3" } },
                { "Page2", new[] { "Page3" } },
                { "Page3", new[] { "Page4", "Page3" } }
            };

            Expect.Call(source.GetAllOutgoingLinks()).Return(outgoingLinks);

            // ACLs
            Expect.Call(source.AclManager).Return(sourceAclManager);
            AclEntry[] entries =
            {
                new AclEntry("Res1", "Act1", "Subj1", Value.Grant),
                new AclEntry("Res2", "Act2", "Subj2", Value.Deny)
            };
            Expect.Call(sourceAclManager.RetrieveAllEntries()).Return(entries);

            // Setup DESTINATION -----------------

            // Settings
            destination.BeginBulkUpdate();
            LastCall.On(destination).Repeat.Once();
            foreach (var pair in settings)
            {
                Expect.Call(destination.SetSetting(pair.Key, pair.Value)).Return(true);
            }
            destination.EndBulkUpdate();
            LastCall.On(destination).Repeat.Once();

            // Meta-data (global)
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.AccountActivationMessage, null, "AAM")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.PasswordResetProcedureMessage, null, "PRM"))
            .Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.LoginNotice, null, "")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.PageChangeMessage, null, "PCM")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.DiscussionChangeMessage, null, "DCM")).Return(true);

            // Meta-data (root)
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.EditNotice, null, "")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.Footer, null, "FOOT")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.Header, null, "HEADER")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.HtmlHead, null, "HTML")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.PageFooter, null, "P_FOOT")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.PageHeader, null, "P_HEADER")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.Sidebar, null, "SIDEBAR")).Return(true);

            // Meta-data ("NS" namespace)
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.EditNotice, "NS", "NS_EDIT")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.Footer, "NS", "NS_FOOT")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.Header, "NS", "NS_HEADER")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.HtmlHead, "NS", "NS_HTML")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.PageFooter, "NS", "NS_P_FOOT")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.PageHeader, "NS", "NS_P_HEADER")).Return(true);
            Expect.Call(destination.SetMetaDataItem(MetaDataItem.Sidebar, "NS", "NS_SIDEBAR")).Return(true);

            // Plugin assemblies
            Expect.Call(destination.StorePluginAssembly("Plugins1.dll", asm1)).Return(true);
            Expect.Call(destination.StorePluginAssembly("Plugins2.dll", asm2)).Return(true);

            // Plugin status
            Expect.Call(destination.SetPluginStatus("Test1.Plugin1", true)).Return(true);
            Expect.Call(destination.SetPluginStatus("Test2.Plugin2", false)).Return(true);

            // Plugin config
            Expect.Call(destination.SetPluginConfiguration("Test1.Plugin1", "Config1")).Return(true);
            Expect.Call(destination.SetPluginConfiguration("Test2.Plugin2", "")).Return(true);

            // Outgoing links
            foreach (var pair in outgoingLinks)
            {
                Expect.Call(destination.StoreOutgoingLinks(pair.Key, pair.Value)).Return(true);
            }

            // ACLs
            Expect.Call(destination.AclManager).Return(destinationAclManager).Repeat.Any();
            foreach (var e in entries)
            {
                Expect.Call(destinationAclManager.StoreEntry(e.Resource, e.Action, e.Subject, e.Value)).Return(true);
            }

            mocks.ReplayAll();

            DataMigrator.CopySettingsStorageProviderData(source, destination,
                                                         new[] { "NS" }, new[] { "Test1.Plugin1", "Test2.Plugin2" });

            mocks.VerifyAll();
        }
        public void SessionCallbackWithinSynchronizedTransaction()
        {
            SingleConnectionFactory scf      = new SingleConnectionFactory(mockConnectionFactory);
            EmsTemplate             template = CreateTemplate();

            template.ConnectionFactory = scf;

            mockConnection.Start();
            LastCall.On(mockConnection).Repeat.Times(2);
            Expect.Call(mockSession.Transacted).Return(UseTransactedSession).Repeat.Twice();

            if (UseTransactedTemplate)
            {
                mockSession.Commit();
                LastCall.On(mockSession).Repeat.Once();
            }

            mockSession.Close();
            LastCall.On(mockSession).Repeat.Once();
            mockConnection.Stop();
            LastCall.On(mockConnection).Repeat.Once();
            mockConnection.Close();
            LastCall.On(mockConnection).Repeat.Once();

            mocks.ReplayAll();


            TransactionSynchronizationManager.InitSynchronization();

            try
            {
                template.Execute(delegate(ISession session)
                {
                    bool b = session.Transacted;
                    return(null);
                });
                template.Execute(delegate(ISession session)
                {
                    bool b = session.Transacted;
                    return(null);
                });

                Assert.AreSame(mockSession, ConnectionFactoryUtils.GetTransactionalSession(scf, null, false));
                Assert.AreSame(mockSession,
                               ConnectionFactoryUtils.GetTransactionalSession(scf, scf.CreateConnection(), false));

                //In Java this test was doing 'double-duty' and testing TransactionAwareConnectionFactoryProxy, which has
                //not been implemented in .NET

                template.Execute(delegate(ISession session)
                {
                    bool b = session.Transacted;
                    return(null);
                });

                IList synchs = TransactionSynchronizationManager.Synchronizations;
                Assert.AreEqual(1, synchs.Count);
                ITransactionSynchronization synch = (ITransactionSynchronization)synchs[0];
                synch.BeforeCommit(false);
                synch.BeforeCompletion();
                synch.AfterCommit();
                synch.AfterCompletion(TransactionSynchronizationStatus.Unknown);
            }
            finally
            {
                TransactionSynchronizationManager.ClearSynchronization();
                //Assert.IsTrue(TransactionSynchronizationManager.ResourceDictionary.Count == 0);
                //Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
                scf.Dispose();
            }
            Assert.IsTrue(TransactionSynchronizationManager.ResourceDictionary.Count == 0);
            mocks.VerifyAll();
        }
Example #3
0
        public void TransactionCommit()
        {
            IDbProvider     provider       = mocks.StrictMock <IDbProvider>();
            IDbConnection   connection     = mocks.StrictMock <IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock <ISessionFactory>();
            ISession        session        = mocks.StrictMock <ISession>();
            ITransaction    transaction    = mocks.StrictMock <ITransaction>();
            IQuery          query          = mocks.StrictMock <IQuery>();

            IList list = new ArrayList();

            list.Add("test");
            using (mocks.Ordered())
            {
                Expect.Call(sessionFactory.OpenSession()).Return(session);
                Expect.Call(session.Connection).Return(connection);
                Expect.Call(session.BeginTransaction(IsolationLevel.Serializable)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);
                Expect.Call(session.CreateQuery("some query string")).Return(query);
                Expect.Call(query.List()).Return(list);
                transaction.Commit();
                LastCall.On(transaction).Repeat.Once();
                Expect.Call(session.Close()).Return(null);
            }

            mocks.ReplayAll();


            LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory);

            lsfo.AfterPropertiesSet();

            ISessionFactory sfProxy = lsfo.GetObject() as ISessionFactory;

            Assert.IsNotNull(sfProxy);

            HibernateTransactionManager tm = new HibernateTransactionManager();

            tm.TransactionSynchronization = TransactionSynchronizationState.Always;
            tm.AdoExceptionTranslator     = new FallbackExceptionTranslator();
            tm.SessionFactory             = sfProxy;
            tm.DbProvider = provider;
            TransactionTemplate tt = new TransactionTemplate(tm);

            tt.TransactionIsolationLevel = IsolationLevel.Serializable;

            Assert.IsFalse(TransactionSynchronizationManager.HasResource(sfProxy), "Hasn't thread session");
            Assert.IsFalse(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
            Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
            Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive, "Actual transaction not active");

            object result = tt.Execute(new TransactionCommitTxCallback(sfProxy, provider));

            Assert.IsTrue(result == list, "Incorrect result list");

            Assert.IsFalse(TransactionSynchronizationManager.HasResource(sfProxy), "Hasn't thread session");
            Assert.IsFalse(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
            Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
            Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive, "Actual transaction not active");


            mocks.VerifyAll();
        }
        public void MigrateFilesStorageProviderData()
        {
            var mocks = new MockRepository();

            var source           = mocks.StrictMock <IFilesStorageProviderV30>();
            var destination      = mocks.StrictMock <IFilesStorageProviderV30>();
            var settingsProvider = mocks.StrictMock <ISettingsStorageProviderV30>();
            var aclManager       = mocks.StrictMock <IAclManager>();

            Expect.Call(settingsProvider.AclManager).Return(aclManager).Repeat.Any();

            // Setup SOURCE -----------------

            // Directories
            Expect.Call(source.ListDirectories("/")).Return(new[] { "/Dir1/", "/Dir2/" });
            Expect.Call(source.ListDirectories("/Dir1/")).Return(new[] { "/Dir1/Sub/" });
            Expect.Call(source.ListDirectories("/Dir2/")).Return(new string[0]);
            Expect.Call(source.ListDirectories("/Dir1/Sub/")).Return(new string[0]);

            // Settings (permissions)
            Expect.Call(aclManager.RenameResource(
                            Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(source, "/"),
                            Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(destination, "/")))
            .Return(true);
            Expect.Call(aclManager.RenameResource(
                            Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(source, "/Dir1/"),
                            Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(destination, "/Dir1/")))
            .Return(true);
            Expect.Call(aclManager.RenameResource(
                            Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(source, "/Dir2/"),
                            Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(destination, "/Dir2/")))
            .Return(true);
            Expect.Call(aclManager.RenameResource(
                            Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(source, "/Dir1/Sub/"),
                            Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(destination, "/Dir1/Sub/")))
            .Return(true);

            // Filenames
            Expect.Call(source.ListFiles("/")).Return(new[] { "/File1.txt", "/File2.txt" });
            Expect.Call(source.ListFiles("/Dir1/")).Return(new[] { "/Dir1/File.txt" });
            Expect.Call(source.ListFiles("/Dir2/")).Return(new string[0]);
            Expect.Call(source.ListFiles("/Dir1/Sub/")).Return(new[] { "/Dir1/Sub/File.txt" });

            // File content
            Expect.Call(source.RetrieveFile("/File1.txt", null, false)).Constraints(
                RMC.Is.Equal("/File1.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(
                new RetrieveFile(
                    delegate(string file, Stream stream, bool count)
            {
                var stuff = Encoding.Unicode.GetBytes("content1");
                stream.Write(stuff, 0, stuff.Length);
                return(true);
            }));

            Expect.Call(source.RetrieveFile("/File2.txt", null, false)).Constraints(
                RMC.Is.Equal("/File2.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(
                new RetrieveFile(
                    delegate(string file, Stream stream, bool count)
            {
                var stuff = Encoding.Unicode.GetBytes("content2");
                stream.Write(stuff, 0, stuff.Length);
                return(true);
            }));

            Expect.Call(source.RetrieveFile("/Dir1/File.txt", null, false)).Constraints(
                RMC.Is.Equal("/Dir1/File.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(
                new RetrieveFile(
                    delegate(string file, Stream stream, bool count)
            {
                var stuff = Encoding.Unicode.GetBytes("content3");
                stream.Write(stuff, 0, stuff.Length);
                return(true);
            }));

            Expect.Call(source.RetrieveFile("/Dir1/Sub/File.txt", null, false)).Constraints(
                RMC.Is.Equal("/Dir1/Sub/File.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(
                new RetrieveFile(
                    delegate(string file, Stream stream, bool count)
            {
                var stuff = Encoding.Unicode.GetBytes("content4");
                stream.Write(stuff, 0, stuff.Length);
                return(true);
            }));

            // File details
            Expect.Call(source.GetFileDetails("/File1.txt")).Return(new FileDetails(8, DateTime.Now, 52));
            Expect.Call(source.GetFileDetails("/File2.txt")).Return(new FileDetails(8, DateTime.Now, 0));
            Expect.Call(source.GetFileDetails("/Dir1/File.txt")).Return(new FileDetails(8, DateTime.Now, 21));
            Expect.Call(source.GetFileDetails("/Dir1/Sub/File.txt")).Return(new FileDetails(8, DateTime.Now, 123));

            // Page attachments
            Expect.Call(source.GetPagesWithAttachments()).Return(new[] { "MainPage", "Sub.Page", "Sub.Another" });
            Expect.Call(source.ListPageAttachments(null))
            .Constraints(RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "MainPage"); }))
            .Return(new[] { "Attachment.txt" });
            Expect.Call(source.ListPageAttachments(null))
            .Constraints(RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "Sub.Page"); }))
            .Return(new[] { "Attachment2.txt" });
            Expect.Call(source.ListPageAttachments(null))
            .Constraints(RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "Sub.Another"); }))
            .Return(new string[0]);

            // Page attachment content
            Expect.Call(source.RetrievePageAttachment(null, "Attachment.txt", null, false)).Constraints(
                RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "MainPage"); }),
                RMC.Is.Equal("Attachment.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(
                new RetrieveAttachment(
                    delegate(PageInfo page, string name, Stream stream, bool count)
            {
                var stuff = Encoding.Unicode.GetBytes("content5");
                stream.Write(stuff, 0, stuff.Length);
                return(true);
            }));

            Expect.Call(source.RetrievePageAttachment(null, "Attachment2.txt", null, false)).Constraints(
                RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "Sub.Page"); }),
                RMC.Is.Equal("Attachment2.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(
                new RetrieveAttachment(
                    delegate(PageInfo page, string name, Stream stream, bool count)
            {
                var stuff = Encoding.Unicode.GetBytes("content6");
                stream.Write(stuff, 0, stuff.Length);
                return(true);
            }));

            // Attachment details
            Expect.Call(source.GetPageAttachmentDetails(null, "Attachment.txt")).Constraints(
                RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "MainPage"); }),
                RMC.Is.Equal("Attachment.txt")).Return(new FileDetails(8, DateTime.Now, 8));
            Expect.Call(source.GetPageAttachmentDetails(null, "Attachment2.txt")).Constraints(
                RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "Sub.Page"); }),
                RMC.Is.Equal("Attachment2.txt")).Return(new FileDetails(8, DateTime.Now, 29));

            // Setup DESTINATION ------------------------

            // Directories
            Expect.Call(destination.CreateDirectory("/", "Dir1")).Return(true);
            Expect.Call(destination.CreateDirectory("/", "Dir2")).Return(true);
            Expect.Call(destination.CreateDirectory("/Dir1/", "Sub")).Return(true);

            // Files
            Expect.Call(destination.StoreFile("/File1.txt", null, false)).Constraints(
                RMC.Is.Equal("/File1.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(new StoreFile(
                                                                                                  delegate(string name, Stream stream, bool overwrite)
            {
                var buff = new byte[512];
                var read = stream.Read(buff, 0, (int)stream.Length);
                Assert.AreEqual("content1", Encoding.Unicode.GetString(buff, 0, read), "Wrong data");
                return(true);
            }));

            Expect.Call(destination.StoreFile("/File2.txt", null, false)).Constraints(
                RMC.Is.Equal("/File2.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(new StoreFile(
                                                                                                  delegate(string name, Stream stream, bool overwrite)
            {
                var buff = new byte[512];
                var read = stream.Read(buff, 0, (int)stream.Length);
                Assert.AreEqual("content2", Encoding.Unicode.GetString(buff, 0, read), "Wrong data");
                return(true);
            }));

            Expect.Call(destination.StoreFile("/Dir1/File.txt", null, false)).Constraints(
                RMC.Is.Equal("/Dir1/File.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(new StoreFile(
                                                                                                      delegate(string name, Stream stream, bool overwrite)
            {
                var buff = new byte[512];
                var read = stream.Read(buff, 0, (int)stream.Length);
                Assert.AreEqual("content3", Encoding.Unicode.GetString(buff, 0, read), "Wrong data");
                return(true);
            }));

            Expect.Call(destination.StoreFile("/Dir1/Sub/File.txt", null, false)).Constraints(
                RMC.Is.Equal("/Dir1/Sub/File.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(new StoreFile(
                                                                                                          delegate(string name, Stream stream, bool overwrite)
            {
                var buff = new byte[512];
                var read = stream.Read(buff, 0, (int)stream.Length);
                Assert.AreEqual("content4", Encoding.Unicode.GetString(buff, 0, read), "Wrong data");
                return(true);
            }));

            // File retrieval count
            destination.SetFileRetrievalCount("/File1.txt", 52);
            LastCall.On(destination).Repeat.Once();
            destination.SetFileRetrievalCount("/File2.txt", 0);
            LastCall.On(destination).Repeat.Once();
            destination.SetFileRetrievalCount("/Dir1/File.txt", 21);
            LastCall.On(destination).Repeat.Once();
            destination.SetFileRetrievalCount("/Dir1/Sub/File.txt", 123);
            LastCall.On(destination).Repeat.Once();

            // Page attachments
            Expect.Call(destination.StorePageAttachment(null, "Attachment.txt", null, false)).Constraints(
                RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "MainPage"); }),
                RMC.Is.Equal("Attachment.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(new StoreAttachment(
                                                                                                      delegate(PageInfo page, string name, Stream stream, bool overwrite)
            {
                var buff = new byte[512];
                var read = stream.Read(buff, 0, (int)stream.Length);
                Assert.AreEqual("content5", Encoding.Unicode.GetString(buff, 0, read), "Wrong data");
                return(true);
            }));

            Expect.Call(destination.StorePageAttachment(null, "Attachment2.txt", null, false)).Constraints(
                RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "Sub.Page"); }),
                RMC.Is.Equal("Attachment2.txt"), RMC.Is.TypeOf <Stream>(), RMC.Is.Equal(false)).Do(new StoreAttachment(
                                                                                                       delegate(PageInfo page, string name, Stream stream, bool overwrite)
            {
                var buff = new byte[512];
                var read = stream.Read(buff, 0, (int)stream.Length);
                Assert.AreEqual("content6", Encoding.Unicode.GetString(buff, 0, read), "Wrong data");
                return(true);
            }));

            // Attachment retrieval count
            destination.SetPageAttachmentRetrievalCount(null, "Attachment.txt", 8);
            LastCall.On(destination)
            .Constraints(RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "MainPage"); }),
                         RMC.Is.Equal("Attachment.txt"), RMC.Is.Equal(8))
            .Repeat.Once();
            destination.SetPageAttachmentRetrievalCount(null, "Attachment2.txt", 29);
            LastCall.On(destination)
            .Constraints(RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "Sub.Page"); }),
                         RMC.Is.Equal("Attachment2.txt"), RMC.Is.Equal(29))
            .Repeat.Once();

            // Delete source content
            Expect.Call(source.DeleteFile("/File1.txt")).Return(true);
            Expect.Call(source.DeleteFile("/File2.txt")).Return(true);
            Expect.Call(source.DeleteDirectory("/Dir1/")).Return(true);
            Expect.Call(source.DeleteDirectory("/Dir2/")).Return(true);

            Expect.Call(source.DeletePageAttachment(null, "Attachment.aspx"))
            .Constraints(RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "MainPage"); }),
                         RMC.Is.Equal("Attachment.txt"))
            .Return(true);
            Expect.Call(source.DeletePageAttachment(null, "Attachment2.aspx"))
            .Constraints(RMC.Is.Matching(delegate(PageInfo p) { return(p.FullName == "Sub.Page"); }),
                         RMC.Is.Equal("Attachment2.txt"))
            .Return(true);

            mocks.Replay(source);
            mocks.Replay(destination);
            mocks.Replay(settingsProvider);
            mocks.Replay(aclManager);

            DataMigrator.MigrateFilesStorageProviderData(source, destination, settingsProvider);

            mocks.Verify(source);
            mocks.Verify(destination);
            mocks.Verify(settingsProvider);
            mocks.Verify(aclManager);
        }
Example #5
0
        public void TransactionWithPropagationSupportsAndInnerTransaction()
        {
            IDbConnection   connection     = mocks.StrictMock <IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock <ISessionFactory>();
            ISession        session1       = mocks.StrictMock <ISession>();
            ISession        session2       = mocks.StrictMock <ISession>();
            ITransaction    transaction    = mocks.StrictMock <ITransaction>();

            Expect.Call(sessionFactory.OpenSession()).Return(session1);
            Expect.Call(session1.Connection).Return(connection);
            Expect.Call(session1.SessionFactory).Return(sessionFactory);
            Expect.Call(session1.FlushMode).Return(FlushMode.Auto).Repeat.Twice();

            session1.Flush();
            LastCall.IgnoreArguments().Repeat.Twice();
            Expect.Call(session1.Close()).Return(null);

            Expect.Call(sessionFactory.OpenSession()).Return(session2);
            Expect.Call(session2.Connection).Return(connection).Repeat.Twice();
            Expect.Call(session2.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
            Expect.Call(session2.FlushMode).Return(FlushMode.Auto);
            session2.Flush();
            LastCall.IgnoreArguments();
            Expect.Call(session2.IsOpen).Return(true);


            transaction.Commit();
            LastCall.On(transaction).Repeat.Once();


            Expect.Call(session2.Close()).Return(null);

            mocks.ReplayAll();

            LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory);

            lsfo.AfterPropertiesSet();
            ISessionFactory sfProxy = (ISessionFactory)lsfo.GetObject();

            Assert.IsNotNull(sfProxy);

            HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);

            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);

            tt.PropagationBehavior = TransactionPropagation.Supports;
            TransactionTemplate tt2 = new TransactionTemplate(tm);

            tt2.PropagationBehavior = TransactionPropagation.Required;

            HibernateTemplate ht = new HibernateTemplate(sessionFactory);

            ht.TemplateFlushMode   = TemplateFlushMode.Eager;
            ht.ExposeNativeSession = true;

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");

            tt.Execute(new TransactionWithPropagationSupportsAndInnerTransactionTxCallback(tt2, sessionFactory, ht, session1, session2));

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");

            mocks.ReplayAll();
        }
Example #6
0
        /// <summary>
        /// Does the test transaction commit with flush failure.
        /// </summary>
        /// <param name="fallbackTranslation">if set to <c>true</c> if the exception throw
        /// is of the type NHibernate.ADOException, in which case HibernateTransactionManager
        /// will 'fallback' to using the error codes in the underlying exception thrown by
        /// the provider, ie. a SqlException, MySqlException.  Otherwise, if it is
        /// another subclass of HibernateException, then perform a direct maping as
        /// found in SessionFactoryUtils.ConvertHibernateAccessException.</param>
        private void DoTransactionCommitWithFlushFailure(bool fallbackTranslation)
        {
            #region Mock Setup

            IDbProvider     provider       = new TestDbProvider();
            IDbConnection   connection     = mocks.StrictMock <IDbConnection>();
            ISessionFactory sessionFactory = mocks.StrictMock <ISessionFactory>();
            ISession        session        = mocks.StrictMock <ISession>();
            ITransaction    transaction    = mocks.StrictMock <ITransaction>();
            IDbTransaction  adoTransaction = mocks.StrictMock <IDbTransaction>();

            Exception rootCause = null;
            using (mocks.Ordered())
            {
                Expect.Call(sessionFactory.OpenSession()).Return(session);
                Expect.Call(session.Connection).Return(connection);
                Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);
                transaction.Commit();
                Exception sqlException = new TestSqlException("mymsg", "2627");
                if (fallbackTranslation)
                {
                    //error code 2627 will map to a DataAccessIntegrity exception in sqlserver, which is the metadata
                    //used by TestDbProvider.
                    rootCause = sqlException;
                    LastCall.On(transaction).Throw(new ADOException("mymsg", sqlException));
                }
                else
                {
                    rootCause = new PropertyValueException("mymsg", typeof(string).Name, "Name");
                    LastCall.On(transaction).Throw(rootCause);
                }

                Expect.Call(adoTransaction.Connection).Return(connection);
                LastCall.On(adoTransaction).Repeat.Once();

                transaction.Rollback();
                LastCall.On(transaction).Repeat.Once();
                Expect.Call(session.Close()).Return(null);
            }

            #endregion

            mocks.ReplayAll();


            TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;
            tm.DbProvider = provider;
            tm.StubbedTransactionThatReturnsExpectedConnection = adoTransaction;

            TransactionTemplate tt = new TransactionTemplate(tm);
            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
            Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");

            IList list = new ArrayList();
            list.Add("test");
            try
            {
                tt.Execute(new TransactionCommitWithFlushFailureCallback(sessionFactory, list));
                Assert.Fail("Should have thrown DataIntegrityViolationException");
            }
            catch (DataIntegrityViolationException ex)
            {
                Assert.AreEqual(rootCause, ex.InnerException);
                Assert.IsTrue(ex.Message.IndexOf("mymsg") != -1);
            }

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
            Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");

            mocks.VerifyAll();
        }
 public void CallingLastCallWithoutHavingLastCallThrows()
 {
     Assert.Throws <InvalidOperationException>(
         "There is no matching last call on this object. Are you sure that the last call was a virtual or interface method call?",
         () => LastCall.On(demo));
 }
 public void ReturnDerivedType()
 {
     demo.EnumNoArgs();
     LastCall.On(demo).Return(DemoEnum.Demo);
 }
Example #9
0
 public void DifferentArgumentsFromMethodThrows()
 {
     demo.VoidThreeArgs(0, "", 0f);
     Assert.Throws <InvalidOperationException>("Callback arguments didn't match the method arguments",
                                               () => LastCall.On(demo).Callback <int, string, string>(OtherThreeArgs));
 }
Example #10
0
        public void Test_04_NegativeTest_MockLogger()
        {
            MockRepository mocks = new MockRepository();

            ILogger logger = mocks.CreateMock <ILogger>();

            logger.TestStart(null, DateTime.Now, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            // S E T U P
            logger.TestStageStart(TestStage.Setup, DateTime.Now);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.TestStageEnd(TestStage.Setup, DateTime.Now, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            // E X E C U T E
            logger.TestStageStart(TestStage.Execution, DateTime.Now);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.TestStepStart(null, DateTime.Now, true, true);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.TestStepEnd(null, DateTime.Now, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.TestStepStart(null, DateTime.Now, true, true);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.Log(LogLevel.INFO, null);
            LastCall.On(logger).Repeat.Any().IgnoreArguments();

            logger.LogData(null, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.ValidatorStart(null, DateTime.Now);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.Log(LogLevel.INFO, null);
            LastCall.On(logger).Repeat.Any().IgnoreArguments();

            logger.Log(LogLevel.ERROR, null, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.LogException(null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.ValidatorEnd(null, DateTime.Now, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.TestStepEnd(null, DateTime.Now, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.TestStageEnd(TestStage.Execution, DateTime.Now, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            // C L E A N U P
            logger.TestStageStart(TestStage.Cleanup, DateTime.Now);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.TestStepStart(null, DateTime.Now, true, true);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.TestStepEnd(null, DateTime.Now, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.TestStageEnd(TestStage.Cleanup, DateTime.Now, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.TestEnd(null, DateTime.Now, null);
            LastCall.On(logger).Repeat.Once().IgnoreArguments();

            logger.Flush();
            logger.Close();

            mocks.ReplayAll();

            Context ctx     = new Context(logger);
            BizUnit bizUnit = new BizUnit(@"..\..\..\Test\BizUnit.Tests\TestCases\Test_04_NegativeTest.xml", ctx);

            try
            {
                bizUnit.RunTest();
            }
            catch (Exception) {}

            mocks.VerifyAll();
        }
Example #11
0
        public void MediaPropertiesMustChangeOnlyAfterUpdate()
        {
            MockRepository rep = new MockRepository();
            IFileSystem    fs  = rep.CreateMock <IFileSystem>();
            MyFileStream   stm = rep.CreateMock <MyFileStream>(rep);

            Expect.Call(fs.OpenFile("test")).Return(stm);

            DateTime time1 = new DateTime(2000, 1, 1);
            long     size1 = 100;

            Expect.Call(stm.Length).Repeat.Any().Return(size1);
            Expect.Call(stm.LastWriteTime).Repeat.Any().Return(time1);
            Expect.Call(stm.IsDeleted).Repeat.Any().Return(false);

            rep.ReplayAll();

            using (SimpleFileMedia media = new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test")))
            {
                // Media properties are the same as stm's ones
                Assert.AreEqual(time1, media.LastModified);
                Assert.AreEqual(size1, media.Size);

                rep.VerifyAll();

                rep.BackToRecordAll();
                // Chnage the properties of stm
                DateTime time2 = new DateTime(2000, 2, 2);
                long     size2 = 200;
                Expect.Call(stm.Length).Repeat.Any().Return(size2);
                Expect.Call(stm.LastWriteTime).Repeat.Any().Return(time2);
                Expect.Call(stm.IsDeleted).Repeat.Any().Return(false);
                rep.ReplayAll();

                // Properties have not still changed
                Assert.AreEqual(time1, media.LastModified);
                Assert.AreEqual(size1, media.Size);

                // This Update should refresh media's properties
                media.Update();

                Assert.AreEqual(time2, media.LastModified);
                Assert.AreEqual(size2, media.Size);

                // Subsequent calls change nothing
                media.Update();
                media.Update();
                Assert.AreEqual(time2, media.LastModified);
                Assert.AreEqual(size2, media.Size);

                rep.VerifyAll();


                rep.BackToRecordAll();
                stm.Dispose();
                LastCall.On(stm).Repeat.AtLeastOnce();
                rep.ReplayAll();
            }

            rep.VerifyAll();
        }
Example #12
0
        public void FileDeletedByAnotherProcessAndThenNewFileAppeared()
        {
            MockRepository rep = new MockRepository();

            IFileSystem fs = rep.CreateMock <IFileSystem>();

            // Create and init the first stream
            long         initialSize1 = 100;
            DateTime     modifTime1   = new DateTime(2000, 3, 4);
            MyFileStream stm1         = rep.CreateMock <MyFileStream>(rep);

            Expect.Call(stm1.Length).Repeat.Any().Return(initialSize1);
            Expect.Call(stm1.IsDeleted).Repeat.Any().Return(false);
            Expect.Call(stm1.LastWriteTime).Repeat.Any().Return(modifTime1);

            // Instruct file system to return the first stream
            Expect.Call(fs.OpenFile("test")).Return(stm1);

            rep.ReplayAll();

            using (SimpleFileMedia media = new SimpleFileMedia(fs, SimpleFileMedia.CreateConnectionParamsFromFileName("test")))
            {
                // Check that media refers to the first stream stm1
                Assert.AreEqual(initialSize1, media.DataStream.Length);
                Assert.AreEqual(initialSize1, media.Size);
                Assert.AreEqual(true, media.IsAvailable);

                rep.VerifyAll();



                rep.BackToRecordAll();
                // Simulate file deletion: Length and LastWriteTime keep returning file properties,
                // but IsDeleted now returns "true".
                Expect.Call(stm1.Length).Repeat.Any().Return(initialSize1);
                Expect.Call(stm1.LastWriteTime).Repeat.Any().Return(modifTime1);
                Expect.Call(stm1.IsDeleted).Repeat.Any().Return(true);

                // We expect stream stm1 to be released/disposed
                stm1.Dispose();
                LastCall.On(stm1).Repeat.AtLeastOnce();

                // Factory cannot open the file that has been deleted while being locked
                Expect.Call(fs.OpenFile("test")).Repeat.Any().Throw(new UnauthorizedAccessException());
                rep.ReplayAll();


                // Properties must return previous values as long as Update is not called
                Assert.AreEqual(initialSize1, media.Size);
                Assert.AreEqual(initialSize1, media.DataStream.Length);
                Assert.AreEqual(true, media.IsAvailable);

                // This update should detect file deletion and release it
                media.Update();
                Assert.AreEqual(0, media.Size);
                Assert.AreEqual(0, media.DataStream.Length);
                Assert.AreEqual(false, media.IsAvailable);

                // Subsequent Updates should change nothing
                media.Update();
                media.Update();
                Assert.AreEqual(0, media.Size);
                Assert.AreEqual(0, media.DataStream.Length);
                Assert.AreEqual(false, media.IsAvailable);

                rep.VerifyAll();


                rep.BackToRecordAll();
                // Simulate that new file with name "test" appeared
                long         initialSize2 = 200;
                DateTime     modifTime2   = new DateTime(2000, 4, 5);
                MyFileStream stm2         = rep.CreateMock <MyFileStream>(rep);
                Expect.Call(stm2.Length).Repeat.Any().Return(initialSize2);
                Expect.Call(stm2.IsDeleted).Repeat.Any().Return(false);
                Expect.Call(stm2.LastWriteTime).Repeat.Any().Return(modifTime2);
                stm2.Dispose();
                LastCall.On(stm2).Repeat.AtLeastOnce();
                Expect.Call(fs.OpenFile("test")).Return(stm2);
                rep.ReplayAll();


                // Properties must return previous values as long as Update is not called
                Assert.AreEqual(0, media.Size);
                Assert.AreEqual(0, media.DataStream.Length);
                Assert.AreEqual(false, media.IsAvailable);

                // This Update will pick up new file
                media.Update();
                Assert.AreEqual(initialSize2, media.DataStream.Length);
                Assert.AreEqual(initialSize2, media.Size);
                Assert.AreEqual(true, media.IsAvailable);

                // Subsequent Updates should change nothing
                media.Update();
                media.Update();
                Assert.AreEqual(initialSize2, media.Size);
                Assert.AreEqual(initialSize2, media.DataStream.Length);
                Assert.AreEqual(true, media.IsAvailable);
            }

            rep.VerifyAll();
        }
        public void Format()
        {
            MockRepository mocks = new MockRepository();

            IFilesStorageProviderV30 prov = mocks.StrictMock <IFilesStorageProviderV30>();

            string content = string.Format(
                @"This is a test page.
<countDownloads pattern=""#CoUnT#-#DaIlY#-#WeEkLy#-#MoNtHlY#"" startDate=""{0:yyyy'/'MM'/'dd}"">
	<file name=""/my/file.zip"" provider=""{1}"" />
	<file name=""/my/other/file.zip"" />
	<file name=""/my/inexistent-file.zip"" provider=""{1}"" />
	<file name=""/my/other/inexistent-file.zip"" />

	<attachment name=""attn.zip"" page=""page"" provider=""{1}"" />
	<attachment name=""attn.zip"" page=""page"" />
	<attachment name=""inexistent-attn.zip"" page=""page"" provider=""{1}"" />
	<attachment name=""inexistent-attn.zip"" page=""page"" />
	<attachment name=""attn.zip"" page=""inexistent-page"" provider=""{1}"" />
	<attachment name=""attn.zip"" page=""inexistent-page"" />
</countDownloads>", DateTime.Today.AddDays(-60), prov.GetType().FullName);

            // */file.zip was downloaded 13 times
            // attn.zip was downloaded 56 times
            // Expected output: 138-2-16-68

            IHostV30 host = mocks.StrictMock <IHostV30>();

            host.LogEntry(null, LogEntryType.Warning, null, null);
            LastCall.On(host).IgnoreArguments().Repeat.Any();
            Expect.Call(host.GetSettingValue(SettingName.DefaultFilesStorageProvider)).Return(
                prov.GetType().FullName).Repeat.Times(4);
            Expect.Call(host.GetFilesStorageProviders(true)).Return(
                new IFilesStorageProviderV30[] { prov }).Repeat.Times(8);

            StFileInfo[] myFiles = new StFileInfo[] {
                new StFileInfo(1000, DateTime.Now, 13, "/my/File.zip", prov),
                new StFileInfo(10000, DateTime.Now, 1000, "/my/other-file.zip", prov)
            };
            StFileInfo[] myOtherFiles = new StFileInfo[] {
                new StFileInfo(1000, DateTime.Now, 13, "/my/OTHER/file.zip", prov),
                new StFileInfo(10000, DateTime.Now, 2000, "/my/OTHER/other-file.zip", prov)
            };

            StFileInfo[] attachments = new StFileInfo[] {
                new StFileInfo(2000, DateTime.Now, 56, "aTTn.zip", prov),
                new StFileInfo(20000, DateTime.Now, 1000, "other-attn.zip", prov)
            };

            // /my/*
            Expect.Call(host.ListFiles(null)).IgnoreArguments().Constraints(
                RMC.Is.Matching(
                    delegate(StDirectoryInfo dir) {
                return(dir.FullPath == "/my/");
            })).Return(myFiles).Repeat.Times(2);

            // /my/other/*
            Expect.Call(host.ListFiles(null)).IgnoreArguments().Constraints(
                RMC.Is.Matching(
                    delegate(StDirectoryInfo dir) {
                return(dir.FullPath == "/my/other/");
            })).Return(myOtherFiles).Repeat.Times(2);

            PageInfo page = new PageInfo("page", null, DateTime.Now);

            Expect.Call(host.FindPage("page")).Return(page).Repeat.Times(4);
            Expect.Call(host.FindPage("inexistent-page")).Return(null).Repeat.Twice();

            Expect.Call(host.ListPageAttachments(page)).Return(attachments).Repeat.Times(4);

            mocks.ReplayAll();

            DownloadCounter counter = new DownloadCounter();

            counter.Init(host, "");

            string output = counter.Format(content, null, FormattingPhase.Phase3);

            Assert.IsTrue(output == @"This is a test page.
138-2-16-68" || output == @"This is a test page.
138-2-16-69", "Wrong output");

            mocks.VerifyAll();
        }