首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

django单元测试编纂

2013-04-09 
django单元测试编写1.获取测试数据:.manage.py dumpdata --indent 4app名 存储文件.json2.编写测试用例1)

django单元测试编写

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 unittestfrom myapp.models import Animalclass 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_code200>>> response = c.get('/customer/details/')>>> response.content'<!DOCTYPE html...'

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

from django.test import LiveServerTestCasefrom selenium.webdriver.firefox.webdriver import WebDriverclass 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 Clientfrom django.test import TestCasefrom django.contrib.auth.models import Userfrom 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) 


ok!

热点排行