Masering Django와 Django 공식문서을 보며 정리하는 글이다.
Unit testinga software testing precess where indiveidual units of a software application are tested to ensure they do what they are expected to do.
Unit testing is based on four fundamental concepts:
automated tests?The testing work is done for you by the system, without having to perform time consuming manual testing.
test-driven developmentwrite tests before write code.
python manage.py test <app name> looked for tests in the application.django.test.TestCase classa Python class that acts as a dummy web browser
It simulate GET and POST requests on a URL and observe the response.
Django a few extensions of a base class of unittest.TestCase.
TestCase.setUpTestData()클래스 레벨에서 테스트 데이터를 초기에 설정한다.
이미 unittest.setUp()이 비슷한 역할을 하지만, setUp()는 같은 클래스 안에 있는 test 메서드가 실행되기 전 매번 호출되는 반면, setUpTestData()는 단 한 번 호출되기 때문에 테스트 속도가 더 빠르다.
Every test case in a *TestCase instance has access to an instance of a Django test client. This client can be accessed as self.client. This client is recreated for each test, so you don't have to worry about state(such as cookies) carrying over from one test to another.
Instead of instantiating a Client in each test:
import unittest
from django.test import Clinet
class SimpleTest(unittest.TestCase):
def test_details(self):
client = Client()
response = client.get('/customer/details/')
self.assertEqual(response.stauts_code, 200)
... you can just refer to self.client, like so:
from django.test import TestCase
class SimpleTest(TestCase):
def test_details(self):
response = self.client.get('/customer/details/')
self.assertEqual(response.status_code, 200)
To make it easy to put test data into the database, Django's custom TransactionTestCase class provides a way of loding fixtures. A fixture is a collections of data that Django knows how to import into a database.
The most straigthforward way of creating a fixture is to use the manage.py dumpdata command. Once you've created a fixture and placed it in a fixtures directory in one of your INSTALLED_APPS, you can use it in your unit tests by sepcifying a fixtures class sttribute on your django.test.TestCase subclass.
Use the fuctions to temporarily alter the value of settings in tests.
Management commands can be tested with the call_command() function.
The unittest library provides the @skipIf and @skipUnless decorators to allow you to skip tests if you know ahead of time that tose tests are going to fail under certain conditions.
You can prevent the test databases from being destroyed by adding the --keepdb flag to the test command.