[TOC]
<span id="start">test function</span>
name_function.py
def get_formatted_name(first,last):
"""Generate(生成) a neatly(整齐的) formatted full name."""
full_name = first + ' ' + last
return full_name.title()
names.py
from name_function import get_formatted_name
print("Enter 'q' at any time to qiut.")
while True:
first = input("\nPlease give me a first name: ")
if first == 'q':
break
last = input("Please give me a last name: ")
if last == 'q'
break
formatted_name = get_formatted_name(first,last)
print("\tNeatly formatted name: "+ formatted_name + '.')
1.Unit testing and test cases.
The module <unittest> in the Python standard library provide code testing tools.Unit test are used to verify that there is no problem with some aspect of the function.A test case is a set of unit tests,these unit tests together verify that the function behaves in all cases.
2.Pass the test
test_name_function.py
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase): # This class must inherit class unittest.TestCase.
"""test name_function.py"""
def test_first_last_name(self):
"""Can you handle a name like Janis Joplin correctly?"""
formatted_name = get_formatted_name('janis','joplin')
self.assertEqual(formatted_name,'Janis Joplin')
unittest.main()
assertEqual function
Explanation:
First we import the module 'unittest' and the function 'get_formatted_name' to test.We created a class named NamesTestCase,you can name it any way you want,but it's best to make it look relevant to the function you're testing.This class must inherit class unittest.TestCase.
<span id="jump">assert</span> function:it use to verify whether the results were in line with the expected results.
The output from running test_name_function.py:
.
------------------------------------------------
Ran 1 test in 0.000s
OK
The period in the first line indicates a test passed
Test class
1.all kinds of assert
we have a lot of assert function in python.
assertEqual(a,b)-----------------verify a == b
assertNotEqual(a,b)--------------verify a != b
assertTrue(x)--------------------verify x is True
assertFalse(x)-------------------verify x is False
assertIn(item,list)--------------verify item in list
assertNotIn(item,list)-----------verify item not in list
[to be continued]
import json
numbers = [1,2,3,4,5]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)#stroe date to file
Let's first import module json,then create a list of numbers.
The file extension **.json** is usually used to indicate that the file stores data in JSON format.
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)# use json.load() to load the information stored in numbers.json.
print(numbers)
2.Sava and read user-generated data
Store username:
import json
username = input("What is your name? ")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We'll remeber you wehn you come back, "+username+" !")
Read file data:
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print("Welcome back, " + username + "!")
Now,we need to merge two programs into one program.When the program runtime,we will try to get the username from the file 'username.json'.So let's first write a 'try' code that tries to restore the username,If this file doesn't exist,we prompt the user for a username in the 'except' code block,and store in the file 'username,json'.
import json
# If the previously stored username is loaded
# Else prompt the user to enter the username an store it.
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except:
username = input("What is your name? ")
with open(filename,'w') as f_obj:
json.jump(username,f_obj)
print("We'll remember you when you come back, "+ username + "!")
else:
print("Welcome back, "+username+"!")
3.reconstruction(重构)
You often encounter situations where the code works correctly and can be further improved---Divide the code into a series of functions that do the work.This process is called reconstruction.
import json
def greet_user():
"""greet the user and indicate their name"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name? ")
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We'll remember you when you come back, "+username+"!")
else:
print("Welcome back, "+username+"!")
greet_user()
reconstruction:
improt json
def get_stored_username():
"""if stored the username,load it"""
try:
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""prompt the user enters the username"""
username = input("What is your name? ")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
return username
def greet_user():
"""greet the user and divide their names"""
username = get_stored_username()
if username:
print("Welcome back, "+username+"!")
else:
username = get_new_username()
print("We'll remember you when you come back, "+username+"!")
greet_user()
网友评论