示例#1
0
        public async Task MentionUser_Duplicate_Test()
        {
            string user1 = "UnitTestUser05";
            string user2 = "UnitTestUser06";

            var user = TestHelper.SetPrincipal(user1);

            string mentionTwiceContent = $"Hello @{user2}, I am mentioning you twice using two different forms ok. So here: /u/{user2} ha ha";
            var    cmd    = new CreateCommentCommand(submission.ID, null, mentionTwiceContent).SetUserContext(user);
            var    result = await cmd.Execute();

            Assert.IsTrue(result.Success, result.Message);

            using (var db = new VoatDataContext())
            {
                var count = db.Message.Where(x => x.Sender == user1 && x.Recipient == user2 && x.CommentID == result.Response.ID).Count();
                Assert.AreEqual(1, count, "Received duplicates and now users are annoyed and burning down the village! Run!");
            }


            //change casing test
            user = TestHelper.SetPrincipal(user2);
            mentionTwiceContent = $"Hello @{user1.ToLower()}, I am mentioning you twice using two different forms ok. So here: /u/{user1.ToUpper()} ha ha";
            cmd    = new CreateCommentCommand(submission.ID, null, mentionTwiceContent).SetUserContext(user);
            result = await cmd.Execute();

            Assert.IsTrue(result.Success, result.Message);

            using (var db = new VoatDataContext())
            {
                var count = db.Message.Where(x => x.Sender == user2 && x.Recipient == user1 && x.CommentID == result.Response.ID).Count();
                Assert.AreEqual(1, count, "Received duplicates and now users are annoyed and burning down the village! Run!");
            }
        }
示例#2
0
        public async Task MentionUser_MentionWithReply_Duplicate_Test()
        {
            // This test will require rewriting the notification code. Current this does not pass and as such has it's test method commented out.

            //We have two pipelines for sending notifications. They need to be centralized to allow this test to pass. Future people, solve this.

            string user1 = "UnitTestUser09";
            string user2 = "UnitTestUser10";

            var    user           = TestHelper.SetPrincipal(user1);
            string commentContent = $"Some ground breaking inciteful comment here";
            var    cmd            = new CreateCommentCommand(submission.ID, null, commentContent);
            var    result         = await cmd.Execute();

            Assert.IsTrue(result.Success, result.Message);

            user           = TestHelper.SetPrincipal(user2);
            commentContent = $"Hey @{user1} I'm replying to your comment and mentioning you because I'm super annoying. Like you.";
            cmd            = new CreateCommentCommand(submission.ID, result.Response.ID, commentContent);
            result         = await cmd.Execute();

            Assert.IsTrue(result.Success, result.Message);

            using (var db = new VoatDataContext())
            {
                var count = db.Message.Where(x => x.Sender == user2 && x.Recipient == user1 && x.CommentID == result.Response.ID).Count();
                Assert.AreEqual(1, count, "Received duplicates and now users are annoyed and burning down the village! Run!");
            }
        }
示例#3
0
        public override void ClassInitialize()
        {
            List <RuleSet> inserts = new List <RuleSet>();

            //create basic rules
            using (var db = new VoatDataContext())
            {
                inserts.Add(db.RuleSet.Add(new RuleSet()
                {
                    IsActive = true, ContentType = null, SortOrder = -100, Name = "Test - Spam", Description = "Test - Spam", CreatedBy = "Voat", CreationDate = Voat.Data.Repository.CurrentDate
                }).Entity);
                inserts.Add(db.RuleSet.Add(new RuleSet()
                {
                    IsActive = true, ContentType = null, SortOrder = -90, Name = "Test - No Dox", Description = "Test - No Dox Description", CreatedBy = "Voat", CreationDate = Voat.Data.Repository.CurrentDate
                }).Entity);
                inserts.Add(db.RuleSet.Add(new RuleSet()
                {
                    IsActive = true, ContentType = null, SortOrder = -80, Name = "Test - No Illegal", Description = "Test - No Illegal Description", CreatedBy = "Voat", CreationDate = Voat.Data.Repository.CurrentDate
                }).Entity);

                //add rules per sub
                inserts.Add(db.RuleSet.Add(new RuleSet()
                {
                    IsActive = true, ContentType = null, Subverse = SUBVERSES.Unit, SortOrder = 1, Name = "Test - Rule #1", Description = "Test - Rule #1", CreatedBy = USERNAMES.Unit, CreationDate = Voat.Data.Repository.CurrentDate
                }).Entity);
                inserts.Add(db.RuleSet.Add(new RuleSet()
                {
                    IsActive = true, ContentType = null, Subverse = SUBVERSES.Unit, SortOrder = 2, Name = "Test - Rule #2", Description = "Test - Rule #2", CreatedBy = USERNAMES.Unit, CreationDate = Voat.Data.Repository.CurrentDate
                }).Entity);

                db.SaveChanges();
            }
            ids = inserts.Select(x => x.ID).ToList();
        }
