public void EnlistCommitTransactionTest( )
        {
            var testCache = new TestCache( );

            using (var scope = new TransactionScope(TransactionScopeOption.Required))
            {
                var cacheManager = new TransactionEventNotificationManager(testCache);

                // Add some items to the cache while inside a transaction
                testCache.AddItem("A");
                cacheManager.EnlistTransaction(Transaction.Current);

                testCache.AddItem("B");
                cacheManager.EnlistTransaction(Transaction.Current);

                testCache.AddItem("C");
                cacheManager.EnlistTransaction(Transaction.Current);

                // Commit the transaction
                scope.Complete( );
            }

            Assert.IsTrue(testCache.Contains("A"));
            Assert.IsTrue(testCache.Contains("B"));
            Assert.IsTrue(testCache.Contains("C"));
        }
Esempio n. 2
0
 public Dependencies()
 {
     _typeCache = new TestCache();
     _baseUriSelectionPolicy = new Mock<IBaseUriSelectionPolicy>();
     _baseUriSelectionPolicy.Setup(policy => policy.SelectBaseUri(It.IsAny<EntityId>()))
                            .Returns(new Uri("http://magi/"));
 }
Esempio n. 3
0
        public void LruBoundedCache_must_maintain_good_average_probe_distance()
        {
            foreach (var u in Enumerable.Range(1, 10))
            {
                var seed = ThreadLocalRandom.Current.Next(1024);

                // Cache emulating 60% fill rate
                var cache = new TestCache(1024, 600, seed.ToString());

                for (var i = 0; i < 10000; i++)
                {
                    cache.GetOrCompute(ThreadLocalRandom.Current.NextDouble().ToString(CultureInfo.InvariantCulture));
                }

                var stats = cache.Stats;

                // Have not seen lower than 890
                stats.Entries.Should().BeGreaterThan(750);

                // Have not seen higher than 1.8
                stats.AverageProbeDistance.Should().BeLessThan(2.5);

                // Have not seen higher than 15
                stats.MaxProbeDistance.Should().BeLessThan(25);
            }
        }
Esempio n. 4
0
        public void FilterBeforePersistDoesNotAllowDuplicateComments()
        {
            //arrange
            var recentCommentChecksums = new Queue <string>();

            recentCommentChecksums.Enqueue("TestChecksum");
            var subtextContext = new Mock <ISubtextContext>();
            var cache          = new TestCache();

            cache["COMMENT FILTER:.RECENT_COMMENTS"] = recentCommentChecksums;
            subtextContext.Setup(c => c.Cache).Returns(cache);
            subtextContext.Setup(c => c.User.IsInRole("Admins")).Returns(false);
            subtextContext.Setup(c => c.Blog).Returns(new Blog {
                CommentDelayInMinutes = 0, DuplicateCommentsEnabled = false
            });
            var commentSpamFilter = new Mock <ICommentSpamService>();
            var commentFilter     = new CommentFilter(subtextContext.Object, commentSpamFilter.Object);

            //act, assert
            UnitTestHelper.AssertThrows <CommentDuplicateException>(() =>
                                                                    commentFilter.FilterBeforePersist(
                                                                        new FeedbackItem(FeedbackType.Comment)
            {
                ChecksumHash = "TestChecksum"
            })
                                                                    );
        }
