Browse Source

Fix post count includes deleted posts

Closes #380.

The test was faulty as well.
Peter Justin 7 years ago
parent
commit
85b6a7a04e
2 changed files with 15 additions and 8 deletions
  1. 8 4
      flaskbb/forum/models.py
  2. 7 4
      tests/unit/test_forum_models.py

+ 8 - 4
flaskbb/forum/models.py

@@ -246,10 +246,11 @@ class Post(HideableCRUDMixin, db.Model):
             self.topic.delete()
             return self
 
+        db.session.delete(self)
+
         self._deal_with_last_post()
         self._update_counts()
 
-        db.session.delete(self)
         db.session.commit()
         return self
 
@@ -312,7 +313,7 @@ class Post(HideableCRUDMixin, db.Model):
                     self.topic.forum.last_post_created = None
 
             # check if there is a second last post in this topic
-            if self.topic.second_last_post:
+            if self.topic.second_last_post is not None:
                 # Now the second last post will be the last post
                 self.topic.last_post_id = self.topic.second_last_post
 
@@ -426,8 +427,11 @@ class Topic(HideableCRUDMixin, db.Model):
     # Properties
     @property
     def second_last_post(self):
-        """Returns the second last post."""
-        return self.posts[-2].id
+        """Returns the second last post or None."""
+        try:
+            return self.posts[-2].id
+        except IndexError:
+            return None
 
     @property
     def slug(self):

+ 7 - 4
tests/unit/test_forum_models.py

@@ -500,10 +500,12 @@ def test_post_delete(topic):
     """
     post_middle = Post(content="Test Content Middle")
     post_middle.save(topic=topic, user=topic.user)
+    assert topic.post_count == 2  # post_middle + first_post
 
     post_last = Post(content="Test Content Last")
     post_last.save(topic=topic, user=topic.user)
 
+    # first post + post_middle + post_last
     assert topic.post_count == 3
     assert topic.forum.post_count == 3
     assert topic.user.post_count == 3
@@ -513,13 +515,14 @@ def test_post_delete(topic):
     # Check the last posts
     assert topic.last_post == post_last
     assert topic.forum.last_post == post_last
+    assert topic.post_count == 2
 
     post_last.delete()
 
-    # That was a bit trickier..
-    assert topic.post_count == 2
-    assert topic.forum.post_count == 2
-    assert topic.user.post_count == 2
+    # only the first_post remains
+    assert topic.post_count == 1
+    assert topic.forum.post_count == 1
+    assert topic.user.post_count == 1
     assert topic.first_post_id == topic.last_post_id
 
     assert topic.forum.last_post_id == topic.last_post_id