classes: tests and solutions

classes tests

the code from person/tests/test_person.py from classes

  1import datetime
  2import random
  3import src.person
  4import unittest
  5
  6
  7def pick_one(*choices):
  8    return random.choice(choices)
  9
 10
 11def get_random_name():
 12    return pick_one(
 13        'jane', 'joe', 'john', 'person',
 14        'doe', 'smith', 'blow', 'public',
 15    )
 16
 17
 18class TestPerson(unittest.TestCase):
 19
 20    def setUp(self):
 21        self.random_first_name = get_random_name()
 22        self.random_last_name = get_random_name()
 23        this_year = datetime.datetime.now().year
 24        self.random_year_of_birth = random.randint(
 25            this_year-120, this_year
 26        )
 27        self.age = this_year - self.random_year_of_birth
 28
 29    def test_factory_w_keyword_arguments(self):
 30        a_person = dict(
 31            first_name=self.random_first_name,
 32            last_name=self.random_last_name,
 33            sex=pick_one('F', 'M'),
 34        )
 35
 36        reality = src.person.factory(
 37            **a_person,
 38            year_of_birth=self.random_year_of_birth,
 39        )
 40        my_expectation = dict(
 41            **a_person,
 42            age=self.age,
 43        )
 44        self.assertEqual(reality, my_expectation)
 45
 46    def test_factory_w_optional_arguments(self):
 47        reality = src.person.factory(
 48            first_name=self.random_first_name,
 49            year_of_birth=self.random_year_of_birth,
 50        )
 51        my_expectation = dict(
 52            first_name=self.random_first_name,
 53            last_name='doe',
 54            sex='M',
 55            age=self.age,
 56        )
 57        self.assertEqual(reality, my_expectation)
 58
 59    def test_factory_person_says_hello(self):
 60        a_random_person = src.person.factory(
 61            first_name=self.random_first_name,
 62            last_name=self.random_last_name,
 63            year_of_birth=self.random_year_of_birth,
 64        )
 65
 66        reality = src.person.say_hello(a_random_person)
 67        my_expectation = (
 68            f'Hi, my name is {self.random_first_name}'
 69            f' {self.random_last_name}'
 70            f' and I am {self.age}'
 71        )
 72        self.assertEqual(reality, my_expectation)
 73
 74    def test_classy_person_says_hello(self):
 75        a_random_person = src.person.Person(
 76            first_name=self.random_first_name,
 77            last_name=self.random_last_name,
 78            year_of_birth=self.random_year_of_birth,
 79        )
 80
 81        reality = a_random_person.say_hello()
 82        my_expectation = (
 83            f'Hi, my name is {self.random_first_name}'
 84            f' {self.random_last_name}'
 85            f' and I am {self.age}'
 86        )
 87        self.assertEqual(reality, my_expectation)
 88
 89    def test_attributes_and_methods_of_person_class(self):
 90        reality = dir(src.person.Person)
 91        my_expectation = [
 92            '__class__',
 93            '__delattr__',
 94            '__dict__',
 95            '__dir__',
 96            '__doc__',
 97            '__eq__',
 98            '__firstlineno__',
 99            '__format__',
100            '__ge__',
101            '__getattribute__',
102            '__getstate__',
103            '__gt__',
104            '__hash__',
105            '__init__',
106            '__init_subclass__',
107            '__le__',
108            '__lt__',
109            '__module__',
110            '__ne__',
111            '__new__',
112            '__reduce__',
113            '__reduce_ex__',
114            '__repr__',
115            '__setattr__',
116            '__sizeof__',
117            '__static_attributes__',
118            '__str__',
119            '__subclasshook__',
120            '__weakref__',
121            'say_hello',
122        ]
123        self.assertEqual(reality, my_expectation)
124
125    def test_attributes_and_methods_of_person_instance(self):
126        an_instance_of_person = src.person.Person(
127            first_name=self.random_first_name,
128            last_name=self.random_last_name,
129            year_of_birth=self.random_year_of_birth,
130            sex=pick_one('F', 'M')
131        )
132
133        reality = dir(an_instance_of_person)
134        my_expectation = [
135            '__class__',
136            '__delattr__',
137            '__dict__',
138            '__dir__',
139            '__doc__',
140            '__eq__',
141            '__firstlineno__',
142            '__format__',
143            '__ge__',
144            '__getattribute__',
145            '__getstate__',
146            '__gt__',
147            '__hash__',
148            '__init__',
149            '__init_subclass__',
150            '__le__',
151            '__lt__',
152            '__module__',
153            '__ne__',
154            '__new__',
155            '__reduce__',
156            '__reduce_ex__',
157            '__repr__',
158            '__setattr__',
159            '__sizeof__',
160            '__static_attributes__',
161            '__str__',
162            '__subclasshook__',
163            '__weakref__',
164            'first_name',
165            'last_name',
166            'say_hello',
167            'sex',
168            'year_of_birth',
169        ]
170        self.assertEqual(reality, my_expectation)
171
172
173# Exceptions seen
174# AssertionError
175# NameError
176# AttributeError
177# TypeError
178# SyntaxError

