2017-04-21 53 views
0

對於我在Django中製作的項目,我有一個頁面,其中包含允許用戶上傳zip文件的表單。 然後從這個zip文件,我打開它並從那裏讀取一個文件。 我開始與單元測試,以驗證所有情況:
- 不是一個.zip擴展
- zipfile.is_zipfile()返回false
- 找不到我想讀裏面
文件 - 文件中是無效的Django單元上傳zip文件

對於我的單元測試,我爲每個錯誤不同的文件,並將其上傳使用django.test.Client像這樣:

with open_file('wrong_format.zip') as file: 
      response = self.client.post(url, {'archive': file}) 
      self.assertEqual(response.status_code, 200) 
      self.assertContains(response, '<li>Only zip archived are allowed</li>') 

,但我得到了以下錯誤:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x99 in position 10: invalid start byte

當我從瀏覽器執行它時,它工作正常。

這裏的堆棧:

Traceback (most recent call last): 
    File "/app/plugins/tests/uploads.py", line 33, in test_bad_archive 
    response = self.client.post(url, {'archive': file}) 
    File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 548, in post 
    secure=secure, **extra) 
    File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 347, in post 
    post_data = self._encode_data(data, content_type) 
    File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 311, in _encode_data 
    return encode_multipart(BOUNDARY, data) 
    File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 201, in encode_multipart 
    lines.extend(encode_file(boundary, key, value)) 
    File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 254, in encode_file 
    to_bytes(file.read()) 
    File "/usr/local/lib/python3.6/codecs.py", line 321, in decode 
    (result, consumed) = self._buffer_decode(data, self.errors, final) 
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x99 in position 10: invalid start byte 
+0

你能發佈堆棧跟蹤嗎?這將有助於查看哪些功能內部存在此問題。 – Anonymous

+0

是的,我只是編輯它 –

+0

什麼是'open_file()'?爲什麼不定期的'open()'?另外我認爲問題在於你不是以二進制模式打開文件('open('file.zip','rb')')。 – Anonymous

回答

0

打開該文件,而不二進制標誌b是在Python 2,其中二進制和字符串是相同的數據類型確定,但是Python 3是更加嚴格了。所以如果你做open(file, 'rb')系統不會嘗試解釋壓縮文件爲文本。