示例#4
0
        public void DeleteComment_Owner()
        {
            //Assert.Inconclusive("Complete this test");

            var user      = TestHelper.SetPrincipal("TestUser01");
            var cmdcreate = new CreateCommentCommand(1, null, "This is my data too you know").SetUserContext(user);
            var c         = cmdcreate.Execute().Result;

            VoatAssert.IsValid(c);

            int id = c.Response.ID;

            var cmd = new DeleteCommentCommand(id).SetUserContext(user);
            var r   = cmd.Execute().Result;

            VoatAssert.IsValid(r);

            //verify
            using (var db = new VoatDataContext())
            {
                var comment = db.Comment.FirstOrDefault(x => x.ID == id);
                Assert.AreEqual(true, comment.IsDeleted);
                Assert.AreNotEqual(c.Response.Content, comment.Content);

                //Ensure content is replaced in moderator deletion
                Assert.IsTrue(comment.Content.StartsWith("Deleted by"));
                Assert.AreEqual(comment.FormattedContent, Formatting.FormatMessage(comment.Content));
            }
        }
示例#5
0
 public void TestLogException()
 {
     if (log == null)
     {
         Assert.Inconclusive($"{loggerName} Logger disabled");
     }
     else
     {
         try
         {
             //Open the worm hole to narnia
             int wormhole             = 42;
             int idontcarewhathappens = 0;
             int narnia = wormhole / idontcarewhathappens;
         }
         catch (Exception ex)
         {
             var activityID = Guid.NewGuid();
             log.Log(ex, (Guid?)activityID);
             System.Threading.Thread.Sleep(1000);// batched logger writes on seperate thread, need to wait a bit
             using (var db = new VoatDataContext())
             {
                 var entry = db.EventLog.FirstOrDefault(x => x.ActivityID.ToUpper() == activityID.ToString().ToUpper());
                 Assert.IsNotNull(entry, "If this isn't here, perhaps the narnia wormhole is open?");
             }
         }
     }
 }
示例#6
0
        public void TestLogEntry()
        {
            if (log == null)
            {
                Assert.Inconclusive($"{loggerName} Logger disabled");
            }
            else
            {
                LogInformation info = new LogInformation();
                info.Type       = LogType.Information;
                info.Origin     = "UnitTests";
                info.Category   = "Unit Test";
                info.Message    = "Test Message";
                info.Data       = new { url = "http://www.com" };
                info.ActivityID = Guid.NewGuid();

                log.Log(info);

                System.Threading.Thread.Sleep(1000);

                using (var db = new VoatDataContext())
                {
                    var entry = db.EventLog.FirstOrDefault(x => x.ActivityID.ToUpper() == info.ActivityID.ToString().ToUpper());
                    Assert.IsNotNull(entry, "Crickie! Where is the log data at!?");
                    Assert.AreEqual(info.Type.ToString(), entry.Type);
                    Assert.AreEqual(info.Origin, entry.Origin);
                    Assert.AreEqual(info.Category, entry.Category);
                    Assert.AreEqual(info.Message, entry.Message);
                    Assert.AreEqual(JsonConvert.SerializeObject(info.Data), entry.Data);
                    Assert.AreEqual(info.ActivityID.ToString().ToUpper(), entry.ActivityID.ToUpper());
                }
            }
        }
示例#7
0
        private async Task <CommandResponse <bool?> > SetSubverseListChange(SubverseSet set, Subverse subverse, SubscriptionAction action)
        {
            using (var db = new VoatDataContext())
            {
                CommandResponse <bool?> response = new CommandResponse <bool?>(true, Status.Success, "");
                var actionTaken = SubscriptionAction.Toggle;

                var setSubverseRecord = db.SubverseSetList.FirstOrDefault(n => n.SubverseSetID == set.ID && n.SubverseID == subverse.ID);

                if (setSubverseRecord == null && ((action == SubscriptionAction.Subscribe) || action == SubscriptionAction.Toggle))
                {
                    db.SubverseSetList.Add(new SubverseSetList {
                        SubverseSetID = set.ID, SubverseID = subverse.ID, CreationDate = CurrentDate
                    });
                    actionTaken = SubscriptionAction.Subscribe;
                }
                else if (setSubverseRecord != null && ((action == SubscriptionAction.Unsubscribe) || action == SubscriptionAction.Toggle))
                {
                    db.SubverseSetList.Remove(setSubverseRecord);
                    actionTaken = SubscriptionAction.Unsubscribe;
                }

                await db.SaveChangesAsync().ConfigureAwait(CONSTANTS.AWAIT_CAPTURE_CONTEXT);

                //If Subscribe is to a front page, update subscriber count
                if (set.Type == (int)SetType.Front && !String.IsNullOrEmpty(set.UserName))
                {
                    await UpdateSubverseSubscriberCount(new DomainReference(DomainType.Subverse, subverse.Name), actionTaken);
                }
                response.Response = actionTaken == SubscriptionAction.Toggle ? (bool?)null : actionTaken == SubscriptionAction.Subscribe;
                return(response);
            }
        }
 public static void VoteContent(VoatDataContext context, Domain.Models.ContentType contentType, int id, int count, Domain.Models.VoteValue vote)
 {
     for (int i = 0; i < count; i++)
     {
         string userName = String.Format("VoteUser{0}", i.ToString().PadLeft(4, '0'));
         if (contentType == Domain.Models.ContentType.Comment)
         {
             context.CommentVoteTracker.Add(
                 new CommentVoteTracker()
             {
                 UserName     = userName,
                 IPAddress    = Guid.NewGuid().ToString(),
                 CommentID    = id,
                 VoteStatus   = (int)vote,
                 VoteValue    = (int)vote,
                 CreationDate = DateTime.UtcNow
             });
         }
         else if (contentType == Domain.Models.ContentType.Submission)
         {
             context.SubmissionVoteTracker.Add(
                 new SubmissionVoteTracker()
             {
                 UserName     = userName,
                 IPAddress    = Guid.NewGuid().ToString(),
                 SubmissionID = id,
                 VoteStatus   = (int)vote,
                 VoteValue    = (int)vote,
                 CreationDate = DateTime.UtcNow
             });
         }
     }
     context.SaveChanges();
 }
        public async Task SendBadRecipientInfo_CheckExists()
        {
            var id     = Guid.NewGuid().ToString();
            var sender = USERNAMES.User100CCP;

            var user = TestHelper.SetPrincipal(sender);
            var cmd  = new SendMessageCommand(new Domain.Models.SendMessage()
            {
                Recipient = "Do you like chocolate", Message = id, Subject = "All That Matters"
            }, false, true).SetUserContext(user);
            var response = await cmd.Execute();

            VoatAssert.IsValid(response, Status.Error);

            Assert.AreNotEqual("Comment points too low to send messages. Need at least 10 CCP.", response.Message);

            using (var db = new VoatDataContext())
            {
                var count = (from x in db.Message
                             where
                             x.Content == id
                             select x).Count();
                Assert.AreEqual(0, count, "Expecting no messages to make it through");
            }
        }
