views:

98

answers:

1

I've never done any unit testing before, and would like to learn what it is and how it can be useful in my Python code.

I've read through a few Python unit testing tutorials online but they're all so complicated and assume an extended programming background. I'm using Python with Pylons to create a simple web app.

Any simple examples would be greatly appreciated.

Thanks!

+4  A: 

Consider this.

Here's a class we've written.

class Something( object ):
    def __init__( self, a, b ):
        self.a= a
        self.b= b
    def sum( self ):
        return self.a+self.b+self.a

That's a test for that class.

import unittest
class TestSomething( unittest.TestCase ):
    def setUp( self ):
        self.s = Something( 1, 2 )
    def test_should_sum( self ):
        self.assertEquals( 3, self.s.sum() )

if __name__ == "__main__":
    unittest.main()

Does the class -- as a stand-alone unit -- pass the test?

If not, what's the bug?

We've taken the class -- as a stand-alone unit -- and tested it. That's unit testing.

S.Lott
Thank you! How do you typically run TestSomething? From the python console? Is there a better way? Also, what does "if __name__ == "__main__":" do? Thanks.
ensnare
@ensnare: Yes. And if you don't know what `__main__` is about, search stack overflow. Do not ask that question -- it's been answered here, heavily.
S.Lott