Posted by: theinvinciblezombiecow on: August 8, 2008
Well, wrote my first python code today. It’s a simple class and associated unittests, just to get the hang of it. I’ve also adjusted my intentions a bit:
The code is under read more. Yes, it’s silly, but you have to start somewhere am I right?
import unittest
class Person(object):
def __init__(self, first_name):
self.first_name = first_name
def __get_first_name(self):
return self.__first_name
def __set_first_name(self, value):
#empty sequences are false, so we can use "if not" here
if not value:
raise Exception('Empty first name')
self.__first_name = value
first_name = property(fget=__get_first_name, fset=__set_first_name)
class TestPersonProperties(unittest.TestCase):
def test_person_valid_name_property_and_constructor(self):
p = Person('John')
self.assertEqual(p.first_name, 'John')
p.first_name = 'meh'
self.assertEqual(p.first_name, 'meh')
def test_person_invalid_name_property_empty(self):
p = Person('Jane')
self.assertEqual(p.first_name, 'Jane')
try:
p.first_name = ''
except Exception:
self.assertEqual(1,1)
def test_person_invalid_name_property_none(self):
p = Person('Jane')
self.assertEqual(p.first_name, 'Jane')
try:
p.first_name = None
except Exception:
self.assertEqual(1,1)
def test_person_invalid_name_constructor_empty(self):
try:
p = Person('j')
except Exception:
self.assertEqual(1,1)
def test_person_invalid_name_constructor_none(self):
try:
p = Person(None)
except Exception:
self.assertEqual(1,1)
def test_person_invalid_property_set_and_retrieve(self):
p = Person('Tarzan')
p.last_name = 'Me'
self.assertEqual(p.last_name, 'Me')
def test_person_invalid_property_retrieve_without_set(self):
try:
p = Person('Tarzan')
self.assertEqual(p.last_name, '')
except AttributeError:
self.assertEqual(1,1)
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestPersonProperties)
unittest.TextTestRunner(verbosity=2).run(suite)