Esempio n. 5
0
        public void LruBoundedCache_must_work_with_lower_age_threshold()
        {
            foreach (var i in Enumerable.Range(1, 10))
            {
                var seed  = ThreadLocalRandom.Current.Next(1024);
                var cache = new TestCache(4, 2, seed.ToString());

                cache.ExpectComputed("A", "A:0");
                cache.ExpectComputed("B", "B:1");
                cache.ExpectComputed("C", "C:2");
                cache.ExpectComputed("D", "D:3");
                cache.ExpectComputed("E", "E:4");

                cache.ExpectCached("D", "D:3");
                cache.ExpectCached("E", "E:4");

                cache.ExpectComputed("F", "F:5");
                cache.ExpectComputed("G", "G:6");
                cache.ExpectComputed("H", "H:7");
                cache.ExpectComputed("I", "I:8");
                cache.ExpectComputed("J", "J:9");

                cache.ExpectCached("I", "I:8");
                cache.ExpectCached("J", "J:9");
            }
        }
        public void ClearTransactionEventNotifiersTest( )
        {
            var testCache = new TestCache( );

            using (var scope = new TransactionScope(TransactionScopeOption.Required))
            {
                var cacheManager = new TransactionEventNotificationManager(testCache);

                // Add some items to the cache while inside a transaction
                testCache.AddItem("A");
                cacheManager.EnlistTransaction(Transaction.Current);

                testCache.AddItem("B");
                cacheManager.EnlistTransaction(Transaction.Current);

                testCache.AddItem("C");
                cacheManager.EnlistTransaction(Transaction.Current);

                // Clear the event notifiers
                cacheManager.ClearTransactionEventNotifiers( );

                // Commit the transaction
                // as the. As the event notifiers have been removed
                // the items will not be commited
                scope.Complete( );
            }

            Assert.IsFalse(testCache.Contains("A"));
            Assert.IsFalse(testCache.Contains("B"));
            Assert.IsFalse(testCache.Contains("C"));
        }
Esempio n. 7
0
        public void PipGraphIsCachedCorrectly()
        {
            var testCache = new TestCache();
            var config    = (CommandLineConfiguration)BuildAndGetConfiguration(CreateWriteReadProject("first.txt", "second.txt"));

            config.Cache.CacheGraph = true;
            config.Cache.AllowFetchingCachedGraphFromContentCache = true;
            config.Cache.Incremental = true;

            // First time the graph should be computed
            var engineResult = RunEngineWithConfig(config, testCache);

            Assert.True(engineResult.IsSuccess);

            AssertInformationalEventLogged(global::BuildXL.FrontEnd.Core.Tracing.LogEventId.FrontEndStartEvaluateValues);
            AssertInformationalEventLogged(LogEventId.EndSerializingPipGraph);
            AssertLogContains(false, "Storing pip graph descriptor to cache: Status: Success");

            // The second build should fetch and reuse the graph from the cache
            engineResult = RunEngineWithConfig(config, testCache);
            Assert.True(engineResult.IsSuccess);

            AssertInformationalEventLogged(global::BuildXL.FrontEnd.Core.Tracing.LogEventId.FrontEndStartEvaluateValues, count: 0);
            AssertInformationalEventLogged(LogEventId.EndDeserializingEngineState);
        }
Esempio n. 8
0
        public void LruBoundedCache_must_evict_oldest_when_full()
        {
            foreach (var i in Enumerable.Range(1, 10))
            {
                var seed  = ThreadLocalRandom.Current.Next(1024);
                var cache = new TestCache(4, 4, seed.ToString());

                cache.ExpectComputed("A", "A:0");
                cache.ExpectComputed("B", "B:1");
                cache.ExpectComputed("C", "C:2");
                cache.ExpectComputed("D", "D:3");
                cache.ExpectComputed("E", "E:4");

                cache.ExpectCached("B", "B:1");
                cache.ExpectCached("C", "C:2");
                cache.ExpectCached("D", "D:3");
                cache.ExpectCached("E", "E:4");

                cache.ExpectComputed("A", "A:5");
                cache.ExpectComputed("B", "B:6");
                cache.ExpectComputed("C", "C:7");
                cache.ExpectComputed("D", "D:8");
                cache.ExpectComputed("E", "E:9");

                cache.ExpectCached("B", "B:6");
                cache.ExpectCached("C", "C:7");
                cache.ExpectCached("D", "D:8");
                cache.ExpectCached("E", "E:9");
            }
        }
