<blockquote>
<p>Unlike TemporaryFile(), the user of mkstemp() is responsible for deleting the temporary file when done with it.
- <a href="https://docs.python.org/2/library/tempfile.html#tempfile.mkstemp" rel="nofollow noreferrer">Python Documentation</a></p>
</blockquote>
<p>因此,在tearDown中删除文件是正确的解决方案。</p>
<p>我个人会做一些测试功能,比如</p>
<pre><code>def test_filename(self):
self.assertEqual(self.fc_obj.filename, self.fname)
self.assertIsTrue(os.path.isfile(self.fc_obj.filename))
def test_handle(self):
self.assertIsNone(self.fc_obj.filehandle)
def open_file(self):
# if you implemented an "open" method
# you can use this method every time you test the opened file
result = self.fc_obj.open()
self.assertIsTrue(result, "File open failed")
self.assertIsNotNone(self.fc_obj.filehandle)
# if you plan to implement a read and a write method you can add the following test
def test_read_write_file(self):
self.open_file()
random_data = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
self.fc_obj.write(random_data)
self.assertEqual(self.fc_obj.read(), random_data)
</code></pre>
<p>等等,为您计划实现的所有内容定义一个测试,实现它并运行测试。到目前为止,您的类看起来还不错,但是正如您可能已经看到的,您应该尽可能具体地进行测试,例如使用</p>
<pre><code>self.assertEqual(self.fc_obj.filename, self.fname)
</code></pre>
<p>而不是</p>
<pre><code>self.assertIsNotNone(self.fc_obj.filename)
</code></pre>
<p>如果您想对打开的FileChunk对象进行大量测试,还可以添加第二个<code>unittest.TestCase</code>。</p>
<pre><code>class TestOpenFileChunk(unittest.TestCase);
def setUp(self):
self.fhandle, self.fname = mkstemp()
self.fc_obj = FileChunk(filename=self.fname)
self.fc_obj.open()
def tearDown(self):
# if you have this method
self.fc_object.close()
# and then
try:
os.remove(self.fname)
except OSError as why:
print(why)
def test_read_write(self):
#...
</code></pre>
<p>如果只想创建一次FileChunk对象,还可以使用<code>setUpClass</code>和<code>tearDownClass</code>方法。</p>
<pre><code>class TestOpenFileChunk(unittest.TestCase);
@classmethod
def setUpClass(cls):
cls.fhandle, cls.fname = mkstemp()
cls.fc_obj = FileChunk(filename=self.fname)
cls.fc_obj.open()
@classmethod
def tearDownClass(cls):
# if you have this method
cls.fc_obj.close()
# and then
try:
os.remove(cls.fname)
except OSError as why:
print(why)
</code></pre>
<p>并像在测试方法中一样使用self.fc_obj。</p>