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='"')
CodePudding user response:
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')