Esempio n. 9
0
        protected virtual BuildXLEngineResult CreateAndRunEngine(
            ICommandLineConfiguration config,
            AppDeployment appDeployment,
            string testRootDirectory,
            bool rememberAllChangedTrackedInputs,
            out BuildXLEngine engine,
            Action <EngineTestHooksData> verifyEngineTestHooksData = null,
            TestCache testCache = null)
        {
            testCache = testCache ?? TestCache;

            using (EngineTestHooksData testHooks = new EngineTestHooksData
            {
                AppDeployment = appDeployment,
                CacheFactory = (context) => new EngineCache(
                    testCache.GetArtifacts(context),
                    testCache.Fingerprints)
            })
            {
                engine = CreateEngine(config, appDeployment, testRootDirectory, rememberAllChangedTrackedInputs, verifyEngineTestHooksData);

                // Ignore DX222 for csc.exe being outside of src directory
                IgnoreWarnings();

                engine.TestHooks = testHooks;

                var result = engine.RunForFrontEndTests(LoggingContext);
                return(result);
            }
        }
Esempio n. 10
0
        public void FilterAfterPersistWithCommentModerationEnabledCausesNewCommentsToNeedApproval()
        {
            //arrange
            var subtextContext = new Mock <ISubtextContext>();
            var cache          = new TestCache();

            subtextContext.Setup(c => c.Cache).Returns(cache);
            subtextContext.Setup(c => c.User.IsInRole("Admins")).Returns(false);
            subtextContext.Setup(c => c.Blog).Returns(new Blog {
                ModerationEnabled = true
            });
            FeedbackItem savedFeedback = null;

            subtextContext.Setup(c => c.Repository.UpdateInternal(It.IsAny <FeedbackItem>())).Callback <FeedbackItem>(
                f => savedFeedback = f);

            var commentSpamFilter = new Mock <ICommentSpamService>();
            var commentFilter     = new CommentFilter(subtextContext.Object, commentSpamFilter.Object);
            var feedback          = new FeedbackItem(FeedbackType.Comment);

            Assert.IsFalse(feedback.NeedsModeratorApproval);

            //act
            commentFilter.FilterAfterPersist(feedback);

            //assert
            Assert.IsTrue(savedFeedback.NeedsModeratorApproval);
        }
Esempio n. 11
0
        public void Cache_AddGet()
        {
            var cache = new TestCache(TimeSpan.FromMilliseconds(100));

            var ev = new InnerData(new Transaction("123", ""))
            {
                Transaction = { Destination = new List <ServerId>() }
            };

            cache.AddToCache("123", ev);
            var ret = cache.Get("123");

            Assert.AreEqual(ev, ret);
            Thread.Sleep(200);
            ret = cache.Get("123");
            Assert.AreEqual(null, ret);
            cache.AddToCache("123", ev);
            ret = cache.Get("123");
            Assert.AreEqual(ev, ret);

            cache.AddToCache("1234", ev);
            ret = cache.Get("1234");
            Assert.AreEqual(ev, ret);
            Thread.Sleep(200);
            ret = cache.Get("1234");
            Assert.AreEqual(null, ret);
        }
Esempio n. 12
0
        public DsTestWithCacheBase(ITestOutputHelper output, bool usePassThroughFileSystem = false) : base(output, usePassThroughFileSystem)
        {
            RegisterEventSource(global::BuildXL.FrontEnd.Script.ETWLogger.Log);
            RegisterEventSource(global::BuildXL.Engine.ETWLogger.Log);

            TestCache = new TestCache();
        }
        public void UseParameterCachingWithPersistSecurityInfoFalse()
        {
            try
            {
                DeleteUser();
                CreateUser();

                DatabaseProviderFactory factory = new DatabaseProviderFactory(new TestConfigurationContext());
                Database dbsec = factory.CreateDatabase("NorthwindPersistFalse");
                connection = dbsec.GetConnection();
                connection.Open();

                DBCommandWrapper storedProc1 = dbsec.GetStoredProcCommandWrapper("CustOrdersOrders", "ALFKI");
                storedProc1.Command.Connection = connection;
                TestCache testCache = new TestCache();
                testCache.FillParameters(storedProc1, '@');

                DBCommandWrapper storedProc2 = dbsec.GetStoredProcCommandWrapper("CustOrdersOrders", "ALFKI");
                storedProc2.Command.Connection = connection;
                testCache.FillParameters(storedProc2, '@');

                Assert.IsTrue(testCache.CacheUsed);
            }
            finally
            {
                DeleteUser();
            }
        }