classes solutions

the solutions in person/src/person.py from classes

 1import datetime
 2
 3
 4def say_hello(a_dictionary):
 5    return (
 6        f'Hi, my name is {a_dictionary.get("first_name")}'
 7        f' {a_dictionary.get("last_name")}'
 8        f' and I am {a_dictionary.get("age")}'
 9    )
10
11
12def factory(
13        first_name, year_of_birth,
14        last_name='doe', sex='M',
15    ):
16    return {
17        'first_name': first_name,
18        'last_name': last_name,
19        'sex': sex,
20        'age': (
21            datetime.datetime.today().year
22           -year_of_birth
23        ),
24    }
25
26
27class Person:
28
29    def __init__(
30            self, first_name, last_name='doe',
31            year_of_birth=None, sex=None,
32        ):
33        self.first_name = first_name
34        self.last_name = last_name
35        self.year_of_birth = year_of_birth
36        return None
37
38    def say_hello(self, person):
39        age = (
40            datetime.datetime.today().year
41          - self.year_of_birth
42        )
43        return (
44            f'Hi, my name is {self.first_name}'
45            f' {self.last_name} and I am {age}'
46        )

inheritance tests

the code from person/tests/test_classes.py from inheritance

  1import src.classes
  2import unittest
  3
  4
  5class TestClasses(unittest.TestCase):
  6
  7    def test_making_a_class_w_pass(self):
  8        an_instance = src.classes.WPass()
  9        assert isinstance(an_instance, object)
 10        self.assertIsInstance(an_instance, object)
 11
 12        a_class = src.classes.WPass
 13        assert issubclass(a_class, object)
 14        self.assertIsSubclass(a_class, object)
 15
 16    def test_making_a_class_w_parentheses(self):
 17        an_instance = src.classes.WParentheses()
 18        assert isinstance(an_instance, object)
 19        self.assertIsInstance(an_instance, object)
 20
 21        a_class = src.classes.WParentheses
 22        assert issubclass(a_class, object)
 23        self.assertIsSubclass(a_class, object)
 24
 25    def test_making_a_class_w_object(self):
 26        an_instance = src.classes.WObject()
 27        assert isinstance(an_instance, object)
 28        self.assertIsInstance(an_instance, object)
 29
 30        a_class = src.classes.WObject
 31        assert issubclass(a_class, object)
 32        self.assertIsSubclass(a_class, object)
 33
 34    def test_is_none_an_object(self):
 35        assert isinstance(None, object)
 36        self.assertIsInstance(None, object)
 37
 38    def test_is_a_boolean_an_object(self):
 39        assert issubclass(bool, object)
 40        self.assertIsSubclass(bool, object)
 41
 42    def test_is_an_integer_an_object(self):
 43        assert issubclass(int, object)
 44        self.assertIsSubclass(int, object)
 45
 46    def test_is_a_float_an_object(self):
 47        assert issubclass(float, object)
 48        self.assertIsSubclass(float, object)
 49
 50    def test_is_a_string_an_object(self):
 51        assert issubclass(str, object)
 52        self.assertIsSubclass(str, object)
 53
 54    def test_is_a_tuple_an_object(self):
 55        assert issubclass(tuple, object)
 56        self.assertIsSubclass(tuple, object)
 57
 58    def test_is_a_list_an_object(self):
 59        assert issubclass(list, object)
 60        self.assertIsSubclass(list, object)
 61
 62    def test_is_a_set_an_object(self):
 63        assert issubclass(set, object)
 64        self.assertIsSubclass(set, object)
 65
 66    def test_is_a_dictionary_an_object(self):
 67        assert issubclass(dict, object)
 68        self.assertIsSubclass(dict, object)
 69
 70    def test_attributes_and_methods_of_objects(self):
 71        reality = dir(object)
 72        my_expectation = [
 73            '__class__',
 74            '__delattr__',
 75            '__dir__',
 76            '__doc__',
 77            '__eq__',
 78            '__format__',
 79            '__ge__',
 80            '__getattribute__',
 81            '__getstate__',
 82            '__gt__',
 83            '__hash__',
 84            '__init__',
 85            '__init_subclass__',
 86            '__le__',
 87            '__lt__',
 88            '__ne__',
 89            '__new__',
 90            '__reduce__',
 91            '__reduce_ex__',
 92            '__repr__',
 93            '__setattr__',
 94            '__sizeof__',
 95            '__str__',
 96            '__subclasshook__'
 97        ]
 98        self.assertEqual(reality, my_expectation)
 99
