首页 > 解决方案 > Python 鼻子处理参数和动态生成的测试

问题描述

我有下面的最小工作示例,用于动态生成测试用例并使用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

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

标签: pythonpython-multiprocessingnose

解决方案


据我所知,您只需要确保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.')

推荐阅读