Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

How do I mock an uploaded file in django?

from django.core.files.uploadedfile import SimpleUploadedFile

# To mock a simple raw text file
mock_profile_image = SimpleUploadedFile('simple_file.txt', 'raw-text', content_type='text')

# To mock an image

# Just invoke this function and you'll get a png file
def get_mock_img(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)):
    file_obj = StringIO()
    image = Image.new("RGB", size=size, color=color)
    image.save(file_obj, ext)
    file_obj.seek(0)
    return File(file_obj, name=name)

mock_profile_image = SimpleUploadedFile('profile_img.png', get_mock_img(), content_type='image/png')

# or
with open(img_path, 'rb') as img_file:
	mock_profile_image = SimpleUploadedFile('profile_img.png', img_file.read(), content_type='image/png')
 
PREVIOUS NEXT
Tagged: #How #I #mock #uploaded #file
ADD COMMENT
Topic
Name
3+2 =