objects
I made functions that make dictionaries (test_factory_w_keyword_arguments) and strings (test_factory_person_says_hello) in how to make a person.
I can also use an object for a person, because it is a group of attributes (variables) and methods (functions) that belong together.
preview
I have these tests by the end of the chapter
questions about objects
requirements
how to make a person
open the project
I change directory to the
personfolderthe terminal shows I am in the
personfolder.../pumping_python/personI use
pytest-watcherto run the teststhe terminal is my friend, and shows
I hold ctrl on the keyboard, then click on
tests/test_person.pyto open it
test_classy_person_says_hello
I made a person say hello with a function, I can also do the same thing with an object because it is attributes and methods that belong together.
RED: make it fail
I add a new test to test_person.py
69 def test_factory_person_says_hello(self):
70 first_name = get_random_name()
71 last_name = get_random_name()
72 sex = pick_one('F', 'M')
73
74 year_of_birth = get_random_year_of_birth()
75 age = calculate_age(year_of_birth)
76
77 a_random_person = src.person.person(
78 first_name=first_name,
79 last_name=last_name,
80 sex=sex,
81 year_of_birth=year_of_birth,
82 )
83
84 reality = src.person.say_hello(a_random_person)
85 my_expectation = (
86 f'Hello, my name is {first_name} {last_name}'
87 f' and I am {age}'
88 )
89 self.assertEqual(reality, my_expectation)
90
91 def test_classy_person_says_hello(self):
92 joe = src.person.Person(
93 first_name='joe',
94 last_name='blow',
95 year_of_birth=1996,
96 )
97
98 reality = src.person.say_hello(joe)
99 my_expectation = None
100 self.assertEqual(reality, my_expectation)
101
102
103# Exceptions seen
the terminal is my friend, and shows AttributeError
AttributeError: module 'src.person' has no attribute 'Person'
because there is no definition for Person in src/person/__init__.py in the src folder
GREEN: make it pass
I add an object to
src/person/__init__.pyI add a constructor method to the
Personobject so it can take arguments, it is used to define how copies of the object are madethe terminal is my friend, and shows TypeError
TypeError: Person.__init__() got an unexpected keyword argument 'first_name'because the definition for
__init__does not allow calling it with inputs (the parentheses are empty) and the test sends'first_name'as input.a constructor method is used to make copies of an object
I add the name in parentheses so that the
__init__constructor method can take inputthe terminal is my friend, and shows TypeError
TypeError: Person.__init__() got multiple values for argument 'first_name'because the
__init__constructor method takes the instance it belongs to as the first argumentI add
selfas the first argument the way I do with all the test methods in the bookI add
last_nameto the definition of__init__the terminal is my friend, and shows TypeError
TypeError: Person.__init__() got an unexpected keyword argument 'year_of_birth'still the same as making the person function
I add
year_of_birthto the definition of the __init__ methodthe terminal is my friend, and shows AttributeError
AttributeError: 'Person' object has no attribute 'get'because
the test calls the
say_hellofunctionthe
say_hellofunction expects a dictionarythe
say_hellofunction calls the get method on what it receives andthe
Personobject it receives is not a dictionary and does not have a get method
I change
realityin test_classy_person_says_hello to use a method I can add toPerson, intest_person.pythe terminal is my friend, and shows AttributeError
AttributeError: 'Person' object has no attribute 'say_hello'because the test calls the
say_hellofunction which does not yet exist in thePersonobjectI add a method definition for it to the
Personobject insrc/person/__init__.pythe terminal is my friend, and shows TypeError
TypeError: Person.say_hello() takes 0 positional arguments but 2 were givenbecause the definition for
say_hellodoes not allow inputs and the test called the method with one positional argument (person). Why did the error say two were given when the test only sends one?I add
personto the method definitionthe terminal is my friend, and shows TypeError
TypeError: Person.say_hello() takes 1 positional argument but 2 were givenbecause methods take the copy of the object (
self) they belong to as the first argument.
what is the staticmethod decorator?
I can use the staticmethod decorator if I do not want to add
selfto the method definition whenit does not use anything that belongs to the object that way I am not sending more information than what the method needs. I add @staticmethod tosay_hellothe test passes. I can call methods from outside the object they belong to.
I made a copy of the
Personobject namedjoeI called the say_hello method of the
Personobject withjoe(which is a copy of thePersonobject) as input. Confused? It is confusing and there is a better way.
REFACTOR: make it better
I want the say_hello method of the Person object to return a string for the person it receives, the same way the say_hello function returns a string for the person (dictionary) it receives as input
I change
my_expectationto an f-string in test_classy_person_says_hello intest_person.pythe terminal is my friend, and shows AssertionError
AssertionError: None != 'Hello, my name is joe blow and I am XX'I copy the value from the terminal and paste it in the return statement for the say_hello method of the
Personobject insrc/person/__init__.pythe test passes.
I add an assertion for the next person to test_classy_person_says_hello in
test_person.pythe terminal is my friend, and shows TypeError
TypeError: Person.__init__() got an unexpected keyword argument 'sex'because the
__init__method definition does not have a parameter namedsexI add
sexto the definition of the __init__ methodthe terminal is my friend, and shows TypeError
TypeError: Person.__init__() missing 1 required positional argument: 'sex'because when the test calls the
Personobject to makejoeit does not provide a value forsexwhich I just made a required argument when I added it to the__init__method definition, I have to make it a choiceI add a default value for
sexto make it optionalthe terminal is my friend, and shows TypeError
TypeError: Person.__init__() missing 1 required positional argument: 'last_name'because when the test calls the
Personobject to makejaneit does not provide a value forlast_namewhich is a required argument, I have to make it a choice as wellI add a default value for
last_nameto make it optionalthe terminal is my friend, and shows SyntaxError
SyntaxError: parameter without a default follows parameter with a defaultbecause parameters without default values must come before parameters with default values.
I add a default value for
year_of_birthto make it optionalthe terminal is my friend, and shows AssertionError
AssertionError: 'Hello, my name is joe blow and I am XX' != 'Hello, my name is jane doe and I am YY'Progress. I can make the
say_hellofunction use attributes of the person it receives as input to make the message.I change the string in the return statement of the
say_hellomethod of thePersonobject to an f-string with thefirst_nameattribute of the person it receives, insrc/person/__init__.pythe terminal is my friend, and shows AttributeError
AttributeError: 'Person' object has no attribute 'first_name'because there is no definition for
first_namein thePersonobject definitionI add an attribute to the
Personobject forfirst_namethe terminal is my friend, and shows AssertionError
AssertionError: 'Hello, my name is jane blow and I am XX' != 'Hello, my name is joe blow and I am XX'because I used a fixed value (
jane) and the first assertion of the test expectsjoe. I have to get the value from the object that is passed to thesay_hellomethod.I add a variable to the __init__ method to use it to allow changing the
first_nameattribute anytime a copy of thePersonobject is madethe terminal still shows AssertionError
AssertionError: 'Hello, my name is jane blow and I am XX' != 'Hello, my name is joe blow and I am XX'I change the variable to an object attribute by adding
self.before itthe terminal is my friend, and shows AssertionError
AssertionError: 'Hello, my name is jane blow and I am XX' != 'Hello, my name is jane doe and I am YY'the first names are the same, the last names and ages are different
I add the
last_nameattribute to the string in the return statement of thesay_hellomethodthe terminal is my friend, and shows AttributeError
AttributeError: 'Person' object has no attribute 'last_name'. Did you mean: 'first_name'?because there is no definition for
last_namein thePersonobject definitionI add an attribute to the
Personobject forlast_namethe terminal is my friend, and shows AssertionError
AssertionError: 'Hello, my name is joe doe and I am XX' != 'Hello, my name is joe blow and I am XX'because I used a fixed value (
doe) and the first assertion of the test expectsblow. I have to get the value from the object that is passed to thesay_hellomethod.I add a variable to the __init__ method to use it to allow changing the
last_nameattribute anytime a copy of thePersonobject is madethe terminal still shows AssertionError
AssertionError: 'Hello, my name is joe doe and I am XX' != 'Hello, my name is joe blow and I am XX'I change
last_nameto an object attribute in the __init__ method by addingself.before itthe terminal is my friend, and shows AssertionError
AssertionError: 'Hello, my name is jane None and I am XX' != 'Hello, my name is jane doe and I am YY'the first names are the same and last names and ages are different
the __init__ method used None for the value of
self.last_namebecause the default value for thelast_nameparameter of the method is None. This means thatsrc.person.Person( first_name='jane', sex='F', year_of_birth=1991, )is the same as
src.person.Person.__init__( first_name='jane', sex='F', year_of_birth=1991, last_name=None, )because a method uses the default value for a parameter when it is called without the parameter.
I change the default value for
last_namein the __init__ method to'doe'to give the test what it wantsthe terminal is my friend, and shows AssertionError
AssertionError: 'Hello, my name is jane doe and I am XX' != 'Hello, my name is jane doe and I am YY'the age is the only thing that is different
I add a calculation for the age with the
year_of_birthattribute to the return statement of thesay_hellomethodthe terminal is my friend, and shows AttributeError
AttributeError: 'Person' object has no attribute 'year_of_birth'because there is no definition for
year_of_birthin thePersonobject definitionI add an attribute to the
Personobject foryear_of_birththe terminal is my friend, and shows AssertionError
AssertionError: 'Hello, my name is joe blow and I am YY' != 'Hello, my name is joe blow and I am XX'because I used a fixed value (
1991) and the first assertion of the test expectsdatetime.datetime.now().year-1996. I have to get the value from the object that is passed to thesay_hellomethod.I add a variable to the __init__ method to use it to allow changing the
year_of_birthattribute anytime a copy of thePersonobject is madethe terminal still shows AssertionError
AssertionError: 'Hello, my name is joe blow and I am YY' != 'Hello, my name is joe blow and I am XX'I change
year_of_birthto an object attribute in the __init__ method by addingself.before itthe test passes. What a beautiful life.
self.first_name,self.last_nameandself.year_of_birthare now defined twice in the object. I remove the first definition since the attributes are also made in the __init__ method and that gets called when copies of thePersonobject are made, no need to have a default person bejane doeborn in1991the test is still green.
datetime.datetime.today().yeargets used to calculate the age in the say_hello method of thePersonobject and the return statement of the person function. I make a helper function to calculate the age, the same way I do in the tests1import datetime 2 3 4def calculate_age(year_of_birth): 5 return ( 6 datetime.datetime.today().year 7 - year_of_birth 8 ) 9 10 11def say_hello(a_dictionary):I use the new function for the age calculation in the person function
still green.
I use the new function for the age calculation in the say_hello method of the
Personobjectgreen.
The say_hello method is in the
Personobject, there is no need for it to take a copy of thePersonobject as input since it should be able to access the attributes of the object it belongs to. I changeperson.toself.to use object attributes insteadthe terminal is my friend, and shows NameError
NameError: name 'self' is not definedI change the name of the input parameter from
persontoselfthe test is green again.
I remove the staticmethod decorator because I no longer need it since the say_hello method is using object attributes
the test is still green.
I change the call to
src.person.say_hello(joe)forjoebecause I can call methods directly from a copy of an object, in test_classy_person_says_hello intest_person.pystill green.
I change the call to
src.person.say_hello(joe)forjaneas wellgreen.
I add an assertion for the next person
the terminal is my friend, and shows AssertionError
AssertionError: 'Hello, my name is john smith and I am AAA' != 'Hello, my name is jane doe and I am YY'I change
my_expectationto matchrealityforjohnthe test passes.
I add an assertion for
marythe terminal is my friend, and shows AssertionError
AssertionError: 'Hello, my name is mary public and I am ZZ' != 'Hello, my name is john smith and I am AAA'I change
my_expectationto matchrealityformarythe test passes.
I open a new terminal then change directories to
person
test_classy_person_says_hello with random values
I want to use random values to test_classy_person_says_hello
I go back to the terminal where the tests are running
I add variables
I use the variables to remove repetition of
'joe','blow'and1996the test is still green.
I add variables
I use the variables to remove repetition of
'jane'and1991the test is still green.
I do the same thing with
johnthe test is still green.
I do the same thing with
marythe test is still green
I can add a random person with random values for the
first_name,last_nameandagevariables that are sent in the call tosrc.person.Personto replacejoe,jane,johnandmarysince they are all made the same waythe terminal is my friend and shows AssertionError
AssertionError: 'Hello, my name is Z Y and I am X' != ''I change
my_expectationto matchrealityfora_random_personthe test passes.
I remove the commented lines and the other people from test_classy_person_says_hello because
a_random_personcovers their cases
extract random_first_name object attribute
I make the values for first_name in the tests the same way each time, since TestPerson is an object, I can use an object attribute to remove repetition of how I make it, then have all the methods reference it
I go back to the terminal where the tests are running
I add an object attribute called
random_first_nameto theTestPersonobjectI use the new object attribute in test_factory_w_keyword_arguments
the test is still green.
I use the new object attribute in test_factory_w_optional_arguments
the test is still green.
I use the new object attribute in test_factory_person_says_hello
the test is still green.
I use the new object attribute in test_classy_person_says_hello
the test is still green.
extract random_year_of_birth object attribute
I call the get_random_year_of_birth function for year_of_birth in each test, since TestPerson is an object, I can use an object attribute to remove repetition of those calls, then have all the methods reference the value it returns
I go back to the terminal where the tests are running
I add an object attribute called
random_year_of_birthto theTestPersonobjectI use
self.random_year_of_birthin test_factory_w_keyword_argumentsstill green.
I use
self.random_year_of_birthin test_factory_w_optional_argumentsstill green.
I use
self.random_year_of_birthin test_factory_person_says_hellostill green.
I use
self.random_year_of_birthin test_classy_person_says_hellostill green.
extract random_last_name object attribute
The last_name variable is made the same way in three of the four tests, I can use an object attribute to remove its repetition then have all the methods reference the value
I go back to the terminal where the tests are running
I add an object attribute called
random_last_nameto theTestPersonobjectI use
self.random_last_namein test_factory_w_keyword_argumentsgreen.
I use
self.random_last_namein test_factory_person_says_hellogreen.
I use
self.random_last_namein test_classy_person_says_hellogreen.
extract age object attribute
I call the calculate_age function with the self.random_year_of_birth attribute in each test, since TestPerson is an object, I can use an object attribute to remove repetition of those calls, then have all the methods reference the value it returns
I go back to the terminal where the tests are running
I add an object attribute called
ageto theTestPersonobjectI use
self.agein test_factory_w_keyword_argumentsstill green.
I remove the commented lines and unused variables from test_factory_w_keyword_arguments
I use
self.agein test_factory_w_optional_argumentsstill green.
I remove the commented lines and unused variables from test_factory_w_optional_arguments
I use
self.agein test_factory_person_says_hellostill green.
I remove the commented lines and unused variables from test_factory_person_says_hello
I remove the
sexvariable and parameter because it is not used in this test. I guessa_random_personis not all that random since it will always have'M'assexin this test.I use
self.agein test_classy_person_says_hellostill green.
I remove the commented lines and unused variables from test_classy_person_says_hello
I also do not need the
sexvariable and parameter in this test.
how to use the setUp method to reset object attributes for every test
A problem with the current setup with the object attributes is that they are made once when the object is initialized. This means that even though they all use random values, those values are created once and every test that references the values after that is using the exact same values for each test.
I want each test to get new random values every time they run and the unittest.TestCase class has a way to do that - the `setUp method`_, it runs before every test is run.
RED: make it fail
I go back to the terminal where the tests are running
I add the `unittest.TestCase.setUp method`_ to
TestPersonthen move the object attributes into itthe terminal is my friend, and shows AttributeError
FAILED ...test_classy_person_says_hello - AttributeError: 'TestPerson' object has no attribute 'random_first_name' FAILED ...test_factory_person_says_hello - AttributeError: 'TestPerson' object has no attribute 'random_first_name' FAILED ...test_factory_w_keyword_arguments - AttributeError: 'TestPerson' object has no attribute 'random_first_name' FAILED ...test_factory_w_optional_arguments - AttributeError: 'TestPerson' object has no attribute 'random_first_name'because the
first_namevariable now belongs to the `setUp method`_, the other methods have no way to reach it. I have to make it an object attribute.
GREEN: make it pass
I change the
first_namevariable to an object attribute in the `setUp method`_ for the test methods to be able to use itthe terminal is my friend, and shows AttributeError
FAILED ...test_classy_person_says_hello - AttributeError: 'TestPerson' object has no attribute 'random_last_name'. Did you mean: 'random_first_name'? FAILED ...test_factory_person_says_hello - AttributeError: 'TestPerson' object has no attribute 'random_last_name'. Did you mean: 'random_first_name'? FAILED ...test_factory_w_keyword_arguments - AttributeError: 'TestPerson' object has no attribute 'random_last_name'. Did you mean: 'random_first_name'? FAILED ...test_factory_w_optional_arguments - AttributeError: 'TestPerson' object has no attribute 'random_year_of_birth'.because the
year_of_birthandlast_namevariables now belong to the `setUp method`_, the other methods have no way to reach them. I have to make them object attributesI change the
year_of_birthandlast_namevariables to object attributes in the `setUp method`_ for the test methods to be able to use them as wellthe terminal is my friend, and shows AttributeError
FAILED ...test_classy_person_says_hello - AttributeError: 'TestPerson' object has no attribute 'age' FAILED ...test_factory_person_says_hello - AttributeError: 'TestPerson' object has no attribute 'age' FAILED ...test_factory_w_keyword_arguments - AttributeError: 'TestPerson' object has no attribute 'age' FAILED ...test_factory_w_optional_arguments - AttributeError: 'TestPerson' object has no attribute 'age'because the
agebelongs to the `setUp method`_, and the other methods have no way to reach it. I have to make it an object attributeI change the
agevariable to object attributes in the `setUp method`_ for the other methods to be able to use itthe test passes.
The `unittest.TestCase.setUp method`_ runs before every test, in this case it sets these object attributes (variables) to new values before every test
self.random_first_nameto the result of calling theget_random_namefunction, which returns a random nameself.random_last_nameto the result of calling theget_random_namefunction, which returns a random nameself.random_year_of_birthto the result of calling theget_random_year_of_birthfunction which returns a random year between 120 years ago and the current yearself.ageto the result of calling thecalculate_agefunction, which returns the current year minusself.random_year_of_birth
REFACTOR: make it better
I no longer need the calculate_age function because it is only called by the `setUp method`_. I use `datetime.datetime.now`_ directly
the test is still green.
I no longer need the get_random_year_of_birth function because it is only called by the `setUp method`_. I use random.randint directly
still green.
I use the
this_yearvariable in the calculation forself.agegreen.
datetime.datetime.now().yearis now called once each time the `setUp method`_ runsI remove the commented lines
I remove the calculate_age and get_random_year_of_birth functions
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):
test_dir_person_instance
Python has the dir built-in function which shows the attributes and methods of the object it is given in parentheses. It allows me to see what makes up an object without looking at the code or reading the documentation. I can then run tests to see what each thing does.
RED: make it fail
I go back to the terminal where the tests are running
I add a new test with the dir built-in function in
test_person.pythe terminal is my friend, and shows AssertionError
AssertionError: Lists differ: ['__class__', '__delattr__', '__dict__', '[377 chars]llo'] != Nonebecause dir returned a list (anything in square brackets
[ ]) andmy_expectationis None
GREEN: make it pass
I copy (ctrl/command+c) the values from the terminal and paste (ctrl/command+v) them as
my_expectationthe terminal is my friend, and shows SyntaxError
E [371 chars]llo' E ^ E SyntaxError: unterminated string literal (detected at line 94)because I have a closing quote (
') without a matching opening one and enclosures must be closed once openI add the opening quote
the terminal is my friend and shows AssertionError
AssertionError: Lists differ: ['__c[32 chars]_', '__dir__', '__doc__', '__eq__', '__firstli[329 chars]llo'] != ['__c[32 chars]_', '[371 chars]llo']it shows me the entire list below the message
I copy (ctrl/command+c) the values from the terminal and paste (ctrl/command+v) them as
my_expectationNameError: name 'E' is not definedI use the
find and replacefeature of the Integrated Development Environment (IDE) to remove the extra characters, then remove the commented linesthe test passes.
the
__init__andsay_hellomethods I defined are in the listthere are names in the list that I did not define, which leads to the question of where did they come from?
The attributes I defined in the __init__ method are not in the list, because the test called dir on
src.person.Personwhich is the object, not an instance (copy) of the class
test_dir_person_object
RED: make it fail
I add a test for the attributes and methods of an instance/copy of the Person object to see the difference between it and the original
118 '__str__',
119 '__subclasshook__',
120 '__weakref__',
121 'say_hello',
122 ]
123 self.assertEqual(reality, my_expectation)
124
125 def test_dir_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 'say_hello',
165 ]
166 self.assertEqual(reality, my_expectation)
167
168
169# Exceptions
the terminal is my friend, and shows AssertionError
AssertionError: Lists differ:
['__c[393 chars]ef__', 'first_name', 'last_name',
'say_hello', 'year_of_birth']
!= ['__c[393 chars]ef__', 'say_hello']
because first_name, last_name and year_of_birth are missing. Why is there no sex?
GREEN: make it pass
I add the missing attributes to my_expectation
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 'year_of_birth',
168 ]
169 self.assertEqual(reality, my_expectation)
170
171
172# Exceptions seen
the test passes.
REFACTOR: make it better
I add
sexto the listthe terminal is my friend, and shows AssertionError
AssertionError: Lists differ: ['__c[400 chars]'first_name', 'last_name', 'say_hello', 'year_of_birth'] != ['__c[400 chars]'first_name', 'last_name', 'say_hello', 'sex', 'year_of_birth']the
sexattribute is not defined anywhere in thePersonobjectI add
self.sexto the __init__ method of thePersonobject insrc/person/__init__.pythe test passes
I remove the commented lines
1import datetime 2 3 4def calculate_age(year_of_birth): 5 return ( 6 datetime.datetime.today().year 7 - year_of_birth 8 ) 9 10 11def say_hello(a_dictionary): 12 return ( 13 f'Hello, my name is {a_dictionary.get("first_name")}' 14 f' {a_dictionary.get("last_name")}' 15 f' and I am {a_dictionary.get("age")}' 16 ) 17 18 19def person( 20 first_name, year_of_birth, 21 last_name='doe', sex='M', 22 ): 23 return { 24 'first_name': first_name, 25 'last_name': last_name, 26 'sex': sex, 27 'age': calculate_age(year_of_birth), 28 } 29 30 31class Person: 32 33 def __init__( 34 self, first_name, last_name='doe', 35 year_of_birth=None, sex=None, 36 ): 37 self.first_name = first_name 38 self.last_name = last_name 39 self.year_of_birth = year_of_birth 40 self.sex = sex 41 return None 42 43 def say_hello(self): 44 age = calculate_age(self.year_of_birth) 45 return ( 46 f'Hello, my name is {self.first_name}' 47 f' {self.last_name}' 48 f' and I am {age}' 49 )
close the project
I close
test_person.pyandsrc/person/__init__.pyI click in the terminal where the tests are running
I use q on the keyboard to leave the tests. The terminal goes back to the command line.
I change directory to the parent of
personthe terminal shows
.../pumping_pythonI am back in the
pumping_pythondirectory.
code from the chapter
review
There are few problems with what I have now
anyone seeing the tests for the first time has to read the object attributes
class TestPerson(unittest.TestCase): def setUp(self): self.random_first_name = get_random_name() self.random_last_name = get_random_name() this_year = datetime.datetime.now().year self.random_year_of_birth = random.randint( this_year-120, this_year ) self.age = this_year - self.random_year_of_birth def test_factory_w_keyword_arguments(self):to know how they are created then referenced in each test
test_factory_w_keyword_arguments needs the person reading the test to know about double starred expressions
src.person.person( **a_person, year_of_birth=self.random_year_of_birth, )dict( **a_person, age=self.age, )to know why using the dictionary works in the call to
src.person.personand inside another dictionarytest_factory_person_says_hello and test_classy_person_says_hello need the person reading the test to know about f-strings
f'Hello, my name is {self.random_first_name}' f' {self.random_last_name} ' f'and I am {self.age}'
To review
an object is attributes and methods that belong together
an object can be used for something
A object attributes is a variable that belongs to an object
objects make it easier to write tests for something
Tip
what is next?
You have gone through a lot of things and know:
I know how to make a Python Test Driven Development environment manually.
how to make dictionaries with functions
Would you like to test what causes AttributeError or Would you like to know where the extra attributes and methods of the Person object came from?
You know enough to go into the world and use Python. If you stopped going through the book at this point, you would be fine because you know how to make objects, functions and can make dictionaries which is what is behind a lot of the things you will encounter.
rate pumping python
If this has been a 7 star experience for you, please CLICK HERE to leave a 5 star review of pumping python. It helps other people get into the book too.