I'm writing my first test as a Django developer. How do I write a test for the image property of this model shown below
class Project(models.Model):
engineer = models.ForeignKey(Engineer, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
tech_used = models.CharField(max_length=200)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
image = models.ImageField(default="project.png")
description = models.TextField(null=True, blank=True)
repo_url = models.URLField(null=True, blank=True)
live_url = models.URLField(null=True, blank=True)
make_public = models.BooleanField(default=False)
def __str__(self):
return self.name
@property
def image_url(self):
try:
url = self.image.url
except:
url = ""
return url
class Meta:
ordering = ["-created"]
I have tried to conjure some patches from here and there although I don't fully understand what my test.py code I just thought to include it to my question to show my efforts
class TestModels(TestCase):
def setUp(self):
new_image = BytesIO()
self.image = Project.objects.create(
image=ImageFile(new_image)
)
def test_image_url(self):
self.assertEquals(self.image.image_url, '')
Please a help on the above question and an explanation of whatever code given as help will be highly appreciated.
Following this answer , one possible way is:
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.utils import timezone
from .models import Engineer, Project
class ProjectImageUploadTest(TestCase):
def setUp(self):
self.engineer = Engineer.objects.create(name='Engineer')
self.project = {
'engineer': self.engineer,
'name': 'Test project',
'tech_used': 'Test tech',
'updated': timezone.now(),
'created': timezone.now(),
'image': None,
'description': 'Test description',
'repo_url': 'https://www.repo.example.com',
'live_url': 'https://www.live.example.com',
'make_public': False
}
self.obj = Project.objects.create(**self.project)
def tearDown(self):
self.obj.image.delete()
def test_upload_image(self):
img_url = r'X:\Path\to\your\image.png'
self.obj.image= SimpleUploadedFile(
name='test_image.jpg',
content=open(img_url, 'rb').read(),
content_type='image/png')
self.obj.save()
self.obj.refresh_from_db()
self.assertNotEqual(self.obj.image, None)
I would like to complement saying that is also possible to implement the test using Python's tempfile .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.