Search code examples
djangodjango-testingdjango-testsdjango-file-upload

Error when testing the view with a file upload


I would like to test a file upload from my view with the following function:

def test_post(self):
    with open("path/to/myfile/test_file.txt") as file:
        post_data = {
            'description': "Some important file",
            'file': file,
        }
        response = self.client.post(self.test_url, post_data)
        self.assertEqual(response.status_code, 302)

        document = Document.objects.first()
        self.assertEqual(document.description, "My File")
        self.assertEqual(document.filename, 'test_file.txt')

When I test the file upload on the actual website, it works. But when I run this test, I get the following error:

django.core.exceptions.SuspiciousFileOperation: Storage can not find an available filename for "WHJpMYuGGCMdSKFruieo/Documents/eWEjGvEojETTghSVCijsaCINZVxTvzpXNRBvmpjOrYvKAKCjYu/test_file_KTEMuQa.txt". Please make sure that the corresponding file field allows sufficient "max_length".

Here is my form save method:

def save(self, commit=True):
    instance = super(DocumentForm, self).save(commit=False)
    instance.filename = self.cleaned_data['file'].name
    if commit:
        instance.save()  # error occurs here
    return instance

Seeing as it works on the actual website, I suspect it has something to do with the way I setup the file in the test; probably something small.


Solution

  • For the sake of brevity, I had removed irrelevant model fields from my original question. But when Ahtisham requested to see the upload_to attribute (which had a custom function), I removed those irrelevant fields and it worked!

    So this is my original code (which didn't work) with the irrelevant fields:

    def documents_path(instance, filename):
        grant = instance.grant  
        client = grant.client
        return '{0}/Grant Documents/{1}/{2}'.format(client.folder_name, grant.name, filename)
    
    ....
    
    file = models.FileField(upload_to=documents_path)
    

    But this works:

    def documents_path(instance, filename):
       return 'Documents/{0}'.format(filename)
    

    The reason why it worked on the actual website is because it wasn't using long characters from the test fixtures. Seems like those fields that I thought were irrelevant for the question were actually quite important!

    TL;DR I decreased the length of the custom document path.