如何在使用pythonunittest运行测试方法后添加额外的断言?

2024-04-25 16:49:56 发布

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

我进行了92次92次测试,我想确保在通话过程中没有无声错误发生。 不幸的是,在OpenGL中的错误并不是很好。我想测试glGetError()是否返回其他结果GL_NO_ERROR如果我每个TestCase测试一次就足够了。如果我可以在每个测试方法之后添加一个断言,那会更好。(我不想在92个方法中手动添加)

我做了一个示例片段,它显示了一个不可接受的解决方案,因为assert是在tearDownClass(cls)方法中完成的,tearDownClass不应该执行任何测试逻辑。在

如何在测试后添加额外的断言?

The lines with comments show what I wan't to achieve.

import struct
import unittest

import ModernGL


class TestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.ctx = ModernGL.create_standalone_context()

    @classmethod
    def tearDownClass(cls):
        error = cls.ctx.error                   # Store error in a variable
        cls.ctx.release()                       # Then release the context
        cls.assertEqual(error, 'GL_NO_ERROR')   # Check if there were errors before the release

    def test_1(self):
        ...

    def test_2(self):
        ...

    def test_3(self):
        ...            


if __name__ == '__main__':
    unittest.main()

注意:

cls.ctx.error是一个属性glGetError()作为字符串),可能的值是:

^{pr2}$

Tags: notestimportselfreleasedef错误error
1条回答
网友
1楼 · 发布于 2024-04-25 16:49:56

您可以在tearDown(与tearDownClass相反)方法中进行测试,因为这是一个常规的实例方法:

class TestCase(unittest.TestCase):

    def setUp(self):
        self.ctx = ModernGL.create_standalone_context()

    def tearDown(self):
        error = self.ctx.error                   # Store error in a variable
        self.ctx.release()                       # Then release the context
        self.assertEqual(error, 'GL_NO_ERROR')   # Check if there were errors before the release

相关问题 更多 >