Python nose 处理参数和动态生成的测试

Python nose processes parameter and dynamically generated tests

我有下面的最小工作示例,用于动态生成测试用例并 运行 使用 nose 对它们进行设置。

class RegressionTests(unittest.TestCase):
    """Our base class for dynamically created test cases."""

    def regression(self, input):
        """Method that runs the test."""

        self.assertEqual(1, 1)


def create(input):
    """Called by create_all below to create each test method."""

    def do_test(self):
        self.regression(input)
    return do_test


def create_all():
    """Create all of the unit test cases dynamically"""

    logging.info('Start creating all unit tests.')

    inputs = ['A', 'B', 'C']
    
    for input in inputs:

        testable_name = 'test_{0}'.format(input)
        testable = create(input)
        testable.__name__ = testable_name
        class_name = 'Test_{0}'.format(input)

        globals()[class_name] = type(class_name, (RegressionTests,), {testable_name: testable})
        logging.debug('Created test case %s with test method %s', class_name, testable_name)

    logging.info('Finished creating all unit tests.')


if __name__ == '__main__':

    # Create all the test cases dynamically
    create_all()

    # Execute the tests
    logging.info('Start running tests.')
    nose.runmodule(name='__main__')
    logging.info('Finished running tests.')

当我 运行 使用 python nose_mwe.py --nocapture --verbosity=2 进行测试时,它们 运行 很好,我得到了输出:

test_A (__main__.Test_A) ... ok
test_B (__main__.Test_B) ... ok
test_C (__main__.Test_C) ... ok

但是,当我尝试使用 processes 命令行参数并行进行测试时 运行,例如python nose_mwe.py --processes=3 --nocapture --verbosity=2,我收到以下错误。

Failure: ValueError (No such test Test_A.test_A) ... ERROR
Failure: ValueError (No such test Test_B.test_B) ... ERROR
Failure: ValueError (No such test Test_C.test_C) ... ERROR

这里是否缺少一些简单的东西来允许动态生成的测试并行 运行?

据我所知,您只需要确保在每个测试过程中 create_all 是 运行。只需将它移出 __main__ 测试即可,因此文件末尾看起来像:

# as above

# Create all the test cases dynamically
create_all()

if __name__ == '__main__':
    # Execute the tests
    logging.info('Start running tests.')
    nose.runmodule(name='__main__')
    logging.info('Finished running tests.')