# 11.2.3 test_code 2017-7-2 Shenzhen ''
import unittest
from survey import AnonymousSurvey
class TestAnonmyousSurvey(unittest.TestCase)
def test_store_single_response(self)
question = "what language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
def test_store_three_responses(self)
question = "what language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
responses = ['English', 'Spanish', 'Mandarin']
for response in responses
my_survey.store_response(response)
for response in responses
self.assertIn(response, my_survey.responses)
unittest.main()
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
[Finished in 0.4s]
# 11.2.2 test_code 2017-7-2 Shenzhen ''
# 11.2.2 test_code 2017-7-2 Shenzhen ''
from survey import AnonymousSurvey
question = "What language did you learn first?"
my_survey = AnonymousSurvey(question)
my_survey.show_question()
print("enter 'q' at anytime to quit")
while True
response = input('language ')
if response == 'q'
break
my_survey.store_response(response)
print("\n Thank you to everyone who participated in the new survey!")
my_survey.show_results()
What language did you learn first?
enter 'q' at anytime to quit
language chinese
language english
language q
Thank you to everyone who participated in the new survey!
Survey results
- chinese
- english
***Repl Closed***
# 11.2.2 test_code 2017-7-2 Shenzhen ''
class AnonymousSurvey()
def __init__(self,question)
self.question=question
self.responses=[]
def show_question(self)
print(self.question)
def store_response(self, new_response)
self.responses.append(new_response)
def show_results(self)
print("Survey results ")
for response in self.responses
print('- ' + response)
question = "What language did you learn first?"
my_survey = AnonymousSurvey(question)
my_survey.show_question()
my_survey.store_response('chinese')
my_survey.store_response('english')
my_survey.show_results()
What language did you learn first?
Survey results
- chinese
- english
[Finished in 0.2s]
# 11-2 test_code 2017-7-2 Shenzhen ''
# 11.1.5 test_code 2017-7-2 Shenzhen ''
#添加新测试,用于测试包含中间名的姓名。
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase)
"""test name_function.py"""
def test_first_last_neme(self)
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
def test_first_last_middle_name(self)
formatted_name = get_formatted_name('wolfgang','mozart','amadeus')
self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
unittest.main()
.. #.. 表示两个测试通过
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK #OK表示全部测试都通过了
[Finished in 0.4s]
# 11.1.4 test_code 2017-7-22 Shenzhen ''
#解决测试用例没有通过的情况
#修改函数如下,测试就通过了。
def get_formatted_name(first, last, middle= '')
if middle
full_name = first + ' '+ middle +' '+ last
else
full_name = first + ' ' + last
return full_name.title()
# 11.1.3 test_code 2017-7-22 Shenzhen ''
给函数添加一个中间名,测试函数是否还能通过
#只包含一个方法的测试用例,检查函数在给定名和姓时候能否正确工作
import unittest #标准库中的模块unittest提供了代码测试工具。
from name_function import get_formatted_name #导入要测试的函数
class NamesTestCase(unittest.TestCase) #这个类名字必须要包含Test,名字最好和要测试的函数有些关系
"""test name_function.py"""
def test_first_last_neme(self) #所有以test打头的方法都自动运行。
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
#assertEqual()断言方法核实得到的结果是否与期望的结果一致
unittest.main() #让python运行文件中的测试,
#下面是被修改过的get_formatted_name()函数
def get_formatted_name(first, last, middle)
full_name = first + ' '+ middle + ' ' + last
return full_name.title()
E #E指出测试用例中有个单元测试导致了错误,
======================================================================
ERROR test_first_last_neme (__main__.NamesTestCase) #这个函数导致错误
----------------------------------------------------------------------
Traceback (most recent call last)
File "D\Sublime text_work\Python_work\test.py", line 8, in test_first_last_neme
formatted_name = get_formatted_name('janis', 'joplin')
TypeError get_formatted_name() missing 1 required positional argument 'middle'
#告诉出问题的具体原因是缺少一个需要的位置实参 'middle'
----------------------------------------------------------------------
Ran 1 test in 0.001s #运行了一个单元测试用了0.001s
FAILED (errors=1) #指出整个测试用例没有通过,因为运行该测试用例时候发生了一个错误
[Finished in 0.4s with exit code 1]
'''
单元测试用于合适函数的某个方面没有问题,测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的
行为都符合要求。良好的测试用例考虑到了函数可能收到的各种输入。
'''
# 11.1.2 test_code 2017-7-2 Shenzhen ''
#只包含一个方法的测试用例,检查函数在给定名和姓时候能否正确工作
import unittest #标准库中的模块unittest提供了代码测试工具。
from name_function import get_formatted_name #导入要测试的函数
class NamesTestCase(unittest.TestCase) #这个类名字必须要包含Test,名字最好和要测试的函数有些关系
"""test name_function.py"""
def test_first_last_neme(self) #所有以test打头的方法都自动运行。
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
#assertEqual()断言方法核实得到的结果是否与期望的结果一致
unittest.main() #让python运行文件中的测试,
. # . 表示有一个测试通过了
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK #OK表示所有测试都通过了
[Finished in 0.6s]
#当稍微改动程序为 formatted_name = get_formatted_name('jans', 'joplin')
F #表示测试有错误
======================================================================
FAIL test_first_last_neme (__main__.NamesTestCase) #指出这行有错误
----------------------------------------------------------------------
Traceback (most recent call last)
File "D\Sublime text_work\Python_work\test.py", line 9, in test_first_last_neme
self.assertEqual(formatted_name, 'Janis Joplin')
AssertionError 'Jans Joplin' != 'Janis Joplin' #断言错误,formatted_name和'Janis Joplin'不相等
- Jans Joplin
+ Janis Joplin
? +
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1) #最终测试结果:失败一个
[Finished in 0.5s with exit code 1]
# 10-13 file 2017-7-2 Shenzhen ''
import json
def get_stored_username()
filename = 'username.json'
try
with open(filename) as f_obj
username = json.load(f_obj)
except FileNotFoundError
return None
else
return username
def get_new_username()
username = input("what is your name?")
filename = 'username.json'
with open(filename,'w') as f_obj
json.dump(username,f_obj)
def greet_user()
username = get_stored_username()
if username == get_stored_username()
print("welcome back, " + username)
else
username = get_new_username()
print("we will remeber you when you come back, " + username)
greet_user()
# 10-12 file 2017-7-2 Shenzhen ''
import json
filename = 'favorate_num.json'
try
with open(filename) as f_obj
favorate_num = json.load(f_obj)
print("i know your favorate number! It is " + favorate_num)
except FileNotFoundError
favorate_num =input("enter your favorate number ")
with open(filename,'w') as f_obj
json.dump(favorate_num, f_obj)
print("your favorate number is " + favorate_num)
# 10-11 file 2017-7-2 Shenzhen ''
import json
favorate_num =input("enter your favorate number ")
filename = 'favorate_num.json'
with open(filename,'w') as f_obj
json.dump(favorate_num, f_obj)
print("your favorate number is " + favorate_num)
# 10-11 file 2017-7-2 Shenzhen ''
import json
filename = 'favorate_num.json'
with open(filename) as f_obj
favorate_num = json.load(f_obj)
print("i know your favorate number! It is " + favorate_num)
# 10.4.3 file 2017-7-2 Shenzhen ''
import json
def get_stored_username()
filename = 'username.json'
try
with open(filename) as f_obj
username = json.load(f_obj)
except FileNotFoundError
return None
else
return username
def get_new_username()
username = input("what is your name?")
filename = 'username.json'
with open(filename,'w') as f_obj #文件不存在就创建
json.dump(username,f_obj) #给文件写入username
def greet_user()
username = get_stored_username()
if username
print("welcome back, " + username)
else
username = get_new_username()
print("we will remeber you when you come back, " + username)
greet_user()
# 10.4.2 file 2017-7-2 Shenzhen ''
import json
#如果以前存储了用户名,直接调用,如果没有存储,新建用户名
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 #'w'标记,表示,如果文件不存在,就创建该文件
json.dump(username, f_obj) #文件创建好了后,写入内容username
print("we will remeber you when you come back, " + username)
else
print("welcome back, " + username)
# 10.4.2 file 2017-7-2 Shenzhen ''
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 will remeber you when you come back, " + username)
# 10.4.2 file 2017-7-2 Shenzhen ''
import json
filename = 'username.json'
with open(filename) as f_obj
username = json.load(f_obj)
print("welcome back, " + username)
# 10.4.1 file 2017-7-2 Shenzhen ''
import json
filename= 'numbers.json'
with open(filename) as f_obj
numbers = json.load(f_obj)
#函数json.load()从参数代表的文件中下载数据
print(numbers)
# 10.4.1 file 2017-7-2 Shenzhen ''
import json
numbers = [2,3,4,5,6,7,89]
filename= 'numbers.json'
with open(filename,'w') as f_obj
json.dump(numbers, f_obj) #函数json.dump()接受两个实参,
#要存储的数据:numbers,和可用于存储数据的文件对象
#该函数作用就是把数据写入文件中和write()函数功能一样
# 10-10 file 2017-7-2 Shenzhen ''
file_name = 'CarbonSpineTableTop_UC.stl'
try
with open(file_name) as file_object
contents=file_object.read()
except FileNotFoundError
message = "Sorry, the file " + file_name + " does not exist."
print(message)
else
words = contents.count('vertex')
print(words)
36
[Finished in 0.2s]
# 10-9 file 2017-7-2 Shenzhen ''
try
filename1 = 'cats.txt'
filename2 = 'dogs.txt'
with open(filename1) as file_object
contents1 = file_object.read()
print(contents1)
with open(filename2) as file_object
contents2 = file_object.read()
print(contents2)
except FileNotFoundError
pass
# 10-8 file 2017-7-2 Shenzhen ''
try
filename1 = 'cats.txt'
filename2 = 'dogs.txt'
with open(filename1) as file_object
contents1 = file_object.read()
print(contents1)
with open(filename2) as file_object
contents2 = file_object.read()
print(contents2)
except FileNotFoundError
print("i can not find the file 'dog.txt', please creat it. ")
mimi huahua taoqi
i can not find the file 'dog.txt', please creat it.
[Finished in 0.2s]
# 10-7 file 2017-7-2 Shenzhen ''
print("input two numbers and caculate the add of them. " +
"press 'q' to exit the input ")
while True
while True
first_number = input("input the first number ")
if first_number == 'q'
break
second_number = input("input the second number ")
if first_number == 'q'
break
try
answer = int(first_number) + int(second_number)
except ValueError
print("you have to input number.")
else
print(answer)
if first_number == 'q' or second_number == 'q'
break
# 10-6 file 2017-7-2 Shenzhen ''
print("input two numbers and caculate the add of them. " +
"press 'q' to exit the input ")
while True
first_number = input("input the first number ")
if first_number == 'q'
break
second_number = input("input the second number ")
if first_number == 'q'
break
try
answer = int(first_number) + int(second_number)
except ValueError
print("you have to input number.")
else
print(answer)
# 10.3.8 file 2017-7-2 Shenzhen ''
def count_words(file_name)
#计算文件中含有多少个字符
try
with open(file_name) as file_object
contents=file_object.read()
except FileNotFoundError
pass #直接忽略掉不存在的文件,也不会报错,
else
words = contents.split()
num_words = len(words)
print("the file " + file_name +"has about " + str(num_words) + " words.")
file_names =[ 'alice.txt', 'siddhartha.txt','moby_dick.txt','little_women.txt']
for file_name in file_names
count_words(file_name)
# 10.3.7 file 2017-7-2 Shenzhen ''
def count_words(file_name)
#计算文件中含有多少个字符
try
with open(file_name) as file_object
contents=file_object.read()
except FileNotFoundError
message = "Sorry, the file " + file_name + " does not exist."
print(message)
else
words = contents.split()
num_words = len(words)
print("the file " + file_name +"has about " + str(num_words) + " words.")
file_names =[ 'alice.txt', 'siddhartha.txt','moby_dick.txt','little_women.txt']
for file_name in file_names
count_words(file_name)
# 10.3.6 file 2017-7-2 Shenzhen ''
file_name = 'alice.txt'
try
with open(file_name) as file_object
contents=file_object.read()
except FileNotFoundError
message = "Sorry, the file " + file_name + " does not exist."
print(message)
else
words = contents.split() #计算words中字符串个数,也就是单词个数
#words = contents #计算words中字符个数
num_words = len(words)
print("the file " + file_name +"has about " + str(num_words) + " words.")
# 10.3.6 file 2017-7-2 Shenzhen ''
title= "alice in wonderland"
print(title)
print(title.split()) #split()可以把有三个单词的字符串分割为有许多元素(三个单词)的列表
alice in wonderland 这是字符串的形式
['alice', 'in', 'wonderland'] #列表形式
[Finished in 0.3s]
# 10.3.5 file 2017-7-2 Shenzhen ''
file_name = 'alice.txt'
try #使用try except 代码块避免程序碰到异常崩溃。
with open(file_name) as file_object
contents=file_object.read()
except FileNotFoundError
message = "Sorry, the file " + file_name + " does not exist."
print(message)
Sorry, the file alice.txt does not exist.
[Finished in 0.2s]
# 10.3.3 file 2017-7-2 Shenzhen ''
print("give me two numbers and i will divide them")
print("enter 'q' to exit")
while True
first_number = input("first number ")
if first_number == 'q'
break
second_number = input("second number")
if second_number =='q'
break
answer = int(first_number)/int(second_number)
print(answer)
# 10.3.2 file 2017-7-2 Shenzhen ''
try #
print(5/0)
except ZeroDivisionError
print("you can nont divide by zero!")
# 10-3 file 2017-7-2 Shenzhen ''
#filename = 'learning_python.txt'
print("please input your name")
with open('programming.txt','a') as file_object
file_object.write("\nI also love finding meaning in large datasets.")
file_object.write("\nI like creating apps that runs in a browser.")
file_object.write("\ngung yang")
# 10.1.8 file 2017-7-2 Shenzhen ''
#filename = 'learning_python.txt'
with open('programming.txt','a') as file_object
file_object.write("\nI also love finding meaning in large datasets.")
file_object.write("\nI like creating apps that runs in a browser.")
# 10.1.7 file 2017-7-2 Shenzhen ''
#filename = 'learning_python.txt'
with open('programming.txt','w') as file_object
file_object.write("I love programming.")
file_object.write("\nI like creating new games.")
# 10.1.7 file 2017-7-2 Shenzhen ''
#filename = 'learning_python.txt'
with open('programming.txt','a') as file_object
file_object.write("\nI also love finding meaning in large datasets.")
file_object.write("\nI like creating apps that runs in a browser.")
#或者如下
open('programming.txt','w').write("I love programming."
+ "\nI also love finding meaning in large datasets."
+ "\nI like creating apps that runs in a browser.")
# 10.2.1 file 2017-7-2 Shenzhen ''
#filename = 'learning_python.txt'
#打开这个文件,如果文件不存在,就创建一个这样的文件。打开文件,格式化文件内容,输入write里的内容
with open('programming.txt','w') as file_object
file_object.write("I love programming.")
#或者写成
open('programming.txt','w').write("I love programming.")
# 10-2 file 2017-7-2 Shenzhen ''
#problem程序无法使用replace函数。该问题已经解决,
filename = 'learning_python.txt'
with open(filename) as file_object
lines = file_object.readlines()
for line in lines
#print(line.rstrip())
message = line.replace('Python', 'C') #replace()就是用新字符替换旧字符串。
#新字符串放在右侧
print(message)
#或者写成如下程序
print(open('learning_python.txt').read().replace('Python', 'C'))
In C I can deal with all kinds of number and characters
In C I can use loop like do .. while; while(); if else; if elif elif else;
In C I can deal with file
In C I can make a game called space war
[Finished in 0.3s]
#原来错误程序如下,错误原因再于没有把处理的结果正确打印出来
# 10-2 file 2017-7-2 Shenzhen ''
#problem程序无法使用replace函数
filename = 'learning_python.txt'
with open(filename) as file_object
lines = file_object.readlines()
for line in lines
#print(line.rstrip())
message = line
message.replace('Python', 'C')
print(message.strip())
In Python I can deal with all kinds of number and characters
In Python I can use loop like do .. while; while(); if else; if elif elif else;
In Python I can deal with file
In Python I can make a game called space war
[Finished in 0.3s]
# 10-1 file 2017-7-2 Shenzhen ''
filename = 'learning_python.txt'
with open(filename) as file_object
contents = file_object.read()
print(contents)
with open(filename) as file_object
#contents = file_object.read()
lines = file_object.readlines()
for line in lines
print(line.rstrip())
learning_string = ''
for line in lines
learning_string +=line.strip()
print(learning_string)
# 10.1.7 file 2017-7-2 Shenzhen ''
filename = 'pi_million_digits.txt'
with open(filename) as file_object
lines = file_object.readlines()
pi_string = ''
for line in lines
pi_string += line.strip()
birthday = input("enter your birthday, in the form mmddyy")
if birthday in pi_string
print("your birthday appears in the first million digits of pi!")
else
print("your birthday doesn't appear in the first million digits of pi!")
# 10.1.5 file 2017-7-2 Shenzhen ''
filename = 'pi_million_digits.txt'
with open(filename) as file_object
lines = file_object.readlines()
print(lines)
pi_string = ''
for line in lines
pi_string += line.strip() #把数组中的每个元素(每行为一个元素),添加到字符串中,
#相当于把数组转化为了一个大大的字符串,并且砍去了左右两侧的空格和回车,但是不能删除元素内部的空格
print(pi_string[52] + "...")
print(len(pi_string))
print(pi_string)
['solid CarbonSpineTableTop_UC.xml\n', ' facet normal 0.0127001469276938 -0.976683740874678 0.214307201416703\n', ' outer loop\n', ' vertex 46.776 -922.29 129.226\n', ' vertex 43.791 -913.621 168.911\n', ' vertex -46.622 -923.499 129.251\n', ' endloop\n', ' endfacet\n', ' facet normal -0.000279634081810437 0.000924132031115562 -0.999999533892276\n', ' outer loop\n', ' vertex -46.622 -923.499 129.251\n', ' vertex -41.116 915.566 130.949\n', ' vertex 46.776 -922.29 129.226\n', ' endloop\n', ' endfacet\n', ' facet normal -8.32043915054624E-05 0.000933525936137284 -0.999999560803081\n', ' outer loop\n', ' vertex 46.776 -922.29 129.226\n', ' vertex -41.116 915.566 130.949\n', ' vertex 40.947 921.809 130.948\n', ' endloop\n', ' endfacet\n', ' facet normal -0.999995330588652 0.00299333044944216 0.000615445946858977\n', ' outer loop\n', ' vertex -41.118 908.294 163.068\n', ' vertex -41.116 915.566 130.949\n', ' vertex -46.622 -923.499 129.251\n', ' endloop\n', ' endfacet\n', ' facet normal -0.0739917576942274 0.972642290740622 0.220209432259733\n', ' outer loop\n', ' vertex 40.947 921.809 130.948\n', ' vertex -41.116 915.566 130.949\n', ' vertex -41.118 908.294 163.068\n', ' endloop\n', ' endfacet\n', ' facet normal -0.00173458985321827 -0.969419158869921 0.245404738369038\n', ' outer loop\n', ' vertex 43.791 -913.621 168.911\n', ' vertex -43.535 -913.465 168.91\n', ' vertex -46.622 -923.499 129.251\n', ' endloop\n', ' endfacet\n', ' facet normal -0.997013707777174 0.00157037017712669 0.0772088106495587\n', ' outer loop\n', ' vertex -41.118 908.294 163.068\n', ' vertex -46.622 -923.499 129.251\n', ' vertex -43.535 -913.465 168.91\n', ' endloop\n', ' endfacet\n', ' facet normal 0.00150640610275766 0.92034717740265 0.391099480679313\n', ' outer loop\n', ' vertex -41.118 908.294 163.068\n', ' vertex 41.361 908.159 163.068\n', ' vertex 40.947 921.809 130.948\n', ' endloop\n', ' endfacet\n', ' facet normal 0.999928377094609 0.00317144318875765 -0.0115404778515142\n', ' outer loop\n', ' vertex 40.947 921.809 130.948\n', ' vertex 41.361 908.159 163.068\n', ' vertex 46.776 -922.29 129.226\n', ' endloop\n', ' endfacet\n', ' facet normal 0.997207481463438 0.00156960685246571 0.0746644175472933\n', ' outer loop\n', ' vertex 46.776 -922.29 129.226\n', ' vertex 41.361 908.159 163.068\n', ' vertex 43.791 -913.621 168.911\n', ' endloop\n', ' endfacet\n', ' facet normal -5.72177120225145E-06 0.00320727861954548 0.999994856652332\n', ' outer loop\n', ' vertex 43.791 -913.621 168.911\n', ' vertex 41.361 908.159 163.068\n', ' vertex -43.535 -913.465 168.91\n', ' endloop\n', ' endfacet\n', ' facet normal 5.24877352886244E-06 0.00320676734731182 0.999994858294597\n', ' outer loop\n', ' vertex -43.535 -913.465 168.91\n', ' vertex 41.361 908.159 163.068\n', ' vertex -41.118 908.294 163.068\n', ' endloop\n', ' endfacet\n', 'endsolid CarbonSpineTableTop_UC.xml\n']
solid CarbonSpineTableTop_UC.xmlfacet normal 0.01270...
2283
solid CarbonSpineTableTop_UC.xmlfacet normal 0.0127001469276938 -0.976683740874678 0.214307201416703outer loopvertex 46.776 -922.29 129.226vertex 43.791 -913.621 168.911vertex -46.622 -923.499 129.251endloopendfacetfacet normal -0.000279634081810437 0.000924132031115562 -0.999999533892276outer loopvertex -46.622 -923.499 129.251vertex -41.116 915.566 130.949vertex 46.776 -922.29 129.226endloopendfacetfacet normal -8.32043915054624E-05 0.000933525936137284 -0.999999560803081outer loopvertex 46.776 -922.29 129.226vertex -41.116 915.566 130.949vertex 40.947 921.809 130.948endloopendfacetfacet normal -0.999995330588652 0.00299333044944216 0.000615445946858977outer loopvertex -41.118 908.294 163.068vertex -41.116 915.566 130.949vertex -46.622 -923.499 129.251endloopendfacetfacet normal -0.0739917576942274 0.972642290740622 0.220209432259733outer loopvertex 40.947 921.809 130.948vertex -41.116 915.566 130.949vertex -41.118 908.294 163.068endloopendfacetfacet norm
Python从入门到实践 代码总结
最新推荐文章于 2024-07-09 15:29:18 发布
本文介绍了Python编程中的单元测试,通过`unittest`模块创建和运行测试用例,确保代码的正确性。内容包括如何创建测试类、定义测试方法、断言检查以及如何处理测试失败。此外,还展示了实际的代码示例,如`AnonymousSurvey`类的测试,以及`get_formatted_name`函数的测试用例。文章最后提到了文件操作和用户输入的相关代码,如存储和读取用户名,强调了良好的测试习惯对于确保程序质量的重要性。
摘要由CSDN通过智能技术生成