Skip to content

Instantly share code, notes, and snippets.

@henriquebastos
Last active March 24, 2020 19:30
Show Gist options
  • Save henriquebastos/1aba0cda78fbb48139c7e6bc96f79540 to your computer and use it in GitHub Desktop.
Save henriquebastos/1aba0cda78fbb48139c7e6bc96f79540 to your computer and use it in GitHub Desktop.
This is a simple proof of concept demonstrating how I like to handle files during tests.
"""
This is a simple proof of concept demonstrating how I like to handle files during tests.
Setup
-----
wget http://hbn.link/1NoLHf0
virtualenv .venv
source .venv/bin/activate
pip install django django-inmemorystorage
Usage
-----
python test_image_and_file_field.py
How it works
------------
The script will:
1. setup a single file django project with an in-memory database;
2. create the models Document and Animal;
3. make sure each model has a database table;
4. run our test case.
"""
from django.conf import settings
from django.db import models, connection, utils
from django.test import TestCase, override_settings
from django.core.files.uploadedfile import SimpleUploadedFile
# Configure Django if needed.
if not settings.configured:
from pathlib import Path
from django import setup
settings.configure(
DATABASES=dict(default=dict(ENGINE='django.db.backends.sqlite3', NAME=':memory:')),
ROOT_URLCONF=Path(__file__).stem,
SECRET_KEY='secret'
)
setup()
# Declare the model
class Document(models.Model):
blob = models.FileField()
__module__ = 'app.models' # hack to trick Django
class Meta:
app_label = 'app' # Compensate for the hack above.
class Animal(models.Model):
picture = models.ImageField()
__module__ = 'app.models' # hack to trick Django
class Meta:
app_label = 'app' # Compensate for the hack above.
# Make sure model has a table.
with connection.schema_editor() as schema_editor:
for model in (Document, Animal):
try:
schema_editor.create_model(model)
except utils.OperationalError:
pass # Ignore if table exists
# Declare tests...
# Tiniest Gif ever: 26 bytes
# source: http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever
TINY_GIF = b'GIF89a\x01\x00\x01\x00\x00\xff\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x00;'
@override_settings(DEFAULT_FILE_STORAGE='inmemorystorage.InMemoryStorage')
class TestFields(TestCase):
def test_image_field(self):
Animal.objects.create(picture=SimpleUploadedFile('tiny.gif', TINY_GIF))
self.assertTrue(Animal.objects.exists())
def test_file_field(self):
Document.objects.create(blob=SimpleUploadedFile('license.txt', 'GPL'.encode()))
self.assertTrue(Document.objects.exists())
if __name__ == '__main__':
# Run our test.
from django.test.runner import DiscoverRunner
DiscoverRunner().run_tests('', extras=[TestFields])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment