python unittest setup_如何在python unittest中为此类使用setUp和tearDown

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值