Giving parameters into TestCase from Suite in python

后端 未结 5 867
滥情空心
滥情空心 2020-12-16 22:42

From python documentation(http://docs.python.org/library/unittest.html):

import unittest

class WidgetTestCase(unittest.TestCase):
    def setUp(self):
              


        
5条回答
  •  悲哀的现实
    2020-12-16 23:18

    This is something that has been on my mind recently. Yes it is very possible to do. I called it scenario testing, but I think parameterized may be more accurate. I put a proof of concept up as a gist here. In short it is a meta class that allows you to define a scenario and run the tests against it a bunch. With it your example can be something like this:

    class WidgetTestCase(unittest.TestCase):
        __metaclass__ = ScenarioMeta
        class widget_width(ScenerioTest):
            scenarios = [
                dict(widget_in=Widget("One Way"), expected_tuple=(50, 50)),
                dict(widget_in=Widget("Another Way"), expected_tuple=(100, 150))
            ]
            def __test__(self, widget_in, expected_tuple):
                self.assertEqual(widget_in.size, expected_tuple)
    

    When run, the meta class writes 2 seperate tests out so the output would be something like:

    $ python myscerariotest.py -v
    test_widget_width_0 (__main__.widget_width) ... ok
    test_widget_width_1 (__main__.widget_width) ... ok
    
    
    ----------------------------------------------------------------------
    Ran 2 tests in 0.001s
    
    OK
    

    As you can see the scenarios are converted to tests at runtime.

    Now I am not yet sure if this is even a good idea. I use it in tests where I have a lot of text centric cases that repeat the same assertions on slightly different data, which helps me to catch the little edge cases. But the classes in that gist do work and I believe it accomplishes what you are after.

    Note that the with some trickery the test cases can be given names and even pulled from an external source like a text file or database. Its not documented yet but some digging around in the meta class should get you started. There is also some more info and examples on my post here.

    Edit

    This is an ugly hack that I do not support anymore. The implementation should have been done as a subclass of TestCase, not as a hacked meta class. Live and learn. An even better solution would be to use nose generators.

提交回复
热议问题