lundi 30 mai 2016

Django testing file field with upload_to function

I have a Django model that uses a file field and I am using an upload_to function during its instantiation to prevent name conflicts in the storage directory.

Eg:

# defined in app.models
class ABC(models.Model):
   image = models.ImageField(upload_to=UploadToPathAndRename('images'))

# defined in app.utils
@deconstructible
class UploadToPathAndRename(object):

    def __init__(self, path):
        self.sub_path = path

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]
        # get filename
        if instance.pk:
            filename = '{}.{}'.format(instance.pk, ext)
        else:
            # set filename as random string
            filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(self.sub_path, filename)

I was testing the function as follows

def test_ABC(self, mock_utils):
    with open('app/tests/testimage.png') as image:
        response = self.client.post(reverse('url'),
                            {'id': id, 'image': image})
        self.assertRedirects(response, "expected_url")

But this creates a copy of the image in the images directory. I can't pass a SimpleUploadedFile as Pillow throws an error saying the uploaded image is invalid.

Can someone please show me how to mock the UploadToPathAndRename class so that it becomes easier to test the above code. Thanks.

Aucun commentaire:

Enregistrer un commentaire