我正在编写一个 django-nose 测试来测试文档上传功能。在测试中,我使用SimpleUploadedFile()
from模拟新文档django.core.files.uploadedfile
。问题是与文档实例关联的文件无法在 Windows 上删除(Linux 上的测试通过)。我收到以下错误:
in auto_delete_file_on_delete()->
os.remove(instance.document.path)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process:
这是我的测试:
def test_delete_doc(self):
self.client.login(username='xx', password='xx')
dir_path = os.getcwd()
manager_user = User.objects.get(username='xx')
file_name = "test_document"
file_path = os.path.join(dir_path, file_name)
new_file = open(file_path, "w")
new_file.write("Some file content")
new_file.close()
new_file = open(os.path.join(dir_path, file_name), "rb")
new_doc = SimpleUploadedFile(name=file_name, content=new_file.read())
new_file.close()
self.client.post(reverse('view_upload'),
{'employee_id': manager_user.profile.employee.empId, 'document': new_doc})
self.assertEqual(len(Document.objects.all()), 1)
self.client.post(reverse('delete'), {'file_id': Document.objects.all().first().pk})
self.assertEqual(len(Document.objects.all()), 0)
我的看法(reverse('delete')
指delete_document()
):
def delete_document(request):
instance = Document.objects.get(doc_id=request.POST['file_id'])
instance.delete()
return redirect('view_upload')
以及附加到实例删除的信号:
@receiver(models.signals.post_delete, sender=Document)
def auto_delete_file_on_delete(sender, instance, **kwargs):
if instance.document:
if os.path.isfile(instance.document.path):
os.remove(instance.document.path)
有谁知道为什么会这样?
我已经尝试过(得到同样的错误):
- 用于
with
打开/关闭文件。 - 用来
os.open()/os.read()/os.close()
处理文件。 - 删除
SimpleUploadedFile()
并简单地new_doc = open()
用于打开文件并将其传递给POST
请求。
谢谢!