100
101# Exceptions seen
102# AssertionError
103# NameError
104# AttributeError
105# TypeError

inheritance solutions

the solutions in person/src/classes.py from inheritance

1class WPass: pass
2
3
4class WParentheses(): pass
5
6
7class WObject(object): pass

AssertionError 2: tests

the code from assertion_error/test_assertion_error.py from AssertionError 2: use class attributes

  1import unittest
  2
  3
  4class TestAssertionError(unittest.TestCase):
  5
  6    an_integer = 0
  7    a_float = 0.0
  8    a_string = 'a string'
  9    a_tuple = (1, 2, 3, 'n')
 10    a_list = [1, 2, 3, 'n']
 11    a_set = {1, 2, 3, 'n'}
 12    a_dictionary = {'key': 'value'}
 13
 14    def test_what_is_an_assertion(self):
 15        reality = 1 + 1
 16        my_expectation = 2
 17        assert reality == my_expectation
 18        self.assertEqual(reality, my_expectation)
 19
 20        reality = '1' + '1'
 21        my_expectation = '11'
 22        assert reality == my_expectation
 23        self.assertEqual(reality, my_expectation)
 24
 25        reality = 'I am' + ' alive'
 26        my_expectation = 'I am alive'
 27        assert reality == my_expectation
 28        self.assertEqual(reality, my_expectation)
 29
 30    def test_assertion_error_w_none(self):
 31        assert None is None
 32        self.assertIs(None, None)
 33
 34        assert False is not None
 35        self.assertIsNot(False, None)
 36
 37        assert True is not None
 38        self.assertIsNot(True, None)
 39
 40        assert self.an_integer is not None
 41        self.assertIsNot(self.an_integer, None)
 42
 43        assert self.a_float is not None
 44        self.assertIsNot(self.a_float, None)
 45
 46        assert self.a_string is not None
 47        self.assertIsNot(self.a_string, None)
 48
 49        assert self.a_tuple is not None
 50        self.assertIsNot(self.a_tuple, None)
 51
 52        assert self.a_list is not None
 53        self.assertIsNot(self.a_list, None)
 54
 55        assert self.a_set is not None
 56        self.assertIsNot(self.a_set, None)
 57
 58        assert self.a_dictionary is not None
 59        self.assertIsNot(self.a_dictionary, None)
 60
 61    def test_assertion_error_w_false(self):
 62        assert None is not False
 63        self.assertIsNot(None, False)
 64
 65        assert False is False
 66        self.assertIs(False, False)
 67
 68        assert True is not False
 69        self.assertIsNot(True, False)
 70
 71        assert self.an_integer is not False
 72        self.assertIsNot(self.an_integer, False)
 73
 74        assert self.a_float is not False
 75        self.assertIsNot(self.a_float, False)
 76
 77        assert self.a_string is not False
 78        self.assertIsNot(self.a_string, False)
 79
 80        assert self.a_tuple is not False
 81        self.assertIsNot(self.a_tuple, False)
 82
 83        assert self.a_list is not False
 84        self.assertIsNot(self.a_list, False)
 85
 86        assert self.a_set is not False
 87        self.assertIsNot(self.a_set, False)
 88
 89        assert self.a_dictionary is not False
 90        self.assertIsNot(self.a_dictionary, False)
 91
 92    def test_assertion_error_w_true(self):
 93        assert None is not True
 94        self.assertIsNot(None, True)
 95
 96        assert False is not True
 97        self.assertIsNot(False, True)
 98
 99        assert True is True
