kaucap
kaucap

Reputation: 77

How to test uploadfile in django

I have an uploadform and I want to test it. But there is a problem.

def test_if_can_upload_file(self):
    with open('app_blog/tests/test.txt') as file:
        self.client.post(reverse('csv_blog'), {'attachment': file})
        test_file = file.read()
        self.assertEqual(test_file, 'test file')

When I test it, there is an error:

self.assertEqual(test_file, 'test file')
AssertionError: '' != 'test file'
+ test file

Why is my file shown like it is empty? Actually it is not empty.Or maybe I test my form in a wrong way?

form

class UploadBlogForm(forms.ModelForm):
    file = forms.FileField()

    class Meta:
        model = Blog
        fields = 'file',

view

def upload_blog(request):
    if request.method == "POST":
        upload_file_form = UploadBlogForm(request.POST, request.FILES)
        if upload_file_form.is_valid():
            blog_file = upload_file_form.cleaned_data['file'].read()
            blog_str = blog_file.decode('utf-8').split('\n')
            csv_reader = reader(blog_str, delimiter=":::", quotechar='"')

Upvotes: 1

Views: 122

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

Your self.client.post(…) will already exhaust the file handler and read the entire content of the file, this thus means that when you call file.read(), the cursor already moved to the end of the file, and thus returns an empty string.

You should reopen the file and read the file from the beginning, so:

def test_if_can_upload_file(self):
    with open('app_blog/tests/test.txt') as file:
        self.client.post(reverse('csv_blog'), {'attachment': file})
    with open('app_blog/tests/test.txt') as file:
        test_file = file.read()
        self.assertEqual(test_file, 'test file')

Upvotes: 1

Related Questions