Tuesday, June 28, 2011

Learning Python: #3 - UnitTesting - First Test

I was struggling with something to write to help me learn Python and I decided to do the classic bowling game example. I did a quick search to find out how to write TDD with Python and came across this PowerPoint slide which helped me get started writing the tests.

From that ppt slide, I figured out what my test file and first test should look like.

TestGame.py:
import unittest

class TestGame(unittest.TestCase):
    pass
    
if __name__ == "__main__":
    unittest.main()
and my First Test:
import unittest

class TestGame(unittest.TestCase):

    def testGameHasZeroScore(self):
        game = Game()
        assert game.score == 0, "Score is zero"

if __name__ == "__main__":
    unittest.main()
    
At this point I am still not certain what all of this is doing. Running the test produces this output:

E
======================================================================
ERROR: testGameHasZeroScore (__main__.TestGame)
----------------------------------------------------------------------
Traceback (most recent call last):
File "TestGame.py", line 7, in testGameHasZeroScore
game = Game()
NameError: global name 'Game' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)

This is good then because I know that I'm using the unittest import correctly. At this point I wasn't familiar with why self was being passed to the test method but I assumed it had a need. I found out later why it was needed. To get this test to pass I had to create a Game.py file that created my Game class with a score member, and I had to add from Game import Game to my TestGame.py file under the current import statement. Here is my Game class:

Game.py:
class Game: 
    score = 0

And my TestGame.py:
import unittest
from Game import Game

class TestGame(unittest.TestCase):

    def testGameHasZeroScore(self):
        game = Game()
        assert game.score == 0, "Score is zero"

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

Running this now produces this output:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

Awesome! I have completed my first unit test with Python.

No comments:

Post a Comment