100        self.assertIs(True, True)
101
102        assert self.an_integer is not True
103        self.assertIsNot(self.an_integer, True)
104
105        assert self.a_float is not True
106        self.assertIsNot(self.a_float, True)
107
108        assert self.a_string is not True
109        self.assertIsNot(self.a_string, True)
110
111        assert self.a_tuple is not True
112        self.assertIsNot(self.a_tuple, True)
113
114        assert self.a_list is not True
115        self.assertIsNot(self.a_list, True)
116
117        assert self.a_set is not True
118        self.assertIsNot(self.a_set, True)
119
120        assert self.a_dictionary is not True
121        self.assertIsNot(self.a_dictionary, True)
122
123    def test_assertion_error_w_equality(self):
124        assert None == None
125        self.assertEqual(None, None)
126
127        assert False != None
128        self.assertNotEqual(False, None)
129
130        assert False != True
131        self.assertNotEqual(False, True)
132
133        assert False == False
134        self.assertEqual(False, False)
135
136        assert True != None
137        self.assertNotEqual(True, None)
138
139        assert True == True
140        self.assertEqual(True, True)
141
142    def test_assertion_error_w_is_vs_equal(self):
143        assert 0 is not 0.0
144        self.assertIsNot(0, 0.0)
145
146        assert 0 == 0.0
147        self.assertEqual(0, 0.0)
148
149
150# NOTES
151# a dictionary is not True
152# a dictionary is not False
153# a dictionary is not None
154# a set is not True
155# a set is not False
156# a set is not None
157# a list is not True
158# a list is not False
159# a list is not None
160# a tuple is not True
161# a tuple is not False
162# a tuple is not None
163# a string is not True
164# a string is not False
165# a string is not None
166# a float is not True
167# a float is not False
168# a float is not None
169# an integer is not True
170# an integer is not False
171# an integer is not None
172# True is True and equal to True
173# True is not False and NOT equal to False
174# True is not None and NOT equal to None
175# False is not True and NOT equal to True
176# False is False and equal to False
177# False is not None and NOT equal to None
178# None is not True and NOT equal to True
179# None is not False and NOT equal to False
180# None is None and equal to None
181
182
183# Exceptions seen
184# AssertionError
185# NameError

booleans 4: tests

the code from booleans/tests/test_booleans.py from booleans 4: inheritance

 1import unittest
 2
 3
 4class TestBooleans(unittest.TestCase):
 5
 6    def test_what_is_false(self):
 7        self.assertIsInstance(False, (bool, int))
 8        self.assertNotIsInstance(False, float)
 9
