def test_clean_zip__empty(self): form = ThemeForm() data_file = self._data_file('zips/empty.zip') form.cleaned_data = {'theme_files_zip': data_file} # Python 2.6 can't actually open this empty file because of a bug. if is_zipfile(data_file): zip_file = zipfile.ZipFile(data_file) self.assertEqual(len(zip_file.namelist()), 0) zip_file.close() self.assertRaisesMessage(ValidationError, 'Zip archive cannot be empty.', form.clean_theme_files_zip) else: self.assertRaisesMessage(ValidationError, 'Must be a valid zip archive.', form.clean_theme_files_zip) data_file.close()
def clean_theme_files_zip(self): value = self.cleaned_data.get('theme_files_zip') if not value: return value if not is_zipfile(value): raise ValidationError('Must be a valid zip archive.') try: zip_file = zipfile.ZipFile(value) except zipfile.error: raise ValidationError('Must be a valid zip archive.') names = zip_file.namelist() if not names: raise ValidationError('Zip archive cannot be empty.') for n in names: if n.startswith('/') or '..' in n.split('/'): raise ValidationError('Zip archive contains invalid names.') return value