Django TestCase:SimpleUploadedFile显示错误的文件类型

时间:2013-04-27 09:12:04

标签: django django-testing

我一直在努力让测试在上传表单上运行。但是,每当我运行测试时,它都说文件的类型错误。

上传表单使用随机生成的文件名保存文件:

class Video(models.Model):
    def get_generated_path(self):
        # Generates random path for video file upload

    original_file = models.CharField(null=True)
    uploaded_file = models.FileField(storage=FileSystemStorage(location=
        settings.MEDIA_ROOT), upload_to=get_generated_path)
    video_name = models.TextField()

形式如下:

 class VideoForm(forms.Form):
      video_file = forms.FileField()
      video_name = forms.CharField()

      def clean_video_file(forms.Form):
          content = self.cleaned_data['video_file']
          content_type = content.content_type.split('/')[0]
          if content_type in settings.CONTENT_TYPES:
              if content._size > settings.MAX_UPLOAD_SIZE:
                  raise forms.ValidationError(_('Please keep filesize under %s. 
                      Current filesize %s') % (filesizeformat(
                      settings.MAX_UPLOAD_SIZE), filesizeformat(content._size)))
          else:
              raise forms.ValidationError(_('File type is not supported, 
                  content type is: %s' % content_type))
          return content

大多数剩余的逻辑都在视图中:

 def upload_video(request):
     try:
         # Check if user is authenticated
         if form.is_valid():
             video_file = request.FILES['video_file']
             video_name = form.cleaned_data['video_name']
             save_video = Video.objects.create(
                  original_file = 'uploaded_videos' + user.username,
                  video_name = video_name)
             return HTTPResponseRedirect('next-page')
      except Exception, e:
             ...

测试写成:

def test_video_form(TestCase):
    user = #Create a dummy user
    test_video = SimpleUploadedFile('test_video.flv', open(
        'path/to/test/video', 'rb'))
    form = VideoForm(user, {'video_name': test_video}, )
    self.assertTrue(form.is_valid())

上述测试总是失败,因为它说'test_video.flv'的文件类型是纯文本/文本。我检查了'test_video.flv'及其正确的类型。 如何将这些文件传递给上传表单并进行测试。

1 个答案:

答案 0 :(得分:3)

SimpleUploadedFile默认为content_type text/plain。这就是为什么您的测试代码在clean_video_file和此行中失败的原因:

 raise forms.ValidationError(_('File type is not supported, 
              content type is: %s' % content_type))

正在打印:

File type is not supported, 
              content type is: text/plain

content_type = 'video'传递到SimpleUploadedFile行,如下所示。

def test_video_form(TestCase):
    user = #Create a dummy user
    test_video = SimpleUploadedFile('test_video.flv', open(
    'path/to/test/video', 'rb'), content_type='video') # Notice the change here.
    form = VideoForm(user, {'video_name': test_video}, )
    self.assertTrue(form.is_valid())