From 5384af68467cabf5a099c582e62356cd2f716925 Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Thu, 3 Dec 2020 22:04:45 +0100 Subject: [PATCH] Add some models tests --- articles/models.py | 2 ++ articles/tests/test_models.py | 41 +++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 articles/tests/test_models.py diff --git a/articles/models.py b/articles/models.py index 18e1f3f..5a7e5ab 100644 --- a/articles/models.py +++ b/articles/models.py @@ -110,11 +110,13 @@ class Article(AdminUrlMixin, models.Model): self.published_at = timezone.now() self.status = self.PUBLISHED self.save() + return self def unpublish(self): self.published_at = None self.status = self.DRAFT self.save() + return self def save(self, *args, **kwargs): if not self.slug: diff --git a/articles/tests/test_models.py b/articles/tests/test_models.py new file mode 100644 index 0000000..7a80f96 --- /dev/null +++ b/articles/tests/test_models.py @@ -0,0 +1,41 @@ +import pytest + +from articles.models import Article, User + + +@pytest.mark.django_db +def test_publish_article(unpublished_article: Article): + assert unpublished_article.status == Article.DRAFT + assert unpublished_article.published_at is None + published_article = unpublished_article.publish() + assert published_article.status == Article.PUBLISHED + assert published_article.published_at is not None + + +@pytest.mark.django_db +def test_unpublish_article(published_article: Article): + assert published_article.status == Article.PUBLISHED + assert published_article.published_at is not None + unpublished_article = published_article.unpublish() + assert unpublished_article.status == Article.DRAFT + assert unpublished_article.published_at is None + + +@pytest.mark.django_db +def test_save_article_adds_missing_slug(author: User): + # Explicitly calling bulk_create with one article because it doesn't call save(). + articles = Article.objects.bulk_create( + [Article(author=author, title="noice title", slug="", status=Article.DRAFT)] + ) + article = articles[0] + assert article.slug == "" + article.save() + assert article.slug != "" + + +@pytest.mark.django_db +def test_save_article_doesnt_change_existing_slug(published_article: Article): + original_slug = published_article.slug + published_article.title = "This is a brand new title" + published_article.save() + assert published_article.slug == original_slug