Esempio n. 14
0
        public void LruBoundedCache_must_not_cache_noncacheable_values()
        {
            var cache = new TestCache(4, 4);

            cache.ExpectComputedOnly("#A", "#A:0");
            cache.ExpectComputedOnly("#A", "#A:1");
            cache.ExpectComputedOnly("#A", "#A:2");
            cache.ExpectComputedOnly("#A", "#A:3");

            cache.ExpectComputed("A", "A:4");
            cache.ExpectComputed("B", "B:5");
            cache.ExpectComputed("C", "C:6");
            cache.ExpectComputed("D", "D:7");
            cache.ExpectComputed("E", "E:8");

            cache.ExpectComputedOnly("#A", "#A:9");
            cache.ExpectComputedOnly("#A", "#A:10");
            cache.ExpectComputedOnly("#A", "#A:11");
            cache.ExpectComputedOnly("#A", "#A:12");

            // Cacheable values are not affected
            cache.ExpectCached("B", "B:5");
            cache.ExpectCached("C", "C:6");
            cache.ExpectCached("D", "D:7");
            cache.ExpectCached("E", "E:8");
        }
Esempio n. 15
0
        public void Cache_CheckShared()
        {
            var cache     = new TestCache();
            var shared    = "The quick brown fox jumped over the lazy dog.";
            var unshared1 = new object();
            var unshared2 = new object();

            var foo1 = new Foo {
                Shared = shared, Unshared = unshared1
            };
            var foo2 = new Foo {
                Shared = Copy(shared), Unshared = unshared2
            };

            var ref1 = cache.Create(foo1);
            var ref2 = cache.Create(foo2);

            var rc1 = ref1.Value;
            var rc2 = ref2.Value;

            Assert.AreNotSame(foo1, rc1);
            Assert.AreSame(foo1.Shared, rc1.Shared);
            Assert.AreSame(shared, rc1.Shared);
            Assert.AreSame(unshared1, rc1.Unshared);

            Assert.AreNotSame(foo2, rc2);
            Assert.AreNotSame(foo2.Shared, rc2.Shared);
            Assert.AreSame(shared, rc2.Shared);
            Assert.AreSame(unshared2, rc2.Unshared);
        }
        protected BuildXLEngineResult RunYarnProjects(
            ICommandLineConfiguration config,
            TestCache testCache = null,
            IDetoursEventListener detoursListener = null)
        {
            // This bootstraps the 'repo'
            if (!YarnInit(config))
            {
                throw new InvalidOperationException("Yarn init failed.");
            }

            using (var tempFiles = new TempFileStorage(canGetFileNames: true, rootPath: TestOutputDirectory))
            {
                var appDeployment = CreateAppDeployment(tempFiles);

                ((CommandLineConfiguration)config).Engine.Phase           = Phase;
                ((CommandLineConfiguration)config).Sandbox.FileSystemMode = FileSystemMode.RealAndMinimalPipGraph;

                var engineResult = CreateAndRunEngine(
                    config,
                    appDeployment,
                    testRootDirectory: null,
                    rememberAllChangedTrackedInputs: true,
                    engine: out var engine,
                    testCache: testCache,
                    detoursListener: detoursListener);

                return(engineResult);
            }
        }
        public void TransactionExceedingTimeoutTest( )
        {
            var testCache = new TestCache( );

            using (var scope = new TransactionScope(TransactionScopeOption.Required))
            {
                // Create a notification manager with a time out interval of 1 seconds.
                var cacheManager = new TransactionEventNotificationManager(testCache, 0);

                // Add an items to the cache while inside a transaction
                testCache.AddItem("A");
                cacheManager.EnlistTransaction(Transaction.Current);

                testCache.AddItem("B");
                cacheManager.EnlistTransaction(Transaction.Current);

                testCache.AddItem("C");
                cacheManager.EnlistTransaction(Transaction.Current);

                scope.Complete( );

                // As the transaction exceeded the timeout, its data will not
                // be committed
            }

            Assert.IsFalse(testCache.Contains("A"));
            Assert.IsFalse(testCache.Contains("B"));
            Assert.IsFalse(testCache.Contains("C"));
        }
        public void EnlistRolledbackTransactionTest( )
        {
            var testCache = new TestCache( );

            using (new TransactionScope(TransactionScopeOption.Required))
            {
                var cacheManager = new TransactionEventNotificationManager(testCache);

                // Add some items to the cache while inside a transaction
                testCache.AddItem("A");
                cacheManager.EnlistTransaction(Transaction.Current);

                testCache.AddItem("B");
                cacheManager.EnlistTransaction(Transaction.Current);

                testCache.AddItem("C");
                cacheManager.EnlistTransaction(Transaction.Current);

                // Roll back transaction
            }

            Assert.IsFalse(testCache.Contains("A"));
            Assert.IsFalse(testCache.Contains("B"));
            Assert.IsFalse(testCache.Contains("C"));
        }
        public void EnlistNullTransactionTest( )
        {
            var testCache = new TestCache( );

            var cacheManager = new TransactionEventNotificationManager(testCache);

            cacheManager.EnlistTransaction(null);
        }
