现在的位置: 首页 > 综合 > 正文

django单元测试编写

2013年10月16日 ⁄ 综合 ⁄ 共 2359字 ⁄ 字号 评论关闭

1.获取测试数据:

.manage.py dumpdata --indent 4  app名 >存储文件.json

2.编写测试用例

  1)对于一个django应用app,系统会自动从两个地方寻找测试用例:
      1.models.py文件,寻找其中的unittest.TestCase子类。
      2.寻找app根目录下的tests.py文件中的unittest.TestCase子类
  注意:如果使用app根目录下的tests.py文件编写测试的话,我们需要models.py文件,就算是空的也需要。

      3.测试示例:

from django.utils import unittest
from myapp.models import Animal

class AnimalTestCase(unittest.TestCase):
    def setUp(self):
        self.lion = Animal(name="lion", sound="roar")
        self.cat = Animal(name="cat", sound="meow")

    def test_animals_can_speak(self):
        """Animals that can speak are correctly identified"""
        self.assertEqual(self.lion.speak(), 'The lion says "roar"')
        self.assertEqual(self.cat.speak(), 'The cat says "meow"')

3.运行测试:

./manage.py test 或者 ./manage.py test animals(app名)

   1)测试时使用的是测试数据库,不会影响到真实数据,大家可以放心使用。我们还可以使用fixture来进行测试数据的初试化操作。

4.django提供的测试工具

  1)test client
      可以用来模仿浏览器的请求和相应,示例:

>>> from django.test.client import Client
>>> c = Client()
>>> response = c.post('/login/', {'username': 'john', 'password': 'smith'}) #不要使用带domain的url
>>> response.status_code
200
>>> response = c.get('/customer/details/')
>>> response.content
'<!DOCTYPE html...'

   2)使用LiveServerTestCase和selenium模拟真实情况下的交互操作。

from django.test import LiveServerTestCase
from selenium.webdriver.firefox.webdriver import WebDriver

class MySeleniumTests(LiveServerTestCase):
    fixtures = ['user-data.json']

    @classmethod
    def setUpClass(cls):
        cls.selenium = WebDriver()
        super(MySeleniumTests, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        cls.selenium.quit()
        super(MySeleniumTests, cls).tearDownClass()

    def test_login(self):
        self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
        username_input = self.selenium.find_element_by_name("username")
        username_input.send_keys('myuser')
        password_input = self.selenium.find_element_by_name("password")
        password_input.send_keys('secret')
        self.selenium.find_element_by_xpath('//input[@value="Log in"]').click()

    3)django测试示例:

 

from django.test.client import Client
from django.test import TestCase
from django.contrib.auth.models import User
from models import *

class agentTest(TestCase):
    fixtures = ['agent.json', 'agent']
    def setUp(self):
        user = User.objects.create_user('root','xxx@qq.com','root')
        user.save()

    def test_agentList(self):
        response = self.client.login(username='root',password='root')
        response = self.client.get('/agent/index/')
        self.assertEqual(response.status_code,200)
 

注意:

 1)fixtures可以一次载入全部的model:

fixtures = ['testdata.json']

 2)备份数据的时候使用如下格式备份所有的app

manage.py dumpdata --indent 4 app1 app2 app3 app4>testdata.json

ok!

抱歉!评论已关闭.