Instantiate Python unittest.TestCase with arguments

后端 未结 3 554
暖寄归人
暖寄归人 2021-01-07 22:48

I would like to iterate over a list of items, and run an assertion on each of them. One example might be checking whether each number in a list is odd.

TestCas

3条回答
  •  感动是毒
    2021-01-07 23:30

    I would go this way:

    TestCase file containing test logic itself:

    import my_config
    from unittest import TestCase
    
    class TestOdd(unittest.TestCase):
        def runTest(self):
            """Assert that the item is odd"""
            self.assertTrue(int(my_config.options['number']) %2==1, "Number should be odd")
    

    then in the TestSuite file:

    import argparse
    import my_config
    import TestCase
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser()
        parser.add_argument('-num', '--number', type=int, default=0)
        my_config.options = parser.parse_args()
        
        suite_case = unittest.TestLoader().loadTestsFromTestCase(TestCase)
        test_suite = unittest.TestSuite([suite_case])
    
        unittest.TextTestRunner(verbosity=1, failfast=True, buffer=False).run(test_suite)
    

    my_config.py helping file:

    options = {}
    

    and then from command line we can execute:

    python3 -m unittest TestSuite.py --number=1
    python3 -m unittest TestSuite.py --number=2
    .
    .
    python3 -m unittest TestSuite.py --number=1000
    

    Or execution calling from command line could be done by using for cycle inside Shell script.

提交回复
热议问题