Django之第一个app<19>

本文介绍了自动化测试的基本概念及其重要性,并通过实例演示了如何在Django项目中编写和运行自动化测试,包括测试用例的设计和视图测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本节内容概括:

  • 介绍”自动化测试”
  • 基本的测试策略
  • 编写第一个测试
  • 测试一个视图

介绍”自动化测试”

自动化测试是系统为你所做的。你只需创建一系列测试一次,以后你的应用改动的时候,不必再花时间来手动测试,你仍然可以检查你的代码是否可以像你当初期待的那样工作。

基本的测试策略

一些编程人员遵循"测试驱动式开发",他们在写代码之前就写测试了,这可能与你想的不一样,但是实际上这样对一种人非常熟悉:他们描述一个问题,然后创建一些代码来解决它。

编写第一个测试

放应用测试的地方一般是应用的test.py文件。测试系统将会自动发现文件名以test开头的文件中的测试。

将下面的代码放到polls应用中的tests.py文件中:

from django.test import TestCase
import datetime
from django.utils import timezone
from .model import Question
# Create your tests here.

class QuestionMethodTests(TestCase):
    def test_was_published_recently_with_future_question(self):
        time=timezone.now()+datetime.timedelta(days=30)
        future_question=Question(pub_date=time)
        self.assertEqual(future_question.was_published_recently(),False)

这里我们创建了一个django.test.TestCase的子类,里面有一个方法,创建了一个拥有未来pub_dateQuestion实例。然后我们检查was_published_recently()的输出时,应当是False

在终端,运行我们的测试:

$ python manage.py test polls

结果为:

charies:mysite weichuang$ python manage.py test polls
Creating test database for alias 'default'...
F
======================================================================
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionMethodTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/weichuang/Desktop/mysite/polls/tests.py", line 11, in test_was_published_recently_with_future_question
    self.assertEqual(future_question.was_published_recently(),False)
AssertionError: True != False

----------------------------------------------------------------------
Ran 1 test in 0.001s

测试一个视图

Django提供了一个测试Client来模拟一个用户在以视图的级别与代码交互,我们可以在test.py或者shell中使用它。

我们再次开启shell,这里我们需要做一些事情,而在test.py是不用的。首先在shell中设置测试环境:

>>> from django.test.utils import setup_test_enviroment
>>> setup_test_environment()

接下来,我们需要导入测试客户端类:

>>>from django.test import Client
>>>client=Client()

准备好后,我们可以叫客户端为我们做一些事情了:

>>> # get a response from '/'
>>> response = client.get('/')
>>> # we should expect a 404 from that address
>>> response.status_code
404
>>> # on the other hand we should expect to find something at '/polls/'
>>> # we'll use 'reverse()' rather than a hardcoded URL
>>> from django.core.urlresolvers import reverse
>>> response = client.get(reverse('polls:index'))
>>> response.status_code
200
>>> response.content
'\n\n\n    <p>No polls are available.</p>\n\n'
>>> # note - you might get unexpected results if your ``TIME_ZONE``
>>> # in ``settings.py`` is not correct. If you need to change it,
>>> # you will also need to restart your shell session
>>> from polls.models import Question
>>> from django.utils import timezone
>>> # create a Question and save it
>>> q = Question(question_text="Who is your favorite Beatle?", pub_date=timezone.now())
>>> q.save()
>>> # check the response once again
>>> response = client.get('/polls/')
>>> response.content
'\n\n\n    <ul>\n    \n        <li><a href="/polls/1/">Who is your favorite Beatle?</a></li>\n    \n    </ul>\n\n'
>>> # If the following doesn't work, you probably omitted the call to
>>> # setup_test_environment() described above
>>> response.context['latest_question_list']
[<Question: Who is your favorite Beatle?>]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值