Skip to content
Advertisement

Python unittest not recognizing tests

I’m trying to learn how to use the unittest framework in python. I keep getting the message below when I run my file containing the tests.

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

I’ve searched here and elsewhere and can’t figure out why it is not recognizing the tests. Each test starts with test and the other portions of the unittest seem to match what the documentation requires.

Here is the text of the script:

import unittest
from datetime import datetime, timedelta

class Activity(object):
    'Holds detail information on a activity'
    def __init__(self, location, activity_name, activity_id, start_date, end_date):
        self.activity_name = activity_name
        self.activity_id = activity_id
        self.start_date = datetime.strptime(start_date, '%m/%d/%Y').date()
        self.end_date = datetime.strptime(end_date, '%m/%d/%Y').date()
        self.location = location

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

class TestActivity(unittest.TestCase):

    def setUp(self):
        self.activity = Activity('UVU', 'OpenWest', 'Beginning Python'
                            , '00000', '12/1/2013', '12/30/3013')

    def test_activity_creation(self):
        self.assertEqual(self.activity.location, 'UVU')
        self.assertEqual(self.activity.activity_name, 'OpenWest')
        self.assertEqual(self.activity.activity_id, '00000')
        self.assertEqual(self.activity.start_date, datetime.strptime('12/1/2013', '%m/%d/%Y').date())
        self.assertEqual(self.activity.start_date, datetime.strptime('12/30/2013', '%m/%d/%Y').date())

    def test1(self):
        self.assertEqual(1,1)

    def tearDown(self):
        del self.activity

Any help is appreciated

Advertisement

Answer

If you move

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

To the end of the script, then it will work.

Update

Here is my speculation: when you called unittest.main() in the middle of the script, your test class has not been defined yet, thus unittest did not pick up any tests. By moving the unittest.main() to the end, or more precisely–after your define your test class, you make sure that unittest sees those tests.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement