how to make a person: tests and solution
tests
the code in person/tests/test_person.py from how to make a person
1import datetime
2import random
3import src.person
4import unittest
5
6
7def choose(*choices):
8 return random.choice(choices)
9
10
11def this_year():
12 return datetime.datetime.now().year
13
14
15class TestPerson(unittest.TestCase):
16
17 def setUp(self):
18 self.random_year_of_birth = random.randint(
19 this_year()-120, this_year()
20 )
21 self.random_first_name = choose('jane', 'joe', 'john', 'person')
22
23 def test_factory_takes_keyword_arguments(self):
24 a_person = dict(
25 first_name=self.random_first_name,
26 last_name=choose('doe', 'smith', 'blow', 'public'),
27 sex=choose('F', 'M'),
28 )
29
30 self.assertEqual(
31 src.person.factory(
32 **a_person,
33 year_of_birth=self.random_year_of_birth,
34 ),
35 dict(
36 **a_person,
37 age=this_year()-self.random_year_of_birth,
38 )
39 )
40
41 def test_factory_w_default_arguments(self):
42 self.assertEqual(
43 src.person.factory(
44 first_name=self.random_first_name,
45 year_of_birth=self.random_year_of_birth,
46 ),
47 dict(
48 first_name=self.random_first_name,
49 last_name='doe',
50 sex='M',
51 age=this_year()-self.random_year_of_birth,
52 )
53 )
54
55
56# Exceptions seen
57# AssertionError
58# NameError
59# AttributeError
60# TypeError
61# SyntaxError
solution
the solution in person/src/person.py from how to make a person
1import datetime
2
3
4def factory(
5 first_name, year_of_birth,
6 last_name='doe', sex='M',
7 ):
8 return {
9 'first_name': first_name,
10 'last_name': last_name,
11 'sex': sex,
12 'age': datetime.datetime.today().year - year_of_birth,
13 }