I'm trying to make the transition to testing with Django. This is the particular model in question for testing:
class Media(models.Model):
file = models.FileField(upload_to='upload',)
thumbnail = models.ImageField(upload_to='upload', blank=True,)
# ...
PART 1: How do I deal with these FileFields? (Particularly in the sense that I need to generate fake entries to test bits of code)
PART 2: Below is the testing code I've begun to write. Am I doing this correctly or should I be using a form of "mocking"?
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
from mediamanager.models import Media
class MediaManagerTestCase(TestCase):
def setUp(self):
self.fake_user = User.objects.create(username='fakeuser', is_staff=false)
self.fake_staff = User.objects.create(username='fakestaff', is_staff=true)
self.fake_admin = User.objects.create(username='fakeadmin', is_superuser=true)
self.fake_media_image = Media.objects.create() # Hmmm...
self.fake_media_video = Media.objects.create() # How do i do this...
def testMediaCanEdit(self):
perm = self.fake_media_image.can_edit(self.fake_user)
self.assertEquals(perm, false)
If the code in question is built into Django, don't test it. Examples like the fields on a Model or testing how the built-in template. Node renders included tags. If your model has custom methods, you should test that, usually with unit tests.
The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.
Automated Testing is a widely used tool that uses a collection of predefined test cases. Learn how Django and Selenium to ensure a bug free system. Table of contents.
Hi i just had the same problem, after some googling i ended up with:
from django.test import TestCase
from django.core.files import File as DjangoFile
from home.models import Tab, File
class FileModelTest(TestCase):
def setUp(self):
self.tab = Tab.objects.create(
title="Title",
html="<p>test</p>",
published=True
)
self.file = File.objects.create(
tab=self.tab,
file=DjangoFile(open("home/tests/models.py"), "test_file.css")
)
def tearDown(self):
self.file.delete()
self.tab.delete()
Hope this helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With