测试一:
cap.py:
def just_do_it(text):
return text.capitalize()
test_cap.py
import unittest
import cap
class TestCap(unittest.TestCase):
#setup方法会在每个测试方法执行之前执行,tearDown方法是在每个测试方法执行之后执行
def setUp(self):
pass
def tearDown(self):
pass
def test_one_word(self):
text='duck'
result=cap.just_do_it(text)
self.assertEqual(result,'Duck')
def test_multiple_words(self):
text='a veritable flock of ducks'
result=cap.just_do_it(text)
self.assertEqual(result,'A Veritable Flock Of Ducks')
if __name__=='__main__':
unittest.main()
输出:
FAIL: test_multiple_words (main.TestCap)
Traceback (most recent call last):
File “test_cap.py”, line 16, in test_multiple_words
self.assertEqual(result,‘A Veritable Flock Of Ducks’)
AssertionError: ‘A veritable flock of ducks’ != ‘A Veritable Flock Of Ducks’
- A veritable flock of ducks
? ^ ^ ^ ^
- A Veritable Flock Of Ducks
? ^ ^ ^ ^
Ran 2 tests in 0.001s
FAILED (failures=1)
测试二:
cap.py:
def just_do_it(text):
return text.title()
test_cap.py:
import unittest
import cap
class TestCap(unittest.TestCase):
#setup方法会在每个测试方法执行之前执行,tearDown方法是在每个测试方法执行之后执行
def setUp(self):
pass
def tearDown(self):
pass
def test_one_word(self):
text='duck'
result=cap.just_do_it(text)
self.assertEqual(result,'Duck')
def test_multiple_words(self):
text='a veritable flock of ducks'
result=cap.just_do_it(text)
self.assertEqual(result,'A Veritable Flock Of Ducks')
def test_words_with_apostrophes(self):
text="I'm fresh out of ideas"
result=cap.just_do_it(text)
self.assertEqual(result,"I'm Fresh Out Of Ideas")
if __name__=='__main__':
unittest.main()
输出:
title不能处理撇号
…F
FAIL: test_words_with_apostrophes (main.TestCap)
Traceback (most recent call last):
File “test_cap.py”, line 20, in test_words_with_apostrophes
self.assertEqual(result,“I’m Fresh Out Of Ideas”)
AssertionError: “I’M Fresh Out Of Ideas” != “I’m Fresh Out Of Ideas”
- I’M Fresh Out Of Ideas
? ^
- I’m Fresh Out Of Ideas
? ^
Ran 3 tests in 0.001s
FAILED (failures=1)
cap.py:
def just_do_it(text):
from string import capwords
return capwords(text)
test_cap.py:
import unittest
import cap
class TestCap(unittest.TestCase):
#setup方法会在每个测试方法执行之前执行,tearDown方法是在每个测试方法执行之后执行
def setUp(self):
pass
def tearDown(self):
pass
def test_one_word(self):
text='duck'
result=cap.just_do_it(text)
self.assertEqual(result,'Duck')
def test_multiple_words(self):
text='a veritable flock of ducks'
result=cap.just_do_it(text)
self.assertEqual(result,'A Veritable Flock Of Ducks')
def test_words_with_apostrophes(self):
text="I'm fresh out of ideas"
result=cap.just_do_it(text)
self.assertEqual(result,"I'm Fresh Out Of Ideas")
def test_with_quotes(self):
text="\"You're despicable,\"said Daffy Duck"
result=cap.just_do_it(text)
self.assertEqual(result,"\"You're Despicable,\"Said Daffy Duck")
if __name__=='__main__':
unittest.main()
输出:
…F.
FAIL: test_with_quotes (main.TestCap)
Traceback (most recent call last):
File “test_cap.py”, line 24, in test_with_quotes
self.assertEqual(result,""You’re Despicable,“Said Daffy Duck”)
AssertionError: ‘"you’re Despicable,"said Daffy Duck’ != ‘"You’re Despicable,"Said Daffy Duck’
- "you’re Despicable,"said Daffy Duck
? ^ ^
- "You’re Despicable,"Said Daffy Duck
? ^ ^
Ran 4 tests in 0.001s
FAILED (failures=1)
使用nose进行测试
test_cap_nose.py:
from nose.tools import eq_
import cap
def test_one_word():
text='duck'
result=cap.just_do_it(text)
eq_(result,'Duck')
def test_multiple_words():
text='a veritable flock of ducks'
result=cap.just_do_it(text)
eq_(result,'A Veritable Flock Of Ducks')
def test_words_with_apostrophes():
text="I'm fresh out of ideas"
result=cap.just_do_it(text)
eq_(result,"I'm Fresh Out Of Ideas")
def test_with_quotes():
text="\"You're despicable,\"said Daffy Duck"
result=cap.just_do_it(text)
eq_(result,"\"You're Despicable,\"Said Daffy Duck")
输出:
…F
FAIL: test_cap_nose.test_with_quotes
Traceback (most recent call last):
File “/home/sjj/.conda/envs/tf/lib/python3.7/site-packages/nose/case.py”, line 198, in runTest
self.test(*self.arg)
File “/home/sjj/PycharmProjects/day_01/test_cap_nose.py”, line 18, in test_with_quotes
eq_(result,""You’re Despicable,“Said Daffy Duck”)
AssertionError: ‘"you’re Despicable,"said Daffy Duck’ != ‘"You’re Despicable,"Said Daffy Duck’
Ran 4 tests in 0.001s
FAILED (failures=1)
def func(*argc,**kwargs):
print(vars())
# def dump(func):
# "打印输出函数"
# def wrapped(*args,**kwargs):
# print("Function name: %s"%func.__name__)
# print("Input arguments: %s"%' '.join(map(str,args)))
# print("Input keyword arguments: %s"%kwargs.items())
# output=func(*args,**kwargs)
# print('Output:',output)
# return output
# return wrapped
func(1,2,3)
输出:
{‘argc’: (1, 2, 3), ‘kwargs’: {}}
#装饰器,打印输入的参数和函数的返回值
def dump(func):
"打印输出函数"
def wrapped(*args,**kwargs):
print("Function name: %s"%func.__name__)
print("Input arguments: %s"%' '.join(map(str,args)))
print("Input keyword arguments: %s"%kwargs.items())
output=func(*args,**kwargs)
print('Output:',output)
return output
return wrapped
@dump
def double(*args,**kwargs):
"每个参数乘以2"
output_list=[2*arg for arg in args]
output_dict={k:2*v for k,v in kwargs.items()}
return output_list,output_dict
if __name__=='__main__':
output=double(3,5,first=100,next=98.6,last=-40)
输出:
Function name: double
Input arguments: 3 5
Input keyword arguments: dict_items([(‘first’, 100), (‘next’, 98.6), (‘last’, -40)])
Output: ([6, 10], {‘first’: 200, ‘next’: 197.2, ‘last’: -80})
使用pdb进行测试
def process_cities(filename):
with open(filename,'rt') as file:
for line in file:
line=line.strip()
if 'quit' in line.lower():
return
country,city=line.split(',')
city=city.strip()
country=country.strip()
print(city.title(),country.title(),sep=',')
if __name__=='__main__':
#采用命令行的第一个参数
import sys
process_cities(sys.argv[1])
cities1.csv:
France,Paris
venuzuela,caracas
LithuniA,vilnius
python capitals.py cities1.csv
输出:
Paris,France
Caracas,Venuzuela
Vilnius,Lithunia
cities2.csv:
argentina,buenos aires
bolivia,la paz
brazil,brasilia
chile,santiago
colobima,Bogota
ecuador,quito
falkland islands,stanley
french guiana,cayenne
guyana,georgetown
paraguay,Asuncion
peru,lima
suriname,paramaribo
uruguay,montevideo
venezuela,caracas
quit
python capitals.py cities2.csv
输出:
Buenos Aires,Argentina
La Paz,Bolivia
Brasilia,Brazil
Santiago,Chile
Bogota,Colobima
python -m pdb capitals.py cities2.csv
/home/sjj/PycharmProjects/day_01/capitals.py(1)()
-> def process_cities(filename):
(Pdb) c
Buenos Aires,Argentina
La Paz,Bolivia
Brasilia,Brazil
Santiago,Chile
Bogota,Colobima
The program finished and will be restarted
/home/sjj/PycharmProjects/day_01/capitals.py(1)()
-> def process_cities(filename):
(Pdb) s
/home/sjj/PycharmProjects/day_01/capitals.py(11)()
-> if name’main’:
(Pdb) s
/home/sjj/PycharmProjects/day_01/capitals.py(13)()
-> import sys
(Pdb) s
/home/sjj/PycharmProjects/day_01/capitals.py(14)()
-> process_cities(sys.argv[1])
(Pdb) s
–Call–
/home/sjj/PycharmProjects/day_01/capitals.py(1)process_cities()
-> def process_cities(filename):
(Pdb) s
/home/sjj/PycharmProjects/day_01/capitals.py(2)process_cities()
-> with open(filename,‘rt’) as file:
(Pdb) l
1 def process_cities(filename):
2 -> with open(filename,‘rt’) as file:
3 for line in file:
4 line=line.strip()
5 if ‘quit’ in line.lower():
6 return
7 country,city=line.split(’,’)
8 city=city.strip()
9 country=country.strip()
10 print(city.title(),country.title(),sep=’,’)
11 if name’main’:
(Pdb) b 6
Breakpoint 1 at /home/sjj/PycharmProjects/day_01/capitals.py:6
(Pdb) c
Buenos Aires,Argentina
La Paz,Bolivia
Brasilia,Brazil
Santiago,Chile
Bogota,Colobima
/home/sjj/PycharmProjects/day_01/capitals.py(6)process_cities()
-> return
(Pdb) p line
‘ecuador,quito’
(Pdb) b
Num Type Disp Enb Where
1 breakpoint keep yes at /home/sjj/PycharmProjects/day_01/capitals.py:6
breakpoint already hit 1 time
(Pdb) l
1 def process_cities(filename):
2 with open(filename,‘rt’) as file:
3 for line in file:
4 line=line.strip()
5 if ‘quit’ in line.lower():
6 B-> return
7 country,city=line.split(’,’)
8 city=city.strip()
9 country=country.strip()
10 print(city.title(),country.title(),sep=’,’)
11 if name==‘main’:
(Pdb)
修改后的code:
python -m pdb capitals.py cities2.csv
> /home/sjj/PycharmProjects/day_01/capitals.py(1)<module>()
-> def process_cities(filename):
(Pdb) c
Buenos Aires,Argentina
La Paz,Bolivia
Brasilia,Brazil
Santiago,Chile
Bogota,Colobima
The program finished and will be restarted
> /home/sjj/PycharmProjects/day_01/capitals.py(1)<module>()
-> def process_cities(filename):
(Pdb) s
> /home/sjj/PycharmProjects/day_01/capitals.py(11)<module>()
-> if __name__=='__main__':
(Pdb) s
> /home/sjj/PycharmProjects/day_01/capitals.py(13)<module>()
-> import sys
(Pdb) s
> /home/sjj/PycharmProjects/day_01/capitals.py(14)<module>()
-> process_cities(sys.argv[1])
(Pdb) s
--Call--
> /home/sjj/PycharmProjects/day_01/capitals.py(1)process_cities()
-> def process_cities(filename):
(Pdb) s
> /home/sjj/PycharmProjects/day_01/capitals.py(2)process_cities()
-> with open(filename,'rt') as file:
(Pdb) l
1 def process_cities(filename):
2 -> with open(filename,'rt') as file:
3 for line in file:
4 line=line.strip()
5 if 'quit' in line.lower():
6 return
7 country,city=line.split(',')
8 city=city.strip()
9 country=country.strip()
10 print(city.title(),country.title(),sep=',')
11 if __name__=='__main__':
(Pdb) b 6
Breakpoint 1 at /home/sjj/PycharmProjects/day_01/capitals.py:6
(Pdb) c
Buenos Aires,Argentina
La Paz,Bolivia
Brasilia,Brazil
Santiago,Chile
Bogota,Colobima
> /home/sjj/PycharmProjects/day_01/capitals.py(6)process_cities()
-> return
(Pdb) p line
'ecuador,quito'
(Pdb) b
Num Type Disp Enb Where
1 breakpoint keep yes at /home/sjj/PycharmProjects/day_01/capitals.py:6
breakpoint already hit 1 time
(Pdb) l
1 def process_cities(filename):
2 with open(filename,'rt') as file:
3 for line in file:
4 line=line.strip()
5 if 'quit' in line.lower():
6 B-> return
7 country,city=line.split(',')
8 city=city.strip()
9 country=country.strip()
10 print(city.title(),country.title(),sep=',')
11 if __name__=='__main__':
(Pdb)
输出:
python capitals.py cities2.csv
Buenos Aires,Argentina
La Paz,Bolivia
Brasilia,Brazil
Santiago,Chile
Bogota,Colobima
Quito,Ecuador
Stanley,Falkland Islands
Cayenne,French Guiana
Georgetown,Guyana
Asuncion,Paraguay
Lima,Peru
Paramaribo,Suriname
Montevideo,Uruguay
Caracas,Venezuela
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('Looks like rain')
logging.info('And hail')
logging.warn('Did I hear thunder')
logging.error('Was that lightning')
logging.critical('Stop')
输出:
DEBUG:root:Looks like rain
INFO:root:And hail
/home/sjj/PycharmProjects/day_01/capitals.py:20: DeprecationWarning: The ‘warn’ function is deprecated, use ‘warning’ instead
logging.warn(‘Did I hear thunder’)
WARNING:root:Did I hear thunder
ERROR:root:Was that lightning
CRITICAL:root:Stop
import logging
# logging.basicConfig(level=logging.DEBUG)
# logging.debug('Looks like rain')
# logging.info('And hail')
# logging.warn('Did I hear thunder')
# logging.error('Was that lightning')
# logging.critical('Stop')
logging.basicConfig(level='DEBUG')
logger=logging.getLogger('bunyan')
logger.debug('Timber!')
输出:
DEBUG:bunyan:Timber!
import logging
logging.basicConfig(level='DEBUG',filename='blue_ox.log')
logger=logging.getLogger('bunyan')
logger.debug("Where's my axe?")
logger.warn('I need my axe')
输出:
优化代码
1)计算时间
from time import time
t1=time()
num = 5
num *=2
print(time()-t1)
输出:
1.430511474609375e-06
from timeit import timeit
print(timeit('num=5;num*=2',number=1))
输出:
8.970000635599717e-07
from timeit import repeat
print(repeat('num=5;num*=2',number=1,repeat=3))
输出:
[1.116999555961229e-06, 2.5600093067623675e-07, 1.539992808829993e-07]
from timeit import timeit
def make_list_1():
result=[]
for value in range(1000):
result.append(value)
return result
def make_list_2():
result=[value for value in range(1000)]
return result
print('make_list_1 takes',timeit(make_list_1,number=1000),'seconds')
print('make_list_2 takes',timeit(make_list_2,number=1000),'seconds')
列表解析比手动添加快很多
输出:
make_list_1 takes 0.0637735039999825 seconds
make_list_2 takes 0.027384453000195208 seconds