There is some way to mock storage.
After reading django source code, the below is my implementation to avoid uploading file to s3 regardless of using default storage or assigning the storage in filefield or imagefield.
from unittest.mock import patch
from django.db.models.fields.files import FileField, FieldFile, ImageField, ImageFieldFile
from django.core.files.storage import FileSystemStorage
from rest_framework.test import APITestCase
class CustomFileSystemStorage(FileSystemStorage):
def url(self, *args, **kwargs):
return self.path(*args, **kwargs)
class CustomFieldFile(FieldFile):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.storage = CustomFileSystemStorage()
class CustomImageFieldFile(ImageFieldFile):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.storage = CustomFileSystemStorage()
class PatchMeta(type):
"""A metaclass to patch all inherited classes."""
def __new__(meta, name, bases, attrs):
cls = type.__new__(meta, name, bases, attrs)
cls = patch.object(ImageField, 'attr_class', CustomImageFieldFile)(cls)
cls = patch.object(FileField, 'attr_class', CustomFieldFile)(cls)
return cls
class CustomBaseTestCase(APITestCase, metaclass=PatchMeta):
"""You can inherit this class to do any testcase for mocking storage"""
pass
With inheriting CustomBaseTestCase class, you can change your storage to avoid uploading files to any server