9 Django Test
When testing, prepare a new database for testing instead of using an existing database. After running all the tests, the database will be deleted. When running test in the shell, you can add the -keepdb parameter to leave the test database.
For example
models.py
from django.db import models
import django.utils.timezone as timezone
class File(models.Model):
username = models.CharField(max_length=200)
filename = models.CharField(max_length=200)
fileshortname = models.CharField(max_length=200)
filetype = models.CharField(max_length=200)
filedata = models.FileField(upload_to='files')
filepic = models.ImageField(null=True, upload_to='covers')
uploadtime = models.DateTimeField('updated time', default = timezone.now)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.filename
def setFileType(self):
if self.filename is None:
self.filetype = None
else:
e = self.filename.split('.')[-1]
self.filetype = e
tests.py
from django.test import TestCase
from models import File
class FileTestCase(TestCase):
def test_setfiletype_when_can_not_Splited(self):
testfileobj = File.objects.create(filename='testfile')
testfileobj.setFileType()
self.assertIsNone(testfileobj.fileshortname)
The Django TestCase class inherits from Python.unittest, so use assertEqual, assertTrue, assertIs, etc. to write your test code.
tests.py
from django.test import TestCase
from models import File, Tag
class FileTestCase(TestCase):
...
def test_no_file(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_upload_large_file(self):
#Prepare in advance
with open('testfile.dat') as fd
response = self.client.post('upload/', {'filedata':fd, 'fileshortname':'test', 'tags': 'test'})
self.assertEqual(response.status_code, 200)
You can use the client to check a simple view.
Recommended Posts