[Fixed]-Testing Django Models with FileField

6👍

This is a partial answer to my question, and to help anyone else who found this question from a search.

Django includes a facility it refers to as ‘fixtures’ to handle the primary loading of data during testing. Creating a fixture is a 2 step process:

  1. Add some fake data to the app’s model using the admin tool
  2. Run the following: manage.py dumpdata [appname] –indent=2 > filename.json

The fixture file *.json remains in your Django project root folder.

In your tests.py file, you can load the fixture on the Django TestCase class as so:

class YourTestCase(TestCase):    
    fixtures = ['filename.json','whatever.json',]

Once the fixture is loaded, you can use the data as you would normally use the ORM. Here’s my working test case from the above code if you’d like an example.

from django.test import TestCase

from django.contrib.auth.models import User
from mediamanager.models import Media

class MediaManagerTestCase(TestCase):

    fixtures = ['auth_data.json','mediamanager_data.json',]

    def setUp(self):
        self.fakeuser = User.objects.get(username='fakeuser')
        self.fakestaff = User.objects.get(username='fakestaff')
        self.fakeadmin = User.objects.get(username='fakeadmin')

    def test_media_can_edit(self):
        um = Media.objects.get(pk=1)    # Media owned by fakeuser
        sm = Media.objects.get(pk=2)    # Media owned by fakstaff

        self.assertEquals(um.can_edit(self.fakeuser), True)
        self.assertEquals(sm.can_edit(self.fakeuser), False)

        self.assertEquals(um.can_edit(self.fakestaff), True)
        self.assertEquals(sm.can_edit(self.fakestaff), True)

        self.assertEquals(um.can_edit(self.fakeadmin), True)
        self.assertEquals(sm.can_edit(self.fakeadmin), True)

20👍

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.

0👍

You should initialize your files after fixtures creation:

def setUp(self):
    files = UpFile.objects.all()
    for file in files:
        filepath = os.path.join(settings.MEDIA_ROOT, file.upfile.name)
        open(filepath, 'w').close()

Leave a comment