10        for false_item in (
11            False,
12            None, bool(None),
13            0, 0.0, bool(0), bool(0.0),
14            str(), bool(str()),
15            tuple(), bool(tuple()),
16            list(), bool(list()),
17            set(), bool(set()),
18            dict(), bool(dict()),
19        ):
20            with self.subTest(item=false_item):
21                self.assertFalse(false_item)
22
23    def test_what_is_true(self):
24        self.assertIsInstance(True, (bool, int))
25        self.assertNotIsInstance(True, float)
26
27        for true_item in (
28            True,
29            -1, bool(-1), 1, bool(1),
30            -0.1, bool(-0.1), 0.1, bool(0.1),
31            "a string with things", bool("a string with things"),
32            ((1, 2, 3, 'n')), bool((1, 2, 3, 'n')),
33            [1, 2, 3, 'n'], bool([1, 2, 3, 'n']),
34            {1, 2, 3, 'n'}, bool({1, 2, 3, 'n'}),
35            {'key': 'value'}, bool({'key': 'value'}),
36        ):
37            with self.subTest(item=true_item):
38                self.assertTrue(true_item)
39
40    def test_the_value_of_false(self):
41        self.assertEqual(False+1, 1)
42        self.assertEqual(False-1, -1)
43        self.assertEqual(False*1, 0)
44        with self.assertRaises(ZeroDivisionError):
45            1 / False
46
47    def test_the_value_of_true(self):
48        self.assertEqual(True+1, 2)
49        self.assertEqual(True-1, 0)
50        self.assertEqual(True*1, 1)
51        self.assertEqual(True/1, 1)
52
53    def test_if_bool_is_an_int(self):
54        self.assertNotIsInstance(bool, int)
55
56
57# NOTES
58# a dictionary with things is True
59# a set with things is True
60# a list with things is True
61# a tuple with things is True
62# a string with things is True
63# positive and negative numbers are True
64# True is True
65# True is not false
66# True is a boolean
67# True is an integer
68# True is not a float
69# True is 1
70# the empty dictionary is False
71# the empty set is False
72# the empty list is False
73# the empty tuple is False
74# the empty string is False
75# 0 is False
76# None is False
77# False is False
78# False is not true
79# False is a boolean
80# False is an integer
81# False is not a float
82# False is 0
83
84
85# Exceptions seen
86# AssertionError

how to make a calculator 8: tests