Esempio n. 20
0
 public void CachedItemParallelCountTest()
 {
     using (var cache = new TestCache(5))
     {
         TestItem item = new TestItem();
         Parallel.For(0, 5, (i) => cache.Release(item));
         cache.CachedCount.Should().Be(5);
     }
 }
Esempio n. 21
0
        public void PassthroughVariablesAreHonored(bool isPassThrough)
        {
            var testCache = new TestCache();

            const string TestProj1       = "test1.csproj";
            var          pathToTestProj1 = R("public", TestProj1);

            Environment.SetEnvironmentVariable("Test", "originalValue");

            var environment = new Dictionary <string, DiscriminatingUnion <string, UnitValue> > {
                ["Test"] = isPassThrough ?
                           new DiscriminatingUnion <string, UnitValue>(UnitValue.Unit) :
                           new DiscriminatingUnion <string, UnitValue>(Environment.GetEnvironmentVariable("Test"))
            };

            var config = (CommandLineConfiguration)Build(
                runInContainer: false,
                environment: environment,
                globalProperties: null,
                filenameEntryPoint: pathToTestProj1,
                msBuildRuntime: null,
                dotnetSearchLocations: null)
                         .AddSpec(pathToTestProj1, CreateWriteFileTestProject("MyFile"))
                         .PersistSpecsAndGetConfiguration();

            config.Sandbox.FileSystemMode = FileSystemMode.RealAndMinimalPipGraph;

            config.Cache.CacheGraph = true;
            config.Cache.AllowFetchingCachedGraphFromContentCache = true;
            config.Cache.Incremental = true;

            // First time the graph should be computed
            var engineResult = RunEngineWithConfig(config, testCache);

            Assert.True(engineResult.IsSuccess);

            AssertInformationalEventLogged(global::BuildXL.FrontEnd.Core.Tracing.LogEventId.FrontEndStartEvaluateValues);
            AssertInformationalEventLogged(LogEventId.EndSerializingPipGraph);
            AssertLogContains(false, "Storing pip graph descriptor to cache: Status: Success");

            Environment.SetEnvironmentVariable("Test", "modifiedValue");

            engineResult = RunEngineWithConfig(config, testCache);
            Assert.True(engineResult.IsSuccess);

            // If the variable is a passthrough, the change shouldn't affect caching
            if (isPassThrough)
            {
                AssertInformationalEventLogged(global::BuildXL.FrontEnd.Core.Tracing.LogEventId.FrontEndStartEvaluateValues, count: 0);
                AssertInformationalEventLogged(LogEventId.EndDeserializingEngineState);
            }
            else
            {
                AssertInformationalEventLogged(global::BuildXL.FrontEnd.Core.Tracing.LogEventId.FrontEndStartEvaluateValues);
                AssertInformationalEventLogged(LogEventId.EndSerializingPipGraph);
            }
        }
