Reputation: 321
I'm creating a django project that will accept user content, and during development I'm trying to create a test case that will test that the model uploads normally.
I have a file structure like so:
Site
|----temp
| |----django-test
|----app
|----test_image.jpg
|----test_manual.pdf
|----tests.py
My test case code is such:
from django.test import TestCase, override_settings
from django.core.files import File
import sys
import os
from .models import Manual
# Create your tests here.
class ManualModelTests(TestCase):
@override_settings(MEDIA_ROOT='/tmp/django_test')
def test_normal_manual_upload(self):
in_image = open(os.path.join('manuals','test_image.jpg'), 'r+b')
in_pdf = open(os.path.join('manuals','test_manual.pdf'), 'r+b')
thumbnail = File(in_image)
in_manual = File(in_pdf)
new_manual = Manual.objects.create(
photo=thumbnail,
manual=in_manual,
make='yoshimura',
model='001',
year_min=2007,
year_max=2010
)
#uploaded_image = open(os.path.join('temp','django_test','images','test_image.jpg'), 'r+b')
#uploaded_pdf = open(os.path.join('temp','django_test','manuals','test_manual.pdf'), 'r+b') #self.assertIs(open(), in_image)
#self.assertIs(uploaded_img, in_image)
#self.assertIs(uploaded_pdf, in_pdf)
Here is the model code:
class Manual(models.Model):
photo = models.ImageField(upload_to="photos")
make = models.CharField(max_length=50)
model = models.CharField(max_length=100)
manual = models.FileField(upload_to="manuals")
year_min = models.PositiveIntegerField(default=0)
year_max = models.PositiveIntegerField(default=0)
For some reason I'm getting a FileNotFound upon opening 'test_image.jpg'). My questions are
Upvotes: 0
Views: 663
Reputation: 23024
You're getting a FileNotFoundError
because open
will try and locate the files relative to the current working directory, which is probably Site
.
It may be better to open the files using a path relative to the test module itself, using __file__
, as that wouldn't depend on the current working directory. For example:
open(os.path.join(os.path.dirname(__file__), 'test_image.jpg'), 'r+b')
For the assertions, it may be easiest just to test for the existence of the uploaded files. If they exist, then the upload must have worked. For example:
self.assertTrue(os.path.exists('/tmp/django_test/test_image.jpg'))
You should also add a tearDown()
method to your test to remove the uploaded files once the test finishes.
def tearDown(self):
try:
os.remove('/tmp/django_test/test_image.jpg')
except FileNotFoundError:
pass
Upvotes: 1