【发布时间】:2015-11-13 17:04:01
【问题描述】:
我正在尝试测试我自己的反网络版本,可以在here 找到。但是,我正在使用 Python 的 unittest 模块对其进行测试。代码如下:
import unittest
from unittest.mock import patch
from antiweb import main
import sys
import os
import tempfile
import shutil
class Test_Antiweb(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp()
self.testfile_source ="#@start()\n\n#@include(test_area)\n\n#@start(test_area)\n#This is test_area text\n#@(test_area)"
with open(os.path.join(self.test_dir, "testfile.py"), "w") as test:
test.write(self.testfile_source)
def test_antiweb(self):
self.test_args = ['antiweb.py', '-i', "-o docs", os.path.join(self.test_dir, "testfile.py")]
with patch.object(sys, 'argv', self.test_args):
success = main()
self.assertTrue(success)
def tearDown(self):
shutil.rmtree(self.test_dir)
if __name__ == '__main__':
unittest.main()
一切正常,除了tearDown 函数。在没有tearDown 的情况下执行单元测试时,临时文件夹及其内容已完美创建。但是使用tearDown 函数我得到一个错误:
======================================================================
ERROR: test_antiweb (antiweb_tests.Test_Antiweb)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\<username>\Documents\GitHub\antiweb\antiweb_tests.py", line 29, in tearDown
shutil.rmtree(self.test_dir)
File "C:\Python34\lib\shutil.py", line 478, in rmtree
return _rmtree_unsafe(path, onerror)
File "C:\Python34\lib\shutil.py", line 377, in _rmtree_unsafe
onerror(os.rmdir, path, sys.exc_info())
File "C:\Python34\lib\shutil.py", line 375, in _rmtree_unsafe
os.rmdir(path)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\
<username>\\AppData\\Local\\Temp\\tmp3lk01fn5'
当我然后查看临时文件夹时,文件夹本身仍然存在,但现在是空的。在这里包含我的反网络文件太多了,所以如果你需要它,我会再次链接here。
【问题讨论】:
-
好的,我知道出了什么问题:
-
在antiweb中,我将工作目录更改为临时文件夹,所以我在临时文件夹中。然后当我尝试删除我现在所在的文件夹时,我收到该错误^^
-
我猜你现在必须自己回答这个问题:-)
标签: python python-unittest shutil