Esempio n. 22
0
 public void GetCachedItem()
 {
     using (var cache = new TestCache(5))
     {
         TestItem item = new TestItem();
         cache.Release(item);
         cache.Acquire().Should().BeSameAs(item);
         cache.Acquire().Should().NotBeSameAs(item);
     }
 }
Esempio n. 23
0
        public void LruBoundedCache_must_handle_explict_set()
        {
            var cache = new TestCache(4, 4);

            cache.ExpectComputed("A", "A:0");
            cache.TrySet("A", "A:1").Should().Be(true);
            cache.Get("A").Should().Be("A:1");

            cache.TrySet("B", "B:X").Should().Be(true);
            cache.Get("B").Should().Be("B:X");
        }
Esempio n. 24
0
        public IActionResult GetSessionCache(string cacheKey)
        {
            var value = _sessionCache.Get(cacheKey);
            var obj   = new TestCache()
            {
                CacheKey = cacheKey, Value = value
            };
            var x = new ObjectResult(obj);

            return(x);
        }
        public void IsCacheUsed()
        {
            TestCache testCache = new TestCache();
            testCache.FillParameters(storedProcedure, '@');

            DBCommandWrapper storedProcDuplicate = db.GetStoredProcCommandWrapper("CustOrdersOrders", "ALFKI");
            storedProcDuplicate.Command.Connection = connection;
            testCache.FillParameters(storedProcDuplicate, '@');

            Assert.IsTrue(testCache.CacheUsed, "Cache is not used");
        }
Esempio n. 26
0
            static void DoFirst(TestCache cache, string shared)
            {
                var foo1 = new Foo {
                    Shared = shared
                };

                var rt1 = RoundtripCache(cache, foo1);

                Assert.AreNotSame(foo1, rt1);
                Assert.AreSame(shared, rt1.Shared);
                Assert.AreSame(foo1.Shared, rt1.Shared);
            }
Esempio n. 27
0
        private void runTest()
        {
            var tester = new TestCache(m_StudentCache, new Student()
            {
                Id            = 999,
                Birthdate     = DateTime.Now,
                AvarageGrades = 99,
                FullName      = "Dummy Student"
            });

            tester.RunTests();
        }
Esempio n. 28
0
            static void DoSecond(TestCache cache, string shared)
            {
                var foo2 = new Foo {
                    Shared = Copy(shared)
                };

                var rt2 = RoundtripCache(cache, foo2);

                Assert.AreNotSame(foo2, rt2);
                Assert.AreNotSame(shared, rt2.Shared);
                Assert.AreSame(foo2.Shared, rt2.Shared);
            }
