在单元测试方面,Django继承python的unittest.TestCase实现了自己的django.test.TestCase,编写测试用例通常从这里开始。测试代码通常位于app的tests.py文件中

##为何要在django中使用test

  • When you’re writing new code, you can use tests to validate your code works as expected.

  • When you’re refactoring or modifying old code, you can use tests to ensure your changes haven’t affected your application’s behavior unexpectedly.

  • With Django’s test-execution framework and assorted utilities, you can simulate requests, insert test data, inspect your application’s output and generally verify your code is doing what it should be doing.

##Writing and running tests

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
:::text
from django.test import TestCase
from myapp.models import Animal

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

    def test_animals_can_speak(self):
        """函数必须以text_xx命名方式"""
        lion = Animal.objects.get(name="lion")
        cat = Animal.objects.get(name="cat")
        self.assertEqual(lion.speak(), 'The lion says "roar"')
        self.assertEqual(cat.speak(), 'The cat says "meow"')

你可以有几种方式运行单元测试:

  • python manage.py test:执行所有的测试用例
  • python manage.py test app_name, 执行该app的所有测试用例
  • python manage.py test app_name.case_name: 执行指定的测试用例

##Testing tools:Overview and a quick example

1
2
3
4
5
6
7
8
9
:::text
>>> from django.test.client import Client
>>> c = Client()
>>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
>>> response.status_code
200
>>> response = c.get('/customer/details/')
>>> response.content
'<!DOCTYPE html...'

##The request factory

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
:::text
from django.contrib.auth.models import User
from django.test import TestCase, RequestFactory

class SimpleTest(TestCase):
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.user = User.objects.create_user(
            username='jacob', email='jacob@…', password='top_secret')

    def test_details(self):
        # Create an instance of a GET request.
        request = self.factory.get('/customer/details')

        # Recall that middleware are not supported. You can simulate a
        # logged-in user by setting request.user manually.
        request.user = self.user

        # Test my_view() as if it were deployed at /customer/details
        response = my_view(request)
        self.assertEqual(response.status_code, 200)

##unit test file upload in django

1
2
3
4
:::text
c = Client()
with open('wishlist.doc') as fp:
  c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})

##参考资料