the code from calculator/tests/test_calculator.py from how to make a calculator 8

  1import random
  2import src.calculator
  3import unittest
  4
  5
  6def a_random_number():
  7    return random.triangular(-1000.0, 1000.0)
  8
  9
 10class TestCalculator(unittest.TestCase):
 11
 12    @staticmethod
 13    def get_division_result(x, y):
 14        try:
 15            return x / y
 16        except ZeroDivisionError:
 17            return 'brmph?! I cannot divide by 0. Try again...'
 18
 19    def setUp(self):
 20        self.random_first_number = a_random_number()
 21        self.random_second_number = a_random_number()
 22
 23        x = self.random_first_number
 24        y = self.random_second_number
 25
 26        self.calculator_tests = {
 27            'add': x+y,
 28            'subtract': x-y,
 29            'multiply': x*y,
 30            'divide': self.get_division_result(x, y)
 31        }
 32
 33    def test_calculator_w_list_items(self):
 34        # two_numbers = [
 35        #     self.random_first_number,
 36        #     self.random_second_number
 37        # ]
 38        a_dictionary = {
 39            'x': self.random_first_number,
 40            'y': self.random_second_number
 41        }
 42        two_numbers = list(a_dictionary.values())
 43
 44        for operation in self.calculator_tests:
 45            with self.subTest(operation=operation):
 46                self.assertEqual(
 47                    src.calculator.__getattribute__(operation)(
 48                        *two_numbers
 49                    ),
 50                    self.calculator_tests[operation]
 51                )
 52
 53        self.assertEqual(
 54            src.calculator.add(
 55                two_numbers[0],
 56                two_numbers[1]
 57            ),
 58            self.random_first_number+self.random_second_number
 59        )
 60        self.assertEqual(
 61            src.calculator.divide(
 62                two_numbers[-2],
 63                two_numbers[-1]
 64            ),
 65            self.random_first_number/self.random_second_number
 66        )
 67        self.assertEqual(
 68            src.calculator.multiply(
 69                two_numbers[1],
 70                two_numbers[-1]
 71            ),
 72            self.random_second_number*self.random_second_number
 73        )
 74        self.assertEqual(
 75            src.calculator.subtract(
 76                two_numbers[-2],
 77                two_numbers[0]
 78            ),
 79            self.random_first_number-self.random_first_number
 80        )
 81
 82    def test_calculator_w_dictionary_items(self):
 83        two_numbers = {
 84            'first_input': self.random_first_number,
 85            'second_input': self.random_second_number,
 86        }
 87
 88        for operation in self.calculator_tests:
 89            with self.subTest(operation=operation):
 90                self.assertEqual(
 91                    src.calculator.__getattribute__(operation)(
 92                        **two_numbers
 93                    ),
 94                    self.calculator_tests[operation]
 95                )
 96
 97        self.assertEqual(
 98            src.calculator.add(
 99                two_numbers['first_input'],
100                two_numbers['second_input']
101            ),
102            self.random_first_number+self.random_second_number
103        )
104        self.assertEqual(
105            src.calculator.divide(
106                two_numbers['first_input'],
107                two_numbers['second_input']
108            ),
109            self.random_first_number/self.random_second_number
110        )
111        self.assertEqual(
112            src.calculator.multiply(
113                two_numbers['second_input'],
114                two_numbers['second_input']
115            ),
116            self.random_second_number*self.random_second_number
117        )
118        self.assertEqual(
119            src.calculator.subtract(
120                two_numbers['first_input'],
121                two_numbers['first_input']
122            ),
123            self.random_first_number-self.random_first_number
124        )
125
126    def test_calculator_raises_type_error_when_given_more_than_two_inputs(self):
127        for operation in self.calculator_tests:
128            with (
129                self.subTest(operation=operation),
130                self.assertRaises(TypeError),
131            ):
132                src.calculator.__getattribute__(operation)(
133                    [0, 1, 2]
134                )
135
136    def test_calculator_sends_message_when_input_is_not_a_number(self):
137        for bad_input in (
138            None,
139            True, False,
140            str(), 'text',
141            tuple(), (0, 1, 2, 'n'),
142            list(), [0, 1, 2, 'n'],
143            set(), {0, 1, 2, 'n'},
144            dict(), {'key': 'value'},
145        ):
146            for operation in self.calculator_tests:
147                with self.subTest(
148                    operation=operation,
149                    bad_input=bad_input,
150                ):
151                    self.assertEqual(
152                        src.calculator.__getattribute__(operation)(
153                            bad_input, a_random_number()
154                        ),
155                        'brmph?! Numbers only. Try again...'
156                    )
157
158    def test_calculator_functions(self):
159        for operation in self.calculator_tests:
160            with self.subTest(operation=operation):
161                self.assertEqual(
162                    src.calculator.__getattribute__(operation)(
163                        self.random_first_number,
164                        self.random_second_number
165                    ),
166                    self.calculator_tests[operation]
167                )
168
169
170# Exceptions seen
171# AssertionError
172# NameError
173# AttributeError
174# TypeError
175# KeyError

how to make a calculator 8: solutions

the solutions in calculator/src/calculator.py from how to make a calculator 8

 1def check_input(function):
 2    def wrapper(first_input, second_input):
 3        if isinstance(
 4            first_input,
 5            (dict, set, list, tuple, str, bool)
 6        ) or first_input is None:
 7            return 'brmph?! Numbers only. Try again...'
 8        return function(first_input, second_input)
 9    return wrapper
10
11
12@check_input
13def add(first_input, second_input):
14    return first_input + second_input
15
16
17@check_input
18def divide(first_input, second_input):
19    return first_input / second_input
20
21
22@check_input
23def multiply(first_input, second_input):
24    return first_input * second_input
25
26
27@check_input
28def subtract(first_input, second_input):
29    return first_input - second_input