Django 自动化测试

django 自动化测试的简单例子:下面是在学习django 自动化测试时自己写的两个小的测试例子,很初级,但能帮助理解写测试的思路,写下来帮助记忆。

from django.test import TestCase, Client
from django.utils import timezone
from django.urls import reverse
from blog.models import Article, Category

class ArticleViewTest(TestCase):
    # test if the read time increased 1 after open the html
    def test_increase_read(self):
        article = Article(
            title='test',
            content='test',
            status='p',
        )
        article.save()
        self.assertIs(article.read, 0)

        url = reverse('blog:blog-detail', args=(article.id,))
        response = self.client.get(url)
        read_article = Article.objects.get(id=article.id)
        self.assertIs(read_article.read, 1)

    def test_was_published(self):
        '''
        if status was published that means the publish date was late than now
        :return:
        '''

        client = Client()
        url = reverse('blog:blog-home')
        response = client.get(url)
        response = client.get(reverse('blog:blog-home'))
        cur_page_items = response.context['cur_page_objects']
        cur_time = timezone.now()
        for article in cur_page_items:
            self.assertIs(article.created_time<cur_time, True)

第一个函数:test_increase_read,先创建一个新的文章实例,然后通过client去访问该文章的详情页面,并查看该文章的阅读次数是否增加一次。

第二个函数: test_was_published,属于针对视图的测试,针对视图的测试不会创建新的临时数据库,而是使用已经存在的数据库,但不会对其进行修改。

    其原理是通过client请求某个视图函数对应的页面,并对请求的结果进行验证。例如上面的例子中,既然是通过视图函数请求的页面,那说明文章必须是已经发表的,而发表的文章则说明‘在过去’创建的,所以发表时间应该早于now.

当需要测试时,测试用例越多越好。

上一篇:bootstrap dropdown menu

下一篇:django 日志