vendredi 12 février 2021

How can I use a singe test file django

For testing, I am currently using TemporaryUploadedFile for the file field on one of my models. The issue is each time I run a test, there is a new file created. Is there a way that I can point the file field to a pre existing file named something like txt.txt stored in a pre-defined directory?

In the test I define the file as :

self.example_file.file = TemporaryUploadedFile(
            "temp.txt",
            size="100kb",
            content_type="txt",
            charset=b"This is the content of the file!"
        )

In the mdoel the file is created using models.FileField:

example_file = models.FileField(
        blank=True,
        null=True,
        upload_to=UploadToPath('files'),
    )

What I would like to be able to do is in the test is simply point to a one off pre existing file. I can not figure out how to do it.

If this can not be done and anyone knows of a better alternative where I do not need to upload a new file each time I use the file field in testing it would be great to know how to do that as well!

Aucun commentaire:

Enregistrer un commentaire