What is the clean way to unittest FileField in django?

前端 未结 5 1846
感动是毒
感动是毒 2021-01-30 08:09

I have a model with a FileField. I want to unittest it. django test framework has great ways to manage database and emails. Is there something similar for FileFields?

Ho

5条回答
  •  清歌不尽
    2021-01-30 09:03

    Django provides a great way to do this - use a SimpleUploadedFile or a TemporaryUploadedFile. SimpleUploadedFile is generally the simpler option if all you need to store is some sentinel data:

    from django.core.files.uploadedfile import SimpleUploadedFile
    
    my_model.file_field = SimpleUploadedFile(
        "best_file_eva.txt",
        b"these are the file contents!"   # note the b in front of the string [bytes]
    )
    

    It's one of django's magical features-that-don't-show-up-in-the-docs :). However it is referred to here and implemented here.

    Limitations

    Note that you can only put bytes in a SimpleUploadedFile since it's implemented using BytesIO behind the scenes. If you need more realistic, file-like behavior you can use TemporaryUploadedFile.

    For Python 2

    If you're stuck on python 2, skip the b prefix in the content:

    my_model.file_field = SimpleUploadedFile(
        "best_file_eva.txt",
        "these are the file contents!" # no b
    )
    

提交回复
热议问题