Unlike TemporaryFile(), the user of mkstemp() is responsible for deleting the temporary file when done with it.
- Python Documentation
因此,在tearDown中删除文件是正确的解决方案。
我个人会做一些测试功能,比如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)
等等,为您计划实现的所有内容定义一个测试,实现它并运行测试。到目前为止,您的类看起来还不错,但是正如您可能已经看到的,您应该尽可能具体地进行测试,例如使用self.assertEqual(self.fc_obj.filename, self.fname)
而不是self.assertIsNotNone(self.fc_obj.filename)
如果您想对打开的FileChunk对象进行大量测试,还可以添加第二个unittest.TestCase。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):
#...
如果只想创建一次FileChunk对象,还可以使用setUpClass和tearDownClass方法。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)
并像在测试方法中一样使用self.fc_obj。