Esempio n. 29
0
        public void Cache_GarbageCollected()
        {
            var cache  = new TestCache();
            var shared = "The quick brown fox jumped over the lazy dog.";

            DoFirst(cache, shared);

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            DoSecond(cache, shared);
        public void IsCacheUsed()
        {
            TestCache testCache = new TestCache();

            testCache.FillParameters(storedProcedure, '@');

            DBCommandWrapper storedProcDuplicate = db.GetStoredProcCommandWrapper("CustOrdersOrders", "ALFKI");

            storedProcDuplicate.Command.Connection = connection;
            testCache.FillParameters(storedProcDuplicate, '@');

            Assert.IsTrue(testCache.CacheUsed, "Cache is not used");
        }
Esempio n. 31
0
        public void CachedItemCountTest()
        {
            using (var cache = new TestCache(5))
            {
                TestItem item = new TestItem();
                for (int i = 0; i < 7; i++)
                {
                    cache.Release(item);
                }

                cache.CachedCount.Should().Be(5);
            }
        }
Esempio n. 32
0
    public void ListSingleCache()
    {
      var testCache = new TestCache();
      testCache.InnerCache.Add("lorem", "ipsum");

      var cmd = new Cmd.Cache();
      InitCommand(cmd);
      cmd.CacheName = CACHE_NAME;

      var result = cmd.Run();
      Assert.That(result.Status, Is.EqualTo(CommandStatus.Success));
      Assert.That(result.Message, Is.StringContaining("lorem"));
    }
Esempio n. 33
0
    public void GetEntriesPartial()
    {
      var testCache = new TestCache();
      testCache.InnerCache.Add("lorem1", "ipsum1");
      testCache.InnerCache.Add("lorem2", "ipsum2");
      testCache.InnerCache.Add("dolor", "sit");

      var cmd = new Cmd.Cache();
      InitCommand(cmd);
      cmd.CacheName = CACHE_NAME;
      cmd.KeyName = "lorem";
      cmd.KeyNamePartial = true;

      var result = cmd.Run();
      Assert.That(result.Status, Is.EqualTo(CommandStatus.Success));
      Assert.That(result.Message, Is.StringContaining("lorem1"));
      Assert.That(result.Message, Is.StringContaining("ipsum1"));
      Assert.That(result.Message, Is.StringContaining("lorem2"));
      Assert.That(result.Message, Is.StringContaining("ipsum2"));
    }
Esempio n. 34
0
        public void FilterAfterPersistWithCommentModerationEnabledCausesNewCommentsToNeedApproval()
        {
            //arrange
            var subtextContext = new Mock<ISubtextContext>();
            var cache = new TestCache();
            subtextContext.Setup(c => c.Cache).Returns(cache);
            subtextContext.Setup(c => c.User.IsInRole("Admins")).Returns(false);
            subtextContext.Setup(c => c.Blog).Returns(new Blog { ModerationEnabled = true });
            FeedbackItem savedFeedback = null;
            subtextContext.Setup(c => c.Repository.UpdateInternal(It.IsAny<FeedbackItem>())).Callback<FeedbackItem>(
                f => savedFeedback = f);

            var commentSpamFilter = new Mock<ICommentSpamService>();
            var commentFilter = new CommentFilter(subtextContext.Object, commentSpamFilter.Object);
            var feedback = new FeedbackItem(FeedbackType.Comment);
            Assert.IsFalse(feedback.NeedsModeratorApproval);

            //act
            commentFilter.FilterAfterPersist(feedback);

            //assert
            Assert.IsTrue(savedFeedback.NeedsModeratorApproval);
        }
        public void UseParameterCachingWithPersistSecurityInfoFalse()
        {
            try
            {
                DeleteUser();
                CreateUser();

                DatabaseProviderFactory factory = new DatabaseProviderFactory(new TestConfigurationContext());
                Database dbsec = factory.CreateDatabase("NorthwindPersistFalse");
                connection = dbsec.GetConnection();
                connection.Open();

                DBCommandWrapper storedProc1 = dbsec.GetStoredProcCommandWrapper("CustOrdersOrders", "ALFKI");
                storedProc1.Command.Connection = connection;
                TestCache testCache = new TestCache();
                testCache.FillParameters(storedProc1, '@');

                DBCommandWrapper storedProc2 = dbsec.GetStoredProcCommandWrapper("CustOrdersOrders", "ALFKI");
                storedProc2.Command.Connection = connection;
                testCache.FillParameters(storedProc2, '@');

                Assert.IsTrue(testCache.CacheUsed);
            }
            finally
            {
                DeleteUser();
            }
        }
Esempio n. 36
0
    public void ClearSingelEntry()
    {
      var testCache = new TestCache();
      testCache.InnerCache.Add("lorem", "ipsum");
      testCache.InnerCache.Add("dolor", "sit");

      var cmd = new Cmd.Cache();
      InitCommand(cmd);
      cmd.CacheName = CACHE_NAME;
      cmd.KeyName = "dolor";
      cmd.Clear = true;

      var result = cmd.Run();
      Assert.That(result.Status, Is.EqualTo(CommandStatus.Success));
      Assert.That(testCache.InnerCache["dolor"], Is.Null);
      Assert.That(testCache.InnerCache["lorem"], Is.EqualTo("ipsum"));
    }
        public void IsInstallationActionRequired_WithCachedInstallationStatusOfNeedsInstallation_ReturnsTrue()
        {
            //arrange
            var installer = new Mock<IInstaller>();
            installer.Setup(i => i.GetCurrentInstallationVersion()).Throws(new InvalidOperationException());
            var cache = new TestCache();
            cache["NeedsInstallation"] = InstallationState.NeedsInstallation;
            var manager = new InstallationManager(installer.Object, cache);

            //act
            bool result = manager.InstallationActionRequired(new Version(), null);

            //assert
            Assert.IsTrue(result);
        }
        public void IsInstallationActionRequired_WithInstallerReturningNull_ReturnsTrue()
        {
            //arrange
            var installer = new Mock<IInstaller>();
            installer.Setup(i => i.GetCurrentInstallationVersion()).Returns((Version)null);
            var cache = new TestCache();
            cache["NeedsInstallation"] = null;
            var manager = new InstallationManager(installer.Object, cache);

            //act
            bool result = manager.InstallationActionRequired(new Version(), null);

            //assert
            Assert.IsTrue(result);
        }
        public void ResetInstallationStatusCache_WithApplicationNeedingInstallation_SetsStatusToNull()
        {
            // arrange
            var cache = new TestCache();
            cache["NeedsInstallation"] = InstallationState.NeedsInstallation;
            var installManager = new InstallationManager(null, cache);

            // act
            installManager.ResetInstallationStatusCache();

            // assert
            Assert.IsNull(cache["NeedsInstallation"]);
        }
        public void Upgrade_ResetsInstallationStatusCache()
        {
            // arrange
            var cache = new TestCache();
            cache["NeedsInstallation"] = InstallationState.NeedsInstallation;
            var installer = new Mock<IInstaller>();
            installer.Setup(i => i.Upgrade(It.IsAny<Version>()));
            var installManager = new InstallationManager(installer.Object, cache);

            // act
            installManager.Upgrade(new Version());

            // assert
            Assert.IsNull(cache["NeedsInstallation"]);
        }
Esempio n. 41
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") })
                );
        }
