Avoid converting functions to methods in a class

Ben Finney ben+python at benfinney.id.au
Fri Feb 19 23:55:56 EST 2010


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

> I have a convention when writing unit tests

Incidentally, you may be interested in the specific forum for testing in
Python <URL:http://lists.idyll.org/listinfo/testing-in-python> that is a
good resource for asking questions like this.

> to put the target of the test into a class attribute, as follows:
>
> class MyTest(unittest.TestCase):
>     target = mymodule.someclass
>
>     def test_spam(self):
>         """Test that someclass has a spam attribute."""
>         self.failUnless(hasattr(self.target, 'spam'))
>
>
> It works well until I write a test for stand-alone functions:
>
> class AnotherTest(unittest.TestCase):
>     target = mymodule.function
>
>     def test_foo(self):
>         self.assertEquals(self.target('a', 'b'), 'foo')

I think this is because you're binding the ‘target’ attribute at the
class definition, binding it to that class.

Instead, this smells like something that should be a fixture for each
test case::

    class SomeClassTestCase(unittest.TestCase):

        def setUp(self):
            """ Set up test fixtures. """
            self.target = mymodule.SomeClass

        def test_has_spam(self):
            """ Should have a spam attribute. """
            self.failUnless(hasattr(self.target, 'spam'))

        def test_has_no_bacon(self):
            """ Should not have a bacon attribute. """
            self.failIf(hasattr(self.target, 'bacon'))


    class SomeFunctionTest(unittest.TestCase):

        def setUp(self):
            """ Set up test fixtures. """
            self.target = mymodule.some_function

        def test_a_b_input_returns_foo(self):
            """ Should return 'foo' from 'a', 'b' inputs. """
            self.assertEquals(self.target('a', 'b'), 'foo')

        def test_c_d_input_raises_valueerror(self):
            """ Should raise ValueError from 'c', 'd' inputs. """
            self.assertRaises(
                ValueError,
                self.target, 'c', 'd')

-- 
 \        “A free press is one where it's okay to state the conclusion |
  `\                      you're led to by the evidence.” —Bill Moyers |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list