示例#10
0
        public static void SetUp(TestContext context, TestDataInitializer intializer, bool configure = true)
        {
            //bool preventDrop = false;

            if (configure)
            {
                //Configure App
                var config = new ConfigurationBuilder()
                             .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                             .Build();
                config.ConfigureVoat();
                //config["voat:test:preventDatabaseDrop"] != "True"
            }

            FilePather.Instance = new FilePather(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));

            //Drop and reseed database
            using (var db = new VoatDataContext())
            {
                intializer.InitializeDatabase(db); //This attempts to create and seed unit test db
            }

            //This causes the voat rules engine to init using config section for load
            var rulesEngine = VoatRulesEngine.Instance;

            //purge redis for unit tests if enabled
            var defaultHandler = CacheConfigurationSettings.Instance.Handlers.FirstOrDefault(x => x.Enabled && x.Type.ToLower().Contains("redis"));

            if (defaultHandler != null)
            {
                var instance = defaultHandler.Construct <ICacheHandler>();
                instance.Purge();
            }
        }
示例#11
0
        public void CreateComment_DisabledSubverse()
        {
            //insert post via db into disabled sub
            Submission submission = null;

            using (var db = new VoatDataContext())
            {
                submission = new Submission()
                {
                    Subverse     = SUBVERSES.Disabled,
                    Title        = "Super Sneaky",
                    Content      = "How can I post to disabled subs?",
                    UserName     = USERNAMES.Unit,
                    CreationDate = DateTime.UtcNow
                };
                db.Submission.Add(submission);
                db.SaveChanges();
            }

            var user = TestHelper.SetPrincipal("TestUser05");
            var cmd  = new CreateCommentCommand(submission.ID, null, "Are you @FuzzyWords?").SetUserContext(user);
            var c    = cmd.Execute().Result;

            Assert.IsFalse(c.Success, "Disabled subs should not allow comments");
            Assert.AreEqual(Status.Denied, c.Status);
            Assert.AreEqual(c.Message, "Subverse is disabled");
        }
        public async Task SendPrivateMessageFromSubverse()
        {
            var id        = Guid.NewGuid().ToString();
            var sender    = "unit";
            var recipient = USERNAMES.User100CCP;

            var user = TestHelper.SetPrincipal(sender);

            var message = new Domain.Models.SendMessage()
            {
                Sender    = $"v/{sender}",
                Recipient = recipient,
                Subject   = id,
                Message   = id
            };
            var cmd = new SendMessageCommand(message).SetUserContext(user);
            var r   = await cmd.Execute();

            VoatAssert.IsValid(r);

            using (var db = new VoatDataContext())
            {
                var record = (from x in db.Message
                              where
                              x.Sender == sender &&
                              x.SenderType == (int)Domain.Models.IdentityType.Subverse &&
                              x.Recipient == recipient &&
                              x.RecipientType == (int)Domain.Models.IdentityType.User &&
                              x.Title == id &&
                              x.Content == id
                              select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find message in database");
            }
        }
示例#13
0
        public async Task CreateComment_TestCommentReplyNotification()
        {
            var userName = "******";
            var user     = TestHelper.SetPrincipal(userName);
            var body     = Guid.NewGuid().ToString();
            var cmd      = new CreateCommentCommand(1, 2, body).SetUserContext(user);
            var c        = await cmd.Execute();

            Assert.IsNotNull(c, "response null");
            if (!c.Success)
            {
                if (c.Exception != null)
                {
                    Assert.Fail(c.Exception.ToString());
                }
                else
                {
                    Assert.Fail(c.Message);
                }
            }
            Assert.AreEqual(Status.Success, c.Status);

            //check for comment reply entry
            using (var db = new VoatDataContext())
            {
                var notice = db.Message.FirstOrDefault(x => x.Sender == userName && x.Recipient == USERNAMES.Unit && x.SubmissionID == 1 && x.CommentID == c.Response.ID);
                Assert.IsNotNull(notice, "Did not find a reply notification");
            }
        }
示例#14
0
        public void BannedDomainTest()
        {
            var domain      = "paydayloansforeverybody.com";
            var reason      = "Total Rip off!";
            var createdBy   = "AntiSpamcist";
            var createdDate = DateTime.UtcNow.AddDays(-10);

            using (var db = new VoatDataContext())
            {
                db.BannedDomain.Add(new BannedDomain()
                {
                    Domain       = domain,
                    Reason       = reason,
                    CreatedBy    = createdBy,
                    CreationDate = createdDate
                });
                db.SaveChanges();
            }
            using (var repo = new Voat.Data.Repository())
            {
                var result = repo.BannedDomains(new string[] { "yahoo.com", "google.com", domain, domain.ToUpper(), "testuri.org" });
                Assert.IsNotNull(result, "Result was null");
                Assert.IsTrue(result.Any(), "Result expected");
                Assert.AreEqual(1, result.Count(), "Count off");
                var bd = result.First();
                Assert.AreEqual(domain, bd.Domain);
                Assert.AreEqual(reason, bd.Reason);
                Assert.AreEqual(createdBy, bd.CreatedBy);
                Assert.AreEqual(createdDate.ToString(), bd.CreationDate.ToString());

                result = repo.BannedDomains(new string[] { "subdomain." + domain });
                Assert.IsNotNull(result, "subdomain failure");
                Assert.IsTrue(result.Any(), "Subdomain Result expected");
            }
        }
示例#15
0
        public SubverseSet GetSet(string name, string userName, SetType?type = null, bool createIfMissing = false)
        {
            var normalization = Normalization.Lower;

            var q = new DapperQuery();

            q.Select = $"SELECT * FROM {SqlFormatter.Table("SubverseSet", "subSet")}";
            q.Where  = SqlFormatter.ToNormalized("subSet.\"Name\"", normalization) + " = @Name";

            if (type.HasValue)
            {
                q.Append(x => x.Where, "subSet.\"Type\" = @Type");
            }

            if (!String.IsNullOrEmpty(userName))
            {
                q.Append(x => x.Where, SqlFormatter.ToNormalized("subSet.\"UserName\"", normalization) + " = @UserName");
            }
            else
            {
                q.Append(x => x.Where, "subSet.\"UserName\" IS NULL");
            }

            q.Parameters = new DynamicParameters(new {
                Name     = name.ToNormalized(normalization),
                UserName = userName.ToNormalized(normalization),
                Type     = (int?)type
            });

            using (var db = new VoatDataContext())
            {
                var set = db.Connection.QueryFirstOrDefault <SubverseSet>(q.ToString(), q.Parameters);
                return(set);
            }
        }
示例#16
0
        public static int BuildCommentTree(string subverse, string commentContent, int rootDepth, int nestedDepth, int recurseCount)
        {
            using (var db = new VoatDataContext())
            {
                var s = db.Subverse.Where(x => x.Name == subverse).FirstOrDefault();
                //create submission
                var submission = new Submission()
                {
                    CreationDate = DateTime.UtcNow,
                    Content      = $"Comment Tree for v/{subverse}",
                    Subverse     = subverse,
                    Title        = $"Comment Tree for v/{subverse}",
                    Type         = 1,
                    UserName     = "******",
                    IsAnonymized = s.IsAnonymized.HasValue ? s.IsAnonymized.Value : false,
                };
                db.Submission.Add(submission);
                db.SaveChanges();

                Func <VoatDataContext, int?, string, string, int> createComment = (context, parentCommentID, content, userName) => {
                    var comment = new Comment()
                    {
                        SubmissionID     = submission.ID,
                        UserName         = userName,
                        Content          = content,
                        FormattedContent = Formatting.FormatMessage(content),
                        ParentID         = parentCommentID,
                        IsAnonymized     = submission.IsAnonymized,
                        CreationDate     = DateTime.UtcNow
                    };
                    context.Comment.Add(comment);
                    context.SaveChanges();
                    System.Threading.Thread.Sleep(2);
                    return(comment.ID);
                };
                Action <VoatDataContext, int?, int, int, string, int> createNestedComments = null;
                createNestedComments = (context, parentCommentID, depth, currentDepth, path, recurseDepth) => {
                    if (currentDepth <= depth)
                    {
                        var newParentCommentID = parentCommentID;
                        currentDepth += 1;
                        for (int i = 0; i < depth; i++)
                        {
                            var newPath = String.Format("{0}:{1}", path, i + 1);
                            newParentCommentID = createComment(context, parentCommentID, $"{commentContent} - Path {newPath}", String.Format("CommentTreeUser{0}", i + 1));
                            if (currentDepth < recurseDepth)
                            {
                                createNestedComments(db, newParentCommentID, (depth), 0, newPath, recurseDepth - 1);
                            }
                        }
                    }
                };
                for (int i = 0; i < rootDepth; i++)
                {
                    int parentCommentID = createComment(db, null, $"{commentContent} - Path {i + 1}", String.Format("CommentTreeUser{0}", i + 1));
                    createNestedComments(db, parentCommentID, nestedDepth, 0, $"{i + 1}", recurseCount);
                }
                return(submission.ID);
            }
        }
示例#17
0
        public async Task DeleteComment_Moderator()
        {
            //Assert.Inconclusive("Complete this test");
            var content   = "This is my data too you know 2";
            var user      = TestHelper.SetPrincipal("TestUser01");
            var cmdcreate = new CreateCommentCommand(1, null, content).SetUserContext(user);
            var c         = cmdcreate.Execute().Result;

            VoatAssert.IsValid(c);

            int id = c.Response.ID;

            //switch to mod of sub
            user = TestHelper.SetPrincipal(USERNAMES.Unit);
            var cmd = new DeleteCommentCommand(id, "This is spam").SetUserContext(user);
            var r   = await cmd.Execute();

            VoatAssert.IsValid(r);

            //verify
            using (var db = new VoatDataContext())
            {
                var comment = db.Comment.FirstOrDefault(x => x.ID == id);
                Assert.AreEqual(true, comment.IsDeleted);

                //Content should remain unchanged in mod deletion
                Assert.AreEqual(comment.Content, content);
                Assert.AreEqual(comment.FormattedContent, Formatting.FormatMessage(content));
            }
        }
示例#18
0
        public void TestLogEntryLevel()
        {
            if (log == null)
            {
                Assert.Inconclusive($"{loggerName} Logger disabled");
            }
            else
            {
                var level = log.LogLevel;
                try
                {
                    log.LogLevel = LogType.Critical;

                    LogInformation info = new LogInformation();
                    info.Type       = LogType.Information;
                    info.Origin     = "UnitTests";
                    info.Category   = "Unit Test";
                    info.Message    = "Test Message";
                    info.Data       = new { url = "http://www.com" };
                    info.ActivityID = Guid.NewGuid();

                    log.Log(info);

                    using (var db = new VoatDataContext())
                    {
                        var entry = db.EventLog.FirstOrDefault(x => x.ActivityID == info.ActivityID.ToString());
                        Assert.IsNull(entry, "Crickie! Data magically appeared when it shouldn't have!?");
                    }
                }
                finally {
                    log.LogLevel = level;
                }
            }
        }
示例#19
0
        public void PreventBannedDomainPost_MultiPartDomains()
        {
            using (var repo = new VoatDataContext())
            {
                repo.BannedDomain.Add(new BannedDomain()
                {
                    Domain = "one.two.three.com", Reason = "People hate counting", CreatedBy = "UnitTest", CreationDate = DateTime.UtcNow
                });
                repo.SaveChanges();
            }

            var user = TestHelper.SetPrincipal("TestUser02");

            var cmd = new CreateSubmissionCommand(new Domain.Models.UserSubmission()
            {
                Subverse = SUBVERSES.Unit, Title = "Hello Man - Longer because of Rules", Url = "http://www.one.two.three.com/images/feelsgoodman.jpg"
            }).SetUserContext(user);
            var r = cmd.Execute().Result;

            Assert.IsNotNull(r, "Response was null");
            Assert.IsFalse(r.Success, r.Message);
            Assert.AreEqual(r.Message, "Submission contains banned domains");

            cmd = new CreateSubmissionCommand(new Domain.Models.UserSubmission()
            {
                Subverse = SUBVERSES.Unit, Title = "Hello Man - Longer because of Rules", Content = "Check out this cool image I found using dogpile.com: HTTP://one.TWO.three.com/images/feelsgoodman.jpg"
            }).SetUserContext(user);
            r = cmd.Execute().Result;
            Assert.IsNotNull(r, "Response was null");
            Assert.IsFalse(r.Success, r.Message);
            Assert.AreEqual(r.Message, "Submission contains banned domains");
        }
示例#20
0
 public void TestLogDurationWithMinimum()
 {
     if (log == null)
     {
         Assert.Inconclusive($"{loggerName} Logger disabled");
     }
     else
     {
         var activityID = Guid.NewGuid();
         using (var durationLog = new DurationLogger(log,
                                                     new LogInformation()
         {
             ActivityID = activityID,
             Type = LogType.Debug,
             Category = "Duration",
             UserName = "",
             Message = $"{this.GetType().Name}"
         },
                                                     TimeSpan.FromSeconds(10)))
         {
             System.Threading.Thread.Sleep(1000);
         }
         using (var db = new VoatDataContext())
         {
             var entry = db.EventLog.FirstOrDefault(x => x.ActivityID == activityID.ToString().ToUpper());
             Assert.IsNull(entry, "Should not have log entry with specified minimum");
         }
     }
 }
示例#21
0
        public void TestNegativeSCPSubmission()
        {
            var userName = "******";

            //Create user
            TestDataInitializer.CreateUser(userName, DateTime.UtcNow.AddDays(-450));
            //Add submission with negatives directly to db
            using (var context = new VoatDataContext())
            {
                var s = context.Submission.Add(new Submission()
                {
                    CreationDate = DateTime.UtcNow.AddHours(-12),
                    Subverse     = SUBVERSES.Unit,
                    Title        = "Test Negative SCP",
                    Url          = "https://www.youtube.com/watch?v=pnbJEg9r1o8",
                    Type         = 2,
                    UpCount      = 2,
                    DownCount    = 13,
                    UserName     = userName
                });
                context.SaveChanges();
            }



            var user           = TestHelper.SetPrincipal(userName);
            var userSubmission = new Domain.Models.UserSubmission()
            {
                Subverse = SUBVERSES.Unit, Title = "Le Censorship!", Content = "Will this work?"
            };
            var cmd = new CreateSubmissionCommand(userSubmission).SetUserContext(user);
            var r   = cmd.Execute().Result;

            VoatAssert.IsValid(r);
        }
示例#22
0
        public void GetCommentSegmentWithContext()
        {
            var commentID = 22;

            using (var db = new VoatDataContext())
            {
                var nestedcomment = db.Comment.Where(x => x.SubmissionID == _unitSubmissionID && x.Content.Contains("Path 1:1:1:1:1")).FirstOrDefault();
                if (nestedcomment == null)
                {
                    Assert.Fail("Can not find expected comment in database");
                }
                commentID = nestedcomment.ID;
            }

            var user = TestHelper.SetPrincipal("TestUser01");
            var q    = new QueryCommentContext(_unitSubmissionID, commentID, 0, CommentSortAlgorithm.New);
            var r    = q.Execute();

            Assert.IsNotNull(r, "Query returned null");

            string        expectedPath = "Path 1";
            NestedComment comment      = r.Comments.First();

            for (int i = 0; i < 5; i++)
            {
                Assert.IsNotNull(comment, "looping comment was null");
                Assert.IsTrue(comment.Content.EndsWith(expectedPath), $"Expected path to end with {expectedPath}, but got {comment.Content}");
                comment = comment.Children != null?comment.Children.Comments.FirstOrDefault() : null;

                expectedPath += ":1";
            }
        }
示例#23
0
 public override void ClassInitialize()
 {
     using (var db = new VoatDataContext())
     {
         //1
         db.Filter.Add(new Filter()
         {
             Pattern      = ".",
             IsActive     = false,
             Name         = "Match Anything",
             CreationDate = DateTime.UtcNow.AddDays(-10)
         });
         //2
         db.Filter.Add(new Filter()
         {
             Pattern      = @"evildomain\.evil",
             IsActive     = true,
             Name         = "Evil Domain is Banned",
             CreationDate = DateTime.UtcNow.AddDays(-10)
         });
         //3
         db.Filter.Add(new Filter()
         {
             Pattern      = @"google\.com/url",
             IsActive     = true,
             Name         = "Google redirect ban",
             CreationDate = DateTime.UtcNow.AddDays(-10)
         });
         db.SaveChanges();
     }
     //Remove Filters that may be in cache
     CacheHandler.Instance.Remove(CachingKey.Filters());
 }
示例#24
0
 public virtual void InitializeDatabase(VoatDataContext context, bool seed = true)
 {
     CreateSchema(context);
     if (seed)
     {
         Seed(context);
     }
 }
示例#25
0
        public void PreventBannedDomainPost()
        {
            using (var repo = new VoatDataContext())
            {
                repo.BannedDomain.Add(new BannedDomain()
                {
                    Domain = "saiddit.com", Reason = "No one really likes you.", CreatedBy = "UnitTest", CreationDate = DateTime.UtcNow
                });
                repo.SaveChanges();
            }

            var user = TestHelper.SetPrincipal("TestUser02");

            var cmd = new CreateSubmissionCommand(new Domain.Models.UserSubmission()
            {
                Subverse = SUBVERSES.Unit, Title = "Hello Man - Longer because of Rules", Url = "http://www.saiddit.com/images/feelsgoodman.jpg"
            }).SetUserContext(user);
            var r = cmd.Execute().Result;

            Assert.IsNotNull(r, "Response was null");
            Assert.IsFalse(r.Success, r.Message);
            Assert.AreEqual(r.Message, "Submission contains banned domains");

            cmd = new CreateSubmissionCommand(new Domain.Models.UserSubmission()
            {
                Subverse = SUBVERSES.Unit, Title = "Hello Man - Longer because of Rules", Content = "Check out this cool image I found using dogpile.com: http://saiddit.com/images/feelsgoodman.jpg"
            }).SetUserContext(user);
            r = cmd.Execute().Result;
            Assert.IsNotNull(r, "Response was null");
            Assert.IsFalse(r.Success, r.Message);
            Assert.AreEqual(r.Message, "Submission contains banned domains");

            cmd = new CreateSubmissionCommand(new Domain.Models.UserSubmission()
            {
                Subverse = SUBVERSES.Unit, Title = "Test Embedded Banned Domain",
                Content  = "http://yahoo.com/index.html Check out this cool image I found using compuserve.com: http://saiddit.com/images/feelsgoodman.jpg. http://www2.home.geocities.com/index.html"
            }).SetUserContext(user);
            r = cmd.Execute().Result;
            Assert.IsNotNull(r, "Response was null");
            Assert.IsFalse(r.Success, r.Message);
            Assert.AreEqual(r.Message, "Submission contains banned domains");

            //Test URLEncoding Markdown Matching
            cmd = new CreateSubmissionCommand(new Domain.Models.UserSubmission()
            {
                Subverse = SUBVERSES.Unit,
                Title    = "Hello Man - Longer because of Rules",
                Content  = "[https://www.some-fake-domain.com/surl/start](https://www.google.com/url?q=http%3A%2F%2Fww2.saiddit.com%2F%3Flnk%26keyword%3Dsome%2Bkey%2Bword%26charset%3Dutf-8)"
            }).SetUserContext(user);
            r = cmd.Execute().Result;
            Assert.IsNotNull(r, "Response was null");
            Assert.IsFalse(r.Success, r.Message);
            Assert.AreEqual(r.Message, "Submission contains banned domains");
        }
        public async Task SendPrivateMessage()
        {
            var id        = Guid.NewGuid().ToString();
            var sender    = USERNAMES.User100CCP;
            var recipient = USERNAMES.Anon;

            var user = TestHelper.SetPrincipal(sender);

            var message = new Domain.Models.SendMessage()
            {
                //Sender = User.Identity.Name,
                Recipient = recipient,
                Subject   = id,
                Message   = id
            };
            var cmd      = new SendMessageCommand(message).SetUserContext(user);
            var response = await cmd.Execute();

            VoatAssert.IsValid(response);

            using (var db = new VoatDataContext())
            {
                var record = (from x in db.Message
                              where
                              x.Recipient == recipient &&
                              x.Sender == sender &&
                              x.Title == id &&
                              x.Content == id &&
                              x.Subverse == null &&
                              x.CommentID == null &&
                              x.SubmissionID == null &&
                              x.Type == (int)Domain.Models.MessageType.Sent
                              //&& x.Direction == (int)Domain.Models.MessageDirection.OutBound
                              select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find outbound in database");

                record = (from x in db.Message
                          where
                          x.Recipient == recipient &&
                          x.Sender == sender &&
                          x.Title == id &&
                          x.Content == id &&
                          x.Subverse == null &&
                          x.CommentID == null &&
                          x.SubmissionID == null &&
                          x.Type == (int)Domain.Models.MessageType.Private
                          //&& x.Direction == (int)Domain.Models.MessageDirection.InBound
                          select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find inbound in database");
            }
        }
示例#27
0
        public async Task MentionUser_Anon_NoBlock_Test()
        {
            string user1 = "UnitTestUser11";
            string user2 = "UnitTestUser12";

            var user = TestHelper.SetPrincipal(user1);

            //Submission
            var anonSubmission = TestHelper.ContentCreation.CreateSubmission(user1, new Domain.Models.UserSubmission()
            {
                Title = $"I'm harrassing @{user2}!", Content = GetMethodName(true), Subverse = SUBVERSES.Anon
            });

            Assert.IsNotNull(anonSubmission, "Couldn't create test submission");
            Assert.AreNotEqual(0, anonSubmission.ID, "Doesn't appear we have a valid submission id");

            Thread.Sleep(2000);

            using (var db = new VoatDataContext())
            {
                var count = db.Message.Where(x =>
                                             x.Sender == user1 &&
                                             x.Recipient == user2 &&
                                             x.SubmissionID == anonSubmission.ID &&
                                             x.IsAnonymized == true &&
                                             x.Type == (int)Domain.Models.MessageType.SubmissionMention
                                             ).Count();
                Assert.AreEqual(1, count, "Where is the harassment submission message!?!?!?");
            }

            //Comment
            string mentionTwiceContent = $"Hello @{user2}, I am mentioning you in an anon thread because I want to make you feel scared";
            var    cmd    = new CreateCommentCommand(anonSubmission.ID, null, mentionTwiceContent).SetUserContext(user);
            var    result = await cmd.Execute();

            VoatAssert.IsValid(result);

            using (var db = new VoatDataContext())
            {
                var count = db.Message.Where(x =>
                                             x.Sender == user1 &&
                                             x.Recipient == user2 &&
                                             x.CommentID == result.Response.ID &&
                                             x.IsAnonymized == true &&
                                             x.Type == (int)Domain.Models.MessageType.CommentMention

                                             ).Count();
                Assert.AreEqual(1, count, "Where is the harassment comment message!?!?!?");
            }
        }
示例#28
0
        public async Task <IEnumerable <Domain.Models.CommentRemovalLog> > GetModLogRemovedComments(string subverse, SearchOptions options)
        {
            using (var db = new VoatDataContext(CONSTANTS.CONNECTION_READONLY))
            {
                var data = (from b in db.CommentRemovalLog
                            join c in db.Comment on b.CommentID equals c.ID
                            join s in db.Submission on c.SubmissionID equals s.ID
                            where s.Subverse.ToLower() == subverse.ToLower()
                            select b).Include(x => x.Comment).Include(x => x.Comment.Submission);

                var data_ordered = data.OrderByDescending(x => x.CreationDate).Skip(options.Index).Take(options.Count);
                var results      = await data_ordered.ToListAsync().ConfigureAwait(CONSTANTS.AWAIT_CAPTURE_CONTEXT);

                //TODO: Move to DomainMaps
                var mapToDomain = new Func <Data.Models.CommentRemovalLog, Domain.Models.CommentRemovalLog>(d =>
                {
                    var m          = new Domain.Models.CommentRemovalLog();
                    m.CreatedBy    = d.Moderator;
                    m.Reason       = d.Reason;
                    m.CreationDate = d.CreationDate;

                    m.Comment                  = new SubmissionComment();
                    m.Comment.ID               = d.Comment.ID;
                    m.Comment.UpCount          = (int)d.Comment.UpCount;
                    m.Comment.DownCount        = (int)d.Comment.DownCount;
                    m.Comment.Content          = d.Comment.Content;
                    m.Comment.FormattedContent = d.Comment.FormattedContent;
                    m.Comment.IsDeleted        = d.Comment.IsDeleted;
                    m.Comment.CreationDate     = d.Comment.CreationDate;

                    m.Comment.IsAnonymized = d.Comment.IsAnonymized;
                    m.Comment.UserName     = m.Comment.IsAnonymized ? d.Comment.ID.ToString() : d.Comment.UserName;
                    m.Comment.LastEditDate = d.Comment.LastEditDate;
                    m.Comment.ParentID     = d.Comment.ParentID;
                    m.Comment.Subverse     = d.Comment.Submission.Subverse;
                    m.Comment.SubmissionID = d.Comment.SubmissionID;

                    m.Comment.Submission.Title        = d.Comment.Submission.Title;
                    m.Comment.Submission.IsAnonymized = d.Comment.Submission.IsAnonymized;
                    m.Comment.Submission.UserName     = m.Comment.Submission.IsAnonymized ? d.Comment.Submission.ID.ToString() : d.Comment.Submission.UserName;
                    m.Comment.Submission.IsDeleted    = d.Comment.Submission.IsDeleted;

                    return(m);
                });

                var mapped = results.Select(mapToDomain).ToList();

                return(mapped);
            }
        }
        public async Task TestCommentNotification(string sub, string user1, string user2)
        {
            var id = Guid.NewGuid().ToString();

            //Post submission as TestUser1
            var user = TestHelper.SetPrincipal(user1);
            var cmd  = new CreateSubmissionCommand(new Domain.Models.UserSubmission()
            {
                Subverse = sub, Title = "Let's be creative!", Content = "No"
            }).SetUserContext(user);
            var response = await cmd.Execute();

            VoatAssert.IsValid(response);

            var submission = response.Response;

            Assert.IsNotNull(submission, "Expected a non-null submission response");

            //Reply to comment as TestUser2
            user = TestHelper.SetPrincipal(user2);
            var commentCmd      = new CreateCommentCommand(submission.ID, null, "Important Comment").SetUserContext(user);
            var responseComment = await commentCmd.Execute();

            VoatAssert.IsValid(responseComment);

            var comment = responseComment.Response;

            Assert.IsNotNull(comment, "Expected a non-null comment response");


            //Check to see if Comment notification exists in messages
            using (var db = new VoatDataContext())
            {
                var record = (from x in db.Message
                              where
                              x.Recipient == user1 &&
                              x.Sender == user2 &&
                              x.IsAnonymized == submission.IsAnonymized &&
                              x.IsAnonymized == comment.IsAnonymized &&
                              x.CommentID == comment.ID &&
                              x.SubmissionID == submission.ID &&
                              x.Subverse == submission.Subverse &&
                              x.Type == (int)Domain.Models.MessageType.SubmissionReply
                              // && x.Direction == (int)Domain.Models.MessageDirection.InBound
                              select x).FirstOrDefault();
                Assert.IsNotNull(record, "Can not find message in database");
            }
        }
示例#30
0
        public async Task CreateComment_TestSubmissionCommentNotification()
        {
            var userName = "******";
            var user     = TestHelper.SetPrincipal(userName);
            var body     = Guid.NewGuid().ToString();
            var cmd      = new CreateCommentCommand(1, null, body).SetUserContext(user);
            var c        = await cmd.Execute();

            VoatAssert.IsValid(c);

            //check for comment reply entry
            using (var db = new VoatDataContext())
            {
                var notice = db.Message.FirstOrDefault(x => x.Sender == userName && x.Recipient == "anon" && x.SubmissionID == 1);
                Assert.IsNotNull(notice, "Did not find a reply notification");
            }
        }