Testing Django Management Commands with PyTest
,The other day I wanted to test some Django management commands for django-cast and found this excellent post by Adam Johnson:
How to Unit Test a Django Management Command
But I use pytest to write my Django tests, so how would this be different?
A Management Command to Back up Media Files
Ok, so I wrote this little command that creates a backup of all media files. Django 4.2 introduced a new STORAGES setting, so it's now possible to write a backup command that works without having to know exactly how the media files are stored. It only assumes there are entries for production
and backup
storage backends and they are configured correctly. So it doesn't matter if your files are stored on S3 and the backup should be written to the local filesystem, or vice versa. The media_backup
command does not need to know any of this.
from django.core.management.base import BaseCommand
from ...utils import storage_walk_paths
from .storage_backend import get_production_and_backup_storage
class Command(BaseCommand):
help = (
"backup media files from production to backup storage "
"(requires Django >= 4.2 and production and backup storage configured)"
)
@staticmethod
def backup_media_files(production_storage, backup_storage):
for num, path in enumerate(storage_walk_paths(production_storage)):
if not backup_storage.exists(path):
with production_storage.open(path, "rb") as in_f:
backup_storage.save(path, in_f)
if num % 100 == 0: # pragma: no cover
print(".", end="", flush=True)
def handle(self, *args, **options):
self.backup_media_files(*get_production_and_backup_storage())
Read on: TIL: Testing Django Management Commands with PyTest