2012-04-24 132 views
5

我想測試一個自寫的FormField AudioFileFormField,它在存儲之前檢查一個文件是否是audiofile文件。爲此我覆蓋了to_python方法。試圖測試這個FormField我遇到了一些困難。模擬提交測試表單的正確方法是什麼?

這是迄今爲止我的測試用例:

from django import forms 
from django.core.files.uploadedfile import SimpleUploadedFile 
from django.test import TestCase 

class TestAudioFileFormField(TestCase): 
    """ test the formfield to use for AudioFile Uploads """ 

    class TestForm(forms.Form): 
     audiofilefield = AudioFileFormField() 


    def setUp(self): 

     self.AUDIOFILE_TEST_ROOT = os.path.dirname(__file__) + '/data/' 
     self.files = audiofile_files 


    def test_to_python(self): 
     """ assign some files to a form and validate the form """ 

     f = file(self.AUDIOFILE_TEST_ROOT + self.files[0]) 
     file_data = {'audiofilefield':SimpleUploadedFile(self.files[0],f.read())} 
     data = {} 

     form = self.TestForm(data,f) 
     form.is_valid() 

線form.is_valid()會引發一個AttributeError:「文件」對象有沒有屬性「得到」

當我插入一個調試跟蹤權form.is_valid()之前,這是我所得到的在交互式會話:

ipdb> form.is_valid() 
AttributeError: 'file' object has no attribute 'get' 
ipdb> suf = file_data['audiofilefield'] 
ipdb> suf 
<SimpleUploadedFile: invalid_format.mp3 (text/plain)> 
ipdb> dir(suf) 
[lots of info here] 
ipdb> form.is_valid() 
True 

正好我有沒有在互動環節中改變什麼,這樣的形式驗證工作?將文件傳遞給SimpleUploadedFile以避免AttributeError的正確方法是什麼?

回答

7

好,有煥然一新的感覺可能是值得很多。這是我的新test_to_python測試,這一次它的工作原理:

def test_to_python(self): 
    f = file(self.AUDIOFILE_TEST_ROOT + self.files[0]) 
    file_data = {'audiofilefield':SimpleUploadedFile(self.files[0],f.read())} 
    data = {} 
    form = self.TestForm(data,file_data) 
    self.assertTrue(form.is_valid()) 
+2

難道你不覺得這會污染你的'upload /'目錄嗎? – 2016-10-23 10:22:55

5

替代解決方案(因爲這個問題是頂級的谷歌結果爲「Django的測試模擬上傳」):Django的內置測試客戶端接受打開文件對象作爲POST數據:

# the form 
class TestForm(forms.Form): 
    audiofilefield = AudioFileFormField() 

# the view 
def upload_view(request): 
    form = TestForm(data=request.POST or None, files=request.FILES or None) 
    if request.method == 'POST': 
     if form.is_valid(): 
       return HttpResponse('success') 
     else: 
       return HttpResponse('fail') 

# the test function 
class UploadTest(TestCase): 
    def test_upload(self): 
     c = Client() # django.test.client.Client 
     formdata = {} 
     with open('/my/audiofile.mp3', 'rb') as f: 
      formdata['audiofilefield'] = f 
      response = c.post('/my-test-view/', formdata) 
相關問題