[TIP] Using one unit test with different input parameters

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Feb 19 14:18:26 PST 2008


Robert McHardy <robert at mchardy.net> writes:

> --------- tw_test.py -----------
> 
> import unittest, time, re
> from twill import get_browser
> from twill.commands import find, notfind, title, code
> 
> DOMAIN = {'primary': 'wessexfm.com', 'code': 'wx',}
> 
> class Site_Test(unittest.TestCase):
>     def setUp(self):
>         self.tb = get_browser()
>     def test_homepage(self):
>         """Test the / homepage"""
>         self.tb.go('http://www.%s/' % DOMAIN['primary'])
>         code(200)
>         notfind('error occurred while processing this directive')
> 
> 	... etc ...
> 
> if __name__ == "__main__":
>     unittest.main()
> 
> -----------------------------------------
> 
> The client has 28 sites that are very similar.  I'd rather not have
> to clone the test script 28 times with different hard-coded domain
> details...  but I can't figure out how to pass in different
> parameters to the unit test - e.g. a different DOMAIN dict with data
> for other sites, and have the tests run on that domain instead.

I often use the test fixtures to store a container of test parameter
sets, then iterate over those parameter sets inside the test cases::

    class Site_Test(unittest.TestCase):
        def setUp(self):
            self.tb = get_browser()
            self.sites = {
                'wessexfm.com': {
                    'primary': 'wessexfm.com',
                    'code': 'wx',
                    },
                'example.com': {
                    'primary': 'example.com',
                    'code': 'ec',
                    },
                'example.org': {
                    'primary': 'example.org',
                    'code': 'eo',
                    },
                }

        def test_homepage(self):
            """Test the / homepage"""
            for key, params in self.sites.items():
                self.tb.go('http://www.%(primary)s/' % params)
                code(200)
                notfind('error occurred while processing this directive')

        # ... etc ...

In the test case given above, the 'sites' dict could simply be a
module global instead, since it's not necessary to create it each
time. If it contains anything that needs to be set up for each test
case, keep it in the fixtures.

> Any tips or hints gratefully received!

You're using unittest.TestCase, but not using any of the
'failUnlessFoo' methods; that means the unittest reports won't be very
informative about what fails.

-- 
 \             “Holy priceless collection of Etruscan snoods, Batman!” |
  `\                                                            —Robin |
_o__)                                                                  |
Ben Finney




More information about the testing-in-python mailing list