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

2024-05-23 19:44:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难学习测试驱动的开发。

我正在编写一个类,该类将获取文件名或文件描述,并调整输入的大小,并返回文件中数据的大小块。

首先从测试开始,我所能做的就是测试传递的参数是否不是none,并检查参数是否是有效的fileobjects。

我所能做的就是在代码下面,我是应该使用安装和拆卸方法,还是完全错误?我正在创建一个临时文件和在setUp()中定义为读取的类的实例,我应该在tearDown()中删除这个对象吗

下面是代码

class Test_FileChunk(unittest.TestCase):
    """
    """
    def setUp(self):
        self.fhandle, self.fname = mkstemp()
        self.fc_obj = FileChunk(filename=self.fname)

    def tearDown(self):
        try:
            os.remove(self.fname)
        except OSError as oserr:
            print(oserr)

    def test_instance_variables(self):
        self.assertIsNotNone(self.fc_obj.filename)
        self.assertIsNone(self.fc_obj.filehandle)
        self.assertEqual(self.fc_obj.chunk_size, 8192)

    def test_check_if_instance_variables_are_valid_file_objects(self):
        handle = open(self.fc_obj.filename
        self.assertEqual(
            hasattr
                (handle, "r"), 'seek'), True,
                    msg="Is not a valid file object")
        handle.close()

我在stackoverflow上浏览了多个TDD问题和建议的教程,但是看起来遵循TDD教程是非常有趣的,但是实际上做TDD是非常困难的。实际上我可以在ReadChunk类中思考我想做的事情,但是我却无法在实际中先找到测试,然后再编写代码。我可以考虑通过TDD检查传递的值是否是有效的文件对象,如果没有TDD进行编码就不会发生这种情况,但是我不确定是否正确使用了unittest。无法了解全局。有谁能建议一下如何处理这个问题,以及上面截取的代码是否正确。


Tags: 文件对象代码selfobj参数defsetup
2条回答

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对象,还可以使用setUpClasstearDownClass方法。

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。

关于您的代码

安装和拆卸是可选的方法,可以帮助您安装和拆卸。。破坏测试环境。例如,它们通常用于创建和删除临时文件夹,以便在测试期间存储输出或设置(模拟的)数据库连接。

不应使用它们来测试任何功能。因此,在安装程序中不应调用FileChunk对象。在每个测试中,您希望测试FileChunk中方法的特定情况,理想情况下是相互独立的。因此,在每种新情况下都应该调用FileChunk的新实例。因此在这种情况下,在test_instance_variablestest_check_if_instance_variables_valid_file_objects中都要检查。

关于TDD

使用纯TDD是一种心态上的改变。在这方面没有任何简单的教程可以帮助您;因为整本书都是关于如何使用TDD的。

不过,我可以为你提供一些指导。

  1. 标识类的公共接口。外部类应该能够使用哪些方法?这些方法的输入和输出应该是什么?
  2. 确定方法的不同情况。什么时候应该输出真/假?它应该什么时候抛出异常?
  3. 根据在2中找到的案例编写测试用例。
  4. 为FileChunk编写最基本的虚拟类,它基本上什么也不做,但具有单元测试正在测试的所有功能。这样就可以运行所有测试,尽管它们可能会失败。
  5. 开始改进FileChunk类,直到所有测试通过。

在我看来,TDD的一个重要方面是,你不能只是开始做测试。你真的应该知道这个班应该是什么样子。

相关问题 更多 >