Python 中的单元测试套件 [英] Unit Test Suite in Python

查看:31
本文介绍了Python 中的单元测试套件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将 Test Suit 实现为 python 类/模块,以便我拥有测试用例模块和测试套件模块.我也想将测试套件的参数传递给测试用例.

Can I implement Test Suit as a python class/module so that I have Test Case module and Test Suite module. I want to pass a argument from testsuite to testcase too.

像这样:

  • 测试套件模块:

  • Test Suite module:

import unittest

class GPUScoringMatrixTestSuite(unittest.TestSuite):

  def suite():
    suite = unittest.TestSuite()                                            
    suite.addTest(GPUScoringMatrixTestCase('PAM_350.txt'))
    suite.addTest(GPUScoringMatrixTestCase('PAM_250.txt'))                  
    self.run(suite)

  • 测试用例模块:

  • Test Case module:

    class GPUScoringMatrixTestCase(unittest.TestCase):  
    
      def __init__(self, matrix_file): 
        self.filename = matrix_file  
    
      @classmethod 
      def setUpClass(self):  
        self.matrix = GPUScoringMatrix(self.filename) 
    
      def test_sum_penalties(self):   
        sum = 0
        for i in self.matrix.penalties: 
          sum += i
        self.assertEqual(sum, -970, 'Iconsistence penalties between scoring matrices')
    

  • 参数 matrix_file 也不起作用...

    The argument matrix_file isn't work too...

    推荐答案

    我不确定您在这里要做什么,似乎您正在尝试编写代码来生成测试用例.为此,考虑到 Python 对象模型的难以置信的灵活性可能会有所帮助.特别是,您可以生成类型:

    I'm not sure what you're trying to do here, it seems you are trying to write code to generate testcases. For that, maybe it helps taking into account the incredible flexibility of Python's object model. In particular, you can generate types:

    def make_testcase(matrix_file):
        class MatrixTestCase(unittest.TestCase):
            pass
        MatrixTestCase.matrix_file = matrix_file
        return MatrixTestCase
    
    PAM250Tests = make_testcase('PAM_250.txt')
    PAM350Tests = make_testcase('PAM_350.txt')
    

    我希望您不必再去干涉测试套件和 unittest 的自动测试发现,但是这两个 TestCase 派生类会被自动选取.

    I would hope that you don't have to meddle with the test suite and unittest's automatic test discovery then, but that these two TestCase-derived classes are picked up automatically.

    另一种方法是将矩阵文件作为常量存储在派生类中,将测试函数放在基类中.派生类然后从 unittest.TestCase 和附加基类派生.

    A different approach is that you store the matrix file as a constant in a derived class, putting the test functions in a base class. The derived class then derives from both unittest.TestCase and the additional base class.

    这篇关于Python 中的单元测试套件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