Esempio n. 42
0
        public void FilterBeforePersistIgnoresAdminRole()
        {
            //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(true);
            subtextContext.Setup(c => c.Blog).Returns(new Blog { CommentDelayInMinutes = 1 });
            var commentSpamFilter = new Mock<ICommentSpamService>();
            var commentFilter = new CommentFilter(subtextContext.Object, commentSpamFilter.Object);

            //act, assert (no throw)
            commentFilter.FilterBeforePersist(new FeedbackItem(FeedbackType.PingTrack) { IpAddress = IPAddress.Parse("127.0.0.1") });
        }
Esempio n. 43
0
        public void FilterBeforePersistDoesNotAllowDuplicateComments()
        {
            //arrange
            var recentCommentChecksums = new Queue<string>();
            recentCommentChecksums.Enqueue("TestChecksum");
            var subtextContext = new Mock<ISubtextContext>();
            var cache = new TestCache();
            cache["COMMENT FILTER:.RECENT_COMMENTS"] = recentCommentChecksums;
            subtextContext.Setup(c => c.Cache).Returns(cache);
            subtextContext.Setup(c => c.User.IsInRole("Admins")).Returns(false);
            subtextContext.Setup(c => c.Blog).Returns(new Blog { CommentDelayInMinutes = 0, DuplicateCommentsEnabled = false });
            var commentSpamFilter = new Mock<ICommentSpamService>();
            var commentFilter = new CommentFilter(subtextContext.Object, commentSpamFilter.Object);

            //act, assert
            UnitTestHelper.AssertThrows<CommentDuplicateException>(() =>
                                                                   commentFilter.FilterBeforePersist(
                                                                       new FeedbackItem(FeedbackType.Comment) { ChecksumHash = "TestChecksum" })
                );
        }